Ejemplo n.º 1
0
  private double[] fetchDatas(String conditions, String type, int minute) {
    long time = (System.currentTimeMillis()) / 1000 / 60;
    int endMinute = (int) (time % (60)) - DATA_AREADY_MINUTE;
    int startMinute = endMinute - minute;
    double[] datas = null;

    if (startMinute < 0 && endMinute < 0) {
      String period = m_sdf.format(queryDayPeriod(-1).getTime());
      CommandQueryEntity queryEntity = new CommandQueryEntity(period + ";" + conditions + ";;");
      datas = ArrayUtils.toPrimitive(m_appDataService.queryValue(queryEntity, type), 0);
    } else if (startMinute < 0 && endMinute >= 0) {
      String last = m_sdf.format(queryDayPeriod(-1).getTime());
      String current = m_sdf.format(queryDayPeriod(0).getTime());
      CommandQueryEntity lastQueryEntity = new CommandQueryEntity(last + ";" + conditions + ";;");
      CommandQueryEntity currentQueryEntity =
          new CommandQueryEntity(current + ";" + conditions + ";;");
      double[] lastDatas =
          ArrayUtils.toPrimitive(m_appDataService.queryValue(lastQueryEntity, type), 0);
      double[] currentDatas =
          ArrayUtils.toPrimitive(m_appDataService.queryValue(currentQueryEntity, type), 0);
      datas = mergerArray(lastDatas, currentDatas);
    } else if (startMinute >= 0) {
      String period = m_sdf.format(queryDayPeriod(0).getTime());
      CommandQueryEntity queryEntity = new CommandQueryEntity(period + ";" + conditions + ";;");
      datas = ArrayUtils.toPrimitive(m_appDataService.queryValue(queryEntity, type), 0);
    }
    return datas;
  }
Ejemplo n.º 2
0
 protected double calculateSimilarity(Collection<Double> item1, Collection<Double> item2) {
   System.out.println("item1 " + item1);
   System.out.println("item2 " + item2);
   double[] v1 = ArrayUtils.toPrimitive(item1.toArray(new Double[item1.size()]));
   double[] v2 = ArrayUtils.toPrimitive(item2.toArray(new Double[item2.size()]));
   return Vectors.calculateSimiliraty(v1, v2);
 }
  private void fillCategorySet(HistogramDataset defaultcategorydataset) {

    // MOD scorreia 2011-02-10 code simplified in order to avoid unnecessary aggregation (it is now
    // done in the
    // histogram dataset automatically)
    final double minValue = 0; // lower value of the x-axis of the chart
    double maxValue = 0; // higher value of the x-axis of the chart
    List<Double> blockSizeValueList = new ArrayList<Double>();
    // add each block size (number of rows of the block) to the list
    Iterator<String> iterator = prviewData.keySet().iterator();
    while (iterator.hasNext()) {
      String key = iterator.next();
      Integer blockSize = prviewData.get(key).size();
      assert blockSize != null : "no row found for block " + key; // $NON-NLS-1$
      if (blockSize == null) { // should not happen
        blockSize = 0;
      }
      blockSizeValueList.add(blockSize.doubleValue());
      // evaluate the maximum number of rows
      if (maxValue < blockSize) {
        maxValue = blockSize;
      }
    }

    Double[] valueArray = new Double[blockSizeValueList.size()];
    blockSizeValueList.toArray(valueArray);
    defaultcategorydataset.addSeries(
        "Key distribution",
        ArrayUtils.toPrimitive(valueArray),
        BINS,
        minValue,
        maxValue); //$NON-NLS-1$
  }
Ejemplo n.º 4
0
  private void invokeMethod(
      Method method, Object instance, Object parsedValue, String methodName, String fieldName)
      throws NoSuchMethodException {
    if (method == null) {
      throw new NoSuchMethodException(
          String.format("No setter %s for field %s", methodName, fieldName));
    }

    try {
      if (method.getParameterTypes()[0].equals(byte[].class)) {
        method.invoke(
            instance,
            parsedValue instanceof byte[]
                ? parsedValue
                : ArrayUtils.toPrimitive((Byte[]) parsedValue));
      } else {
        method.invoke(instance, parsedValue);
      }
    } catch (InvocationTargetException | IllegalAccessException e) {
      throw new IllegalStateException(
          String.format(
              "There was a problem with set value '%s' to field '%s'", parsedValue, fieldName),
          e);
    }
  }
