Search in sources :

Example 6 with Pair

use of org.eclipse.collections.api.tuple.Pair in project eclipse-collections by eclipse.

the class AbstractMutableSortedBagTestCase method zip.

@Override
@Test
public void zip() {
    super.zip();
    MutableSortedBag<Integer> revInt = this.newWith(Collections.reverseOrder(), 2, 2, 3, 5, 1, 4);
    MutableSortedBag<Integer> integers = this.newWith(1, 3, 2, 2, 4, 5);
    MutableList<Pair<Integer, Integer>> zip = integers.zip(revInt);
    Verify.assertSize(6, zip);
    Assert.assertEquals(FastList.newListWith(Tuples.pair(1, 5), Tuples.pair(2, 4), Tuples.pair(2, 3), Tuples.pair(3, 2), Tuples.pair(4, 2), Tuples.pair(5, 1)), zip);
    MutableList<Pair<Integer, Integer>> revZip = revInt.zip(integers);
    Verify.assertSize(6, revZip);
    Assert.assertEquals(FastList.newListWith(Tuples.pair(5, 1), Tuples.pair(4, 2), Tuples.pair(3, 2), Tuples.pair(2, 3), Tuples.pair(2, 4), Tuples.pair(1, 5)), revZip);
    Person john = new Person("John", "Smith");
    Person johnDoe = new Person("John", "Doe");
    MutableSortedBag<Person> people = this.newWith(john, johnDoe);
    MutableList<Integer> list = FastList.newListWith(1, 2, 3);
    MutableList<Pair<Person, Integer>> pairs = people.zip(list);
    Assert.assertEquals(FastList.newListWith(Tuples.pair(johnDoe, 1), Tuples.pair(john, 2)), pairs);
    Assert.assertTrue(pairs.add(Tuples.pair(new Person("Jack", "Baker"), 3)));
    Assert.assertEquals(Tuples.pair(new Person("Jack", "Baker"), 3), pairs.getLast());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Person(org.eclipse.collections.impl.test.domain.Person) ObjectIntPair(org.eclipse.collections.api.tuple.primitive.ObjectIntPair) Pair(org.eclipse.collections.api.tuple.Pair) Test(org.junit.Test)

Example 7 with Pair

use of org.eclipse.collections.api.tuple.Pair 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 8 with Pair

use of org.eclipse.collections.api.tuple.Pair in project narchy by automenta.

the class DeriveTime method solveMerged.

@Nullable
Function<long[], Term> solveMerged(ArrayHashSet<Event> solutions, int dur) {
    int ss = solutions.size();
    // callee will use the only solution by default
    if (ss <= 1)
        return null;
    SortedSetMultimap<Term, LongLongPair> m = MultimapBuilder.hashKeys(ss).treeSetValues().build();
    solutions.forEach(x -> {
        long w = x.when();
        if (w != TIMELESS)
            m.put(x.id, PrimitiveTuples.pair(w, w));
    });
    int ms = m.size();
    switch(ms) {
        case 0:
            return null;
        case 1:
            Map.Entry<Term, LongLongPair> ee = m.entries().iterator().next();
            LongLongPair ww = ee.getValue();
            long s = ww.getOne();
            long e = ww.getTwo();
            return (w) -> {
                w[0] = s;
                w[1] = e;
                return ee.getKey();
            };
    }
    FasterList<Pair<Term, long[]>> choices = new FasterList(ms);
    // coalesce adjacent events
    m.asMap().forEach((t, cw) -> {
        int cws = cw.size();
        if (cws > 1) {
            long[][] ct = new long[cws][2];
            int i = 0;
            for (LongLongPair p : cw) {
                long[] cc = ct[i++];
                cc[0] = p.getOne();
                cc[1] = p.getTwo();
            }
            // TODO more complete comparison
            long[] prev = ct[0];
            for (int j = 1; j < cws; j++) {
                long[] next = ct[j];
                if (prev[0] == ETERNAL) {
                    assert (j == 1);
                    assert (ct[0][0] == ETERNAL);
                    // ignore eternal solution amongst other temporal solutions
                    ct[0] = null;
                } else if (Math.abs(prev[1] - next[0]) <= dur) {
                    // stretch
                    prev[1] = next[1];
                    ct[j] = null;
                    continue;
                }
                prev = next;
            }
            for (int j = 0; j < cws; j++) {
                long[] nn = ct[j];
                if (nn != null)
                    choices.add(pair(t, nn));
            }
        } else {
            LongLongPair f = ((SortedSet<LongLongPair>) cw).first();
            choices.add(pair(t, new long[] { f.getOne(), f.getTwo() }));
        }
    });
    if (choices.size() > 1) {
        // random fallback
        return (w) -> {
            Pair<Term, long[]> pp = choices.get(d.random);
            long[] cw = pp.getTwo();
            w[0] = cw[0];
            w[1] = cw[1];
            return pp.getOne();
        };
    } else {
        Pair<Term, long[]> c = choices.get(0);
        long[] cw = c.getTwo();
        Term cct = c.getOne();
        return (w) -> {
            w[0] = cw[0];
            w[1] = cw[1];
            return cct;
        };
    }
}
Also used : Derivation(nars.derive.Derivation) java.util(java.util) Tense(nars.time.Tense) CONJ(nars.Op.CONJ) MultimapBuilder(com.google.common.collect.MultimapBuilder) ArrayHashSet(jcog.data.ArrayHashSet) ETERNAL(nars.time.Tense.ETERNAL) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Truth(nars.truth.Truth) Tuples.pair(org.eclipse.collections.impl.tuple.Tuples.pair) EllipsisMatch(nars.derive.match.EllipsisMatch) LongHashSet(org.eclipse.collections.impl.set.mutable.primitive.LongHashSet) Bool(nars.term.atom.Bool) PrimitiveTuples(org.eclipse.collections.impl.tuple.primitive.PrimitiveTuples) NEG(nars.Op.NEG) ObjectByteHashMap(org.eclipse.collections.impl.map.mutable.primitive.ObjectByteHashMap) Pair(org.eclipse.collections.api.tuple.Pair) Longerval(jcog.math.Longerval) LongLongPair(org.eclipse.collections.api.tuple.primitive.LongLongPair) Term(nars.term.Term) SortedSetMultimap(com.google.common.collect.SortedSetMultimap) Predicate(java.util.function.Predicate) FasterList(jcog.list.FasterList) EviDensity(nars.task.EviDensity) Param(nars.Param) Nullable(org.jetbrains.annotations.Nullable) Task(nars.Task) Termed(nars.term.Termed) VarPattern(nars.term.var.VarPattern) TIMELESS(nars.time.Tense.TIMELESS) LongLongPair(org.eclipse.collections.api.tuple.primitive.LongLongPair) FasterList(jcog.list.FasterList) Term(nars.term.Term) ObjectByteHashMap(org.eclipse.collections.impl.map.mutable.primitive.ObjectByteHashMap) Pair(org.eclipse.collections.api.tuple.Pair) LongLongPair(org.eclipse.collections.api.tuple.primitive.LongLongPair) Nullable(org.jetbrains.annotations.Nullable)

Example 9 with Pair

use of org.eclipse.collections.api.tuple.Pair in project narchy by automenta.

the class Conclude method match.

public static void match(final DeriveRuleProto rule, List<PrediTerm<PreDerivation>> pre, List<PrediTerm<Derivation>> post, PatternIndex index, NAR nar) {
    Term pattern = rule.conclusion().sub(0);
    // TODO may interfere with constraints, functors, etc or other features, ie.
    // if the pattern is a product for example?
    // pattern = pattern.replace(ta, Derivation._taskTerm);
    // determine if any cases where a shortcut like this can work (ie. no constraints, not a product etc)
    // //substitute compound occurrences of the exact task and belief terms with the short-cut
    // Term ta = rule.getTask();
    // if (!ta.op().var) {
    // if (pattern.equals(ta))
    // pattern = Derivation.TaskTerm;
    // }
    // Term tb = rule.getBelief();
    // if (!tb.op().var) {
    // //pattern = pattern.replace(tb, Derivation._beliefTerm);
    // if (pattern.equals(tb))
    // pattern = Derivation.BeliefTerm;
    // }
    // HACK unwrap varIntro so we can apply it at the end of the derivation process, not before like other functors
    boolean introVars1;
    Pair<Termed, Term> outerFunctor = Op.functor(pattern, (i) -> i.equals(VAR_INTRO) ? VAR_INTRO : null);
    if (outerFunctor != null) {
        introVars1 = true;
        pattern = outerFunctor.getTwo().sub(0);
    } else {
        introVars1 = false;
    }
    pattern = index.get(pattern, true).term();
    Taskify taskify = new Taskify(nar.newCause((s) -> new RuleCause(rule, s)));
    PrediTerm<Derivation> conc = AndCondition.the(new Termify($.func("derive", pattern), pattern, rule), introVars1 ? AndCondition.the(introVars, taskify) : taskify);
    final Term taskPattern = rule.getTask();
    final Term beliefPattern = rule.getBelief();
    Op to = taskPattern.op();
    boolean taskIsPatVar = to == Op.VAR_PATTERN;
    Op bo = beliefPattern.op();
    boolean belIsPatVar = bo == Op.VAR_PATTERN;
    if (!taskIsPatVar) {
        pre.add(new TaskBeliefOp(to, true, false));
        pre.addAll(SubTermStructure.get(0, taskPattern.structure()));
    }
    if (!belIsPatVar) {
        if (to == bo) {
            pre.add(new AbstractPatternOp.TaskBeliefOpEqual());
        } else {
            pre.add(new TaskBeliefOp(bo, false, true));
            pre.addAll(SubTermStructure.get(1, beliefPattern.structure()));
        }
    }
    if (taskPattern.equals(beliefPattern)) {
        post.add(new UnifyTerm.UnifySubtermThenConclude(0, taskPattern, conc));
    }
    if (taskFirst(taskPattern, beliefPattern)) {
        // task first
        post.add(new UnifyTerm.UnifySubterm(0, taskPattern));
        post.add(new UnifyTerm.UnifySubtermThenConclude(1, beliefPattern, conc));
    } else {
        // belief first
        post.add(new UnifyTerm.UnifySubterm(1, beliefPattern));
        post.add(new UnifyTerm.UnifySubtermThenConclude(0, taskPattern, conc));
    }
// Term beliefPattern = pattern.term(1);
// if (Global.DEBUG) {
// if (beliefPattern.structure() == 0) {
// if nothing else in the rule involves this term
// which will be a singular VAR_PATTERN variable
// then allow null
// if (beliefPattern.op() != Op.VAR_PATTERN)
// throw new RuntimeException("not what was expected");
// }
// }
/*System.out.println( Long.toBinaryString(
                        pStructure) + " " + pattern
        );*/
}
Also used : DepIndepVarIntroduction(nars.op.DepIndepVarIntroduction) PrediTerm(nars.term.pred.PrediTerm) AbstractPatternOp(nars.derive.op.AbstractPatternOp) nars.$(nars.$) DeriveRuleSource(nars.derive.rule.DeriveRuleSource) AndCondition(nars.term.pred.AndCondition) UnifyTerm(nars.derive.op.UnifyTerm) AbstractPred(nars.term.pred.AbstractPred) Nullable(org.jetbrains.annotations.Nullable) VAR_INTRO(nars.derive.Conclude.IntroVars.VAR_INTRO) Task(nars.Task) List(java.util.List) TaskBeliefOp(nars.derive.op.TaskBeliefOp) NAR(nars.NAR) Op(nars.Op) DeriveRuleProto(nars.derive.rule.DeriveRuleProto) PatternIndex(nars.index.term.PatternIndex) Map(java.util.Map) SubTermStructure(nars.derive.op.SubTermStructure) Termed(nars.term.Termed) Cause(nars.control.Cause) Pair(org.eclipse.collections.api.tuple.Pair) Term(nars.term.Term) AbstractPatternOp(nars.derive.op.AbstractPatternOp) TaskBeliefOp(nars.derive.op.TaskBeliefOp) Op(nars.Op) TaskBeliefOp(nars.derive.op.TaskBeliefOp) AbstractPatternOp(nars.derive.op.AbstractPatternOp) UnifyTerm(nars.derive.op.UnifyTerm) PrediTerm(nars.term.pred.PrediTerm) UnifyTerm(nars.derive.op.UnifyTerm) Term(nars.term.Term) Termed(nars.term.Termed)

Example 10 with Pair

use of org.eclipse.collections.api.tuple.Pair in project eclipse-collections by eclipse.

the class ImmutableTreeMapTest method entrySet.

@Override
public void entrySet() {
    super.entrySet();
    Interval interval = Interval.oneTo(100);
    LazyIterable<Pair<String, Integer>> pairs = interval.collect(Object::toString).zip(interval);
    MutableSortedMap<String, Integer> mutableSortedMap = new TreeSortedMap<>(pairs.toArray(new Pair[] {}));
    ImmutableSortedMap<String, Integer> immutableSortedMap = mutableSortedMap.toImmutable();
    MutableList<Map.Entry<String, Integer>> entries = FastList.newList(immutableSortedMap.castToSortedMap().entrySet());
    MutableList<Map.Entry<String, Integer>> sortedEntries = entries.toSortedListBy(Map.Entry::getKey);
    Assert.assertEquals(sortedEntries, entries);
}
Also used : TreeSortedMap(org.eclipse.collections.impl.map.sorted.mutable.TreeSortedMap) Interval(org.eclipse.collections.impl.list.Interval) Pair(org.eclipse.collections.api.tuple.Pair)

Aggregations

Pair (org.eclipse.collections.api.tuple.Pair)10 FasterList (jcog.list.FasterList)5 Term (nars.term.Term)5 Nullable (org.jetbrains.annotations.Nullable)4 List (java.util.List)3 Map (java.util.Map)3 Predicate (java.util.function.Predicate)3 Task (nars.Task)3 ObjectIntPair (org.eclipse.collections.api.tuple.primitive.ObjectIntPair)3 Person (org.eclipse.collections.impl.test.domain.Person)3 Test (org.junit.Test)3 java.util (java.util)2 Supplier (java.util.function.Supplier)2 Stream (java.util.stream.Stream)2 NAR (nars.NAR)2 Op (nars.Op)2 Param (nars.Param)2 Cause (nars.control.Cause)2 DepIndepVarIntroduction (nars.op.DepIndepVarIntroduction)2 Termed (nars.term.Termed)2