java.util.function.ToDoubleFunction Java Examples

The following examples show how to use java.util.function.ToDoubleFunction. 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 Project: jdk1.8-source-analysis   Author: raysonfang   File: ReferencePipeline.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public final DoubleStream mapToDouble(ToDoubleFunction<? super P_OUT> mapper) {
    Objects.requireNonNull(mapper);
    return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
            return new Sink.ChainedReference<P_OUT, Double>(sink) {
                @Override
                public void accept(P_OUT u) {
                    downstream.accept(mapper.applyAsDouble(u));
                }
            };
        }
    };
}
 
Example #2
Source Project: dragonwell8_jdk   Author: alibaba   File: ReferencePipeline.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public final DoubleStream mapToDouble(ToDoubleFunction<? super P_OUT> mapper) {
    Objects.requireNonNull(mapper);
    return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
            return new Sink.ChainedReference<P_OUT, Double>(sink) {
                @Override
                public void accept(P_OUT u) {
                    downstream.accept(mapper.applyAsDouble(u));
                }
            };
        }
    };
}
 
Example #3
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: ReferencePipeline.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public final DoubleStream mapToDouble(ToDoubleFunction<? super P_OUT> mapper) {
    Objects.requireNonNull(mapper);
    return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
            return new Sink.ChainedReference<P_OUT, Double>(sink) {
                @Override
                public void accept(P_OUT u) {
                    downstream.accept(mapper.applyAsDouble(u));
                }
            };
        }
    };
}
 
Example #4
Source Project: jdk8u60   Author: chenghanpeng   File: Collectors.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the sum of a double-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * <p>The sum returned can vary depending upon the order in which
 * values are recorded, due to accumulated rounding error in
 * addition of values of differing magnitudes. Values sorted by increasing
 * absolute magnitude tend to yield more accurate results.  If any recorded
 * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 * sum will be {@code NaN}.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Double>
summingDouble(ToDoubleFunction<? super T> mapper) {
    /*
     * In the arrays allocated for the collect operation, index 0
     * holds the high-order bits of the running sum, index 1 holds
     * the low-order bits of the sum computed via compensated
     * summation, and index 2 holds the simple sum used to compute
     * the proper result if the stream contains infinite values of
     * the same sign.
     */
    return new CollectorImpl<>(
            () -> new double[3],
            (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t));
                        a[2] += mapper.applyAsDouble(t);},
            (a, b) -> { sumWithCompensation(a, b[0]);
                        a[2] += b[2];
                        return sumWithCompensation(a, b[1]); },
            a -> computeFinalSum(a),
            CH_NOID);
}
 
Example #5
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: ReferencePipeline.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public final DoubleStream mapToDouble(ToDoubleFunction<? super P_OUT> mapper) {
    Objects.requireNonNull(mapper);
    return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
            return new Sink.ChainedReference<P_OUT, Double>(sink) {
                @Override
                public void accept(P_OUT u) {
                    downstream.accept(mapper.applyAsDouble(u));
                }
            };
        }
    };
}
 
Example #6
Source Project: desugar_jdk_libs   Author: google   File: Collectors.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the sum of a double-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * <p>The sum returned can vary depending upon the order in which
 * values are recorded, due to accumulated rounding error in
 * addition of values of differing magnitudes. Values sorted by increasing
 * absolute magnitude tend to yield more accurate results.  If any recorded
 * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 * sum will be {@code NaN}.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Double>
summingDouble(ToDoubleFunction<? super T> mapper) {
    /*
     * In the arrays allocated for the collect operation, index 0
     * holds the high-order bits of the running sum, index 1 holds
     * the low-order bits of the sum computed via compensated
     * summation, and index 2 holds the simple sum used to compute
     * the proper result if the stream contains infinite values of
     * the same sign.
     */
    return new CollectorImpl<>(
            () -> new double[3],
            (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t));
                        a[2] += mapper.applyAsDouble(t);},
            (a, b) -> { sumWithCompensation(a, b[0]);
                        a[2] += b[2];
                        return sumWithCompensation(a, b[1]); },
            a -> computeFinalSum(a),
            CH_NOID);
}
 