Ejemplo n.º 5
0
  protected void initializeVerts(Set<Double> setVerts) {

    // rgd1 = array in Double format

    Double rgd1[];

    rgd1 = setVerts.toArray(new Double[setVerts.size()]);
    initializeVerts(ArrayUtils.toPrimitive(rgd1));
  }
 private int[] getAllBoundaries() {
   List<Integer> boundaries = new ArrayList<Integer>(1);
   Calendar c = Calendar.getInstance();
   c.setTimeInMillis(0); // c.set doesn't reset millis
   for (int year = 1902; year <= 2038; year++) {
     c.set(year, Calendar.JANUARY, 1, 0, 0, 0);
     int exactly = (int) (c.getTimeInMillis() / (24 * 60 * 60 * 1000));
     int before = exactly - 1;
     int after = exactly + 1;
     boundaries.add(Integer.valueOf(before));
     boundaries.add(Integer.valueOf(exactly));
     boundaries.add(Integer.valueOf(after));
   }
   Integer[] indices = boundaries.toArray(new Integer[1]);
   return ArrayUtils.toPrimitive(indices);
 }
Ejemplo n.º 7
0
 public void tryEquipmentChangeNotify(Player[] toNotify) {
   synchronized (lastArmor) {
     ArrayList<Integer> toUpdate = new ArrayList<>(5);
     for (int i = 0; i < 5; i++) {
       ItemStack lastArmor = this.lastArmor[i];
       ItemStack currentArmor = getEquipment(i);
       if (!equals(currentArmor, lastArmor)) toUpdate.add(i);
     }
     if (toUpdate.size() != 0)
       Util.getNMS()
           .notifyOfEquipmentChange(
               toNotify,
               (Player) this.getEntity(),
               ArrayUtils.toPrimitive(toUpdate.toArray(new Integer[toUpdate.size()])));
   }
 }
  @Test(enabled = false)
  public void comparison1Unit2Units() {
    final InflationProviderDiscount[] units = new InflationProviderDiscount[2];
    final CurveBuildingBlockBundle[] bb = new CurveBuildingBlockBundle[2];
    final YieldAndDiscountCurve[] curveDsc = new YieldAndDiscountCurve[2];
    final PriceIndexCurve[] curveInflation = new PriceIndexCurve[2];

    for (int loopblock = 0; loopblock < 2; loopblock++) {
      units[loopblock] = CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(loopblock).getFirst();
      bb[loopblock] = CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(loopblock).getSecond();
      curveDsc[loopblock] = units[loopblock].getCurve(USD);
      curveInflation[loopblock] = units[loopblock].getCurve(US_CPI);
    }
    assertEquals(
        "Curve construction: 1 unit / 3 units ",
        curveDsc[0].getNumberOfParameters(),
        curveDsc[1].getNumberOfParameters());
    assertEquals(
        "Curve construction: 1 unit / 3 units ",
        curveInflation[0].getNumberOfParameters(),
        curveInflation[1].getNumberOfParameters());

    assertArrayEquals(
        "Curve construction: 1 unit / 3 units ",
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[0]).getCurve().getXData()),
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[1]).getCurve().getXData()),
        TOLERANCE_CAL);
    assertArrayEquals(
        "Curve construction: 1 unit / 3 units ",
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[0]).getCurve().getYData()),
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[1]).getCurve().getYData()),
        TOLERANCE_CAL);
    assertArrayEquals(
        "Curve construction: 1 unit / 3 units ",
        ArrayUtils.toPrimitive(((PriceIndexCurveSimple) curveInflation[0]).getCurve().getXData()),
        ArrayUtils.toPrimitive(((PriceIndexCurveSimple) curveInflation[1]).getCurve().getXData()),
        TOLERANCE_CAL);
    assertArrayEquals(
        "Curve construction: 1 unit / 3 units ",
        ArrayUtils.toPrimitive(((PriceIndexCurveSimple) curveInflation[0]).getCurve().getYData()),
        ArrayUtils.toPrimitive(((PriceIndexCurveSimple) curveInflation[1]).getCurve().getYData()),
        TOLERANCE_CAL);
  }
