/**
  * Implementation of {@link #putValues} that calls through to {@link #putSharedValues} and {@link
  * #putPrivateValues}.
  *
  * @param cache instance
  * @param values values to put
  * @param filter cache select filter
  */
 public static void putValuesBatched(
     final ViewComputationCache cache,
     final Collection<? extends ComputedValue> values,
     final CacheSelectHint filter) {
   List<ComputedValue> privateValues = null;
   List<ComputedValue> sharedValues = null;
   for (ComputedValue value : values) {
     if (filter.isPrivateValue(value.getSpecification())) {
       if (privateValues == null) {
         privateValues = new ArrayList<ComputedValue>(values.size());
       }
       privateValues.add(value);
     } else {
       if (sharedValues == null) {
         sharedValues = new ArrayList<ComputedValue>(values.size());
       }
       sharedValues.add(value);
     }
   }
   if (sharedValues != null) {
     if (sharedValues.size() == 1) {
       cache.putSharedValue(sharedValues.get(0));
     } else {
       cache.putSharedValues(sharedValues);
     }
   }
   if (privateValues != null) {
     if (privateValues.size() == 1) {
       cache.putPrivateValue(privateValues.get(0));
     } else {
       cache.putPrivateValues(privateValues);
     }
   }
 }
 @Override
 public Set<ComputedValue> execute(
     final FunctionExecutionContext executionContext,
     final FunctionInputs inputs,
     final ComputationTarget target,
     final Set<ValueRequirement> desiredValues) {
   double parentValue = 0;
   double targetValue = 0;
   final UniqueId targetIdentifier = target.getUniqueId();
   for (final ComputedValue c : inputs.getAllValues()) {
     if (targetIdentifier.equals(c.getSpecification().getTargetSpecification().getUniqueId())) {
       targetValue = (Double) c.getValue();
     } else {
       parentValue = (Double) c.getValue();
     }
   }
   final ValueRequirement desiredValue = desiredValues.iterator().next();
   return Collections.singleton(
       new ComputedValue(
           new ValueSpecification(
               ValueRequirementNames.WEIGHT,
               target.toSpecification(),
               desiredValue.getConstraints()),
           targetValue / parentValue));
 }
 @Override
 public Object getValue(final ValueRequirement requirement) {
   final ComputedValue cv = getComputedValue(requirement);
   if (cv != null) {
     return cv.getValue();
   }
   return null;
 }
  /**
   * @param target The target whose result is required
   * @param resultModel The model containing the results
   * @param resultTimestamp The timestamp of the results
   * @return {@code {"rowId": rowId, "0": col0Val, "1": col1Val, ...}} cell values: {@code {"v":
   *     value, "h": [historyVal1, historyVal2, ...]}}
   */
  public Map<String, Object> getTargetResult(
      ComputationTargetSpecification target,
      ViewTargetResultModel resultModel,
      Long resultTimestamp) {
    Integer rowId = getGridStructure().getRowId(target);
    if (rowId == null) {
      // Result not in the grid
      return Collections.emptyMap();
    }

    Map<String, Object> valuesToSend = createTargetResult(rowId);
    // insert nulls into the results for cells which are unsatisfied in the dependency graph
    for (Integer unsatisfiedColId : getGridStructure().getUnsatisfiedCells(rowId)) {
      valuesToSend.put(Integer.toString(unsatisfiedColId), null);
    }

    // Whether or not the row is in the viewport, we may have to store history
    if (resultModel != null) {
      for (String calcConfigName : resultModel.getCalculationConfigurationNames()) {
        for (ComputedValue value : resultModel.getAllValues(calcConfigName)) {
          ValueSpecification specification = value.getSpecification();
          Collection<WebViewGridColumn> columns =
              getGridStructure().getColumns(calcConfigName, specification);
          if (columns == null) {
            // Expect a column for every value
            s_logger.warn(
                "Could not find column for calculation configuration {} with value specification {}",
                calcConfigName,
                specification);
            continue;
          }

          Object originalValue = value.getValue();
          for (WebViewGridColumn column : columns) {
            int colId = column.getId();
            WebGridCell cell = WebGridCell.of(rowId, colId);
            ResultConverter<Object> converter;
            if (originalValue == null) {
              converter = null;
            } else {
              converter =
                  getConverter(
                      column, value.getSpecification().getValueName(), originalValue.getClass());
            }
            Map<String, Object> cellData =
                getCellValue(cell, specification, originalValue, resultTimestamp, converter);
            if (cellData != null) {
              valuesToSend.put(Integer.toString(colId), cellData);
            }
          }
        }
      }
    }
    return valuesToSend;
  }
 private SnapshotDataBundle buildMarketDataMap(final FunctionInputs inputs) {
   final Map<Identifier, Double> marketDataMap = new HashMap<Identifier, Double>();
   for (final ComputedValue value : inputs.getAllValues()) {
     final ComputationTargetSpecification targetSpecification =
         value.getSpecification().getTargetSpecification();
     if (value.getValue() instanceof Double) {
       marketDataMap.put(targetSpecification.getIdentifier(), (Double) value.getValue());
     }
   }
   SnapshotDataBundle snapshotDataBundle = new SnapshotDataBundle();
   snapshotDataBundle.setDataPoints(marketDataMap);
   return snapshotDataBundle;
 }
 @Override
 public ComputedValue getComputedValue(final ValueRequirement requirement) {
   final Pair<String, Object> key =
       Pair.of(
           requirement.getValueName(),
           targetSpecKey(_resolver.getTargetSpecification(requirement.getTargetReference())));
   final ComputedValue[] values = _valuesByRequirement.get(key);
   if (values != null) {
     for (final ComputedValue value : values) {
       // Shortcut to check the properties as we already know the name and target match
       if (requirement.getConstraints().isSatisfiedBy(value.getSpecification().getProperties())) {
         return value;
       }
     }
   }
   return null;
 }
 public static void putValue(
     final ViewComputationCache cache, final ComputedValue value, final CacheSelectHint filter) {
   if (filter.isPrivateValue(value.getSpecification())) {
     cache.putPrivateValue(value);
   } else {
     cache.putSharedValue(value);
   }
 }
 @Override
 protected String[][] getRawDataRows(ViewComputationResultModel result) {
   String[][] rows = new String[getGridStructure().getTargets().size()][];
   int columnCount = getGridStructure().getColumns().size() + getAdditionalCsvColumnCount();
   int offset = getCsvDataColumnOffset();
   for (ComputationTargetSpecification target : result.getAllTargets()) {
     Integer rowId = getGridStructure().getRowId(target);
     if (rowId == null) {
       continue;
     }
     ViewTargetResultModel resultModel = result.getTargetResult(target);
     String[] values = new String[columnCount];
     supplementCsvRowData(rowId, target, values);
     rows[rowId] = values;
     for (String calcConfigName : resultModel.getCalculationConfigurationNames()) {
       for (ComputedValue value : resultModel.getAllValues(calcConfigName)) {
         Object originalValue = value.getValue();
         if (originalValue == null) {
           continue;
         }
         ValueSpecification specification = value.getSpecification();
         Collection<WebViewGridColumn> columns =
             getGridStructure().getColumns(calcConfigName, specification);
         if (columns == null) {
           // Expect a column for every value
           s_logger.warn(
               "Could not find column for calculation configuration {} with value specification {}",
               calcConfigName,
               specification);
           continue;
         }
         for (WebViewGridColumn column : columns) {
           int colId = column.getId();
           ResultConverter<Object> converter =
               getConverter(
                   column, value.getSpecification().getValueName(), originalValue.getClass());
           values[offset + colId] =
               converter.convertToText(
                   getConverterCache(), value.getSpecification(), originalValue);
         }
       }
     }
   }
   return rows;
 }
