Java Code Examples for java.util.OptionalDouble#getAsDouble()

The following examples show how to use java.util.OptionalDouble#getAsDouble() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ForwardOvernightCompoundedRateComputationFn.java    From Strata with Apache License 2.0 6 votes vote down vote up
private double valuationCompositionFactor() {
  LocalDate currentFixing = nextFixing;
  LocalDate currentPublication = computation.calculatePublicationFromFixing(currentFixing);
  if (rates.getValuationDate().equals(currentPublication) &&
      !(currentFixing.isAfter(lastFixingNonCutoff))) { // If currentFixing > lastFixingNonCutoff, everything fixed
    OptionalDouble fixedRate = indexFixingDateSeries.get(currentFixing);
    if (fixedRate.isPresent()) {
      nextFixing = computation.getFixingCalendar().next(nextFixing);
      LocalDate effectiveDate = computation.calculateEffectiveFromFixing(currentFixing);
      LocalDate maturityDate = computation.calculateMaturityFromEffective(effectiveDate);
      double accrualFactor = dayCount.yearFraction(effectiveDate, maturityDate);
      if (currentFixing.isBefore(lastFixingNonCutoff)) {
        return 1.0d + accrualFactor * fixedRate.getAsDouble();
      }
      double compositionFactor = 1.0d + accrualFactor * fixedRate.getAsDouble();
      for (int i = 0; i < cutoffOffset - 1; i++) {
        compositionFactor *= 1.0d + accrualFactorCutoff[i] * fixedRate.getAsDouble();
      }
      return compositionFactor;
    }
  }
  return 1.0d;
}
 
Example 2
Source File: ApproxForwardOvernightAveragedRateComputationFn.java    From Strata with Apache License 2.0 6 votes vote down vote up
private double valuationDateAccumulation() {
  double accumulatedInterest = 0.0d;
  LocalDateDoubleTimeSeries indexFixingDateSeries = rates.getFixings();
  boolean ratePresent = true;
  while (ratePresent && fixedPeriod < nbPeriods &&
      rates.getValuationDate().isEqual(observations.get(fixedPeriod).getPublicationDate())) {
    OvernightIndexObservation obs = observations.get(fixedPeriod);
    OptionalDouble fixedRate = indexFixingDateSeries.get(obs.getFixingDate());
    if (fixedRate.isPresent()) {
      accumulatedInterest += obs.getYearFraction() * fixedRate.getAsDouble();
      fixedPeriod++;
    } else {
      ratePresent = false;
    }
  }
  return accumulatedInterest;
}
 
Example 3
Source File: InstanceWiseF1.java    From AILibs with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public double score(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> actual) {
	this.checkConsistency(expected, actual);
	int[][] expectedMatrix = this.listToMatrix(expected);
	int[][] actualMatrix = this.listToThresholdedRelevanceMatrix(actual);
	F1Measure baseMeasure = new F1Measure(1);
	OptionalDouble res = IntStream.range(0, expectedMatrix.length)
			.mapToDouble(x -> baseMeasure.score(Arrays.stream(expectedMatrix[x]).mapToObj(Integer::valueOf).collect(Collectors.toList()), Arrays.stream(actualMatrix[x]).mapToObj(Integer::valueOf).collect(Collectors.toList())))
			.average();

	if (!res.isPresent()) {
		throw new IllegalStateException("Could not determine average instance-wise f measure.");
	} else {
		return res.getAsDouble();
	}
}
 
Example 4
Source File: BangumiSearchResponse.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 5 votes vote down vote up
public static double getAvgSum(BangumiSearchResponse bangumiSearchResponse) {
    if (bangumiSearchResponse.getResult() != null) {
        OptionalDouble average = bangumiSearchResponse.getResult().stream().filter(b -> b.getRating() != null && b.getRating().getScore() != 0).mapToInt(resultItem -> resultItem.getRating().getScore()).average();
        return average.isPresent() ? average.getAsDouble() : 0;
    }
    return 0;
}
 