Ejemplo n.º 9
0
  private byte[] getLastBytes() {
    List<Byte> lastBytes = new ArrayList<Byte>();

    if (endBytesBuffer != null) {
      lastBytes.addAll(endBytesBuffer);
    }

    if (capturedBytes != null) {
      byte[] capturedByteArray = capturedBytes.toByteArray();
      for (int i = capturedByteArray.length - 1;
          i >= 0 && lastBytes.size() < endOfMessageBytes.length;
          i--) {
        lastBytes.add(capturedByteArray[i]);
      }
    }

    return ArrayUtils.toPrimitive(lastBytes.toArray(new Byte[0]));
  }
  @Override
  public List estimateDensityFunction(Double[] data) {
    // Number Of Density Points to be used
    // This is a measurements of the estimation precision
    // usually, this is set to a default of 512, as in most KDE algorithms default values, i.e. R
    // "density"function, OmicSoft, Matlab algorithms.
    int numberOfDensityPoints =
        PropertiesConfigurationHolder.getInstance().getInt("numberOfDensityPoints");
    List<double[]> densityFunction = new ArrayList<>();
    // init the KDE with a normal generator
    init(ArrayUtils.toPrimitive(AnalysisUtils.excludeNullValues(data)));
    // compute x values
    // array for random samples
    double[] randomSamples = new double[numberOfDensityPoints];
    for (int i = 0; i < numberOfDensityPoints; i++) {
      double nextDouble = kernelDensityGen.nextDouble();
      randomSamples[i] = nextDouble;
    }
    Arrays.sort(randomSamples);
    densityFunction.add(randomSamples);

    // compute y values
    // use normal default kernel
    NormalDist kern = new NormalDist();
    double datasetSize = (double) data.length;
    // calculate optimal bandwidth with the (ROBUST) Silverman's ‘rule of thumb’ (Scott Variation
    // uses factor = 1.06)
    double bandWidth =
        0.99
            * Math.min(
                empiricalDist.getSampleStandardDeviation(),
                (empiricalDist.getInterQuartileRange() / 1.34))
            / Math.pow(datasetSize, 0.2);
    // estimate density and store values in a vector
    double[] estimatedDensityValues =
        KernelDensity.computeDensity(empiricalDist, kern, bandWidth, randomSamples);
    densityFunction.add(estimatedDensityValues);

    return densityFunction;
  }
  @RequestMapping(value = "/stream/{language}/{name}", method = RequestMethod.GET)
  public void getStreamContent(
      @PathVariable String language, @PathVariable String name, HttpServletResponse response)
      throws IOException {
    LOG.info(String.format("Getting resource for : stream:%s:%s", language, name));

    try (OutputStream out = response.getOutputStream()) {

      StreamContent streamContent = cmsLiteService.getStreamContent(language, name);

      response.setContentLength(streamContent.getContent().length);
      response.setContentType(streamContent.getContentType());
      response.setHeader("Accept-Ranges", "bytes");
      response.setStatus(HttpServletResponse.SC_OK);

      out.write(ArrayUtils.toPrimitive(streamContent.getContent()));
    } catch (Exception e) {
      LOG.error(
          String.format(
              "Content not found for : stream:%s:%s%n:%s",
              language, name, Arrays.toString(e.getStackTrace())));
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, NOT_FOUND_RESPONSE);
    }
  }
Ejemplo n.º 12
0
  /**
   * Read in a list of ExactCall objects from reader, keeping only those with starts in startsToKeep
   * or all sites (if this is empty)
   *
   * @param reader a just-opened reader sitting at the start of the file
   * @param startsToKeep a list of start position of the calls to keep, or empty if all calls should
   *     be kept
   * @param parser a genome loc parser to create genome locs
   * @return a list of ExactCall objects in reader
   * @throws IOException
   */
  public static List<ExactCall> readExactLog(
      final BufferedReader reader, final List<Integer> startsToKeep, GenomeLocParser parser)
      throws IOException {
    if (reader == null) throw new IllegalArgumentException("reader cannot be null");
    if (startsToKeep == null) throw new IllegalArgumentException("startsToKeep cannot be null");
    if (parser == null) throw new IllegalArgumentException("GenomeLocParser cannot be null");

    List<ExactCall> calls = new LinkedList<ExactCall>();

    // skip the header line
    reader.readLine();

    // skip the first "type" line
    reader.readLine();

    while (true) {
      final VariantContextBuilder builder = new VariantContextBuilder();
      final List<Allele> alleles = new ArrayList<Allele>();
      final List<Genotype> genotypes = new ArrayList<Genotype>();
      final double[] posteriors = new double[2];
      final double[] priors = MathUtils.normalizeFromLog10(new double[] {0.5, 0.5}, true);
      final List<Integer> mle = new ArrayList<Integer>();
      final Map<Allele, Double> log10pNonRefByAllele = new HashMap<Allele, Double>();
      long runtimeNano = -1;

      GenomeLoc currentLoc = null;
      while (true) {
        final String line = reader.readLine();
        if (line == null) return calls;

        final String[] parts = line.split("\t");
        final GenomeLoc lineLoc = parser.parseGenomeLoc(parts[0]);
        final String variable = parts[1];
        final String key = parts[2];
        final String value = parts[3];

        if (currentLoc == null) currentLoc = lineLoc;

        if (variable.equals("type")) {
          if (startsToKeep.isEmpty() || startsToKeep.contains(currentLoc.getStart())) {
            builder.alleles(alleles);
            final int stop = currentLoc.getStart() + alleles.get(0).length() - 1;
            builder.chr(currentLoc.getContig()).start(currentLoc.getStart()).stop(stop);
            builder.genotypes(genotypes);
            final int[] mleInts = ArrayUtils.toPrimitive(mle.toArray(new Integer[] {}));
            final AFCalcResult result =
                new AFCalcResult(mleInts, 1, alleles, posteriors, priors, log10pNonRefByAllele);
            calls.add(new ExactCall(builder.make(), runtimeNano, result));
          }
          break;
        } else if (variable.equals("allele")) {
          final boolean isRef = key.equals("0");
          alleles.add(Allele.create(value, isRef));
        } else if (variable.equals("PL")) {
          final GenotypeBuilder gb = new GenotypeBuilder(key);
          gb.PL(GenotypeLikelihoods.fromPLField(value).getAsPLs());
          genotypes.add(gb.make());
        } else if (variable.equals("log10PosteriorOfAFEq0")) {
          posteriors[0] = Double.valueOf(value);
        } else if (variable.equals("log10PosteriorOfAFGt0")) {
          posteriors[1] = Double.valueOf(value);
        } else if (variable.equals("MLE")) {
          mle.add(Integer.valueOf(value));
        } else if (variable.equals("pNonRefByAllele")) {
          final Allele a = Allele.create(key);
          log10pNonRefByAllele.put(a, Double.valueOf(value));
        } else if (variable.equals("runtime.nano")) {
          runtimeNano = Long.valueOf(value);
        } else {
          // nothing to do
        }
      }
    }
  }
