下面列出了怎么用java.util.function.ToDoubleBiFunction的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Calculate the metric average for all labels for metrics which divide tp by a specific count
* @param countFunction the specific count of a certain label combination
* @return macro-averaged metric score
*/
private double calcMetricAverage(ToDoubleBiFunction<String, String> countFunction)
{
double metric = 0.0;
int numOfLabels = getNumOfLabels();
if (numOfLabels > 0) {
Set<String> labels = confusionMatrix.getLabels();
for (String label : labels) {
double tp = 0.0;
if (!ignoreLabels.contains(label)) {
tp = confusionMatrix.getEntryCount(label, label);
}
double numIsLabel = 0.0;
for (String predictedLabel : labels) {
numIsLabel += countFunction.applyAsDouble(label, predictedLabel);
}
metric += calcClassMetric(label, tp, numIsLabel);
}
metric = metric / numOfLabels;
}
return metric;
}
/** Internal method to compute the first intersection between a line and this instance.
* @param <L> Line implementation type
* @param line line to intersect with the n-sphere
* @param abscissaFn function used to compute the abscissa value of a point on a line
* @param distanceFn function used to compute the smallest distance between a point
* and a line
* @return the first intersection between the given line and this instance or null if
* no such intersection exists
*/
protected <L extends Embedding<V, Vector1D>> V firstIntersection(final L line,
final ToDoubleBiFunction<L, V> abscissaFn, final ToDoubleBiFunction<L, V> distanceFn) {
final double dist = distanceFn.applyAsDouble(line, center);
int cmp = precision.compare(dist, radius);
if (cmp <= 0) {
// on the boundary or inside the n-sphere
final double abscissa = abscissaFn.applyAsDouble(line, center);
final double abscissaDelta = Math.sqrt((radius * radius) - (dist * dist));
return line.toSpace(Vector1D.of(abscissa - abscissaDelta));
}
return null;
}
/**
* Creates an new instance.
*
* @param cpuLoadEstimator estimates CPU load in terms of cycles
* @param ramLoadEstimator estimates RAM load in terms of bytes
* @param diskLoadEstimator estimates disk accesses in terms of bytes
* @param networkLoadEstimator estimates network in terms of bytes
* @param resourceUtilizationEstimator degree to which the load profile can utilize available resources
* @param overheadMillis overhead that this load profile incurs
* @param configurationKey from that this instances was perceived
*/
public NestableLoadProfileEstimator(LoadEstimator cpuLoadEstimator,
LoadEstimator ramLoadEstimator,
LoadEstimator diskLoadEstimator,
LoadEstimator networkLoadEstimator,
ToDoubleBiFunction<long[], long[]> resourceUtilizationEstimator,
long overheadMillis,
String configurationKey) {
this.cpuLoadEstimator = cpuLoadEstimator;
this.ramLoadEstimator = ramLoadEstimator;
this.diskLoadEstimator = diskLoadEstimator;
this.networkLoadEstimator = networkLoadEstimator;
this.resourceUtilizationEstimator = resourceUtilizationEstimator;
this.overheadMillis = overheadMillis;
this.configurationKey = configurationKey;
}
public static double integrate2d(final ToDoubleBiFunction<Double, Double> getIntegrand,
final double xLowerBound, final double xUpperBound, final int xNumPoints,
final double yLowerBound, final double yUpperBound, final int yNumPoints){
final GaussIntegrator xIntegrator = integratorFactory.legendre(xNumPoints, xLowerBound, xUpperBound);
final GaussIntegrator yIntegrator = integratorFactory.legendre(yNumPoints, yLowerBound, yUpperBound);
final double[] xIntegrationWeights = new IndexRange(0, xNumPoints).mapToDouble(xIntegrator::getWeight);
final double[] xAbscissas = new IndexRange(0, xNumPoints).mapToDouble(xIntegrator::getPoint);
final double[] yIntegrationWeights = new IndexRange(0, yNumPoints).mapToDouble(yIntegrator::getWeight);
final double[] yAbscissas = new IndexRange(0, yNumPoints).mapToDouble(yIntegrator::getPoint);
double integral = 0;
for (int i = 0; i < xNumPoints; i++) {
final double x = xAbscissas[i];
for (int j = 0; j < yNumPoints; j++) {
final double y = yAbscissas[j];
final double integrand = getIntegrand.applyAsDouble(x, y);
integral += xIntegrationWeights[i] * yIntegrationWeights[j] * integrand;
}
}
return integral;
}
public static double integrate2d(final ToDoubleBiFunction<Double, Double> getIntegrand,
final double xLowerBound, final double xUpperBound, final int xNumPoints,
final double yLowerBound, final double yUpperBound, final int yNumPoints){
final GaussIntegrator xIntegrator = integratorFactory.legendre(xNumPoints, xLowerBound, xUpperBound);
final GaussIntegrator yIntegrator = integratorFactory.legendre(yNumPoints, yLowerBound, yUpperBound);
final double[] xIntegrationWeights = new IndexRange(0, xNumPoints).mapToDouble(xIntegrator::getWeight);
final double[] xAbscissas = new IndexRange(0, xNumPoints).mapToDouble(xIntegrator::getPoint);
final double[] yIntegrationWeights = new IndexRange(0, yNumPoints).mapToDouble(yIntegrator::getWeight);
final double[] yAbscissas = new IndexRange(0, yNumPoints).mapToDouble(yIntegrator::getPoint);
double integral = 0;
for (int i = 0; i < xNumPoints; i++) {
final double x = xAbscissas[i];
for (int j = 0; j < yNumPoints; j++) {
final double y = yAbscissas[j];
final double integrand = getIntegrand.applyAsDouble(x, y);
integral += xIntegrationWeights[i] * yIntegrationWeights[j] * integrand;
}
}
return integral;
}
/** Internal method to compute the intersections between a line and this instance. The returned list will
* contain either 0, 1, or 2 points.
* <ul>
* <li><strong>2 points</strong> - The line is a secant line and intersects the n-sphere at two
* distinct points. The points are ordered such that the first point in the list is the first point
* encountered when traveling in the direction of the line. (In other words, the points are ordered
* by increasing abscissa value.)
* </li>
* <li><strong>1 point</strong> - The line is a tangent line and only intersects the n-sphere at a
* single point (as evaluated by the n-sphere's precision context).
* </li>
* <li><strong>0 points</strong> - The line does not intersect the n-sphere.</li>
* </ul>
* @param <L> Line implementation type
* @param line line to intersect with the n-sphere
* @param abscissaFn function used to compute the abscissa value of a point on a line
* @param distanceFn function used to compute the smallest distance between a point
* and a line
* @return a list of intersection points between the given line and this n-sphere
*/
protected <L extends Embedding<V, Vector1D>> List<V> intersections(final L line,
final ToDoubleBiFunction<L, V> abscissaFn, final ToDoubleBiFunction<L, V> distanceFn) {
final double dist = distanceFn.applyAsDouble(line, center);
int cmp = precision.compare(dist, radius);
if (cmp <= 0) {
// on the boundary or inside the n-sphere
final double abscissa = abscissaFn.applyAsDouble(line, center);
final double abscissaDelta = Math.sqrt((radius * radius) - (dist * dist));
final V p0 = line.toSpace(Vector1D.of(abscissa - abscissaDelta));
if (cmp < 0) {
// secant line => two intersections
final V p1 = line.toSpace(Vector1D.of(abscissa + abscissaDelta));
return Arrays.asList(p0, p1);
}
// tangent line => one intersection
return Collections.singletonList(p0);
}
// no intersections
return Collections.emptyList();
}
/**
* Returns a {@link BiCollector} that produces the sum of a double-valued
* function applied to the input pair. If no input entries are present,
* the result is 0.
*
* @since 3.2
*/
public static <K, V> BiCollector<K, V, Double> summingDouble(
ToDoubleBiFunction<? super K, ? super V> mapper) {
requireNonNull(mapper);
return new BiCollector<K, V, Double>() {
@Override
public <E> Collector<E, ?, Double> splitting(
Function<E, K> toKey, Function<E, V> toValue) {
return Collectors.summingDouble(e -> mapper.applyAsDouble(toKey.apply(e), toValue.apply(e)));
}
};
}
/**
* Returns a {@link BiCollector} that produces the arithmetic mean of a double-valued
* function applied to the input pair. If no input entries are present,
* the result is 0.
*
* @since 3.2
*/
public static <K, V> BiCollector<K, V, Double> averagingDouble(
ToDoubleBiFunction<? super K, ? super V> mapper) {
requireNonNull(mapper);
return new BiCollector<K, V, Double>() {
@Override
public <E> Collector<E, ?, Double> splitting(
Function<E, K> toKey, Function<E, V> toValue) {
return Collectors.averagingDouble(e -> mapper.applyAsDouble(toKey.apply(e), toValue.apply(e)));
}
};
}
/**
* Returns a {@link BiCollector} which applies an {@code double}-producing
* mapping function to each input pair, and returns summary statistics
* for the resulting values.
*
*
* @since 3.2
*/
public static <K, V> BiCollector<K, V, DoubleSummaryStatistics> summarizingDouble(
ToDoubleBiFunction<? super K, ? super V> mapper) {
requireNonNull(mapper);
return new BiCollector<K, V, DoubleSummaryStatistics>() {
@Override
public <E> Collector<E, ?, DoubleSummaryStatistics> splitting(
Function<E, K> toKey, Function<E, V> toValue) {
return Collectors.summarizingDouble(e -> mapper.applyAsDouble(toKey.apply(e), toValue.apply(e)));
}
};
}
/**
* Parses a mathematical expression and provides it as a {@link ToDoubleFunction}.
*
* @param expression a mathematical expression
* @return a {@link ToLongBiFunction} wrapping the expression
*/
private static ToDoubleBiFunction<long[], long[]> compileResourceUsage(String expression) {
final Expression expr = ExpressionBuilder.parse(expression).specify(baseContext);
return (inCards, outCards) -> {
Context mathContext = createMathContext(null, inCards, outCards);
return expr.evaluate(mathContext);
};
}
/**
* Creates an new instance.
*
* @param cpuLoadEstimator estimates CPU load in terms of cycles
* @param ramLoadEstimator estimates RAM load in terms of bytes
* @param diskLoadEstimator estimates disk accesses in terms of bytes
* @param networkLoadEstimator estimates network in terms of bytes
* @param resourceUtilizationEstimator degree to which the load profile can utilize available resources
* @param overheadMillis overhead that this load profile incurs
*/
public NestableLoadProfileEstimator(LoadEstimator cpuLoadEstimator,
LoadEstimator ramLoadEstimator,
LoadEstimator diskLoadEstimator,
LoadEstimator networkLoadEstimator,
ToDoubleBiFunction<long[], long[]> resourceUtilizationEstimator,
long overheadMillis) {
this(
cpuLoadEstimator, ramLoadEstimator, diskLoadEstimator, networkLoadEstimator,
resourceUtilizationEstimator, overheadMillis, null
);
}
/**
* @param scorer 打分算法
* @param mapFunction 一个Node,获得tag-score健值对
* @param consumer set选定的标签
*/
public SecondOrderViterbi(
ToDoubleBiFunction<Map.Entry<TagType, Integer>,
Map.Entry<TagType, Integer>> scorer,
Function<ObjType, Map<TagType, Integer>> mapFunction,
BiConsumer<ObjType, TagType> consumer
) {
this.consumer = consumer;
this.scorer = scorer;
this.mapFunction = mapFunction;
}
private TradeCalibrationMeasure(
String name,
Class<T> tradeType,
ToDoubleBiFunction<T, RatesProvider> valueFn,
BiFunction<T, RatesProvider, PointSensitivities> sensitivityFn) {
this.name = name;
this.tradeType = tradeType;
this.valueFn = ArgChecker.notNull(valueFn, "valueFn");
this.sensitivityFn = ArgChecker.notNull(sensitivityFn, "sensitivityFn");
}
private PresentValueCalibrationMeasure(
String name,
Class<T> tradeType,
ToDoubleBiFunction<T, RatesProvider> valueFn,
BiFunction<T, RatesProvider, PointSensitivities> sensitivityFn) {
this.name = name;
this.tradeType = tradeType;
this.valueFn = ArgChecker.notNull(valueFn, "valueFn");
this.sensitivityFn = ArgChecker.notNull(sensitivityFn, "sensitivityFn");
}
private MarketQuoteMeasure(
String name,
Class<T> tradeType,
ToDoubleBiFunction<T, RatesProvider> valueFn,
BiFunction<T, RatesProvider, PointSensitivities> sensitivityFn) {
this.name = name;
this.tradeType = tradeType;
this.valueFn = ArgChecker.notNull(valueFn, "valueFn");
this.sensitivityFn = ArgChecker.notNull(sensitivityFn, "sensitivityFn");
}
/**
* Creates a new instance from a specification {@link String}. Valid specifications are as follows:
* <pre>
* {"cpu":<JUEL expression>,
* "ram":<JUEL expression>,
* "disk":<JUEL expression>,
* "network":<JUEL expression>,
* "import":<["optional", "operator", "properties"]>,
* "in":<#inputs>,
* "out":<#outputs>,
* "p":<correctness probability>,
* "overhead":<overhead in milliseconds>,
* "ru":<resource utilization JUEL expression>
* }
* </pre>
* The JUEL expressions accept as parameters {@code in0}, {@code in1} a.s.o. for the input cardinalities and
* {@code out0}, {@code out1} a.s.o. for the output cardinalities.
*
* @param configKey the {@link Configuration} from that the {@code spec} was retrieved or else {@code null}
* @param spec a specification that adheres to above format
* @return the new instance
*/
public static NestableLoadProfileEstimator createFromJuelSpecification(String configKey, JSONObject spec) {
int numInputs = spec.getInt("in");
int numOutputs = spec.getInt("out");
double correctnessProb = spec.getDouble("p");
List<String> operatorProperties = spec.has("import") ?
StreamSupport.stream(spec.optJSONArray("import").spliterator(), false).map(Objects::toString).collect(Collectors.toList()) :
Collections.emptyList();
LoadEstimator cpuEstimator = new DefaultLoadEstimator(
numInputs,
numOutputs,
correctnessProb,
CardinalityEstimate.EMPTY_ESTIMATE,
parseLoadJuel(spec.getString("cpu"), numInputs, numOutputs, operatorProperties)
);
LoadEstimator ramEstimator = new DefaultLoadEstimator(
numInputs,
numOutputs,
correctnessProb,
CardinalityEstimate.EMPTY_ESTIMATE,
parseLoadJuel(spec.getString("ram"), numInputs, numOutputs, operatorProperties)
);
LoadEstimator diskEstimator = !spec.has("disk") ? null : new DefaultLoadEstimator(
numInputs,
numOutputs,
correctnessProb,
CardinalityEstimate.EMPTY_ESTIMATE,
parseLoadJuel(spec.getString("disk"), numInputs, numOutputs, operatorProperties)
);
LoadEstimator networkEstimator = !spec.has("network") ? null : new DefaultLoadEstimator(
numInputs,
numOutputs,
correctnessProb,
CardinalityEstimate.EMPTY_ESTIMATE,
parseLoadJuel(spec.getString("network"), numInputs, numOutputs, operatorProperties)
);
long overhead = spec.has("overhead") ? spec.getLong("overhead") : 0L;
ToDoubleBiFunction<long[], long[]> resourceUtilizationEstimator = spec.has("ru") ?
parseResourceUsageJuel(spec.getString("ru"), numInputs, numOutputs) :
DEFAULT_RESOURCE_UTILIZATION_ESTIMATOR;
return new NestableLoadProfileEstimator(
cpuEstimator,
ramEstimator,
diskEstimator,
networkEstimator,
resourceUtilizationEstimator,
overhead,
configKey
);
}
/**
* Creates a new instance from a specification {@link String}. Valid specifications are as follows:
* <pre>
* {"cpu":<mathematical expression>,
* "ram":<mathematical expression>,
* "disk":<mathematical expression>,
* "network":<mathematical expression>,
* "import":<["optional", "operator", "properties"]>,
* "in":<#inputs>,
* "out":<#outputs>,
* "p":<correctness probability>,
* "overhead":<overhead in milliseconds>,
* "ru":<resource utilization mathematical expression>
* }
* </pre>
* The JUEL expressions accept as parameters {@code in0}, {@code in1} a.s.o. for the input cardinalities and
* {@code out0}, {@code out1} a.s.o. for the output cardinalities.
*
* @param configKey the {@link Configuration} from that the {@code spec} was retrieved or else {@code null}
* @param spec a specification that adheres to above format
* @return the new instance
*/
public static NestableLoadProfileEstimator createFromMathExSpecification(String configKey, JSONObject spec) {
int numInputs = spec.getInt("in");
int numOutputs = spec.getInt("out");
double correctnessProb = spec.getDouble("p");
List<String> operatorProperties = spec.has("import") ?
StreamSupport.stream(spec.optJSONArray("import").spliterator(), false).map(Objects::toString).collect(Collectors.toList()) :
Collections.emptyList();
LoadEstimator cpuEstimator = new DefaultLoadEstimator(
numInputs,
numOutputs,
correctnessProb,
CardinalityEstimate.EMPTY_ESTIMATE,
compile(spec.getString("cpu"))
);
LoadEstimator ramEstimator = new DefaultLoadEstimator(
numInputs,
numOutputs,
correctnessProb,
CardinalityEstimate.EMPTY_ESTIMATE,
compile(spec.getString("ram"))
);
LoadEstimator diskEstimator = !spec.has("disk") ? null : new DefaultLoadEstimator(
numInputs,
numOutputs,
correctnessProb,
CardinalityEstimate.EMPTY_ESTIMATE,
compile(spec.getString("disk"))
);
LoadEstimator networkEstimator = !spec.has("network") ? null : new DefaultLoadEstimator(
numInputs,
numOutputs,
correctnessProb,
CardinalityEstimate.EMPTY_ESTIMATE,
compile(spec.getString("network"))
);
long overhead = spec.has("overhead") ? spec.getLong("overhead") : 0L;
ToDoubleBiFunction<long[], long[]> resourceUtilizationEstimator = spec.has("ru") ?
compileResourceUsage(spec.getString("ru")) :
DEFAULT_RESOURCE_UTILIZATION_ESTIMATOR;
return new NestableLoadProfileEstimator(
cpuEstimator,
ramEstimator,
diskEstimator,
networkEstimator,
resourceUtilizationEstimator,
overhead,
configKey
);
}
/**
* Utility to create new instances: Rounds the results of a given estimation function.
*/
@SuppressWarnings("unused")
public static ToLongBiFunction<long[], long[]> rounded(ToDoubleBiFunction<long[], long[]> f) {
return (inputCards, outputCards) -> Math.round(f.applyAsDouble(inputCards, outputCards));
}
/**
* Utility to create new instances: Rounds the results of a given estimation function.
*/
@SuppressWarnings("unused")
public static ToLongBiFunction<long[], long[]> rounded(ToDoubleBiFunction<long[], long[]> f) {
return (inputCards, outputCards) -> Math.round(f.applyAsDouble(inputCards, outputCards));
}
/**
* Obtains a calibrator for a specific type of trade.
* <p>
* The functions typically refer to pricers.
*
* @param <R> the trade type
* @param name the name
* @param tradeType the trade type
* @param valueFn the function for calculating the value
* @param sensitivityFn the function for calculating the sensitivity
* @return the calibrator
*/
public static <R extends ResolvedTrade> TradeCalibrationMeasure<R> of(
String name,
Class<R> tradeType,
ToDoubleBiFunction<R, RatesProvider> valueFn,
BiFunction<R, RatesProvider, PointSensitivities> sensitivityFn) {
return new TradeCalibrationMeasure<R>(name, tradeType, valueFn, sensitivityFn);
}
/**
* Obtains a calibrator for a specific type of trade.
* <p>
* The functions typically refer to pricers.
*
* @param <R> the trade type
* @param name the name
* @param tradeType the trade type
* @param valueFn the function for calculating the value
* @param sensitivityFn the function for calculating the sensitivity
* @return the calibrator
*/
public static <R extends ResolvedTrade> PresentValueCalibrationMeasure<R> of(
String name,
Class<R> tradeType,
ToDoubleBiFunction<R, RatesProvider> valueFn,
BiFunction<R, RatesProvider, PointSensitivities> sensitivityFn) {
return new PresentValueCalibrationMeasure<R>(name, tradeType, valueFn, sensitivityFn);
}
/**
* Obtains a calibrator for a specific type of trade.
* <p>
* The functions typically refer to pricers.
*
* @param <R> the trade type
* @param name the name
* @param tradeType the trade type
* @param valueFn the function for calculating the value
* @param sensitivityFn the function for calculating the sensitivity
* @return the calibrator
*/
public static <R extends ResolvedTrade> MarketQuoteMeasure<R> of(
String name,
Class<R> tradeType,
ToDoubleBiFunction<R, RatesProvider> valueFn,
BiFunction<R, RatesProvider, PointSensitivities> sensitivityFn) {
return new MarketQuoteMeasure<R>(name, tradeType, valueFn, sensitivityFn);
}
/**
* Parses a JUEL expression and provides it as a {@link ToLongBiFunction}.
*
* @param juel a JUEL expression
* @param numInputs the number of inputs of the estimated operator, reflected as JUEL variables {@code in0}, {@code in1}, ...
* @param numOutputs the number of outputs of the estimated operator, reflected as JUEL variables {@code out0}, {@code out1}, ...
* @return a {@link ToLongBiFunction} wrapping the JUEL expression
*/
private static ToDoubleBiFunction<long[], long[]> parseResourceUsageJuel(String juel, int numInputs, int numOutputs) {
final Map<String, Class<?>> parameterClasses = createJuelParameterClasses(numInputs, numOutputs);
final JuelUtils.JuelFunction<Double> juelFunction = new JuelUtils.JuelFunction<>(juel, Double.class, parameterClasses);
return (inCards, outCards) -> applyJuelFunction(juelFunction, null, inCards, outCards, Collections.emptyList());
}
/**
* Transforms the entries in the stream to doubles by applying a mapper function to each key and value.
*
* @param mapper a mapper function whose return values are included in the new stream
* @return a stream containing the double values returned from the mapper function
*/
public DoubleStream mapToDouble(ToDoubleBiFunction<? super K, ? super V> mapper) {
return underlying.mapToDouble(e -> mapper.applyAsDouble(e.getKey(), e.getValue()));
}
/**
* Return a function which calculates the distance of two vector elements at
* a given {@code index}.
*
* @param index the vector index
* @return a function which calculates the distance of two vector elements
*/
default ToDoubleBiFunction<V, V> ofIndex(final int index) {
return (u, v) -> distance(u, v, index);
}