Search in sources :

Example 1 with FasterList

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

the class ConjClustering method next.

@Override
protected int next(NAR nar, int work) /* max tasks generated per centroid, >=1 */
{
    if (bag.bag.isEmpty())
        // done for cycle
        return -1;
    this.now = nar.time();
    this.dur = nar.dur();
    this.ditherTime = nar.dtDitherCycles();
    this.confMin = nar.confMin.floatValue();
    this.volMax = Math.round(nar.termVolumeMax.intValue() * termVolumeMaxFactor);
    this.taskLimitPerCentroid = Math.max(1, Math.round(((float) work) / bag.net.centroids.length));
    int generatedExpectation = work * bag.net.centroids.length;
    float forgetRate = 1f - Util.unitize(((float) generatedExpectation) / bag.bag.capacity());
    bag.bag.commit(t -> {
        if (t.get().isDeleted())
            t.delete();
        else
            t.priMult(forgetRate);
    });
    if (!bag.bag.isEmpty()) {
        FasterList gen = new FasterList(generatedExpectation);
        bag.commitGroups(1, Tuples.pair(nar, gen), this::conjoinCentroid);
        int gs = gen.size();
        if (gs > 0) {
            in.input(gen);
            return (int) Math.ceil(((float) gs) / bag.net.centroids.length);
        }
    }
    return 0;
}
Also used : FasterList(jcog.list.FasterList)

Example 2 with FasterList

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

the class ConjClustering method conjoinCentroid.

