Search in sources :

Example 1 with FloatFunction

use of org.eclipse.collections.api.block.function.primitive.FloatFunction in project eclipse-collections by eclipse.

the class ParallelIterableTestCase method sumOfFloatConsistentRounding.

@Test
public void sumOfFloatConsistentRounding() {
    FloatFunction<Integer> roundingSensitiveElementFunction = i -> (i <= 99995) ? 1.0e-18f : 1.0f;
    MutableList<Integer> list = Interval.oneTo(100_000).toList().shuffleThis();
    double baseline = this.getExpectedWith(list.toArray(new Integer[] {})).sumOfFloat(roundingSensitiveElementFunction);
    for (Integer batchSize : BATCH_SIZES) {
        this.batchSize = batchSize;
        ParallelIterable<Integer> testCollection = this.newWith(list.toArray(new Integer[] {}));
        Assert.assertEquals("Batch size: " + this.batchSize, baseline, testCollection.sumOfFloat(roundingSensitiveElementFunction), 1.0e-15d);
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ParallelSortedSetIterable(org.eclipse.collections.api.set.sorted.ParallelSortedSetIterable) NegativeIntervalFunction(org.eclipse.collections.impl.block.function.NegativeIntervalFunction) CharHashBag(org.eclipse.collections.impl.bag.mutable.primitive.CharHashBag) Procedures2(org.eclipse.collections.impl.block.factory.Procedures2) Function(org.eclipse.collections.api.block.function.Function) Predicate(org.eclipse.collections.api.block.predicate.Predicate) Verify(org.eclipse.collections.impl.test.Verify) CheckedPredicate(org.eclipse.collections.impl.block.predicate.checked.CheckedPredicate) MutableList(org.eclipse.collections.api.list.MutableList) ParallelIterable(org.eclipse.collections.api.ParallelIterable) RichIterable(org.eclipse.collections.api.RichIterable) Function0(org.eclipse.collections.api.block.function.Function0) HashBag(org.eclipse.collections.impl.bag.mutable.HashBag) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Function2(org.eclipse.collections.api.block.function.Function2) CheckedFunction(org.eclipse.collections.impl.block.function.checked.CheckedFunction) After(org.junit.After) Tuples(org.eclipse.collections.impl.tuple.Tuples) ParallelListIterable(org.eclipse.collections.api.list.ParallelListIterable) Interval(org.eclipse.collections.impl.list.Interval) NoSuchElementException(java.util.NoSuchElementException) Pair(org.eclipse.collections.api.tuple.Pair) DoubleFunction(org.eclipse.collections.api.block.function.primitive.DoubleFunction) MutableCollection(org.eclipse.collections.api.collection.MutableCollection) ExecutorService(java.util.concurrent.ExecutorService) Comparators(org.eclipse.collections.impl.block.factory.Comparators) Predicates(org.eclipse.collections.impl.block.factory.Predicates) Before(org.junit.Before) Predicates2(org.eclipse.collections.impl.block.factory.Predicates2) CollectionAddProcedure(org.eclipse.collections.impl.block.procedure.CollectionAddProcedure) IntegerPredicates(org.eclipse.collections.impl.block.factory.IntegerPredicates) CheckedProcedure(org.eclipse.collections.impl.block.procedure.checked.CheckedProcedure) IOException(java.io.IOException) Test(org.junit.Test) PassThruFunction0(org.eclipse.collections.impl.block.function.PassThruFunction0) Executors(java.util.concurrent.Executors) ExecutionException(java.util.concurrent.ExecutionException) ParallelSetIterable(org.eclipse.collections.api.set.ParallelSetIterable) ImmutableList(org.eclipse.collections.api.list.ImmutableList) Lists(org.eclipse.collections.impl.factory.Lists) Pattern(java.util.regex.Pattern) Assert(org.junit.Assert) FloatFunction(org.eclipse.collections.api.block.function.primitive.FloatFunction) Test(org.junit.Test)

Example 2 with FloatFunction

use of org.eclipse.collections.api.block.function.primitive.FloatFunction in project narchy by automenta.

the class Optimize method run.

public Result<X> run(int maxIterations, int repeats, FloatFunction<Supplier<X>> eval) {
    assert (repeats >= 1);
    final int dim = tweaks.size();
    double[] mid = new double[dim];
    // double[] sigma = new double[n];
    double[] min = new double[dim];
    double[] max = new double[dim];
    double[] inc = new double[dim];
    // double[] range = new double[dim];
    X example = subject.get();
    int i = 0;
    for (Tweak w : tweaks) {
        TweakFloat s = (TweakFloat) w;
        // initial guess: get from sample, otherwise midpoint of min/max range
        Object guess = s.get(example);
        mid[i] = guess != null ? ((float) guess) : ((s.getMax() + s.getMin()) / 2f);
        min[i] = (s.getMin());
        max[i] = (s.getMax());
        inc[i] = s.getInc();
        // range[i] = max[i] - min[i];
        // sigma[i] = Math.abs(max[i] - min[i]) * 0.75f; //(s.getInc());
        i++;
    }
    FasterList<DoubleObjectPair<double[]>> experiments = new FasterList<>(maxIterations);
    final double[] maxScore = { Double.NEGATIVE_INFINITY };
    ObjectiveFunction func = new ObjectiveFunction(point -> {
        double score;
        try {
            double sum = 0;
            for (int r = 0; r < repeats; r++) {
                Supplier<X> x = () -> subject(point);
                sum += eval.floatValueOf(x);
            }
            score = sum / repeats;
        } catch (Exception e) {
            logger.error("{} {} {}", this, point, e);
            score = Float.NEGATIVE_INFINITY;
        }
        if (trace)
            csv.out(ArrayUtils.add(point, (int) 0, score));
        maxScore[0] = Math.max(maxScore[0], score);
        // System.out.println(
        // n4(score) + " / " + n4(maxScore[0]) + "\t" + n4(point)
        // );
        experiments.add(pair(score, point));
        experimentIteration(point, score);
        return score;
    });
    if (trace)
        csv = new CSVOutput(System.out, Stream.concat(Stream.of("score"), tweaks.stream().map(t -> t.id)).toArray(String[]::new));
    experimentStart();
    try {
        solve(dim, func, mid, min, max, inc, maxIterations);
    } catch (Throwable t) {
        logger.info("solve {} {}", func, t);
    }
    return new Result<>(experiments, tweaks);
}
Also used : MultiDirectionalSimplex(org.apache.commons.math3.optim.nonlinear.scalar.noderiv.MultiDirectionalSimplex) Logger(org.slf4j.Logger) SortedSet(java.util.SortedSet) DoubleObjectPair(org.eclipse.collections.api.tuple.primitive.DoubleObjectPair) MathArrays(org.apache.commons.math3.util.MathArrays) FasterList(jcog.list.FasterList) LoggerFactory(org.slf4j.LoggerFactory) ArrayUtils(org.apache.commons.lang3.ArrayUtils) ObjectiveFunction(org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction) Supplier(java.util.function.Supplier) SimplexOptimizer(org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer) List(java.util.List) Stream(java.util.stream.Stream) MersenneTwister(org.apache.commons.math3.random.MersenneTwister) GoalType(org.apache.commons.math3.optim.nonlinear.scalar.GoalType) Map(java.util.Map) PrimitiveTuples.pair(org.eclipse.collections.impl.tuple.primitive.PrimitiveTuples.pair) CSVOutput(jcog.meter.event.CSVOutput) InitialGuess(org.apache.commons.math3.optim.InitialGuess) MaxEval(org.apache.commons.math3.optim.MaxEval) Pair(org.eclipse.collections.api.tuple.Pair) FloatFunction(org.eclipse.collections.api.block.function.primitive.FloatFunction) Joiner(com.google.common.base.Joiner) SimpleBounds(org.apache.commons.math3.optim.SimpleBounds) FasterList(jcog.list.FasterList) ObjectiveFunction(org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction) DoubleObjectPair(org.eclipse.collections.api.tuple.primitive.DoubleObjectPair) CSVOutput(jcog.meter.event.CSVOutput)

Example 3 with FloatFunction

use of org.eclipse.collections.api.block.function.primitive.FloatFunction in project narchy by automenta.

the class ExeCharts method metaGoalChart.

private static Surface metaGoalChart(NAgent a) {
    return new TreeChart<Cause>() {

        final DurService on;

        final FasterList<ItemVis<Cause>> cache = new FasterList();

        final Function<Cause, TreeChart.ItemVis<Cause>> builder = ((i) -> {
            short id = i.id;
            ItemVis<Cause> item;
            if (cache.capacity() - 1 < id)
                cache.ensureCapacity(id + 16);
            else {
                item = cache.get(id);
                if (item != null)
                    return item;
            }
            String str = i.toString();
            if (str.startsWith("class nars."))
                // skip default toString
                str = str.substring("class nars.".length());
            if (str.startsWith("class "))
                // skip default toString
                str = str.substring(5);
            item = new CauseVis(i, str);
            cache.set(id, item);
            return item;
        });

        {
            on = a.onFrame(() -> {
                update(a.nar().causes, (c, i) -> {
                    float v = c.value();
                    float r, g, b;
                    if (v < 0) {
                        r = 0.75f * Math.max(0.1f, Math.min(1f, -v));
                        g = 0;
                    } else {
                        g = 0.75f * Math.max(0.1f, Math.min(1f, +v));
                        r = 0;
                    }
                    float t = Util.sum(((FloatFunction<Traffic>) (p -> Math.abs(p.last))), c.goal);
                    b = Math.max(r, g) / 2f * Util.unitize(t);
                    i.update(v, r, g, b);
                // i.updateMomentum(
                // //0.01f + Util.sqr(Util.tanhFast(v)+1),
                // //Math.signum(v) *(1+Math.abs(v))*(t),
                // //Math.signum(v) * t,
                // v,
                // 0.25f,
                // r, g, b);
                }, builder);
            });
        }

        @Override
        public void stop() {
            super.stop();
            on.off();
        }
    };
}
Also used : GL2(com.jogamp.opengl.GL2) IntStream(java.util.stream.IntStream) BaseSlider(spacegraph.space2d.widget.slider.BaseSlider) DurService(nars.control.DurService) Causable(nars.exe.Causable) Surface(spacegraph.space2d.Surface) TreeChart(spacegraph.space2d.widget.meter.TreeChart) StringUtils(org.apache.commons.lang3.StringUtils) Draw(spacegraph.video.Draw) Function(java.util.function.Function) AutoSurface(spacegraph.space2d.widget.meta.AutoSurface) Traffic(nars.control.Traffic) Gridding(spacegraph.space2d.container.Gridding) BitmapMatrixView(spacegraph.space2d.widget.meter.BitmapMatrixView) FloatSlider(spacegraph.space2d.widget.slider.FloatSlider) NAgent(nars.NAgent) FasterList(jcog.list.FasterList) FloatRange(jcog.math.FloatRange) nars.$(nars.$) LoopPanel(spacegraph.space2d.widget.meta.LoopPanel) Collectors(java.util.stream.Collectors) Util(jcog.Util) RectFloat2D(jcog.tree.rtree.rect.RectFloat2D) CheckBox(spacegraph.space2d.widget.button.CheckBox) List(java.util.List) Splitting(spacegraph.space2d.container.Splitting) NAR(nars.NAR) Cause(nars.control.Cause) MetaGoal(nars.control.MetaGoal) FloatFunction(org.eclipse.collections.api.block.function.primitive.FloatFunction) Label(spacegraph.space2d.widget.text.Label) Function(java.util.function.Function) FloatFunction(org.eclipse.collections.api.block.function.primitive.FloatFunction) FasterList(jcog.list.FasterList) Cause(nars.control.Cause) Traffic(nars.control.Traffic) TreeChart(spacegraph.space2d.widget.meter.TreeChart) DurService(nars.control.DurService)

Aggregations

FloatFunction (org.eclipse.collections.api.block.function.primitive.FloatFunction)3 List (java.util.List)2 FasterList (jcog.list.FasterList)2 Pair (org.eclipse.collections.api.tuple.Pair)2 Joiner (com.google.common.base.Joiner)1 GL2 (com.jogamp.opengl.GL2)1 IOException (java.io.IOException)1 Map (java.util.Map)1 NoSuchElementException (java.util.NoSuchElementException)1 SortedSet (java.util.SortedSet)1 ExecutionException (java.util.concurrent.ExecutionException)1 ExecutorService (java.util.concurrent.ExecutorService)1 Executors (java.util.concurrent.Executors)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 Function (java.util.function.Function)1 Supplier (java.util.function.Supplier)1 Pattern (java.util.regex.Pattern)1 Collectors (java.util.stream.Collectors)1 IntStream (java.util.stream.IntStream)1 Stream (java.util.stream.Stream)1