Example #7
Source Project: micrometer   Author: micrometer-metrics   File: DropwizardMeterRegistry.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected <T> io.micrometer.core.instrument.Gauge newGauge(Meter.Id id, @Nullable T obj, ToDoubleFunction<T> valueFunction) {
    final WeakReference<T> ref = new WeakReference<>(obj);
    Gauge<Double> gauge = () -> {
        T obj2 = ref.get();
        if (obj2 != null) {
            try {
                return valueFunction.applyAsDouble(obj2);
            } catch (Throwable ex) {
                logger.log("Failed to apply the value function for the gauge '" + id.getName() + "'.", ex);
            }
        }
        return nullGaugeValue();
    };
    registry.register(hierarchicalName(id), gauge);
    return new DropwizardGauge(id, gauge);
}
 
Example #8
Source Project: rheem   Author: rheem-ecosystem   File: OptimizationContext.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Update the {@link LoadProfile} and {@link TimeEstimate} of this instance.
 *
 * @param configuration provides the necessary functions
 */
private void updateCostEstimate(Configuration configuration) {
    if (!this.operator.isExecutionOperator()) return;

    // Estimate the LoadProfile.
    final LoadProfileEstimator loadProfileEstimator = this.getLoadProfileEstimator();
    try {
        this.loadProfile = LoadProfileEstimators.estimateLoadProfile(this, loadProfileEstimator);
    } catch (Exception e) {
        throw new RheemException(String.format("Load profile estimation for %s failed.", this.operator), e);
    }

    // Calculate the TimeEstimate.
    final ExecutionOperator executionOperator = (ExecutionOperator) this.operator;
    final Platform platform = executionOperator.getPlatform();
    final LoadProfileToTimeConverter timeConverter = configuration.getLoadProfileToTimeConverterProvider().provideFor(platform);
    this.timeEstimate = TimeEstimate.MINIMUM.plus(timeConverter.convert(this.loadProfile));
    if (OptimizationContext.this.logger.isDebugEnabled()) {
        OptimizationContext.this.logger.debug(
                "Setting time estimate of {} to {}.", this.operator, this.timeEstimate
        );
    }

    // Calculate the cost estimate.
    final TimeToCostConverter timeToCostConverter = configuration.getTimeToCostConverterProvider().provideFor(platform);
    this.costEstimate = timeToCostConverter.convertWithoutFixCosts(this.timeEstimate);

    // Squash the cost estimate.
    final ToDoubleFunction<ProbabilisticDoubleInterval> costSquasher = configuration.getCostSquasherProvider().provide();
    this.squashedCostEstimate = costSquasher.applyAsDouble(this.costEstimate);
}
 
Example #9
Source Project: micrometer   Author: micrometer-metrics   File: StatsdGauge.java    License: Apache License 2.0 5 votes vote down vote up
StatsdGauge(Id id, StatsdLineBuilder lineBuilder, FluxSink<String> sink, @Nullable T obj, ToDoubleFunction<T> value, boolean alwaysPublish) {
    super(id);
    this.lineBuilder = lineBuilder;
    this.sink = sink;
    this.ref = new WeakReference<>(obj);
    this.value = value;
    this.alwaysPublish = alwaysPublish;
}
 
Example #10
Source Project: micrometer   Author: micrometer-metrics   File: SimpleMeterRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) {
    switch (config.mode()) {
        case CUMULATIVE:
            return new CumulativeFunctionCounter<>(id, obj, countFunction);

        case STEP:
        default:
            return new StepFunctionCounter<>(id, clock, config.step().toMillis(), obj, countFunction);
    }
}
 
Example #11
Source Project: TencentKona-8   Author: Tencent   File: BasicTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testDoubleComparator() {
    Thing[] things = new Thing[doubleValues.length];
    for (int i=0; i<doubleValues.length; i++)
        things[i] = new Thing(0, 0L, doubleValues[i], null);
    Comparator<Thing> comp = Comparator.comparingDouble(new ToDoubleFunction<Thing>() {
        @Override
        public double applyAsDouble(Thing thing) {
            return thing.getDoubleField();
        }
    });

    assertComparisons(things, comp, comparisons);
}
 
Example #12
Source Project: jdk8u60   Author: chenghanpeng   File: BasicTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testDoubleComparator() {
    Thing[] things = new Thing[doubleValues.length];
    for (int i=0; i<doubleValues.length; i++)
        things[i] = new Thing(0, 0L, doubleValues[i], null);
    Comparator<Thing> comp = Comparator.comparingDouble(new ToDoubleFunction<Thing>() {
        @Override
        public double applyAsDouble(Thing thing) {
            return thing.getDoubleField();
        }
    });

    assertComparisons(things, comp, comparisons);
}
 