Ejemplo n.º 13
0
 /**
  * Converts an ArrayList of integer objects to an array with int primitives.
  *
  * @param list the ArrayList
  * @return the int array
  */
 private int[] list2array(ArrayList<Integer> list) {
   return ArrayUtils.toPrimitive((Integer[]) list.toArray(new Integer[list.size()]));
 }
Ejemplo n.º 14
0
  /**
   * Returns the next message from the stream (could be the entire stream contents or part of a
   * batch).
   *
   * @return A byte array representing the next whole message in the stream (could be the entire
   *     stream contents or part of a batch), or null if the stream is done. If an IOException is
   *     caught while reading (e.g. a socket timeout) and returnDataOnException is true, then all
   *     bytes accumulated up to that point are returned.
   * @throws IOException If an IOException is caught while reading (e.g. a socket timeout) and
   *     returnDataOnException is false.
   */
  @Override
  public byte[] read() throws IOException {
    if (streamDone || inputStream == null) {
      return null;
    }

    capturedBytes = new ByteArrayOutputStream();
    List<Byte> firstBytes = new ArrayList<Byte>();
    // A List is used here to allow the buffer to simulate a "shifting window" of potential bytes.
    endBytesBuffer = new ArrayList<Byte>();

    try {
      // Skip to the beginning of the message
      if (checkStartOfMessageBytes) {
        int i = 0;

        while (i < startOfMessageBytes.length) {
          currentByte = inputStream.read();
          logger.trace("Checking for start of message bytes, currentByte: " + currentByte);

          if (currentByte != -1) {
            if (firstBytes.size() < startOfMessageBytes.length) {
              firstBytes.add((byte) currentByte);
            }

            if (currentByte == (int) (startOfMessageBytes[i] & 0xFF)) {
              i++;
            } else {
              i = 0;
            }
          } else {
            streamDone = true;
            if (firstBytes.size() > 0) {
              throw new FrameStreamHandlerException(
                  true,
                  startOfMessageBytes,
                  ArrayUtils.toPrimitive(firstBytes.toArray(new Byte[0])));
            } else {
              // The input stream ended before the begin bytes were detected, so return null
              return null;
            }
          }
        }

        // Begin bytes were found
        checkStartOfMessageBytes = false;
      }

      // Allow the handler to initialize anything it needs to (e.g. mark the input stream)
      batchStreamReader.initialize();

      // Iterate while there are still bytes to read, or if we're checking for end bytes and its
      // buffer is not empty
      while ((currentByte = batchStreamReader.getNextByte()) != -1
          || (endOfMessageBytes.length > 0 && !endBytesBuffer.isEmpty())) {
        // If the input stream is done, get the byte from the buffer instead
        if (currentByte == -1) {
          currentByte = endBytesBuffer.remove(0);
          streamDone = true;
        } else {
          lastByte = (byte) currentByte;
        }

        // Check to see if an end frame has been received
        if (endOfMessageBytes.length > 0 && !streamDone) {
          if (endBytesBuffer.size() == endOfMessageBytes.length) {
            // Shift the buffer window over one, popping the first element and writing it to the
            // output stream
            capturedBytes.write(endBytesBuffer.remove(0));
          }

          // Add the byte to the buffer
          endBytesBuffer.add((byte) currentByte);

          // Check to see if the current buffer window equals the ending byte sequence
          boolean endBytesFound = true;
          for (int i = 0; i <= endBytesBuffer.size() - 1; i++) {
            if (endBytesBuffer.get(i) != endOfMessageBytes[i]) {
              endBytesFound = false;
              break;
            }
          }

          if (endBytesFound) {
            // Ending bytes sequence has been detected
            streamDone = true;
            return capturedBytes.toByteArray();
          }
        } else {
          // Add the byte to the main output stream
          capturedBytes.write(currentByte);
        }

        if (!streamDone) {
          // Allow subclass to check the current byte stream and return immediately
          byte[] returnBytes =
              batchStreamReader.checkForIntermediateMessage(
                  capturedBytes, endBytesBuffer, lastByte);
          if (returnBytes != null) {
            return returnBytes;
          }
        }
      }
    } catch (Throwable e) {
      if (!returnDataOnException) {
        if (e instanceof IOException) {
          // If an IOException occurred and we're not allowing data to return, throw the exception

          if (checkStartOfMessageBytes && firstBytes.size() > 0) {
            // At least some bytes have been read, but the start of message bytes were not detected
            throw new FrameStreamHandlerException(
                true,
                startOfMessageBytes,
                ArrayUtils.toPrimitive(firstBytes.toArray(new Byte[0])),
                e);
          }
          if (capturedBytes.size() + endBytesBuffer.size() > 0 && endOfMessageBytes.length > 0) {
            // At least some bytes have been captured, but the end of message bytes were not
            // detected
            throw new FrameStreamHandlerException(false, endOfMessageBytes, getLastBytes(), e);
          }
          throw (IOException) e;
        } else {
          // If any other Throwable was caught, return null to indicate that we're done
          return null;
        }
      }
    }

    // Flush the buffer to the main output stream
    for (Byte bufByte : endBytesBuffer) {
      capturedBytes.write(bufByte);
    }

    return capturedBytes.size() > 0 ? capturedBytes.toByteArray() : null;
  }
  @Test
  public void comparison1Unit2Units() {
    final MulticurveProviderDiscount[] units = new MulticurveProviderDiscount[2];
    final CurveBuildingBlockBundle[] bb = new CurveBuildingBlockBundle[2];
    final YieldAndDiscountCurve[] curveDsc = new YieldAndDiscountCurve[2];
    final YieldAndDiscountCurve[] curveFwd = new YieldAndDiscountCurve[2];
    for (int loopblock = 0; loopblock < 2; loopblock++) {
      units[loopblock] = CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(loopblock).getFirst();
      bb[loopblock] = CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(loopblock).getSecond();
      curveDsc[loopblock] = units[loopblock].getCurve(AUD);
      curveFwd[loopblock] = units[loopblock].getCurve(AUDBB3M);
    }
    assertEquals(
        "Curve construction: 1 unit / 2 units ",
        curveDsc[0].getNumberOfParameters(),
        curveDsc[1].getNumberOfParameters());
    assertEquals(
        "Curve construction: 1 unit / 2 units ",
        curveFwd[0].getNumberOfParameters(),
        curveFwd[1].getNumberOfParameters());
    assertArrayEquals(
        "Curve construction: 1 unit / 2 units ",
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[0]).getCurve().getXData()),
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[1]).getCurve().getXData()),
        TOLERANCE_CAL);
    assertArrayEquals(
        "Curve construction: 1 unit / 2 units ",
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[0]).getCurve().getYData()),
        ArrayUtils.toPrimitive(((YieldCurve) curveDsc[1]).getCurve().getYData()),
        TOLERANCE_CAL);
    assertArrayEquals(
        "Curve construction: 1 unit / 2 units ",
        ArrayUtils.toPrimitive(((YieldCurve) curveFwd[0]).getCurve().getXData()),
        ArrayUtils.toPrimitive(((YieldCurve) curveFwd[1]).getCurve().getXData()),
        TOLERANCE_CAL);
    assertArrayEquals(
        "Curve construction: 1 unit / 2 units ",
        ArrayUtils.toPrimitive(((YieldCurve) curveFwd[0]).getCurve().getYData()),
        ArrayUtils.toPrimitive(((YieldCurve) curveFwd[1]).getCurve().getYData()),
        TOLERANCE_CAL);

    assertEquals(
        "Curve construction: 1 unit / 2 units ",
        bb[0].getBlock(CURVE_NAME_FWD3_AUD).getFirst(),
        bb[1].getBlock(CURVE_NAME_FWD3_AUD).getFirst());
    // Test note: the discounting curve building blocks are not the same; in one case both curves
    // are build together in the other one after the other.
    final int nbLineDsc = bb[0].getBlock(CURVE_NAME_DSC_AUD).getSecond().getNumberOfRows();
    final int nbLineFwd3 = bb[0].getBlock(CURVE_NAME_FWD3_AUD).getSecond().getNumberOfRows();
    final int nbLineFwd6 = bb[0].getBlock(CURVE_NAME_FWD6_AUD).getSecond().getNumberOfRows();
    assertEquals(
        "Curve construction: 1 unit / 2 units ",
        bb[1].getBlock(CURVE_NAME_DSC_AUD).getSecond().getNumberOfRows(),
        nbLineDsc);
    assertEquals(
        "Curve construction: 1 unit / 2 units ",
        bb[1].getBlock(CURVE_NAME_FWD3_AUD).getSecond().getNumberOfRows(),
        nbLineFwd3);
    assertEquals(
        "Curve construction: 1 unit / 2 units ",
        bb[1].getBlock(CURVE_NAME_FWD6_AUD).getSecond().getNumberOfRows(),
        nbLineFwd6);
  }
  @Override
  public Set<ComputedValue> execute(
      final FunctionExecutionContext executionContext,
      final FunctionInputs inputs,
      final ComputationTarget target,
      final Set<ValueRequirement> desiredValues)
      throws AsynchronousExecution {
    final ZonedDateTime now = ZonedDateTime.now(executionContext.getValuationClock());
    final ValueRequirement requirement = desiredValues.iterator().next();
    final ValueProperties properties = requirement.getConstraints().copy().get();

    final LegacyVanillaCDSSecurity security = (LegacyVanillaCDSSecurity) target.getSecurity();
    // LegacyVanillaCreditDefaultSwapDefinition cds =
    // _converter.visitLegacyVanillaCDSSecurity(security);
    final ValueRequirement desiredValue = desiredValues.iterator().next(); // all same constraints

    final String quoteConventionString =
        desiredValue.getConstraint(ISDAFunctionConstants.CDS_QUOTE_CONVENTION);
    final StandardCDSQuotingConvention quoteConvention =
        StandardCDSQuotingConvention.parse(quoteConventionString);

    final CdsRecoveryRateIdentifier recoveryRateIdentifier =
        security.accept(
            new CreditSecurityToRecoveryRateVisitor(executionContext.getSecuritySource()));
    Object recoveryRateObject =
        inputs.getValue(
            new ValueRequirement(
                "PX_LAST",
                ComputationTargetType.PRIMITIVE,
                recoveryRateIdentifier.getExternalId()));
    if (recoveryRateObject == null) {
      throw new OpenGammaRuntimeException("Could not get recovery rate");
      // s_logger.warn("Could not get recovery rate, defaulting to 0.4: " + recoveryRateIdentifier);
      // recoveryRateObject = 0.4;
    }
    final double recoveryRate = (Double) recoveryRateObject;

    // get the isda curve
    final Object isdaObject = inputs.getValue(ValueRequirementNames.YIELD_CURVE);
    if (isdaObject == null) {
      throw new OpenGammaRuntimeException("Couldn't get isda curve");
    }
    final ISDACompliantYieldCurve yieldCurve = (ISDACompliantYieldCurve) isdaObject;

    // spreads
    NodalTenorDoubleCurve spreadObject =
        (NodalTenorDoubleCurve) inputs.getValue(ValueRequirementNames.BUCKETED_SPREADS);
    if (spreadObject == null) {
      throw new OpenGammaRuntimeException("Unable to get spreads");
    }
    final double[] spreads = ArrayUtils.toPrimitive(spreadObject.getYData());
    // final String pillarString = IMMDateGenerator.isIMMDate(security.getMaturityDate()) ?
    // requirement.getConstraint(ISDAFunctionConstants.ISDA_BUCKET_TENORS) :
    // ISDACompliantCreditCurveFunction.NON_IMM_PILLAR_TENORS;
    final ZonedDateTime[] bucketDates =
        SpreadCurveFunctions.getPillarDates(now, spreadObject.getXData());
    final CDSQuoteConvention[] quotes =
        SpreadCurveFunctions.getQuotes(
            security.getMaturityDate(), spreads, security.getParSpread(), quoteConvention, false);

    // spreads
    NodalTenorDoubleCurve pillarObject =
        (NodalTenorDoubleCurve) inputs.getValue(ValueRequirementNames.PILLAR_SPREADS);
    if (pillarObject == null) {
      throw new OpenGammaRuntimeException("Unable to get pillars");
    }

    // CDS analytics for credit curve (possible performance improvement if earlier result obtained)
    // final LegacyVanillaCreditDefaultSwapDefinition curveCDS = cds.withStartDate(now);
    // security.setStartDate(now); // needed for curve instruments
    final CDSAnalytic[] bucketCDSs = new CDSAnalytic[bucketDates.length];
    for (int i = 0; i < bucketCDSs.length; i++) {
      // security.setMaturityDate(bucketDates[i]);
      final CDSAnalyticVisitor visitor =
          new CDSAnalyticVisitor(
              now.toLocalDate(),
              _holidaySource,
              _regionSource,
              security.getStartDate().toLocalDate(),
              bucketDates[i].toLocalDate(),
              recoveryRate);
      bucketCDSs[i] = security.accept(visitor);
    }

    final ZonedDateTime[] pillarDates =
        SpreadCurveFunctions.getPillarDates(now, pillarObject.getXData());
    final CDSAnalytic[] pillarCDSs = new CDSAnalytic[pillarDates.length];
    for (int i = 0; i < pillarCDSs.length; i++) {
      // security.setMaturityDate(bucketDates[i]);
      final CDSAnalyticVisitor visitor =
          new CDSAnalyticVisitor(
              now.toLocalDate(),
              _holidaySource,
              _regionSource,
              security.getStartDate().toLocalDate(),
              pillarDates[i].toLocalDate(),
              recoveryRate);
      pillarCDSs[i] = security.accept(visitor);
    }

    final ISDACompliantCreditCurve creditCurve =
        (ISDACompliantCreditCurve) inputs.getValue(ValueRequirementNames.HAZARD_RATE_CURVE);
    if (creditCurve == null) {
      throw new OpenGammaRuntimeException("Couldnt get credit curve");
    }

    // final CDSAnalytic analytic = CDSAnalyticConverter.create(cds, now.toLocalDate());
    final CDSAnalyticVisitor visitor =
        new CDSAnalyticVisitor(now.toLocalDate(), _holidaySource, _regionSource, recoveryRate);
    final CDSAnalytic analytic = security.accept(visitor);
    final BuySellProtection buySellProtection =
        security.isBuy() ? BuySellProtection.BUY : BuySellProtection.SELL;
    //    final String term = new Tenor(Period.between(security.getStartDate().toLocalDate(),
    // security.getMaturityDate().toLocalDate())).getPeriod().toString();
    //    final Double cdsQuoteDouble = (Double) inputs.getValue(new
    // ValueRequirement(MarketDataRequirementNames.MARKET_VALUE,
    //        ComputationTargetType.PRIMITIVE, ExternalId.of("Tenor", term)));
    final Double cdsQuoteDouble = (Double) inputs.getValue(MarketDataRequirementNames.MARKET_VALUE);
    if (cdsQuoteDouble == null) {
      throw new OpenGammaRuntimeException("Couldn't get spread for " + security);
    }
    final CDSQuoteConvention quote =
        SpreadCurveFunctions.getQuotes(
            security.getMaturityDate(),
            new double[] {cdsQuoteDouble},
            security.getParSpread(),
            quoteConvention,
            true)[0];

    boolean isNonIMMFAndFromPUF =
        !IMMDateLogic.isIMMDate(security.getMaturityDate().toLocalDate())
            && quote instanceof PointsUpFront;
    boolean isNonIMMAndFromSpread =
        !IMMDateLogic.isIMMDate(security.getMaturityDate().toLocalDate())
            && (quote instanceof QuotedSpread || quote instanceof ParSpread);
    int buySellPremiumFactor = security.isBuy() ? -1 : 1;

    final double notional = security.getNotional().getAmount();
    final double coupon = security.getParSpread() * ONE_BPS;
    final PointsUpFront puf =
        getPointsUpfront(quote, buySellProtection, yieldCurve, analytic, creditCurve);
    final double accruedPremiumPrim =
        isNonIMMAndFromSpread || isNonIMMFAndFromPUF ? 0 : analytic.getAccruedPremium(coupon);
    //    final double accruedPremium = isNonIMMAndFromSpread || isNonIMMFAndFromPUF ? 0 :
    // analytic.getAccruedPremium(coupon) * notional * buySellPremiumFactor;
    final double accruedPremium =
        isNonIMMAndFromSpread || isNonIMMFAndFromPUF
            ? 0
            : accruedPremiumPrim * notional * buySellPremiumFactor;
    final int accruedDays =
        isNonIMMAndFromSpread || isNonIMMFAndFromPUF ? 0 : analytic.getAccuredDays();
    final double quotedSpread =
        getQuotedSpread(quote, puf, buySellProtection, yieldCurve, analytic).getQuotedSpread();
    final double upfrontAmount =
        isNonIMMAndFromSpread
            ? 0
            : getUpfrontAmount(analytic, puf, notional, accruedPremiumPrim, buySellProtection);
    final double cleanPV = puf.getPointsUpFront() * notional;
    final double principal = isNonIMMAndFromSpread ? 0 : cleanPV;
    final double cleanPrice = getCleanPrice(puf);
    final TenorLabelledMatrix1D bucketedCS01 =
        getBucketedCS01(
            analytic,
            bucketCDSs,
            spreadObject.getXData(),
            quote,
            notional,
            yieldCurve,
            creditCurve);
    final double parallelCS01 =
        getParallelCS01(
            quote,
            analytic,
            yieldCurve,
            notional,
            pillarCDSs,
            ArrayUtils.toPrimitive(pillarObject.getYData()));

    final Set<ComputedValue> results = Sets.newHashSetWithExpectedSize(_valueRequirements.length);
    results.add(
        new ComputedValue(
            new ValueSpecification(
                ValueRequirementNames.ACCRUED_PREMIUM, target.toSpecification(), properties),
            accruedPremium));
    results.add(
        new ComputedValue(
            new ValueSpecification(
                ValueRequirementNames.ACCRUED_DAYS, target.toSpecification(), properties),
            accruedDays));
    results.add(
        new ComputedValue(
            new ValueSpecification(
                ValueRequirementNames.QUOTED_SPREAD, target.toSpecification(), properties),
            quotedSpread / ONE_BPS));
    results.add(
        new ComputedValue(
            new ValueSpecification(
                ValueRequirementNames.UPFRONT_AMOUNT, target.toSpecification(), properties),
            upfrontAmount));
    results.add(
        new ComputedValue(
            new ValueSpecification(
                ValueRequirementNames.DIRTY_PRESENT_VALUE, target.toSpecification(), properties),
            upfrontAmount));
    results.add(
        new ComputedValue(
            new ValueSpecification(
                ValueRequirementNames.CLEAN_PRESENT_VALUE, target.toSpecification(), properties),
            cleanPV));
    results.add(
        new ComputedValue(
            new ValueSpecification(
                ValueRequirementNames.PRINCIPAL, target.toSpecification(), properties),
            principal));
    results.add(
        new ComputedValue(
            new ValueSpecification(
                ValueRequirementNames.CLEAN_PRICE, target.toSpecification(), properties),
            cleanPrice));
    results.add(
        new ComputedValue(
            new ValueSpecification(
                ValueRequirementNames.BUCKETED_CS01, target.toSpecification(), properties),
            bucketedCS01));
    results.add(
        new ComputedValue(
            new ValueSpecification(
                ValueRequirementNames.PARALLEL_CS01, target.toSpecification(), properties),
            parallelCS01));
    results.add(
        new ComputedValue(
            new ValueSpecification(
                ValueRequirementNames.POINTS_UPFRONT, target.toSpecification(), properties),
            puf.getPointsUpFront()));
    return results;
  }