Example 5
Source File: ARankingPredictionPerformanceMeasure.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public double loss(final List<? extends IRanking<?>> expected, final List<? extends IRanking<?>> actual) {
	OptionalDouble res = IntStream.range(0, expected.size()).mapToDouble(x -> this.loss(expected.get(0), actual.get(0))).average();
	if (res.isPresent()) {
		return res.getAsDouble();
	}
	throw new IllegalStateException("Could not aggregate " + this.getClass().getSimpleName());
}
 
Example 6
Source File: KendallsTauOfTopK.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public double loss(final List<? extends IRanking<?>> expected, final List<? extends IRanking<?>> actual) {
	OptionalDouble res = IntStream.range(0, expected.size()).mapToDouble(x -> this.loss(expected.get(0), actual.get(0))).average();
	if (res.isPresent()) {
		return res.getAsDouble();
	}
	throw new IllegalStateException("Could not aggregate kendalls tau of top k");
}
 
Example 7
Source File: NDCGLoss.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public double loss(final List<? extends IRanking<?>> expected, final List<? extends IRanking<?>> actual) {
	OptionalDouble res = IntStream.range(0, expected.size()).mapToDouble(x -> this.loss(expected.get(0), actual.get(0))).average();
	if (res.isPresent()) {
		return res.getAsDouble();
	}
	throw new IllegalStateException("Could not aggregate kendalls tau of top k");
}
 
Example 8
Source File: DiscountOvernightIndexRates.java    From Strata with Apache License 2.0 5 votes vote down vote up
private double historicRate(OvernightIndexObservation observation) {
  LocalDate fixingDate = observation.getFixingDate();
  OptionalDouble fixedRate = fixings.get(fixingDate);
  if (fixedRate.isPresent()) {
    return fixedRate.getAsDouble();
  } else if (observation.getPublicationDate().isBefore(getValuationDate())) { // the fixing is required
    if (fixings.isEmpty()) {
      throw new IllegalArgumentException(
          Messages.format("Unable to get fixing for {} on date {}, no time-series supplied", index, fixingDate));
    }
    throw new IllegalArgumentException(Messages.format("Unable to get fixing for {} on date {}", index, fixingDate));
  } else {
    return rateIgnoringFixings(observation);
  }
}
 
Example 9
Source File: APredictionPerformanceMeasure.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
protected double averageInstanceWiseLoss(final List<E> expected, final List<A> actual, final IDeterministicInstancePredictionPerformanceMeasure<A, E> subMeasure) {
	OptionalDouble res = IntStream.range(0, expected.size()).mapToDouble(x -> subMeasure.loss(expected.get(x), actual.get(x))).average();
	if (res.isPresent()) {
		return res.getAsDouble();
	} else {
		throw new IllegalStateException("The submeasure could not be aggregated.");
	}
}
 
Example 10
Source File: OptionalMatchers.java    From java-8-matchers with MIT License 5 votes vote down vote up
/**
 * Matches a non empty OptionalDouble with the given content
 *
 * @param content Expected contents of the Optional
 */
public static Matcher<OptionalDouble> containsDouble(double content) {
    return new TypeSafeMatcher<OptionalDouble>() {
        @Override
        protected boolean matchesSafely(OptionalDouble item) {
            return item.isPresent() && item.getAsDouble() == content;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(Optional.of(content).toString());
        }
    };
}
 
Example 11
Source File: ForwardFxIndexRates.java    From Strata with Apache License 2.0 5 votes vote down vote up
private double historicRate(FxIndexObservation observation) {
  LocalDate fixingDate = observation.getFixingDate();
  OptionalDouble fixedRate = fixings.get(fixingDate);
  if (fixedRate.isPresent()) {
    return fixedRate.getAsDouble();
  } else if (fixingDate.isBefore(getValuationDate())) { // the fixing is required
    if (fixings.isEmpty()) {
      throw new IllegalArgumentException(
          Messages.format("Unable to get fixing for {} on date {}, no time-series supplied", index, fixingDate));
    }
    throw new IllegalArgumentException(Messages.format("Unable to get fixing for {} on date {}", index, fixingDate));
  } else {
    return forwardRate(observation);
  }
}
 