Example #13
Source Project: morpheus-core   Author: zavtech   File: ArrayBase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public final Array<T> applyDoubles(ToDoubleFunction<ArrayValue<T>> function) {
    final int length = length();
    if (length > 0) {
        final ApplyValues action = new ApplyValues(0, length - 1, function);
        if (isParallel()) {
            ForkJoinPool.commonPool().invoke(action);
        } else {
            action.compute();
        }
    }
    return this;
}
 
Example #14
Source Project: morpheus-core   Author: zavtech   File: Function1.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an DOUBLE mapper that wraps to function provided
 * @param function  the function to wrap
 * @param <I>       the input type
 * @return          the newly created mapper
 */
public static <I,O> Function1<I,Double> toDouble(ToDoubleFunction<I> function) {
    return new Function1<I,Double>(FunctionStyle.DOUBLE) {
        @Override
        public final double applyAsDouble(I value) {
            return function.applyAsDouble(value);
        }
    };
}
 
Example #15
Source Project: micrometer   Author: micrometer-metrics   File: DropwizardMeterRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected <T> FunctionTimer newFunctionTimer(Meter.Id id, T obj, ToLongFunction<T> countFunction, ToDoubleFunction<T> totalTimeFunction, TimeUnit totalTimeFunctionUnit) {
    DropwizardFunctionTimer<T> ft = new DropwizardFunctionTimer<>(id, clock, obj, countFunction, totalTimeFunction,
            totalTimeFunctionUnit, getBaseTimeUnit());
    registry.register(hierarchicalName(id), ft.getDropwizardMeter());
    return ft;
}
 
Example #16
Source Project: micrometer   Author: micrometer-metrics   File: DropwizardFunctionCounter.java    License: Apache License 2.0 5 votes vote down vote up
DropwizardFunctionCounter(Id id, Clock clock,
                          T obj, ToDoubleFunction<T> f) {
    super(id);
    this.ref = new WeakReference<>(obj);
    this.f = f;
    this.rate = new DropwizardRate(clock);
    this.dropwizardMeter = new Meter(new DropwizardClock(clock)) {
        @Override
        public double getFifteenMinuteRate() {
            count();
            return rate.getFifteenMinuteRate();
        }

        @Override
        public double getFiveMinuteRate() {
            count();
            return rate.getFiveMinuteRate();
        }

        @Override
        public double getOneMinuteRate() {
            count();
            return rate.getOneMinuteRate();
        }

        @Override
        public long getCount() {
            return (long) count();
        }
    };
}
 
Example #17
Source Project: micrometer   Author: micrometer-metrics   File: StatsdFunctionTimer.java    License: Apache License 2.0 5 votes vote down vote up
StatsdFunctionTimer(Id id, T obj, ToLongFunction<T> countFunction, ToDoubleFunction<T> totalTimeFunction,
                    TimeUnit totalTimeFunctionUnit, TimeUnit baseTimeUnit,
                    StatsdLineBuilder lineBuilder, FluxSink<String> sink) {
    super(id, obj, countFunction, totalTimeFunction, totalTimeFunctionUnit, baseTimeUnit);
    this.lineBuilder = lineBuilder;
    this.sink = sink;
}
 
Example #18
Source Project: micrometer   Author: micrometer-metrics   File: PrometheusMeterRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) {
    FunctionCounter fc = new CumulativeFunctionCounter<>(id, obj, countFunction);
    applyToCollector(id, (collector) -> {
        List<String> tagValues = tagValues(id);
        collector.add(tagValues, (conventionName, tagKeys) -> Stream.of(new MicrometerCollector.Family(Collector.Type.COUNTER, conventionName,
                new Collector.MetricFamilySamples.Sample(conventionName, tagKeys, tagValues, fc.count())
        )));
    });
    return fc;
}
 
Example #19
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: Collectors.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the arithmetic mean of a double-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * <p>The average returned can vary depending upon the order in which
 * values are recorded, due to accumulated rounding error in
 * addition of values of differing magnitudes. Values sorted by increasing
 * absolute magnitude tend to yield more accurate results.  If any recorded
 * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 * average will be {@code NaN}.
 *
 * @implNote The {@code double} format can represent all
 * consecutive integers in the range -2<sup>53</sup> to
 * 2<sup>53</sup>. If the pipeline has more than 2<sup>53</sup>
 * values, the divisor in the average computation will saturate at
 * 2<sup>53</sup>, leading to additional numerical errors.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Double>
