Search in sources :

Example 31 with FasterList

use of jcog.list.FasterList in project narchy by automenta.

the class UserTest method testPutGet.

static User testPutGet(Object obj) {
    User u = new User();
    u.put("key", obj);
    List l = new FasterList();
    u.get("key", l::add);
    assertEquals(1, l.size());
    if (obj instanceof byte[]) {
        assertArrayEquals((byte[]) obj, (byte[]) l.get(0));
    } else {
        assertEquals(obj, l.get(0));
    }
    return u;
}
Also used : FasterList(jcog.list.FasterList) List(java.util.List) FasterList(jcog.list.FasterList)

Example 32 with FasterList

use of jcog.list.FasterList 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 33 with FasterList

use of jcog.list.FasterList in project narchy by automenta.

the class DeriveTime method solution.

protected Supplier<Term> solution(Term pattern, ArrayHashSet<Event> solutions) {
    int ss = solutions.size();
    if (ss == 0) {
        return () -> solveRaw(pattern);
    }
    int timed = ((FasterList) solutions.list).count(t -> t instanceof Absolute);
    if (timed > 0 && timed < ss) {
        if (// filter timeless
        solutions.removeIf(t -> t instanceof Relative))
            ss = solutions.size();
    }
    switch(ss) {
        case 0:
            return () -> solveRaw(pattern);
        case 1:
            return () -> solveThe(solutions.first());
        default:
            // return solveRandomOne(solutions);
            // FasterList<Event> solutionsCopy = new FasterList(solutions.list);
            Function<long[], Term> tt = solveMerged(solutions, d.dur);
            if (tt == null) {
                // choose one at random
                return () -> solveThe(solutions.get(random()));
            } else {
                long[] when = new long[] { TIMELESS, TIMELESS };
                Term ttt = tt.apply(when);
                if (ttt == null || when[0] == TIMELESS)
                    return null;
                return () -> {
                    d.concOcc[0] = when[0];
                    d.concOcc[1] = when[1];
                    return ttt;
                };
            }
    }
}
Also used : FasterList(jcog.list.FasterList) Term(nars.term.Term)

Example 34 with FasterList

use of jcog.list.FasterList in project narchy by automenta.

the class MatchConstraint method combineConstraints.

public static PrediTerm<Derivation> combineConstraints(AndCondition a) {
    RoaringBitmap constraints = new RoaringBitmap();
    @NotNull PrediTerm[] cond1 = a.cond;
    for (int i = 0, cl = cond1.length; i < cl; i++) {
        Term x = cond1[i];
        if (x instanceof MatchConstraint) {
            constraints.add(i);
        }
    }
    if (constraints.getCardinality() < 2) {
        return a;
    } else {
        // identify contiguous runs of constraints
        // inclusive
        List<IntIntPair> ranges = new FasterList<>(1);
        int start = -1, end = -1;
        PeekableIntIterator ii = constraints.getIntIterator();
        while (ii.hasNext()) {
            int next = ii.next();
            if (start == -1) {
                start = end = next;
            } else {
                if (next == end + 1) {
                    end++;
                } else {
                    if (end - start >= 1) {
                        // compile that range
                        ranges.add(pair(start, end));
                    }
                    // broken
                    start = -1;
                }
            }
        }
        if (end - start >= 1)
            ranges.add(pair(start, end));
        if (ranges.size() > 1)
            throw new TODO();
        IntIntPair rr = ranges.get(0);
        List<PrediTerm<Derivation>> l = new FasterList();
        int i;
        for (i = 0; i < start; i++) {
            l.add(a.cond[i]);
        }
        CompoundConstraint.the(Util.map(MatchConstraint.class::cast, MatchConstraint[]::new, ArrayUtils.subarray(a.cond, rr.getOne(), rr.getTwo() + 1))).forEach(l::add);
        i = end + 1;
        for (; i < a.cond.length; i++) {
            l.add(a.cond[i]);
        }
        return AndCondition.the((List) l);
    }
}
Also used : TODO(jcog.TODO) PrediTerm(nars.term.pred.PrediTerm) FasterList(jcog.list.FasterList) PeekableIntIterator(org.roaringbitmap.PeekableIntIterator) PrediTerm(nars.term.pred.PrediTerm) Term(nars.term.Term) Util(jcog.Util) NotNull(org.jetbrains.annotations.NotNull) NotNull(org.jetbrains.annotations.NotNull) RoaringBitmap(org.roaringbitmap.RoaringBitmap) IntIntPair(org.eclipse.collections.api.tuple.primitive.IntIntPair)