Example 12
Source File: MobydroidDevice.java    From MobyDroid with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate running tasks total progress.
 *
 * @return
 */
public float getTasksProgress() {
    Stream<TaskWorker> stream = tasks.stream().filter((taskWorker) -> (taskWorker.getStatus() == TaskWorker.Status.PENDING || taskWorker.getStatus() == TaskWorker.Status.STARTED || taskWorker.getStatus() == TaskWorker.Status.DONE));
    OptionalDouble average = stream.mapToDouble(taskWorker -> taskWorker.getProgress()).average();

    try {
        return (float) average.getAsDouble();
    } catch (NoSuchElementException ex) {
        return 0;
    }

}
 
Example 13
Source File: MobileDeviceAttributesTransformer.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
static AndroidDeviceType getTypeBasedOnSizeInches(OptionalDouble diagonalLength) {

         if (!diagonalLength.isPresent()){
            return AndroidDeviceType.GENERIC;
         }

         if (diagonalLength.getAsDouble() >= DIAGONAL_TABLET_THRESHOLD){
            return AndroidDeviceType.TABLET;
         }else{
            return AndroidDeviceType.PHONE;
         }
      }
 
Example 14
Source File: MetastoreHiveStatisticsProvider.java    From presto with Apache License 2.0 5 votes vote down vote up
private static TableStatistics getTableStatistics(
        Map<String, ColumnHandle> columns,
        Map<String, Type> columnTypes,
        List<HivePartition> partitions,
        Map<String, PartitionStatistics> statistics)
{
    if (statistics.isEmpty()) {
        return TableStatistics.empty();
    }

    checkArgument(!partitions.isEmpty(), "partitions is empty");

    OptionalDouble optionalAverageRowsPerPartition = calculateAverageRowsPerPartition(statistics.values());
    if (optionalAverageRowsPerPartition.isEmpty()) {
        return TableStatistics.empty();
    }
    double averageRowsPerPartition = optionalAverageRowsPerPartition.getAsDouble();
    verify(averageRowsPerPartition >= 0, "averageRowsPerPartition must be greater than or equal to zero");
    int queriedPartitionsCount = partitions.size();
    double rowCount = averageRowsPerPartition * queriedPartitionsCount;

    TableStatistics.Builder result = TableStatistics.builder();
    result.setRowCount(Estimate.of(rowCount));
    for (Map.Entry<String, ColumnHandle> column : columns.entrySet()) {
        String columnName = column.getKey();
        HiveColumnHandle columnHandle = (HiveColumnHandle) column.getValue();
        Type columnType = columnTypes.get(columnName);
        ColumnStatistics columnStatistics;
        if (columnHandle.isPartitionKey()) {
            columnStatistics = createPartitionColumnStatistics(columnHandle, columnType, partitions, statistics, averageRowsPerPartition, rowCount);
        }
        else {
            columnStatistics = createDataColumnStatistics(columnName, columnType, rowCount, statistics.values());
        }
        result.setColumnStatistics(columnHandle, columnStatistics);
    }
    return result.build();
}
 
Example 15
Source File: DiscountIborIndexRates.java    From Strata with Apache License 2.0 5 votes vote down vote up
private double historicRate(IborIndexObservation observation) {
  LocalDate fixingDate = observation.getFixingDate();
  OptionalDouble fixedRate = fixings.get(fixingDate);
  if (fixedRate.isPresent()) {
    return fixedRate.getAsDouble();
  } else if (fixingDate.isBefore(getValuationDate())) { // the fixing is required
    if (fixings.isEmpty()) {
      throw new IllegalArgumentException(
          Messages.format("Unable to get fixing for {} on date {}, no time-series supplied", index, fixingDate));
    }
    throw new IllegalArgumentException(Messages.format("Unable to get fixing for {} on date {}", index, fixingDate));
  } else {
    return rateIgnoringFixings(observation);
  }
}
 