// /**
// * produces a parallel conjunction term consisting of all the task's terms
// */
// public Stream<List<Task>> chunk(Stream<Task> input, int maxComponentsPerTerm, int maxVolume) {
// final int[] group = {0};
// final int[] subterms = {0};
// final int[] currentVolume = {0};
// final float[] currentConf = {1};
// return input.filter(x -> !x.isDeleted())
// .collect(Collectors.groupingBy(x -> {
// 
// int v = x.volume();
// float c = x.conf();
// 
// if ((subterms[0] >= maxComponentsPerTerm) || (currentVolume[0] + v >= maxVolume) || (currentConf[0] * c < confMin)) {
// //next group
// group[0]++;
// subterms[0] = 1;
// currentVolume[0] = v;
// currentConf[0] = c;
// } else {
// subterms[0]++;
// currentVolume[0] += v;
// currentConf[0] *= c;
// }
// 
// return group[0];
// }))
// .entrySet().stream()
// .map(c -> {
// List<Task> v = c.getValue();
// return c.getKey() >= 0 && //only batches of >1
// v.size() > 1 ? v : null;  //ignore the -1 discard group
// })
// .filter(Objects::nonNull);
// 
// }
// static final BiFunction<Task, Task, Task> termPointMerger = (prevZ, newZ) -> ((prevZ == null) || (newZ.conf() >= prevZ.conf())) ?
// newZ : prevZ;
private List<Task> conjoinCentroid(Stream<VLink<Task>> group, Pair<NAR, List<Task>> narAndTarget) {
    NAR nar = narAndTarget.getOne();
    // get only the maximum confidence task for each term at its given starting time
    // in.input(
    // chunk(group.filter(Objects::nonNull).takeWhile(kontinue)
    // .map(x -> x.id), maxConjSize, volMax).takeWhile(kontinue).map(tasks -> {
    Iterator<VLink<Task>> gg = group.filter(x -> x != null && !x.isDeleted()).iterator();
    // Iterators.peekingIterator();
    Map<LongObjectPair<Term>, Task> vv = new HashMap<>();
    FasterList<Task> actualTasks = new FasterList();
    int centroidGen = 0;
    List<Task> gen = narAndTarget.getTwo();
    main: while (gg.hasNext() && centroidGen < taskLimitPerCentroid) {
        vv.clear();
        actualTasks.clear();
        long end = Long.MIN_VALUE;
        long start = Long.MAX_VALUE;
        int dur = nar.dur();
        float freq = 1f;
        float conf = 1f;
        float priMax = Float.NEGATIVE_INFINITY, priMin = Float.POSITIVE_INFINITY;
        int vol = 0;
        int maxVolume = 0;
        do {
            if (!gg.hasNext())
                break;
            Task t = gg.next().id;
            // gg.peek().id;
            Term xt = t.term();
            long zs = Tense.dither(t.start(), ditherTime);
            long ze = Tense.dither(t.end(), ditherTime);
            // assert (end >= start);
            Truth tx = t.truth();
            Term xtn = xt.neg();
            if (tx.isNegative()) {
                xt = xtn;
            }
            int xtv = xt.volume();
            maxVolume = Math.max(maxVolume, xt.volume());
            if (vol + xtv + 1 >= volMax || conf * tx.conf() < confMin) {
                // cant go any further with this task
                continue;
            }
            boolean involved = false;
            LongObjectPair<Term> ps = pair(zs, xt);
            Term xtNeg = xt.neg();
            if (!vv.containsKey(pair(zs, xtNeg)) && null == vv.putIfAbsent(ps, t)) {
                vol += xtv;
                if (start > zs)
                    start = zs;
                if (end < zs)
                    end = zs;
                involved = true;
            }
            if (ze - zs >= dur) {
                // endpoint
                if (vol + xtv + 1 < volMax) {
                    LongObjectPair<Term> pe = pair(ze, xt);
                    if (!vv.containsKey(pair(ze, xtNeg)) && null == vv.putIfAbsent(pe, t)) {
                        // end point, if different from start
                        vol += xtv;
                        if (end < ze)
                            end = ze;
                        involved = true;
                    }
                }
            }
            if (involved) {
                actualTasks.add(t);
                conf *= tx.conf();
                float tf = tx.freq();
                // since it will appear as a negated subterm
                freq *= tx.isNegative() ? (1f - tf) : tf;
                float p = t.priElseZero();
                if (p < priMin)
                    priMin = p;
                if (p > priMax)
                    priMax = p;
            }
        } while (vol < volMax - 1 && conf > confMin);
        int vs = actualTasks.size();
        if (vs < 2)
            continue;
        // the tasks which are actually involved
        Task[] uu = actualTasks.toArrayRecycled(Task[]::new);
        // TODO discount based on evidential overlap? needs N-way overlapFraction function
        ObjectFloatPair<long[]> evidence = Stamp.zip(actualTasks, Param.STAMP_CAPACITY);
        float overlap = evidence.getTwo();
        float e = c2w(conf) * Param.overlapFactor(overlap);
        if (e > 0) {
            final Truth t = Truth.theDithered(freq, e, nar);
            if (t != null) {
                Term cj = Conj.conj(vv.keySet());
                if (cj != null) {
                    cj = cj.normalize();
                    if (Math.abs(cj.dtRange() - (end - start)) < ditherTime) {
                        // test if merge collapse occurred and occurrence time needs recalculated
                        ObjectBooleanPair<Term> cp = Task.tryContent(cj, punc, true);
                        if (cp != null) {
                            // TODO use a truth calculated specific to this fixed-size batch, not all the tasks combined
                            NALTask m = new STMClusterTask(cp, t, start, start, evidence.getOne(), punc, now);
                            // if (evidence.getTwo() > 0) m.setCyclic(true);
                            m.cause = Cause.sample(Param.causeCapacity.intValue(), uu);
                            float p = // priMax;
                            priMin;
                            // (priMin + priMax) / 2f;
                            // complexity deduction
                            // how much more complex the conjunction is than the most complex of its ingredients
                            int v = cp.getOne().volume();
                            float cmplFactor = ((float) v) / (v + maxVolume);
                            m.priSet(Priority.fund(p * cmplFactor, true, uu));
                            gen.add(m);
                            centroidGen++;
                        }
                    } else {
                    // System.out.println("merge collapse, recalcu");
                    }
                }
            }
        }
    }
    return gen.isEmpty() ? null : gen;
}
Also used : Tense(nars.time.Tense) Causable(nars.exe.Causable) ObjectFloatPair(org.eclipse.collections.api.tuple.primitive.ObjectFloatPair) HashMap(java.util.HashMap) VLink(jcog.pri.VLink) InvalidTaskException(nars.task.util.InvalidTaskException) Truth(nars.truth.Truth) Conj(nars.term.compound.util.Conj) Map(java.util.Map) PrimitiveTuples.pair(org.eclipse.collections.impl.tuple.primitive.PrimitiveTuples.pair) Tuples(org.eclipse.collections.impl.tuple.Tuples) Pair(org.eclipse.collections.api.tuple.Pair) LongObjectPair(org.eclipse.collections.api.tuple.primitive.LongObjectPair) TruthFunctions.c2w(nars.truth.TruthFunctions.c2w) Term(nars.term.Term) Iterator(java.util.Iterator) ObjectBooleanPair(org.eclipse.collections.api.tuple.primitive.ObjectBooleanPair) Predicate(java.util.function.Predicate) FasterList(jcog.list.FasterList) Stamp(nars.truth.Stamp) Util(jcog.Util) ITask(nars.task.ITask) NALTask(nars.task.NALTask) Priority(jcog.pri.Priority) Param(nars.Param) Nullable(org.jetbrains.annotations.Nullable) Task(nars.Task) List(java.util.List) Stream(java.util.stream.Stream) NAR(nars.NAR) BagClustering(nars.bag.BagClustering) Cause(nars.control.Cause) CauseChannel(nars.control.CauseChannel) ITask(nars.task.ITask) NALTask(nars.task.NALTask) Task(nars.Task) HashMap(java.util.HashMap) FasterList(jcog.list.FasterList) Term(nars.term.Term) VLink(jcog.pri.VLink) LongObjectPair(org.eclipse.collections.api.tuple.primitive.LongObjectPair) ObjectBooleanPair(org.eclipse.collections.api.tuple.primitive.ObjectBooleanPair) ObjectFloatPair(org.eclipse.collections.api.tuple.primitive.ObjectFloatPair) NALTask(nars.task.NALTask) NAR(nars.NAR) Truth(nars.truth.Truth)