averagingDouble(ToDoubleFunction<? super T> mapper) {
    /*
     * In the arrays allocated for the collect operation, index 0
     * holds the high-order bits of the running sum, index 1 holds
     * the low-order bits of the sum computed via compensated
     * summation, and index 2 holds the number of values seen.
     */
    return new CollectorImpl<>(
            () -> new double[4],
            (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t)); a[2]++; a[3]+= mapper.applyAsDouble(t);},
            (a, b) -> { sumWithCompensation(a, b[0]); sumWithCompensation(a, b[1]); a[2] += b[2]; a[3] += b[3]; return a; },
            a -> (a[2] == 0) ? 0.0d : (computeFinalSum(a) / a[2]),
            CH_NOID);
}
 
Example #20
Source Project: jdk1.8-source-analysis   Author: raysonfang   File: Collectors.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the arithmetic mean of a double-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * <p>The average returned can vary depending upon the order in which
 * values are recorded, due to accumulated rounding error in
 * addition of values of differing magnitudes. Values sorted by increasing
 * absolute magnitude tend to yield more accurate results.  If any recorded
 * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 * average will be {@code NaN}.
 *
 * @implNote The {@code double} format can represent all
 * consecutive integers in the range -2<sup>53</sup> to
 * 2<sup>53</sup>. If the pipeline has more than 2<sup>53</sup>
 * values, the divisor in the average computation will saturate at
 * 2<sup>53</sup>, leading to additional numerical errors.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Double>
averagingDouble(ToDoubleFunction<? super T> mapper) {
    /*
     * In the arrays allocated for the collect operation, index 0
     * holds the high-order bits of the running sum, index 1 holds
     * the low-order bits of the sum computed via compensated
     * summation, and index 2 holds the number of values seen.
     */
    return new CollectorImpl<>(
            () -> new double[4],
            (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t)); a[2]++; a[3]+= mapper.applyAsDouble(t);},
            (a, b) -> { sumWithCompensation(a, b[0]); sumWithCompensation(a, b[1]); a[2] += b[2]; a[3] += b[3]; return a; },
            a -> (a[2] == 0) ? 0.0d : (computeFinalSum(a) / a[2]),
            CH_NOID);
}
 
Example #21
Source Project: micrometer   Author: micrometer-metrics   File: OpenTSDBMeterRegistry.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) {
    return new CumulativeFunctionCounter<>(id, obj, countFunction);
}
 
Example #22
Source Project: Wurst7   Author: Wurst-Imperium   File: ClickAuraHack.java    License: GNU General Public License v3.0 4 votes vote down vote up
private Priority(String name,
	ToDoubleFunction<LivingEntity> keyExtractor)
{
	this.name = name;
	comparator = Comparator.comparingDouble(keyExtractor);
}
 
Example #23
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: DefaultMethodStreams.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper) {
    return s.mapToDouble(mapper);
}
 
Example #24
Source Project: Wurst7   Author: Wurst-Imperium   File: KillauraHack.java    License: GNU General Public License v3.0 4 votes vote down vote up
private Priority(String name,
	ToDoubleFunction<LivingEntity> keyExtractor)
{
	this.name = name;
	comparator = Comparator.comparingDouble(keyExtractor);
}
 
Example #25
Source Project: micrometer   Author: micrometer-metrics   File: StrongReferenceGaugeFunction.java    License: Apache License 2.0 4 votes vote down vote up
StrongReferenceGaugeFunction(@Nullable T obj, ToDoubleFunction<T> f) {
    this.obj = obj;
    this.f = f;
}
 
Example #26
Source Project: dragonwell8_jdk   Author: alibaba   File: Collectors.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the arithmetic mean of a double-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * <p>The average returned can vary depending upon the order in which
 * values are recorded, due to accumulated rounding error in
 * addition of values of differing magnitudes. Values sorted by increasing
 * absolute magnitude tend to yield more accurate results.  If any recorded
 * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 * average will be {@code NaN}.
 *
 * @implNote The {@code double} format can represent all
 * consecutive integers in the range -2<sup>53</sup> to
 * 2<sup>53</sup>. If the pipeline has more than 2<sup>53</sup>
 * values, the divisor in the average computation will saturate at
 * 2<sup>53</sup>, leading to additional numerical errors.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Double>