Example 16
Source File: BasicDouble.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NoSuchElementException.class)
public void testEmptyGet() {
    OptionalDouble empty = OptionalDouble.empty();

    double got = empty.getAsDouble();
}
 
Example 17
Source File: SabrExtrapolationReplicationCmsPeriodPricer.java    From Strata with Apache License 2.0 4 votes vote down vote up
/**
 * Computes the present value sensitivity to strike by replication in SABR framework with extrapolation on the right.
 * 
 * @param cmsPeriod  the CMS 
 * @param provider  the rates provider
 * @param swaptionVolatilities  the swaption volatilities
 * @return the present value sensitivity
 */
public double presentValueSensitivityStrike(
    CmsPeriod cmsPeriod,
    RatesProvider provider,
    SabrSwaptionVolatilities swaptionVolatilities) {

  ArgChecker.isFalse(
      cmsPeriod.getCmsPeriodType().equals(CmsPeriodType.COUPON),
      "presentValueSensitivityStrike is not relevant for CMS coupon");
  Currency ccy = cmsPeriod.getCurrency();
  SwapIndex index = cmsPeriod.getIndex();
  if (provider.getValuationDate().isAfter(cmsPeriod.getPaymentDate())) {
    return 0d;
  }
  ResolvedSwap swap = cmsPeriod.getUnderlyingSwap();
  double dfPayment = provider.discountFactor(ccy, cmsPeriod.getPaymentDate());
  ZonedDateTime valuationDate = swaptionVolatilities.getValuationDateTime();
  LocalDate fixingDate = cmsPeriod.getFixingDate();
  double tenor = swaptionVolatilities.tenor(swap.getStartDate(), swap.getEndDate());
  ZonedDateTime expiryDate = fixingDate.atTime(index.getFixingTime()).atZone(index.getFixingZone());
  double expiryTime = swaptionVolatilities.relativeTime(expiryDate);
  double strike = cmsPeriod.getStrike();
  double shift = swaptionVolatilities.shift(expiryTime, tenor);
  if (!fixingDate.isAfter(valuationDate.toLocalDate())) {
    OptionalDouble fixedRate = provider.timeSeries(cmsPeriod.getIndex()).get(fixingDate);
    if (fixedRate.isPresent()) {
      double payoff = 0d;
      switch (cmsPeriod.getCmsPeriodType()) {
        case CAPLET:
          payoff = fixedRate.getAsDouble() >= strike ? -1d : 0d;
          break;
        case FLOORLET:
          payoff = fixedRate.getAsDouble() < strike ? 1d : 0d;
          break;
        default:
          throw new IllegalArgumentException("unsupported CMS type");
      }
      return payoff * cmsPeriod.getNotional() * cmsPeriod.getYearFraction() * dfPayment;
    } else if (fixingDate.isBefore(valuationDate.toLocalDate())) {
      throw new IllegalArgumentException(Messages.format(
          "Unable to get fixing for {} on date {}, no time-series supplied", cmsPeriod.getIndex(), fixingDate));
    }
  }
  double forward = swapPricer.parRate(swap, provider);
  double eta = index.getTemplate().getConvention().getFixedLeg().getDayCount()
      .relativeYearFraction(cmsPeriod.getPaymentDate(), swap.getStartDate());
  CmsIntegrantProvider intProv = new CmsIntegrantProvider(
      cmsPeriod, swap, swaptionVolatilities, forward, strike, expiryTime, tenor, cutOffStrike, eta);
  double factor = dfPayment * intProv.g(forward) / intProv.h(forward);
  RungeKuttaIntegrator1D integrator = new RungeKuttaIntegrator1D(ABS_TOL, REL_TOL_STRIKE, NUM_ITER);
  double[] kpkpp = intProv.kpkpp(strike);
  double firstPart;
  double thirdPart;
  Function<Double, Double> integrant = intProv.integrantDualDelta();
  if (intProv.getPutCall().isCall()) {
    firstPart = -kpkpp[0] * intProv.bs(strike);
    thirdPart = integrateCall(integrator, integrant, swaptionVolatilities, forward, strike, expiryTime, tenor);
  } else {
    firstPart = -kpkpp[0] * intProv.bs(strike);
    thirdPart = -integrator.integrate(integrant, -shift + ZERO_SHIFT, strike);
  }
  double secondPart =
      intProv.k(strike) * intProv.getSabrExtrapolation().priceDerivativeStrike(strike + shift, intProv.getPutCall());
  return cmsPeriod.getNotional() * cmsPeriod.getYearFraction() * factor * (firstPart + secondPart + thirdPart);
}
 
