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

The following examples show how to use java.util.OptionalDouble#isPresent() . 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: 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 2
Source File: RegionSplitHelper.java    From bboxdb with Apache License 2.0 6 votes vote down vote up
/**
 * Needs the region a split?
 * @param region
 * @return
 * @throws BBoxDBException 
 */
public static boolean isRegionOverflow(final DistributionRegion region) throws BBoxDBException {
	
	// Is the data of the parent completely distributed?
	if(! isParentDataRedistributed(region)) {
		return false;
	}
	
	final OptionalDouble sizeOfRegionInMB = StatisticsHelper.getAndUpdateStatistics(region);

	if(! sizeOfRegionInMB.isPresent()) {
		return false;
	}
	
	try {			
		final long maxSize = getConfiguredRegionMaxSize(region);
		return (sizeOfRegionInMB.getAsDouble() > maxSize);
	} catch (ZookeeperException | ZookeeperNotFoundException e) {
		throw new BBoxDBException(e);
	} 
}
 
Example 3
Source File: StatisticsHelper.java    From bboxdb with Apache License 2.0 6 votes vote down vote up
/**
 * Get the max total size from the statistics map
 * @param statistics
 * @return
 * @throws ZookeeperNotFoundException 
 * @throws ZookeeperException 
 */
public static OptionalDouble getAndUpdateStatistics(final DistributionRegion region) {
	
	try {
		final Map<BBoxDBInstance, Map<String, Long>> statistics 
			= distributionGroupZookeeperAdapter.getRegionStatistics(region);
		
		final OptionalDouble regionSize = statistics
			.values()
			.stream()
			.mapToDouble(p -> p.get(ZookeeperNodeNames.NAME_STATISTICS_TOTAL_SIZE))
			.filter(Objects::nonNull)
			.max();
		
		if(regionSize.isPresent()) {
			final String regionIdentifier = region.getIdentifier();
			updateStatisticsHistory(regionIdentifier, regionSize.getAsDouble());
		}
		
		return regionSize;
	} catch (Exception e) {
		logger.error("Got an exception while reading statistics", e);
		return OptionalDouble.empty();
	} 
}
 
Example 4
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 5
Source File: ComparisonStatsCalculator.java    From presto with Apache License 2.0 5 votes vote down vote up
private static PlanNodeStatsEstimate estimateExpressionEqualToLiteral(
        PlanNodeStatsEstimate inputStatistics,
        SymbolStatsEstimate expressionStatistics,
        Optional<Symbol> expressionSymbol,
        OptionalDouble literalValue)
{
    StatisticRange filterRange;
    if (literalValue.isPresent()) {
        filterRange = new StatisticRange(literalValue.getAsDouble(), literalValue.getAsDouble(), 1);
    }
    else {
        filterRange = new StatisticRange(NEGATIVE_INFINITY, POSITIVE_INFINITY, 1);
    }
    return estimateFilterRange(inputStatistics, expressionStatistics, expressionSymbol, filterRange);
}
 
Example 6
Source File: ShapeDistanceCollectiveAnswerScorer.java    From bioasq with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void prepare(JCas jcas) {
  answers = TypeUtil.getRankedAnswers(jcas);
  distances = HashBasedTable.create();
  bdistances = HashBasedTable.create();
  ImmutableSet<Answer> answerSet = ImmutableSet.copyOf(answers);
  SetMultimap<Answer, String> answer2shapes = HashMultimap.create();
  answers.forEach(answer -> TypeUtil.getCandidateAnswerVariantNames(answer).stream()
          .map(ShapeDistanceCollectiveAnswerScorer::shape)
          .forEach(shape -> answer2shapes.put(answer, shape)));
  for (List<Answer> pair : Sets.cartesianProduct(answerSet, answerSet)) {
    Answer answer1 = pair.get(0);
    Answer answer2 = pair.get(1);
    if (answer1.equals(answer2)) {
      distances.put(answer1, answer2, 1.0);
      bdistances.put(answer1, answer2, 1.0);
    } else {
      OptionalDouble distance = Sets
              .cartesianProduct(answer2shapes.get(answer1), answer2shapes.get(answer2)).stream()
              .mapToDouble(shapepair -> getDistance(shapepair.get(0), shapepair.get(1))).min();
      if (distance.isPresent()) {
        distances.put(answer1, answer2, 1.0 - distance.getAsDouble());
        bdistances.put(answer1, answer2, distance.getAsDouble() == 0.0 ? 1.0 : 0.0);
      }
    }
  }
}
 