averagingDouble(ToDoubleFunction<? super T> mapper) {
    /*
     * In the arrays allocated for the collect operation, index 0
     * holds the high-order bits of the running sum, index 1 holds
     * the low-order bits of the sum computed via compensated
     * summation, and index 2 holds the number of values seen.
     */
    return new CollectorImpl<>(
            () -> new double[4],
            (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t)); a[2]++; a[3]+= mapper.applyAsDouble(t);},
            (a, b) -> { sumWithCompensation(a, b[0]); sumWithCompensation(a, b[1]); a[2] += b[2]; a[3] += b[3]; return a; },
            a -> (a[2] == 0) ? 0.0d : (computeFinalSum(a) / a[2]),
            CH_NOID);
}
 
Example #27
Source Project: micrometer   Author: micrometer-metrics   File: CompositeMeterRegistry.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected <T> Gauge newGauge(Meter.Id id, @Nullable T obj, ToDoubleFunction<T> valueFunction) {
    return new CompositeGauge<>(id, obj, valueFunction);
}
 
Example #28
Source Project: micrometer   Author: micrometer-metrics   File: MultiGauge.java    License: Apache License 2.0 4 votes vote down vote up
private Row(Tags uniqueTags, T obj, ToDoubleFunction<T> valueFunction) {
    this.uniqueTags = uniqueTags;
    this.obj = obj;
    this.valueFunction = valueFunction;
}
 
Example #29
Source Project: micrometer   Author: micrometer-metrics   File: CompositeMeterRegistry.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected <T> TimeGauge newTimeGauge(Meter.Id id, @Nullable T obj, TimeUnit valueFunctionUnit, ToDoubleFunction<T> valueFunction) {
    return new CompositeTimeGauge<>(id, obj, valueFunctionUnit, valueFunction);
}
 
Example #30
Source Project: freecol   Author: FreeCol   File: REFAIPlayer.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Find suitable colony targets.
 *
 * @param aiu The {@code AIUnit} to search with.
 * @param port If true, insist on the colonies being ports.
 * @param aiCarrier The {@code AIUnit} to use as a carrier.
 * @return A list of {@code TargetTuple} target choices.
 */
private List<TargetTuple> findColonyTargets(AIUnit aiu, boolean port,
                                            AIUnit aiCarrier) {
    final Player player = getPlayer();
    final Unit unit = aiu.getUnit();
    final Unit carrier = aiCarrier.getUnit();
    final CachingFunction<Colony, PathNode> pathMapper
        = new CachingFunction<Colony, PathNode>(c ->
            unit.findPath(carrier, c, carrier));
    final Predicate<Colony> pathPred = c ->
        pathMapper.apply(c) != null;
    final Function<Colony, TargetTuple> newTupleMapper = c -> {
        PathNode path = pathMapper.apply(c);
        return new TargetTuple(c, path,
            UnitSeekAndDestroyMission.scorePath(aiu, path));
    };
    final List<TargetTuple> targets
        = transform(flatten(player.getRebels(),
                ((port) ? Player::getConnectedPorts :Player::getColonies)),
            pathPred, newTupleMapper);
    if (targets.isEmpty()) return targets; // Should not happen

    // Increase score for drydock/s, musket and tools suppliers,
    // but decrease for fortifications.
    // FIXME: use Modifiers?
    final int percentTwiddle = 20; // Perturb score by +/-20%
    int[] twiddle = randomInts(logger, "REF target twiddle",
                               getAIRandom(), 2*percentTwiddle+1,
                               targets.size());
    int twidx = 0;
    for (TargetTuple t : targets) {
        final ToDoubleFunction<Building> bdf = b ->
            ((b.hasAbility(Ability.REPAIR_UNITS)) ? 1.5 : 1.0)
            * product(b.getOutputs(), ag ->
                (ag.getType().getMilitary()) ? 2.0
                : (ag.getType().isBuildingMaterial()
                    && ag.getType().isRefined()) ? 1.5
                : 1.0);
        t.score *= 0.01 * (101 - Math.min(100, t.colony.getSoL()))
            * product(t.colony.getBuildings(), b -> b.getLevel() > 1, bdf)
            * ((6 - ((!t.colony.hasStockade()) ? 0
                        : t.colony.getStockade().getLevel())) / 6.0)
            * (1.0 + 0.01 * (twiddle[twidx++] - percentTwiddle));
    }
    targets.sort(Comparator.naturalOrder());
    return targets;
}