Example 18
Source File: DiscountingCmsPeriodPricer.java    From Strata with Apache License 2.0 4 votes vote down vote up
/**
 * Computes the present value curve sensitivity by simple forward rate estimation.
 * 
 * @param cmsPeriod  the CMS 
 * @param provider  the rates provider
 * @return the present value sensitivity
 */
public PointSensitivityBuilder presentValueSensitivity(
    CmsPeriod cmsPeriod,
    RatesProvider provider) {

  Currency ccy = cmsPeriod.getCurrency();
  LocalDate valuationDate = provider.getValuationDate();
  if (valuationDate.isAfter(cmsPeriod.getPaymentDate())) {
    return PointSensitivityBuilder.none();
  }
  LocalDate fixingDate = cmsPeriod.getFixingDate();
  double dfPayment = provider.discountFactor(ccy, cmsPeriod.getPaymentDate());
  if (!fixingDate.isAfter(valuationDate)) { // Using fixing
    OptionalDouble fixedRate = provider.timeSeries(cmsPeriod.getIndex()).get(fixingDate);
    if (fixedRate.isPresent()) {
      double payoff = 0d;
      switch (cmsPeriod.getCmsPeriodType()) {
        case CAPLET:
          payoff = Math.max(fixedRate.getAsDouble() - cmsPeriod.getStrike(), 0d);
          break;
        case FLOORLET:
          payoff = Math.max(cmsPeriod.getStrike() - fixedRate.getAsDouble(), 0d);
          break;
        case COUPON:
          payoff = fixedRate.getAsDouble();
          break;
        default:
          throw new IllegalArgumentException("unsupported CMS type");
      }
      return provider.discountFactors(ccy).zeroRatePointSensitivity(
          cmsPeriod.getPaymentDate()).multipliedBy(payoff * cmsPeriod.getNotional() * cmsPeriod.getYearFraction());
    } else if (fixingDate.isBefore(valuationDate)) {
      throw new IllegalArgumentException(Messages.format(
          "Unable to get fixing for {} on date {}, no time-series supplied", cmsPeriod.getIndex(), fixingDate));
    }
  }
  if (!cmsPeriod.getCmsPeriodType().equals(CmsPeriodType.COUPON)) {
    throw new IllegalArgumentException("Unable to price cap or floor in this pricer");
  }
  // Using forward
  ResolvedSwap swap = cmsPeriod.getUnderlyingSwap();
  ZeroRateSensitivity dfPaymentdr = provider.discountFactors(ccy).zeroRatePointSensitivity(cmsPeriod.getPaymentDate());
  double forward = swapPricer.parRate(swap, provider);
  PointSensitivityBuilder forwardSensi = swapPricer.parRateSensitivity(swap, provider);
  return forwardSensi.multipliedBy(dfPayment).combinedWith(dfPaymentdr.multipliedBy(forward))
      .multipliedBy(cmsPeriod.getNotional() * cmsPeriod.getYearFraction());
}
 
Example 19
Source File: BasicDouble.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NoSuchElementException.class)
public void testEmptyGet() {
    OptionalDouble empty = OptionalDouble.empty();

    double got = empty.getAsDouble();
}
 
Example 20
Source File: SimpleBenchmark.java    From distkv with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Get average time
 *
 * @param costTimes List of cost time
 * @return Average time
 */
private static double getAvgTime(List<Long> costTimes) {
  OptionalDouble optionalDouble = costTimes.stream().mapToLong(Long::longValue).average();
  return optionalDouble.getAsDouble();
}