Example 7
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 8
Source File: OptionalDoubleAttributeConverter.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public AttributeValue transformFrom(OptionalDouble input) {
    if (input.isPresent()) {
        ConverterUtils.validateDouble(input.getAsDouble());
        return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build();
    } else {
        return AttributeValues.nullAttributeValue();
    }
}
 
Example 9
Source File: JaccardScore.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public double score(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> actual) {
	OptionalDouble res = IntStream.range(0, expected.size()).mapToDouble(x -> this.instanceScorer.score(ArrayUtil.argMax(expected.get(x)), this.getThresholdedPredictionAsSet(actual.get(x)))).average();
	if (!res.isPresent()) {
		throw new IllegalStateException("Could not average the jaccord score.");
	} else {
		return res.getAsDouble();
	}
}
 
Example 10
Source File: HistoricIborIndexRates.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 11
Source File: MemoryPagesStore.java    From presto with Apache License 2.0 5 votes vote down vote up
public synchronized List<Page> getPages(
        Long tableId,
        int partNumber,
        int totalParts,
        List<Integer> columnIndexes,
        long expectedRows,
        OptionalLong limit,
        OptionalDouble sampleRatio)
{
    if (!contains(tableId)) {
        throw new PrestoException(MISSING_DATA, "Failed to find table on a worker.");
    }
    TableData tableData = tables.get(tableId);
    if (tableData.getRows() < expectedRows) {
        throw new PrestoException(MISSING_DATA,
                format("Expected to find [%s] rows on a worker, but found [%s].", expectedRows, tableData.getRows()));
    }

    ImmutableList.Builder<Page> partitionedPages = ImmutableList.builder();

    boolean done = false;
    long totalRows = 0;
    for (int i = partNumber; i < tableData.getPages().size() && !done; i += totalParts) {
        if (sampleRatio.isPresent() && ThreadLocalRandom.current().nextDouble() >= sampleRatio.getAsDouble()) {
            continue;
        }

        Page page = tableData.getPages().get(i);
        totalRows += page.getPositionCount();
        if (limit.isPresent() && totalRows > limit.getAsLong()) {
            page = page.getRegion(0, (int) (page.getPositionCount() - (totalRows - limit.getAsLong())));
            done = true;
        }
        partitionedPages.add(getColumns(page, columnIndexes));
    }

    return partitionedPages.build();
}
 
Example 12
Source File: OptionalMatchers.java    From java-8-matchers with MIT License 5 votes vote down vote up
/**
 * Matches an empty OptionalDouble.
 */
public static Matcher<OptionalDouble> emptyDouble() {
    return new TypeSafeMatcher<OptionalDouble>() {
        @Override
        protected boolean matchesSafely(OptionalDouble item) {
            return !item.isPresent();
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("An empty OptionalDouble");
        }
    };
}
 
Example 13
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 14
Source File: MobileDeviceAttributesTransformer.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private static OptionalDouble getDiagonalLength(OptionalDouble dim1, OptionalDouble dim2) {
   if (dim1.isPresent() && dim2.isPresent()){
      return OptionalDouble.of((Math.sqrt(Math.pow(dim1.getAsDouble(), 2) + Math.pow(dim2.getAsDouble(), 2))));
   }

   return OptionalDouble.empty();
}
 
Example 15
Source File: ForwardOvernightCompoundedAnnualRateComputationFn.java    From Strata with Apache License 2.0 5 votes vote down vote up
private double valuationCompositionFactor() {
  LocalDate currentFixing = nextFixing;
  LocalDate currentPublication = computation.calculatePublicationFromFixing(currentFixing);
  if (rates.getValuationDate().equals(currentPublication) && !(currentFixing.isAfter(lastFixing))) {
    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);
      return Math.pow(1.0d + fixedRate.getAsDouble(), accrualFactor);
    }
  }
  return 1.0d;
}
 