Example 35 with FasterList

use of jcog.list.FasterList in project narchy by automenta.

the class DeriveRuleProto method build.

/**
 * compiles the conditions which are necessary to activate this rule
 */
public Pair<Set<PrediTerm<PreDerivation>>, PrediTerm<Derivation>> build(PostCondition post) {
    byte puncOverride = post.puncOverride;
    TruthOperator belief = BeliefFunction.get(post.beliefTruth);
    if ((post.beliefTruth != null) && !post.beliefTruth.equals(TruthOperator.NONE) && (belief == null)) {
        throw new RuntimeException("unknown BeliefFunction: " + post.beliefTruth);
    }
    TruthOperator goal = GoalFunction.get(post.goalTruth);
    if ((post.goalTruth != null) && !post.goalTruth.equals(TruthOperator.NONE) && (goal == null)) {
        throw new RuntimeException("unknown GoalFunction: " + post.goalTruth);
    }
    // //if (puncOverride==0) {
    // if (belief!=null && goal!=null) {
    // if (!belief.single() && !goal.single()) {
    // pre.add(TaskPolarity.belief);
    // } else if (belief.single() ^ goal.single()){
    // throw new TODO();
    // }
    // } else if (belief!=null && !belief.single()) {
    // pre.add(TaskPolarity.belief);
    // } else if (goal!=null && !goal.single()) {
    // pre.add(TaskPolarity.belief);
    // }
    // TODO add more specific conditions that also work
    // }
    String beliefLabel = belief != null ? belief.toString() : "_";
    String goalLabel = goal != null ? goal.toString() : "_";
    FasterList<Term> args = new FasterList();
    args.add($.the(beliefLabel));
    args.add($.the(goalLabel));
    if (puncOverride != 0)
        args.add($.quote(((char) puncOverride)));
    Compound ii = (Compound) $.func("truth", args.toArrayRecycled(Term[]::new));
    Solve truth = (puncOverride == 0) ? new Solve.SolvePuncFromTask(ii, belief, goal) : new Solve.SolvePuncOverride(ii, puncOverride, belief, goal);
    // PREFIX
    // for ensuring uniqueness / no duplicates
    Set<PrediTerm<PreDerivation>> precon = newHashSet(4);
    addAll(precon, PRE);
    precon.addAll(this.pre);
    // //-------------------
    // below here are predicates which affect the derivation
    // SUFFIX (order already determined for matching)
    int n = 1 + this.constraints.size() + this.post.size();
    PrediTerm[] suff = new PrediTerm[n];
    int k = 0;
    suff[k++] = truth;
    for (PrediTerm p : this.constraints) {
        suff[k++] = p;
    }
    for (PrediTerm p : this.post) {
        suff[k++] = p;
    }
    return pair(precon, (PrediTerm<Derivation>) AndCondition.the(suff));
}
Also used : FasterList(jcog.list.FasterList) PrediTerm(nars.term.pred.PrediTerm) Compound(nars.term.Compound) PrediTerm(nars.term.pred.PrediTerm) Term(nars.term.Term) nars.derive.constraint(nars.derive.constraint) TruthOperator(nars.truth.func.TruthOperator)

Aggregations

FasterList (jcog.list.FasterList)48 Term (nars.term.Term)17 List (java.util.List)7 Truth (nars.truth.Truth)5 Pair (org.eclipse.collections.api.tuple.Pair)5 Nullable (org.jetbrains.annotations.Nullable)5 Map (java.util.Map)4 Predicate (java.util.function.Predicate)4 NAR (nars.NAR)4 Task (nars.Task)4 LongObjectPair (org.eclipse.collections.api.tuple.primitive.LongObjectPair)4 java.util (java.util)3 Supplier (java.util.function.Supplier)3 Util (jcog.Util)3 MapNodeGraph (jcog.data.graph.MapNodeGraph)3 NALTask (nars.task.NALTask)3 Bool (nars.term.atom.Bool)3 Test (org.junit.jupiter.api.Test)3 RoaringBitmap (org.roaringbitmap.RoaringBitmap)3 MultimapBuilder (com.google.common.collect.MultimapBuilder)2