Example 3 with FasterList

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

the class RLBooster method accept.

@Override
public void accept(NAR ignored) {
    // TODO provide actual action vector, not what it thinks it enacted by itself
    // NAgent's happiness value, normalized to -1..+1
    float reward = (env.happy.asFloat() - 0.5f) * 2f;
    int O = rl.act(reward, input());
    // System.out.println(now + " "  + o + " " + a.o.floatValue() + " " + " " + a.rewardValue);
    float OFFfreq = 0f;
    // = Float.NaN;
    NAR nar = env.nar();
    long start = env.last;
    long end = env.now;
    // int dur = nar.dur();
    List<Task> e = new FasterList(actions.length);
    for (int o = 0; o < actions.length; o++) {
        Truth off = OFFfreq == OFFfreq ? $.t(OFFfreq, conf.floatValue()) : null;
        // float value = actionDiscretization==1 ? 1f /* full */ :
        // ((float)(j)) / (actionDiscretization-1);
        float value = 1f;
        Truth tK;
        if (o == O) {
            tK = $.t(value, conf.floatValue());
        } else {
            // cancel all other concept goal signals
            tK = off;
        }
        Task tt = new SignalTask(actions[o].term(), GOAL, tK, start, start, end, nar.time.nextStamp());
        if (tt != null)
            e.add(tt);
    }
    in.input(e);
}
Also used : SignalTask(nars.task.signal.SignalTask) ITask(nars.task.ITask) Task(nars.Task) FasterList(jcog.list.FasterList) SignalTask(nars.task.signal.SignalTask) NAR(nars.NAR) Truth(nars.truth.Truth)

Example 4 with FasterList

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

the class EternalTable method setCapacity.

public void setCapacity(int c) {
    int wasCapacity = this.capacity();
    if (wasCapacity != c) {
        List<Task> trash = null;
        synchronized (this) {
            // just to be sure
            wasCapacity = capacity();
            int s = size;
            if (s > c) {
                // TODO can be accelerated by batch/range remove operation
                trash = new FasterList(s - c);
                while (c < s--) {
                    trash.add(removeLast());
                }
            }
            if (wasCapacity != c)
                resize(c);
        }
        // do this outside of the synch
        if (trash != null) {
            // Task s = strongest();
            // if (s!=null) {
            // TaskLink.GeneralTaskLink sl = new TaskLink.GeneralTaskLink(s, 0);
            // trash.forEach(t -> ((NALTask)t).delete(sl));
            // } else {
            trash.forEach(Task::delete);
        // }
        }
    }
}
Also used : NALTask(nars.task.NALTask) Task(nars.Task) FasterList(jcog.list.FasterList)

Example 5 with FasterList

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

the class RTreeBeliefTable method add.

@Override
public boolean add(Task x, TaskConcept c, NAR n) {
    if (capacity() == 0)
        return false;
    float incoming = x.priElseZero();
    List<Tasked> added = new FasterList<>(2);
    write(treeRW -> {
        if (treeRW.add(x)) {
            if (!x.isDeleted()) {
                added.add(x);
                ensureCapacity(treeRW, x, added::add, n);
            }
        }
    });
    for (int i = 0, addedSize = added.size(); i < addedSize; i++) {
        Task y = added.get(i).task();
        if (y != null) {
            // completely activate a temporal task being stored in this table
            float pri = y.pri();
            if (pri == pri) {
                Tasklinks.linkTask(y, pri, c, n);
            }
        } else {
        // eternal task input already done by calling the .task() method. it willl have returned null
        }
    }
    if (x.isDeleted()) {
        Task xisting = x.meta("merge");
        if (xisting != null) {
            // use incoming priority but the existing task instance
            Tasklinks.linkTask(xisting, incoming, c, n);
        }
        return false;
    } else {
        return true;
    }
}
Also used : SignalTask(nars.task.signal.SignalTask) NALTask(nars.task.NALTask) Task(nars.Task) FasterList(jcog.list.FasterList) Tasked(nars.task.Tasked)

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