List of usage examples for java.lang Double doubleValue
@HotSpotIntrinsicCandidate public double doubleValue()
From source file:br.com.topsys.util.TSArrayUtil.java
/** * <p>//from w w w. ja va2 s . co m * Converts an array of object Doubles to primitives handling * <code>null</code>. * </p> * * <p> * This method returns <code>null</code> if <code>null</code> array * input. * </p> * * @param array * a <code>Double</code> array, may be <code>null</code> * @param valueForNull * the value to insert if <code>null</code> found * @return a <code>double</code> array, <code>null</code> if null array * input */ public static double[] toPrimitive(final Double[] array, final double valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_DOUBLE_ARRAY; } final double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { Double b = array[i]; result[i] = (b == null ? valueForNull : b.doubleValue()); } return result; }
From source file:org.adl.sequencer.ADLSeqUtilities.java
/** * Sets the measure associated with the global objective and the student. * // w w w .ja va 2s. com * @param iObjID The ID identifing the desired global objective. * * @param iLearnerID The ID identifing the student. * * @param iScopeID The identifier of the objective's scope. * * @param iMeasure The desired measure. * * @return <code>true</code> if the set was successful; if an error occured * <code>false</code>. */ public static boolean setGlobalObjMeasure(String iObjID, String iLearnerID, String iScopeID, String iMeasure) { if (_Debug) { System.out.println(" :: ADLSeqUtilities --> BEGIN - " + "setGlobalObjMeasure"); System.out.println(" ::--> " + iObjID); System.out.println(" ::--> " + iLearnerID); System.out.println(" ::--> " + iScopeID); System.out.println(" ::--> " + iMeasure); } boolean goodMeasure = true; boolean success = true; // Validate score if (!iMeasure.equals("unknown")) { try { Double tempMeasure = new Double(iMeasure); double range = tempMeasure.doubleValue(); if (range < -1.0 || range > 1.0) { if (_Debug) { System.out.println(" ::--> Invalid range: " + iMeasure); } // The measure is out of range -- ignore goodMeasure = false; } } catch (NumberFormatException e) { if (_Debug) { System.out.println(" ::--> Invalid value: " + iMeasure); } // Invalid format or 'Unknown' goodMeasure = false; } if (!goodMeasure) { success = false; if (_Debug) { System.out.println(" ::--> " + success); System.out.println(" :: ADLSeqUtilities --> END - " + "getGlobalObjMeasure"); } return success; } } System.out.println("NOT IMPLEMENTED - ADLSeqUtilies:setGlobalObjMeasure"); // Get a connection to the global objective DB /*Connection conn = LMSDBHandler.getConnection(); if ( conn != null ) { if ( iObjID != null ) { if ( iLearnerID != null ) { try { PreparedStatement stmtUpdateMeasure = null; // Create the SQL string and covert it to a prepared statement String sqlUpdateMeasure = "UPDATE Objectives SET " + "measure = ? " + "WHERE objID = ? AND " + "learnerID = ? AND scopeID = ?"; stmtUpdateMeasure = conn.prepareStatement(sqlUpdateMeasure); // Insert values into the prepared statement and execute the // update query synchronized( stmtUpdateMeasure ) { stmtUpdateMeasure.setString(1, iMeasure); stmtUpdateMeasure.setString(2, iObjID); stmtUpdateMeasure.setString(3, iLearnerID); if ( iScopeID == null ) { stmtUpdateMeasure.setString(4, ""); } else { stmtUpdateMeasure.setString(4, iScopeID); } stmtUpdateMeasure.executeUpdate(); } // Close the prepared statement stmtUpdateMeasure.close(); } catch ( Exception e ) { if ( _Debug ) { System.out.println(" ::--> ERROR: DB Failure"); e.printStackTrace(); } success = false; } } else { if ( _Debug ) { System.out.println(" ::--> ERROR: NULL learnerID"); } success = false; } } else { if ( _Debug ) { System.out.println(" ::--> ERROR: NULL obj ID"); } success = false; } } else { if ( _Debug ) { System.out.println(" ::--> ERROR: NULL connection"); } success = false; } if ( _Debug ) { System.out.println(" ::--> " + success); System.out.println(" :: ADLSeqUtilities --> END - " + "getGlobalObjMeasure"); }*/ return success; }
From source file:net.ymate.platform.commons.lang.TreeObject.java
/** * * * @param d */ public TreeObject(Double d) { _object = d != null ? d.doubleValue() : Double.MIN_VALUE; _type = TYPE_DOUBLE; }
From source file:net.ymate.platform.commons.lang.TreeObject.java
/** * - Double * * @param d */ public TreeObject add(Double d) { return add(d != null ? d.doubleValue() : 0d, TYPE_DOUBLE); }
From source file:org.adl.datamodels.datatypes.InteractionValidatorImpl.java
/** * Validates the provided string against a known format. * //w w w . j av a2s . co m * @param iValue The value being validated. * * @return An abstract data model error code indicating the result of this * operation. */ @Override public int validate(String iValue) { // Assume the value is valid int valid = DMErrorCodes.NO_ERROR; if (iValue == null) // A null value can never be valid return DMErrorCodes.UNKNOWN_EXCEPTION; // Real Range validator RealRangeValidator realValidator = new RealRangeValidator(); // Lang code validator LangStringValidator langValidator = new LangStringValidator(); // SPM validator for maximum of 250 elements SPMRangeValidator shortSPMValidator = new SPMRangeValidator(250); // SPM validator for maximum of 4000 elements SPMRangeValidator longSPMValidator = new SPMRangeValidator(4000); // URI validator for maximum of 250 elements URIValidator uriValidator = new URIValidator(250, "short_identifier_type"); // SCORM defined separators String comma = "\\[,\\]"; String warn = null; int idx = -1; int result = DMErrorCodes.NO_ERROR; // Swith on the mInteractionType member to determine the type // to validate against. switch (mInteractionType) { case MULTIPLE_CHOICE: { // Check for an empty set if (iValue.length() == 0) { // Value OK break; } // Make sure the last chars of this value are not "[,]" String check = iValue.trim(); idx = check.lastIndexOf("[,]"); if (idx != -1 && (idx == (check.length() - 3))) { // Cannot end with a separator valid = DMErrorCodes.TYPE_MISMATCH; break; } String choices[] = iValue.split(comma); // Check to determine if there are more than 36 choices if (choices.length > 36) { // Number of identifiers SPM Exceeded, create warning. warn = Messages.getString("InteractionValidator.0", mElement); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance().addMessage(new LogMessage(MessageType.WARNING, warn)); } HashSet<String> set = new HashSet<String>(); boolean added = false; // Check to determine if each choice is within the SPM range for (int i = 0; i < choices.length; i++) { // The identifier cannot be empty if (choices[i].trim().equals("")) { // Cannot have an empty identifier valid = DMErrorCodes.TYPE_MISMATCH; break; } // Make sure each short_identifier_type is valid result = uriValidator.validate(choices[i]); if (result == DMErrorCodes.SPM_EXCEEDED) { // SPM of short_identifier_type exceeded, create warning warn = Messages.getString("InteractionValidator.39", mElement, i); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance() .addMessage(new LogMessage(MessageType.WARNING, warn)); } if (result == DMErrorCodes.NO_ERROR || result == DMErrorCodes.SPM_EXCEEDED) { // Make sure this identifier is not already in the set added = set.add(choices[i]); if (!added) { // Cannot have duplicate identifiers valid = DMErrorCodes.TYPE_MISMATCH; break; } } else { // Some type mismatch has occured, we are finished checking valid = result; break; } } break; } case FILL_IN: { // Extract each part of the match_text String matchText[] = iValue.split(comma); // Check to determine if there are more than 10 fill-in responses if (matchText.length > 10) { // Number of match_text SPM Exceeded, create warning. warn = Messages.getString("InteractionValidator.41", mElement); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance().addMessage(new LogMessage(MessageType.WARNING, warn)); } // Validate each match_string for (int i = 0; i < matchText.length; i++) { String matchString = null; String langString = null; // Look for the 'lang' delimiter if (matchText[i].startsWith("{lang=")) { // Find the closing '}' idx = matchText[i].indexOf('}'); if (idx != -1) { matchString = matchText[i].substring(idx + 1); langString = matchText[i].substring(6, idx); // Make sure the lang code is valid result = langValidator.validate(langString); if (result == DMErrorCodes.SPM_EXCEEDED) { // SPM of lang string exceeded, create warning warn = Messages.getString("InteractionValidator.43", mElement, i); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance() .addMessage(new LogMessage(MessageType.WARNING, warn)); } else if (result != DMErrorCodes.NO_ERROR) { // Invalid lang string, we're done valid = result; break; } } else { matchString = matchText[i]; } } else { matchString = matchText[i]; } // Make sure the match_text is valid result = shortSPMValidator.validate(matchString); if (result == DMErrorCodes.SPM_EXCEEDED) { // SPM of match_string exceeded, create warning warn = Messages.getString("InteractionValidator.45", mElement, i); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance() .addMessage(new LogMessage(MessageType.WARNING, warn)); } else if (result != DMErrorCodes.NO_ERROR) { // Invalid match_string, we're done valid = result; break; } } break; } case LONG_FILL_IN: { // Make sure the match_text is valid result = longSPMValidator.validate(iValue); if (result == DMErrorCodes.SPM_EXCEEDED) { // SPM of match_string exceeded, create warning warn = Messages.getString("InteractionValidator.47", mElement); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance().addMessage(new LogMessage(MessageType.WARNING, warn)); } else if (result != DMErrorCodes.NO_ERROR) { // Invalid match_string, we're done valid = result; } break; } case LIKERT: { // Make sure the value is a short_identifier result = uriValidator.validate(iValue); if (result == DMErrorCodes.SPM_EXCEEDED) { // SPM of short_identifier exceeded, create warning warn = Messages.getString("InteractionValidator.48", mElement); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance().addMessage(new LogMessage(MessageType.WARNING, warn)); } else if (result != DMErrorCodes.NO_ERROR) { // Invalid match_string, we're done valid = result; } break; } case MATCHING: { // Should we allow a total empty value if (!mAllowEmpty) { if (StringUtils.isBlank(iValue)) { valid = DMErrorCodes.TYPE_MISMATCH; break; } } else { if (StringUtils.isBlank(iValue)) { // valid -- we're done break; } } // Make sure the last chars of this value are not "[,]" String check = iValue.trim(); idx = check.lastIndexOf("[,]"); if (idx != -1 && (idx == (check.length() - 3))) { // Cannot end with a separator valid = DMErrorCodes.TYPE_MISMATCH; break; } String commas[] = iValue.split(comma); // Check to determine if there are more than 36 pairs if (commas.length > 36) { // Number of identifiers SPM Exceeded, create warning. warn = Messages.getString("InteractionValidator.50", mElement); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance().addMessage(new LogMessage(MessageType.WARNING, warn)); } for (int i = 0; i < commas.length; i++) { if (commas[i].length() == 0) { // Don't allow back to back "[,]" valid = DMErrorCodes.TYPE_MISMATCH; break; } else { // Look at this pair and confirm both short_identifiers // are valid. idx = commas[i].indexOf("[.]"); if (idx == -1) { // Don't have both values valid = DMErrorCodes.TYPE_MISMATCH; break; } // Make sure we only have two values to look at int second = commas[i].indexOf("[.]", idx + 2); if (second != -1) { // Invalid use of the '[.]' valid = DMErrorCodes.TYPE_MISMATCH; break; } String target = commas[i].substring(0, idx); String source = commas[i].substring(idx + 3, commas[i].length()); // Make sure neither value are zero length if (target.length() == 0 || source.length() == 0) { // URI's cannot be zero length valid = DMErrorCodes.TYPE_MISMATCH; break; } // Test the source result = uriValidator.validate(source); if (result == DMErrorCodes.SPM_EXCEEDED) { // SPM of short_identifier_type exceeded, create warning warn = Messages.getString("InteractionValidator.53", mElement, i); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance() .addMessage(new LogMessage(MessageType.WARNING, warn)); } if (result != DMErrorCodes.TYPE_MISMATCH) { // Test the target result = uriValidator.validate(target); if (result == DMErrorCodes.SPM_EXCEEDED) { // SPM of short_identifier_type exceeded, // create warning warn = Messages.getString("InteractionValidator.55", mElement, i); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance() .addMessage(new LogMessage(MessageType.WARNING, warn)); } else if (result != DMErrorCodes.NO_ERROR) { valid = result; } } else { valid = DMErrorCodes.TYPE_MISMATCH; } } if (valid == DMErrorCodes.TYPE_MISMATCH) { // done break; } } break; } case PERFORMANCE: { // Make sure the last chars of this value are not "[,]" String check = iValue.trim(); idx = check.lastIndexOf("[,]"); if (idx != -1 && (idx == (check.length() - 3))) { // Cannot end with a seperator valid = DMErrorCodes.TYPE_MISMATCH; break; } String commaCheck[] = iValue.split(comma); // Check to determine if there are more than 125 records if (commaCheck.length > 125) { // Number of identifiers SPM Exceeded, create warning. warn = Messages.getString("InteractionValidator.58", mElement); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance().addMessage(new LogMessage(MessageType.WARNING, warn)); } for (int i = 0; i < commaCheck.length; i++) { if (commaCheck[i].length() == 0) { // Don't allow back to back "[,]" valid = DMErrorCodes.TYPE_MISMATCH; break; } else { idx = commaCheck[i].indexOf("[.]"); if (idx == -1) { // There must be a seperator valid = DMErrorCodes.TYPE_MISMATCH; break; } // Make sure we only have two values to look at int second = commaCheck[i].indexOf("[.]", idx + 3); if (second != -1) { // Cannot have two '[.]' separators valid = DMErrorCodes.TYPE_MISMATCH; break; } String sn = commaCheck[i].substring(0, idx); String sa = commaCheck[i].substring(idx + 3, commaCheck[i].length()); // Make sure both value are not zero length if (sn.length() == 0 && sa.length() == 0) { valid = DMErrorCodes.TYPE_MISMATCH; break; } // Test the step name if (sn.length() > 0) { result = uriValidator.validate(sn); if (result == DMErrorCodes.SPM_EXCEEDED) { // SPM of step name exceeded, create warning warn = Messages.getString("InteractionValidator.61", mElement, i); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance() .addMessage(new LogMessage(MessageType.WARNING, warn)); } else if (result != DMErrorCodes.NO_ERROR) { valid = result; } } // Test the step answer if (valid != DMErrorCodes.TYPE_MISMATCH) { // Test the step answer idx = sa.indexOf("[:]"); if (idx != -1) { // Make sure there is no second separator int sec = sa.indexOf("[:]", idx + 3); if (sec != -1) { // Too many separators valid = DMErrorCodes.TYPE_MISMATCH; } else { // Test both parts of the range String minString = sa.substring(0, idx); String maxString = sa.substring(idx + 3); try { Double min = null; Double max = null; if (StringUtils.isNotBlank(minString)) { min = new Double(minString); } if (StringUtils.isNotBlank(maxString)) { max = new Double(maxString); } if (min != null && max != null) { if (min.doubleValue() > max.doubleValue()) { // The range minimum cannot exceed max valid = DMErrorCodes.TYPE_MISMATCH; } } } catch (NumberFormatException nfe) { // Some number format exception valid = DMErrorCodes.TYPE_MISMATCH; } } } else { result = shortSPMValidator.validate(sa); if (result == DMErrorCodes.SPM_EXCEEDED) { // SPM of step name exceeded, create warning warn = Messages.getString("InteractionValidator.65", mElement, i); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance() .addMessage(new LogMessage(MessageType.WARNING, warn)); } else if (result != DMErrorCodes.NO_ERROR) { valid = result; } } } } } break; } case SEQUENCING: { String array[] = iValue.split(comma); // Empty string is not allowed if (array.length == 0) { valid = DMErrorCodes.TYPE_MISMATCH; break; } // Ending with an empty string is also not allowed if (iValue.lastIndexOf("[,]") == iValue.length() - 3) { valid = DMErrorCodes.TYPE_MISMATCH; break; } // Check to determine if there are more // than 36 elements in this array if (array.length > 36) { // Number of identifiers SPM Exceeded, create warning. warn = Messages.getString("InteractionValidator.68", mElement); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance().addMessage(new LogMessage(MessageType.WARNING, warn)); } if (!(array.length == 1 && array[0].length() == 0)) { for (int i = 0; i < array.length; i++) { result = uriValidator.validate(array[i]); if (result == DMErrorCodes.SPM_EXCEEDED) { // SPM of step name exceeded, create warning warn = Messages.getString("InteractionValidator.69", mElement, i); // Add the SPM Exceeded warning to the message log DetailedLogMessageCollection.getInstance() .addMessage(new LogMessage(MessageType.WARNING, warn)); } else if (result != DMErrorCodes.NO_ERROR) { valid = result; } } } else { // Set of empty URIs is not allowed valid = DMErrorCodes.TYPE_MISMATCH; } break; } case NUMERIC: { if (mElement.equals("cmi.interactions.n.correct_responses.n.pattern")) { idx = iValue.indexOf("[:]"); if (idx != -1) { // Make sure there is no second separator int sec = iValue.indexOf("[:]", idx + 3); if (sec != -1) { // Too many separators valid = DMErrorCodes.TYPE_MISMATCH; } else { // Test both parts of the range String minString = iValue.substring(0, idx); String maxString = iValue.substring(idx + 3); try { Double min = null; Double max = null; if (StringUtils.isNotBlank(minString)) { min = new Double(minString); } if (StringUtils.isNotBlank(maxString)) { max = new Double(maxString); } if (min != null && max != null) { if (min.doubleValue() > max.doubleValue()) { // The range minimum cannot exceed max valid = DMErrorCodes.TYPE_MISMATCH; } } } catch (NumberFormatException e) { // Some number format exception valid = DMErrorCodes.TYPE_MISMATCH; } } } else { // No separator valid = DMErrorCodes.TYPE_MISMATCH; } } else { valid = realValidator.validate(iValue); } break; } case UNKNOWN_TYPE: { // Assume this is always an error valid = DMErrorCodes.UNKNOWN_EXCEPTION; break; } default: { // Assume this is always an error valid = DMErrorCodes.UNKNOWN_EXCEPTION; } } return valid; }
From source file:org.hawkular.alerts.api.model.condition.EventCondition.java
private boolean processExpression(String expression, Event value) { if (null == expression || expression.isEmpty() || null == value) { return false; }/* www . jav a 2 s.c o m*/ String[] tokens = expression.split(" "); if (tokens.length < 3) { return false; } String eventField = tokens[0]; String operator = tokens[1]; String constant = tokens[2]; for (int i = 3; i < tokens.length; ++i) { constant += " "; constant += tokens[i]; } String sEventValue = null; Long lEventValue = null; String sConstantValue = null; Double dConstantValue = null; if (eventField == null || eventField.isEmpty()) { return false; } if (TENANT_ID.equals(eventField)) { sEventValue = value.getTenantId(); } else if (ID.equals(eventField)) { sEventValue = value.getId(); } else if (CTIME.equals(eventField)) { lEventValue = value.getCtime(); } else if (TEXT.equals(eventField)) { sEventValue = value.getText(); } else if (CATEGORY.equals(eventField)) { sEventValue = value.getCategory(); } else if (eventField.startsWith(TAGS)) { // We get the key from tags.<key> string String key = eventField.substring(5); sEventValue = value.getTags().get(key); } if (sEventValue == null && lEventValue == null) { return false; } if (constant == null) { return false; } int constantLength = constant.length(); if (constant.charAt(0) == '\'' && constant.charAt(constantLength - 1) == '\'') { sConstantValue = constant.substring(1, constantLength - 1); } else if (constant.charAt(0) == '\'' && constant.charAt(constantLength - 1) != '\'') { return false; } else if (constant.charAt(0) != '\'' && constant.charAt(constantLength - 1) == '\'') { return false; } else { dConstantValue = Double.valueOf(constant); } if (EQ.equals(operator)) { if (sEventValue != null && sConstantValue != null) { return sEventValue.equals(sConstantValue); } if (lEventValue != null && dConstantValue != null) { return lEventValue.longValue() == dConstantValue.doubleValue(); } return false; } else if (NON_EQ.equals(operator)) { if (sEventValue != null && sConstantValue != null) { return !sEventValue.equals(sConstantValue); } if (lEventValue != null && dConstantValue != null) { return lEventValue.longValue() != dConstantValue.doubleValue(); } return false; } else if (STARTS.equals(operator)) { if (sEventValue != null && sConstantValue != null) { return sEventValue.startsWith(sConstantValue); } return false; } else if (ENDS.equals(operator)) { if (sEventValue != null && sConstantValue != null) { return sEventValue.endsWith(sConstantValue); } return false; } else if (CONTAINS.equals(operator)) { if (sEventValue != null && sConstantValue != null) { return sEventValue.contains(sConstantValue); } return false; } else if (MATCHES.equals(operator)) { if (sEventValue != null && sConstantValue != null) { return sEventValue.matches(sConstantValue); } return false; } else if (GT.equals(operator)) { Double dEventValue = lEventValue != null ? lEventValue.doubleValue() : null; dEventValue = sEventValue != null ? Double.valueOf(sEventValue) : dEventValue; if (dEventValue != null && dConstantValue != null) { return dEventValue > dConstantValue; } return false; } else if (GTE.equals(operator)) { Double dEventValue = lEventValue != null ? lEventValue.doubleValue() : null; dEventValue = sEventValue != null ? Double.valueOf(sEventValue) : dEventValue; if (dEventValue != null && dConstantValue != null) { return dEventValue >= dConstantValue; } return false; } else if (LT.equals(operator)) { Double dEventValue = lEventValue != null ? lEventValue.doubleValue() : null; dEventValue = sEventValue != null ? Double.valueOf(sEventValue) : dEventValue; if (dEventValue != null && dConstantValue != null) { return dEventValue < dConstantValue; } return false; } else if (LTE.equals(operator)) { Double dEventValue = lEventValue != null ? lEventValue.doubleValue() : null; dEventValue = sEventValue != null ? Double.valueOf(sEventValue) : dEventValue; if (dEventValue != null && dConstantValue != null) { return dEventValue <= dConstantValue; } return false; } return false; }
From source file:org.openmicroscopy.shoola.agents.util.EditorUtil.java
/** * Returns the pixels size as a string.//from w ww . j a va2 s . co m * * @param details The map to convert. * @return See above. */ private static String formatPixelsSize(Map details) { String units = null; UnitsObject o; String x = (String) details.get(PIXEL_SIZE_X); String y = (String) details.get(PIXEL_SIZE_Y); String z = (String) details.get(PIXEL_SIZE_Z); Double dx = null, dy = null, dz = null; NumberFormat nf = NumberFormat.getInstance(); try { dx = Double.parseDouble(x); o = transformSize(dx); units = o.getUnits(); dx = o.getValue(); } catch (Exception e) { } try { dy = Double.parseDouble(y); o = transformSize(dy); if (units == null) units = o.getUnits(); dy = o.getValue(); } catch (Exception e) { } try { dz = Double.parseDouble(z); o = transformSize(dz); if (units == null) units = o.getUnits(); dz = o.getValue(); } catch (Exception e) { } String label = "<b>Pixels Size ("; String value = ""; if (dx != null && dx.doubleValue() > 0) { value += nf.format(dx); label += "X"; } if (dy != null && dy.doubleValue() > 0) { if (value.length() == 0) value += nf.format(dy); else value += "x" + nf.format(dy); label += "Y"; } if (dz != null && dz.doubleValue() > 0) { if (value.length() == 0) value += nf.format(dz); else value += "x" + nf.format(dz); label += "Z"; } label += ") "; if (value.length() == 0) return null; if (units == null) units = UnitsObject.MICRONS; return label + units + ": </b>" + value; }
From source file:com.opengamma.financial.analytics.model.volatility.surface.HestonFourierIRFutureSurfaceFittingFunction.java
@Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final ValueRequirement desiredValue = desiredValues.iterator().next(); //currency//from w w w .j ava 2 s. c o m final Currency currency = Currency.of(((UniqueId) target.getValue()).getValue()); // future curve final Object objectFuturePriceData = inputs.getValue(ValueRequirementNames.FUTURE_PRICE_CURVE_DATA); if (objectFuturePriceData == null) { throw new OpenGammaRuntimeException("Could not get futures price data"); } final NodalDoublesCurve futurePriceData = (NodalDoublesCurve) objectFuturePriceData; // surface final String surfaceName = desiredValue.getConstraint(ValuePropertyNames.SURFACE); final Object objectSurfaceData = inputs.getValue(ValueRequirementNames.STANDARD_VOLATILITY_SURFACE_DATA); if (objectSurfaceData == null) { throw new OpenGammaRuntimeException("Could not get volatility surface data"); } @SuppressWarnings("unchecked") final VolatilitySurfaceData<Double, Double> volatilitySurfaceData = (VolatilitySurfaceData<Double, Double>) objectSurfaceData; //assumes that the sorting is first x, then y if (volatilitySurfaceData.size() == 0) { throw new OpenGammaRuntimeException("Interest rate future option volatility surface definition name=" + futurePriceData.getName() + " contains no data"); } final SortedSet<Double> x = volatilitySurfaceData.getUniqueXValues(); final DoubleArrayList fittedOptionExpiryList = new DoubleArrayList(); final DoubleArrayList futureDelayList = new DoubleArrayList(); final DoubleArrayList kappaList = new DoubleArrayList(); final DoubleArrayList thetaList = new DoubleArrayList(); final DoubleArrayList vol0List = new DoubleArrayList(); final DoubleArrayList omegaList = new DoubleArrayList(); final DoubleArrayList rhoList = new DoubleArrayList(); final DoubleArrayList chiSqList = new DoubleArrayList(); final Map<DoublesPair, DoubleMatrix2D> inverseJacobians = new HashMap<DoublesPair, DoubleMatrix2D>(); for (final Double t : x) { final List<ObjectsPair<Double, Double>> strip = volatilitySurfaceData.getYValuesForX(t); final int n = strip.size(); final DoubleArrayList strikesList = new DoubleArrayList(n); final DoubleArrayList sigmaList = new DoubleArrayList(n); final DoubleArrayList errorsList = new DoubleArrayList(n); final Double futurePrice = futurePriceData.getYValue(t); if (strip.size() > 4 && futurePrice != null) { final double forward = 1 - futurePrice / 100; for (final ObjectsPair<Double, Double> value : strip) { if (value.first != null && value.second != null) { strikesList.add(1 - value.first / 100); sigmaList.add(value.second); errorsList.add(ERROR); } } if (!strikesList.isEmpty()) { final double[] strikes = strikesList.toDoubleArray(); final double[] sigma = sigmaList.toDoubleArray(); final double[] errors = errorsList.toDoubleArray(); ArrayUtils.reverse(strikes); ArrayUtils.reverse(sigma); ArrayUtils.reverse(errors); final LeastSquareResultsWithTransform fittedResult = new HestonModelFitter(forward, strikes, t, sigma, errors, HESTON_FUNCTION).solve(HESTON_INITIAL_VALUES); final DoubleMatrix1D parameters = fittedResult.getModelParameters(); fittedOptionExpiryList.add(t); futureDelayList.add(0); kappaList.add(parameters.getEntry(0)); thetaList.add(parameters.getEntry(1)); vol0List.add(parameters.getEntry(2)); omegaList.add(parameters.getEntry(3)); rhoList.add(parameters.getEntry(4)); inverseJacobians.put(DoublesPair.of(t.doubleValue(), 0.), fittedResult.getModelParameterSensitivityToData()); chiSqList.add(fittedResult.getChiSq()); } } } if (fittedOptionExpiryList.size() < 5) { //don't have sufficient fits to construct a surface throw new OpenGammaRuntimeException( "Could not construct Heston parameter surfaces; have under 5 surface points"); } final double[] fittedOptionExpiry = fittedOptionExpiryList.toDoubleArray(); final double[] futureDelay = futureDelayList.toDoubleArray(); final double[] kappa = kappaList.toDoubleArray(); final double[] theta = thetaList.toDoubleArray(); final double[] vol0 = vol0List.toDoubleArray(); final double[] omega = omegaList.toDoubleArray(); final double[] rho = rhoList.toDoubleArray(); final InterpolatedDoublesSurface kappaSurface = InterpolatedDoublesSurface.from(fittedOptionExpiry, futureDelay, kappa, INTERPOLATOR, "Heston kappa surface"); final InterpolatedDoublesSurface thetaSurface = InterpolatedDoublesSurface.from(fittedOptionExpiry, futureDelay, theta, INTERPOLATOR, "Heston theta surface"); final InterpolatedDoublesSurface vol0Surface = InterpolatedDoublesSurface.from(fittedOptionExpiry, futureDelay, vol0, INTERPOLATOR, "Heston vol0 surface"); final InterpolatedDoublesSurface omegaSurface = InterpolatedDoublesSurface.from(fittedOptionExpiry, futureDelay, omega, INTERPOLATOR, "Heston omega surface"); final InterpolatedDoublesSurface rhoSurface = InterpolatedDoublesSurface.from(fittedOptionExpiry, futureDelay, rho, INTERPOLATOR, "Heston rho surface"); final HestonFittedSurfaces fittedSurfaces = new HestonFittedSurfaces(kappaSurface, thetaSurface, vol0Surface, omegaSurface, rhoSurface, inverseJacobians, currency); final ValueProperties resultProperties = createValueProperties() .with(ValuePropertyNames.CURRENCY, currency.getCode()).with(ValuePropertyNames.SURFACE, surfaceName) .with(InstrumentTypeProperties.PROPERTY_SURFACE_INSTRUMENT_TYPE, InstrumentTypeProperties.IR_FUTURE_OPTION) .get(); final ValueSpecification resultSpecification = new ValueSpecification(ValueRequirementNames.HESTON_SURFACES, target.toSpecification(), resultProperties); return Sets.newHashSet(new ComputedValue(resultSpecification, fittedSurfaces)); }
From source file:models.sos.ObservationDescription.java
/** * createNumberbasedObservation//from w w w . ja v a2 s.c o m * http://www.opengis.net/def/observationType/OGC-OM/2.0/OM_Measurement * http://www.opengis.net/def/observationType/OGC-OM/2.0/OM_CountObservation * * @param phenTime * @param offeringURI * @param sensorURI * @param phenomenonURI * @param uomCode * (ignored for COUNT) * @param value * ( 8.0 Double will be cast to int) * @param featureURI * @param position * (can be null, will only use feature href then) * @param obsType * can be MEASUREMENT or COUNT!!!! * @param sampledFeatureURI * (can be null) * @param foiCodeSpace * (can be null or be used for feature) * @return */ private String createNumberbasedObservation(Date phenTime, String offeringURI, String sensorURI, String phenomenonURI, String uomCode, Double value, String featureURI, Double[] position, String obsType, String sampledFeatureURI, String foiCodeSpace) { StringBuilder sosOMGenerator = new StringBuilder(); // begin sosOMGenerator.append("<sos:offering>" + offeringURI + "</sos:offering>\n" + "<sos:observation>\n" + "<om:OM_Observation gml:id=\"o1\">\n"); // obsType if (obsType != null && obsType.equalsIgnoreCase("MEASUREMENT")) { sosOMGenerator.append("<om:type xlink:href=\"" + SOSConstants.MEASUREMENT_OBS_DEF + "\"/>\n"); } else if (obsType != null && obsType.equalsIgnoreCase("COUNT")) { sosOMGenerator.append("<om:type xlink:href=\"" + SOSConstants.COUNT_OBS_DEF + "\"/>\n"); } // result and phen times sosOMGenerator.append(createObservationTimes(phenTime)); // proc href sosOMGenerator.append("<om:procedure xlink:href=\"" + sensorURI + "\"/>\n"); // here would strict spatial sampling filtering paramter go if (position != null && position.length >= 2) { sosOMGenerator.append(createSpatialSamplingParameter(position)); } // obsprop sosOMGenerator.append("<om:observedProperty xlink:href=\"" + phenomenonURI + "\"/>\n"); // spatialsampling feature sosOMGenerator.append(createSamplingFeature(featureURI, position, sampledFeatureURI, foiCodeSpace)); // actual measurement respective count observation if (obsType != null && obsType.equalsIgnoreCase("MEASUREMENT")) { sosOMGenerator.append( "<om:result xsi:type=\"gml:MeasureType\" uom=\"" + uomCode + "\">" + value + "</om:result>\n"); } else if (obsType != null && obsType.equalsIgnoreCase("COUNT")) { sosOMGenerator .append("<om:result xsi:type=\"xs:integer\">" + (int) value.doubleValue() + "</om:result>\n"); } // footer sosOMGenerator.append("</om:OM_Observation>\n" + "</sos:observation>\n"); return sosOMGenerator.toString(); }
From source file:com.aurel.track.exchange.msProject.exporter.MsProjectExporterBL.java
/** * Add or update the task/*www . j a v a2s .c om*/ * * @param taskElement * @param workItemBean * @param msProjectTaskBean * @param taskID * @param outlineStructure * @param budgetBean * @param actualEstimatedBudgetBean * @param hoursPerWorkday * @param workItemCosts * @param hasChildren * @param defaultTaskType * @param durationFormat * @param isNew */ private static void addUpdateTask(ProjectFile project, Task taskElement, TWorkItemBean workItemBean, TMSProjectTaskBean msProjectTaskBean, int taskID, OutlineStructure outlineStructure, TComputedValuesBean computedValueBean, TActualEstimatedBudgetBean actualEstimatedBudgetBean, Double hoursPerWorkday, List<TCostBean> workItemCosts, boolean hasChildren, Integer defaultTaskType, Integer durationFormat, boolean isNew, Map<Integer, Map<String, List<String[]>>> calendarUIDBasedBaseCalendarExceptionWorkingTimes, Map<Integer, Map<Integer, List<String[]>>> calendarUIDBasedBaseCalendarWeekDayWorkingTimes, LocalLookupContainer localLookupContainer) { outlineStructure.incCurrentLevel(); SystemWBSRT systemWbs = new SystemWBSRT(); if (msProjectTaskBean.getUniqueID() != null) { if (taskElement == null) { taskElement = project.addTask(); } // taskElement.setUniqueID( msProjectTaskBean.getUniqueID()); taskElement.setConstraintType(ConstraintType.getInstance(msProjectTaskBean.getConstraintType())); taskElement.setConstraintDate(msProjectTaskBean.getConstraintDate()); taskElement.setDeadline(msProjectTaskBean.getDeadline()); } // taskElement.setID(Integer.valueOf(taskID)); taskElement.setName(workItemBean.getSynopsis()); taskElement.setUniqueID(workItemBean.getObjectID()); if (isNew && defaultTaskType != null) { taskElement.setType(TaskType.getInstance(defaultTaskType)); } taskElement.setCreateDate(workItemBean.getCreated()); String wbs = systemWbs.getShowValue(SystemFields.WBS, null, workItemBean.getWBSOnLevel(), workItemBean.getObjectID(), localLookupContainer, null); taskElement.setOutlineNumber(wbs); // taskElement.setID(workItemBean.getIDNumber()); StringTokenizer stringTokenizer = new StringTokenizer(wbs, "."); int numberOfLevels = stringTokenizer.countTokens() - 1; if (numberOfLevels == 0) { taskElement.setOutlineLevel(1); } else { taskElement.setOutlineLevel(numberOfLevels + 1); } /* * if(msProjectTaskBean.getOutlineNumber() != null) { * taskElement.setOutlineNumber(msProjectTaskBean.getOutlineNumber()); * }else { // * taskElement.setOutlineLevel(outlineStructure.getAbsoluteLevel()); } */ if (workItemBean.getStartDate() != null && workItemBean.getEndDate() != null) { taskElement.setStart(workItemBean.getTopDownStartDate()); taskElement.setActualStart(workItemBean.getStartDate()); taskElement.setActualFinish(workItemBean.getEndDate()); /* * taskElement.setEarlyStart(workItemBean.getStartDate()); * taskElement.setLateStart(workItemBean.getStartDate()); * taskElement.setEarlyFinish(workItemBean.getEndDate()); * taskElement.setLateFinish(workItemBean.getEndDate()); */ taskElement.setFinish(workItemBean.getTopDownEndDate()); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); if (formatter.format(workItemBean.getStartDate()) .compareTo(formatter.format(workItemBean.getEndDate())) == 0) { taskElement.setDuration(Duration.getInstance(1, TimeUnit.DAYS)); taskElement.setManualDuration(Duration.getInstance(1, TimeUnit.DAYS)); } else { int days = Days.daysBetween(new DateTime(workItemBean.getStartDate()), new DateTime(workItemBean.getEndDate())).getDays(); taskElement.setDuration(Duration.getInstance(days, TimeUnit.DAYS)); } } else if (workItemBean.getStartDate() != null && workItemBean.getEndDate() == null) { taskElement.setStart(workItemBean.getStartDate()); taskElement.setMilestone(true); } taskElement.setPercentageComplete(0); taskElement.setPercentageWorkComplete(0); taskElement.setNotes(workItemBean.getDescription()); // from budgetBean we need only the time unit because the // exported budget is the sum of actual work and remaining work if (computedValueBean != null) { // prepare this transformed values for hasChanged because the // MSProject work seems to be in hours TODO? /* * Double transformedHours = * AccountingBL.transformToTimeUnits(budgetBean.getEstimatedHours(), * hoursPerWorkday, budgetBean.getTimenit(), * AccountingBL.TIMEUNITS.HOURS); if (transformedHours!=null) { * plannedWorkHours = transformedHours.doubleValue(); } */ if (isNew && durationFormat == null) { // for new projects (without previous import the project level // durationFormat is null) if (AccountingBL.TIMEUNITS.HOURS.equals(computedValueBean.getMeasurementUnit())) { durationFormat = LAG_FORMAT.h; } else { durationFormat = LAG_FORMAT.d; } } } // TODO should we set the duration? // Element durationElement = // MsProjectExchangeDOMHelper.getChildByName(taskElement, // TASK_ELEMENTS.Duration); if (isNew && durationFormat != null) { // TODO setDuartionFormat method missing // MsProjectExchangeDOMHelper.setChildTextByName(taskElement, // TASK_ELEMENTS.DurationFormat, durationFormat.toString(), false); // taskElement.setDuration(Duration.getInstance(arg0, // durationFormat)); } int summary; if (hasChildren) { summary = TASK_SUMMARY_TYPE.SUMMARY; } else { summary = TASK_SUMMARY_TYPE.NOT_SUMMARY; } taskElement.setSummary(summary > 0 ? true : false); double actualHours = getSumOfActualWorks(workItemCosts); try { // taskElement.setActualDuration(Duration.getInstance(actualHours, // TimeUnit.HOURS)); } catch (Exception ex) { LOGGER.error("Date parse error: " + ex.getMessage()); } double remainingWorkHours = 0.0; if (actualEstimatedBudgetBean != null) { Double transformedHours = AccountingBL.transformToTimeUnits( actualEstimatedBudgetBean.getEstimatedHours(), hoursPerWorkday, actualEstimatedBudgetBean.getTimeUnit(), AccountingBL.TIMEUNITS.HOURS); if (transformedHours != null) { remainingWorkHours = transformedHours.doubleValue(); } } else { if (isNew && Math.abs(actualHours) < EPSILON && workItemBean.getStartDate() != null && workItemBean.getEndDate() != null) { // "simulate" a remaining value for issue in order to appear the // startDate and endDate in MSProject // as it was set in Genji although to work was set in Genji. Date dateFrom = workItemBean.getStartDate(); Calendar calendar = Calendar.getInstance(); calendar.setTime(dateFrom); CalendarUtil.clearTime(calendar); List<String[]> workingPeriods = null; while (calendar.getTime().before(workItemBean.getEndDate()) || calendar.getTime().getTime() == workItemBean.getEndDate().getTime()) { try { workingPeriods = getWorkingTimeForDay(null, null, calendarUIDBasedBaseCalendarExceptionWorkingTimes.values().iterator().next(), calendarUIDBasedBaseCalendarWeekDayWorkingTimes.values().iterator().next(), calendar.getTime()); } catch (Exception ex) { LOGGER.debug("Element missing: " + ex.getMessage()); } if (workingPeriods != null) { for (Iterator itrWorkPeriod = workingPeriods.iterator(); itrWorkPeriod.hasNext();) { // try each workingTime interval to see where the // work can be added String[] workingTime = (String[]) itrWorkPeriod.next(); String fromTime = workingTime[0]; String toTime = workingTime[1]; Map<String, Integer> timeUnitsMapFromTime = MsProjectExchangeBL .getTimeUnitsMapFromCalendarTime(fromTime); Map<String, Integer> timeUnitsMapToTime = MsProjectExchangeBL .getTimeUnitsMapFromCalendarTime(toTime); double hourDiff = MsProjectExchangeBL.getHoursDiff(timeUnitsMapFromTime, timeUnitsMapToTime); remainingWorkHours += hourDiff; } } calendar.add(Calendar.DATE, 1); } } } taskElement.setRemainingWork(Duration.getInstance(remainingWorkHours, TimeUnit.HOURS)); taskElement.setRemainingDuration(Duration.getInstance(remainingWorkHours, TimeUnit.HOURS)); // the planned work is forced to be the sum of actual work and actual // hours // (instead of the plannedWorkHours) because otherwise MSProject result // is not consistent taskElement.setWork(Duration.getInstance(remainingWorkHours + actualHours, TimeUnit.HOURS)); int days = Days .daysBetween(new DateTime(workItemBean.getStartDate()), new DateTime(workItemBean.getEndDate())) .getDays(); taskElement.setDuration(Duration.getInstance(days, TimeUnit.DAYS)); taskElement.setActualWork(null); // not really needed to update because in track+ UI they are not // modifiable: for new tasks // the msProjectTaskBean is new for existing tasks they can be taken // from the last imported file if (isNew && Math.abs(actualHours) < EPSILON) { if (workItemBean.getStartDate() != null) { msProjectTaskBean.setConstraintType(CONSTRAINT_TYPE.START_NO_EARLIER_THAN); msProjectTaskBean.setConstraintDate(workItemBean.getStartDate()); } else { if (workItemBean.getEndDate() != null) { msProjectTaskBean.setConstraintType(CONSTRAINT_TYPE.FINISH_NO_LATER_THAN); msProjectTaskBean.setConstraintDate(workItemBean.getEndDate()); } } } }