Example #9
0
  @Override
  public ViewCalculationResultModel buildObject(FudgeDeserializer deserializer, FudgeMsg message) {
    final Map<ComputationTargetSpecification, Map<Pair<String, ValueProperties>, ComputedValue>>
        mapNames =
            new HashMap<
                ComputationTargetSpecification,
                Map<Pair<String, ValueProperties>, ComputedValue>>();
    for (FudgeField field : message) {
      final ComputedValue value = deserializer.fieldValueToObject(ComputedValue.class, field);
      final ComputationTargetSpecification target =
          value.getSpecification().getTargetSpecification();
      if (!mapNames.containsKey(target)) {
        mapNames.put(target, new HashMap<Pair<String, ValueProperties>, ComputedValue>());
      }
      mapNames
          .get(target)
          .put(
              Pair.of(
                  value.getSpecification().getValueName(),
                  value.getSpecification().getProperties()),
              value);
    }
    return new ViewCalculationResultModel() {

      @Override
      public Collection<ComputationTargetSpecification> getAllTargets() {
        return mapNames.keySet();
      }

      @Override
      public Map<Pair<String, ValueProperties>, ComputedValue> getValues(
          ComputationTargetSpecification target) {
        return mapNames.get(target);
      }

      @Override
      public Collection<ComputedValue> getAllValues(ComputationTargetSpecification target) {
        Map<Pair<String, ValueProperties>, ComputedValue> targetValuesMap = mapNames.get(target);
        return targetValuesMap != null
            ? Collections.unmodifiableCollection(targetValuesMap.values())
            : null;
      }
    };
  }
 private void addValue(final ComputedValue value) {
   ArgumentChecker.notNull(value, "Computed Value");
   if (value.getValue() instanceof ComputedValue) {
     throw new IllegalArgumentException("Double-nested value");
   }
   _values.add(value);
   _valuesByRequirementName.put(value.getSpecification().getValueName(), value);
   final Pair<String, Object> key =
       Pair.of(
           value.getSpecification().getValueName(),
           targetSpecKey(value.getSpecification().getTargetSpecification()));
   final ComputedValue[] prev = _valuesByRequirement.get(key);
   if (prev == null) {
     _valuesByRequirement.put(key, new ComputedValue[] {value});
   } else {
     final ComputedValue[] values = new ComputedValue[prev.length + 1];
     System.arraycopy(prev, 0, values, 0, prev.length);
     values[prev.length] = value;
     _valuesByRequirement.put(key, values);
   }
 }
 @Override
 public Set<ComputedValue> execute(
     final FunctionExecutionContext executionContext,
     final FunctionInputs inputs,
     final ComputationTarget target,
     final Set<ValueRequirement> desiredValues) {
   final ComputedValue input = inputs.getAllValues().iterator().next();
   final Object value = input.getValue();
   final ValueSpecification specification =
       new ValueSpecification(
           _requirementName,
           target.toSpecification(),
           getResultProperties(input.getSpecification()));
   ComputedValue scaledValue = null;
   if (value instanceof Double) {
     Double doubleValue = (Double) value;
     final double quantity = target.getPosition().getQuantity().doubleValue();
     doubleValue *= quantity;
     scaledValue = new ComputedValue(specification, doubleValue);
   } else if (value instanceof YieldCurveNodeSensitivityDataBundle) {
     final YieldCurveNodeSensitivityDataBundle nodeSensitivities =
         (YieldCurveNodeSensitivityDataBundle) value;
     final double quantity = target.getPosition().getQuantity().doubleValue();
     final Currency ccy = nodeSensitivities.getCurrency();
     final String name = nodeSensitivities.getYieldCurveName();
     final DoubleLabelledMatrix1D m = nodeSensitivities.getLabelledMatrix();
     final double[] scaled = getScaledMatrix(m.getValues(), quantity);
     scaledValue =
         new ComputedValue(
             specification,
             new YieldCurveNodeSensitivityDataBundle(
                 ccy, new DoubleLabelledMatrix1D(m.getKeys(), m.getLabels(), scaled), name));
   } else if (value instanceof DoubleLabelledMatrix1D) {
     final DoubleLabelledMatrix1D m = (DoubleLabelledMatrix1D) value;
     final double quantity = target.getPosition().getQuantity().doubleValue();
     final double[] scaled = getScaledMatrix(m.getValues(), quantity);
     scaledValue =
         new ComputedValue(
             specification, new DoubleLabelledMatrix1D(m.getKeys(), m.getLabels(), scaled));
   } else if (value instanceof LocalDateLabelledMatrix1D) {
     final LocalDateLabelledMatrix1D m = (LocalDateLabelledMatrix1D) value;
     final double quantity = target.getPosition().getQuantity().doubleValue();
     final double[] scaled = getScaledMatrix(m.getValues(), quantity);
     scaledValue =
         new ComputedValue(
             specification, new LocalDateLabelledMatrix1D(m.getKeys(), m.getLabels(), scaled));
   } else if (value instanceof ZonedDateTimeLabelledMatrix1D) {
     final ZonedDateTimeLabelledMatrix1D m = (ZonedDateTimeLabelledMatrix1D) value;
     final double quantity = target.getPosition().getQuantity().doubleValue();
     final double[] scaled = getScaledMatrix(m.getValues(), quantity);
     scaledValue =
         new ComputedValue(
             specification, new ZonedDateTimeLabelledMatrix1D(m.getKeys(), m.getLabels(), scaled));
   } else if (value instanceof CurrencyLabelledMatrix1D) {
     final CurrencyLabelledMatrix1D m = (CurrencyLabelledMatrix1D) value;
     final double quantity = target.getPosition().getQuantity().doubleValue();
     final double[] scaled = getScaledMatrix(m.getValues(), quantity);
     scaledValue =
         new ComputedValue(
             specification, new CurrencyLabelledMatrix1D(m.getKeys(), m.getLabels(), scaled));
   } else if (value instanceof StringLabelledMatrix1D) {
     final StringLabelledMatrix1D m = (StringLabelledMatrix1D) value;
     final double quantity = target.getPosition().getQuantity().doubleValue();
     final double[] scaled = getScaledMatrix(m.getValues(), quantity);
     scaledValue =
         new ComputedValue(specification, new StringLabelledMatrix1D(m.getKeys(), scaled));
   } else if (_requirementName.equals(
       ValueRequirementNames
           .PRESENT_VALUE_CURVE_SENSITIVITY)) { // TODO this should probably not be done like this
     @SuppressWarnings("unchecked")
     final Map<String, List<DoublesPair>> map = (Map<String, List<DoublesPair>>) value;
     final Map<String, List<DoublesPair>> scaled = new HashMap<String, List<DoublesPair>>();
     for (final Map.Entry<String, List<DoublesPair>> entry : map.entrySet()) {
       final List<DoublesPair> scaledList = new ArrayList<DoublesPair>();
       for (final DoublesPair pair : entry.getValue()) {
         scaledList.add(
             DoublesPair.of(
                 pair.first, pair.second * target.getPosition().getQuantity().doubleValue()));
       }
       scaled.put(entry.getKey(), scaledList);
     }
     scaledValue = new ComputedValue(specification, scaled);
   } else if (value instanceof DoubleLabelledMatrix2D) {
     final DoubleLabelledMatrix2D matrix = (DoubleLabelledMatrix2D) value;
     final Double[] xKeys = matrix.getXKeys();
     final Object[] xLabels = matrix.getXLabels();
     final Double[] yKeys = matrix.getYKeys();
     final Object[] yLabels = matrix.getYLabels();
     final double[][] values = matrix.getValues();
     final int n = values.length;
     final int m = values[0].length;
     final double[][] scaledValues = new double[n][m];
     final double scale = target.getPosition().getQuantity().doubleValue();
     for (int i = 0; i < n; i++) {
       for (int j = 0; j < m; j++) {
         scaledValues[i][j] = values[i][j] * scale;
       }
     }
     scaledValue =
         new ComputedValue(
             specification,
             new DoubleLabelledMatrix2D(xKeys, xLabels, yKeys, yLabels, scaledValues));
   } else if (value instanceof DoubleLabelledMatrix3D) {
     final DoubleLabelledMatrix3D matrix = (DoubleLabelledMatrix3D) value;
     final Double[] xKeys = matrix.getXKeys();
     final Object[] xLabels = matrix.getXLabels();
     final Double[] yKeys = matrix.getYKeys();
     final Object[] yLabels = matrix.getYLabels();
     final Double[] zKeys = matrix.getZKeys();
     final Object[] zLabels = matrix.getZLabels();
     final double[][][] values = matrix.getValues();
     final int n = values.length;
     final int m = values[0].length;
     final int l = values[0][0].length;
     final double[][][] scaledValues = new double[n][m][l];
     final double scale = target.getPosition().getQuantity().doubleValue();
     for (int i = 0; i < n; i++) {
       for (int j = 0; j < m; j++) {
         for (int k = 0; k < l; k++) {
           scaledValues[i][j][k] = values[i][j][k] * scale;
         }
       }
     }
     scaledValue =
         new ComputedValue(
             specification,
             new DoubleLabelledMatrix3D(
                 xKeys, xLabels, yKeys, yLabels, zKeys, zLabels, scaledValues));
   } else {
     // REVIEW emcleod 27-1-2011 aaaaaaaaaarrrrrrrrgggggghhhhhhhhh Why is nothing done here?
     scaledValue = new ComputedValue(specification, value);
   }
   return Collections.singleton(scaledValue);
 }
 private DoubleMatrix1D getSensitivities(
     final SecuritySource secSource,
     final FunctionInputs inputs,
     final RawSecurity rawSecurity,
     final InterpolatedYieldCurveSpecificationWithSecurities curveSpec,
     final YieldAndDiscountCurve curve) {
   final Collection<FactorExposureData> decodedSensitivities =
       RawSecurityUtils.decodeFactorExposureData(secSource, rawSecurity);
   final double[] entries = new double[curveSpec.getStrips().size()];
   int i = 0;
   for (final FixedIncomeStripWithSecurity strip : curveSpec.getStrips()) {
     final FactorExposureData swapExternalSensitivitiesData =
         searchForSwapTenorMatch(decodedSensitivities, strip);
     if (swapExternalSensitivitiesData != null) {
       final ComputedValue computedValue =
           inputs.getComputedValue(
               getSensitivityRequirement(swapExternalSensitivitiesData.getExposureExternalId()));
       if (computedValue != null) {
         final ManageableHistoricalTimeSeries mhts =
             (ManageableHistoricalTimeSeries) computedValue.getValue();
         final Double value = mhts.getTimeSeries().getLatestValue();
         entries[i] =
             -value; // * (qty.doubleValue() ); // we invert here because OpenGamma uses -1bp shift
                     // rather than +1.  DV01 function will invert back.
       } else {
         s_logger.warn(
             "Value was null when getting required input data "
                 + swapExternalSensitivitiesData.getExposureExternalId());
         entries[i] = 0d;
       }
     } else {
       entries[i] = 0d;
     }
     i++;
   }
   // Quick hack to map in bond data.
   i = 0;
   for (final FixedIncomeStripWithSecurity strip : curveSpec.getStrips()) {
     final FactorExposureData bondExternalSensitivitiesData =
         searchForBondTenorMatch(decodedSensitivities, strip);
     if (bondExternalSensitivitiesData != null) {
       final ComputedValue computedValue =
           inputs.getComputedValue(
               getSensitivityRequirement(bondExternalSensitivitiesData.getExposureExternalId()));
       if (computedValue != null) {
         final ManageableHistoricalTimeSeries mhts =
             (ManageableHistoricalTimeSeries) computedValue.getValue();
         final Double value = mhts.getTimeSeries().getLatestValue();
         entries[i] -=
             value; // * (qty.doubleValue() ); // we invert here because OpenGamma uses -1bp shift
                    // rather than +1.  DV01 function will invert back.
       } else {
         s_logger.warn(
             "Value was null when getting required input data "
                 + bondExternalSensitivitiesData.getExposureExternalId());
       }
     }
     i++;
   }
   return new DoubleMatrix1D(entries);
 }
 @Override
 public Object getValue(final String requirementName) {
   final ComputedValue computedValue = getComputedValue(requirementName);
   return computedValue != null ? computedValue.getValue() : null;
 }