Ejemplo n.º 17
0
  /**
   * @brief 数组工具
   * @details 详细说明
   * @warning 注意事项
   * @date 2014-7-11 上午11:25:18
   */
  @Test
  public void array() {
    // 追加元素到数组尾部
    int[] array1 = {1, 2};
    array1 = ArrayUtils.add(array1, 3); // => [1, 2, 3]

    System.out.println(array1.length); // 3
    System.out.println(array1[2]); // 3

    // 删除指定位置的元素
    int[] array2 = {1, 2, 3};
    array2 = ArrayUtils.remove(array2, 2); // => [1, 2]

    System.out.println(array2.length); // 2

    // 截取部分元素
    int[] array3 = {1, 2, 3, 4};
    array3 = ArrayUtils.subarray(array3, 1, 3); // => [2, 3]

    System.out.println(array3.length); // 2

    // 数组拷贝
    String[] array4 = {"aaa", "bbb", "ccc"};
    String[] copied = (String[]) ArrayUtils.clone(array4); // => {"aaa", "bbb", "ccc"}

    System.out.println(copied.length); // 3

    // 判断是否包含某元素
    String[] array5 = {"aaa", "bbb", "ccc", "bbb"};
    boolean result1 = ArrayUtils.contains(array5, "bbb"); // => true
    System.out.println(result1); // true

    // 判断某元素在数组中出现的位置(从前往后,没有返回-1)
    int result2 = ArrayUtils.indexOf(array5, "bbb"); // => 1
    System.out.println(result2); // 1

    // 判断某元素在数组中出现的位置(从后往前,没有返回-1)
    int result3 = ArrayUtils.lastIndexOf(array5, "bbb"); // => 3
    System.out.println(result3); // 3

    // 数组转Map
    Map<Object, Object> map =
        ArrayUtils.toMap(
            new String[][] {
              {"key1", "value1"},
              {"key2", "value2"}
            });
    System.out.println(map.get("key1")); // "value1"
    System.out.println(map.get("key2")); // "value2"

    // 判断数组是否为空
    Object[] array61 = new Object[0];
    Object[] array62 = null;
    Object[] array63 = new Object[] {"aaa"};

    System.out.println(ArrayUtils.isEmpty(array61)); // true
    System.out.println(ArrayUtils.isEmpty(array62)); // true

    // 判断数组长度是否相等
    Object[] array71 = new Object[] {"aa", "bb", "cc"};
    Object[] array72 = new Object[] {"dd", "ee", "ff"};

    System.out.println(ArrayUtils.isSameLength(array71, array72)); // true

    // 判断数组元素内容是否相等
    Object[] array81 = new Object[] {"aa", "bb", "cc"};
    Object[] array82 = new Object[] {"aa", "bb", "cc"};

    System.out.println(ArrayUtils.isEquals(array81, array82));

    // Integer[] 转化为 int[]
    Integer[] array9 = new Integer[] {1, 2};
    int[] result = ArrayUtils.toPrimitive(array9);

    System.out.println(result.length); // 2
    System.out.println(result[0]); // 1

    // int[] 转化为 Integer[]
    int[] array10 = new int[] {1, 2};
    Integer[] result10 = ArrayUtils.toObject(array10);

    System.out.println(result.length); // 2
    System.out.println(result10[0].intValue()); // 1
  }