Example 16
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 17
Source File: SimplePriceIndexValues.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Override
public double value(PriceIndexObservation observation) {
  YearMonth fixingMonth = observation.getFixingMonth();
  // If fixing in the past, check time series and returns the historic month price index if present
  if (fixingMonth.isBefore(YearMonth.from(valuationDate))) {
    OptionalDouble fixing = fixings.get(fixingMonth.atEndOfMonth());
    if (fixing.isPresent()) {
      return fixing.getAsDouble();
    }
  }
  // otherwise, return the estimate from the curve.
  double nbMonth = numberOfMonths(fixingMonth);
  return curve.yValue(nbMonth);
}
 
Example 18
Source File: RecordServiceImpl.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
@Override
public boolean forwardEntry(final Record source, final Record.Builder builder, final String sourceColumn,
        final Schema.Entry entry) {
    switch (entry.getType()) {
    case INT:
        final OptionalInt optionalInt = source.getOptionalInt(sourceColumn);
        optionalInt.ifPresent(v -> builder.withInt(entry, v));
        return optionalInt.isPresent();
    case LONG:
        final OptionalLong optionalLong = source.getOptionalLong(sourceColumn);
        optionalLong.ifPresent(v -> builder.withLong(entry, v));
        return optionalLong.isPresent();
    case FLOAT:
        final OptionalDouble optionalFloat = source.getOptionalFloat(sourceColumn);
        optionalFloat.ifPresent(v -> builder.withFloat(entry, (float) v));
        return optionalFloat.isPresent();
    case DOUBLE:
        final OptionalDouble optionalDouble = source.getOptionalDouble(sourceColumn);
        optionalDouble.ifPresent(v -> builder.withDouble(entry, v));
        return optionalDouble.isPresent();
    case BOOLEAN:
        final Optional<Boolean> optionalBoolean = source.getOptionalBoolean(sourceColumn);
        optionalBoolean.ifPresent(v -> builder.withBoolean(entry, v));
        return optionalBoolean.isPresent();
    case STRING:
        final Optional<String> optionalString = source.getOptionalString(sourceColumn);
        optionalString.ifPresent(v -> builder.withString(entry, v));
        return optionalString.isPresent();
    case DATETIME:
        final Optional<ZonedDateTime> optionalDateTime = source.getOptionalDateTime(sourceColumn);
        optionalDateTime.ifPresent(v -> builder.withDateTime(entry, v));
        return optionalDateTime.isPresent();
    case BYTES:
        final Optional<byte[]> optionalBytes = source.getOptionalBytes(sourceColumn);
        optionalBytes.ifPresent(v -> builder.withBytes(entry, v));
        return optionalBytes.isPresent();
    case RECORD:
        final Optional<Record> optionalRecord = source.getOptionalRecord(sourceColumn);
        optionalRecord.ifPresent(v -> builder.withRecord(entry, v));
        return optionalRecord.isPresent();
    case ARRAY:
        final Optional<Collection<Object>> optionalArray = source.getOptionalArray(Object.class, sourceColumn);
        optionalArray.ifPresent(v -> builder.withArray(entry, v));
        return optionalArray.isPresent();
    default:
        throw new IllegalStateException("Unsupported entry type: " + entry);
    }
}
 
Example 19
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 20
Source File: PluginDefaultGroovyMethods.java    From groovy with Apache License 2.0 3 votes vote down vote up
/**
 * If a value is present in the {@code OptionalDouble}, returns an {@code Optional}
 * consisting of the result of applying the given function to the value or else empty.
 * <pre class="groovyTestCase">
 * assert !OptionalDouble.empty().mapToObj(x -&gt; new Object()).isPresent()
 * assert  OptionalDouble.of(Math.PI).mapToObj(x -&gt; new Object()).isPresent()
 * assert !OptionalDouble.of(Math.PI).mapToObj(x -&gt; null).isPresent()
 * assert  OptionalDouble.of(Math.PI).mapToObj(Double::toString).get().startsWith('3.14')
 * </pre>
 *
 * @since 3.0.0
 */
public static <T> Optional<T> mapToObj(final OptionalDouble self, final DoubleFunction<? extends T> mapper) {
    if (!self.isPresent()) {
        return Optional.empty();
    }
    return Optional.ofNullable(mapper.apply(self.getAsDouble()));
}