Search in sources :

Example 1 with PreciseTruth

use of nars.truth.PreciseTruth in project narchy by automenta.

the class DynTruth method eval.

/**
 * TODO make Task truth dithering optional
 */
public Truthed eval(@NotNull Term superterm, @Deprecated BiFunction<DynTruth, NAR, Truth> truthModel, boolean taskOrJustTruth, boolean beliefOrGoal, float freqRes, float confRes, float eviMin, NAR nar) {
    Truth t = truthModel.apply(this, nar);
    if (t == null)
        return null;
    float evi = t.evi();
    if (evi < eviMin)
        return null;
    // this may have already been done in truth calculation
    // //TODO compute max valid overlap to terminate the zip early
    ObjectFloatPair<long[]> ss = Stamp.zip((List) this, Param.STAMP_CAPACITY);
    // evi = evi * Param.overlapFactor(ss.getTwo());
    // if (evi < eviMin)
    // return null;
    float freq = t.freq();
    float f;
    long start, end;
    if (taskOrJustTruth) {
        if (size() > 1) {
            if (superterm.op() == CONJ) {
                long min = TIMELESS;
                long maxRange = 0;
                boolean eternals = false;
                for (int i = 0, thisSize = size(); i < thisSize; i++) {
                    LongInterval ii = get(i);
                    long iis = ii.start();
                    if (iis != ETERNAL) {
                        min = Math.min(min, iis);
                        maxRange = Math.max(maxRange, ii.end() - iis);
                    } else {
                        eternals = true;
                    }
                }
                if (eternals && min == TIMELESS) {
                    start = end = ETERNAL;
                } else {
                    assert (min != TIMELESS);
                    // if (min == Long.MAX_VALUE)
                    // start = end = ETERNAL; //all eternal
                    // else {
                    start = min;
                    end = (min + maxRange);
                }
            // }
            } else {
                // dilute the evidence in proportion to temporal sparseness for non-temporal results
                EviDensity se = new EviDensity(this);
                evi *= se.factor();
                if (evi != evi || evi < eviMin)
                    return null;
                start = se.unionStart;
                end = se.unionEnd;
            }
        } else {
            // only one task
            LongInterval only = get(0);
            start = only.start();
            end = only.end();
        }
        if (superterm.op() == NEG) {
            // unneg if constructing a task, but dont if just returning the truth
            superterm = superterm.unneg();
            f = 1f - freq;
        } else {
            f = freq;
        }
    } else {
        // not used
        start = end = XTERNAL;
        f = freq;
    }
    if (!taskOrJustTruth)
        return Truth.theDithered(f, freqRes, evi, confRes, w2cSafe(eviMin));
    // undithered until final step for max precision
    PreciseTruth tr = new PreciseTruth(f, evi, false);
    // then if the term is valid, see if it is valid for a task
    Term content = truthModel instanceof DynamicTruthModel ? ((DynamicTruthModel) truthModel).construct(superterm, this) : superterm;
    @Nullable ObjectBooleanPair<Term> r = Task.tryContent(// otherwise consider the superterm argument as the task content
    content, beliefOrGoal ? BELIEF : GOAL, !Param.DEBUG_EXTRA);
    if (r == null)
        return null;
    NALTask dyn = new DynamicTruthTask(r.getOne(), beliefOrGoal, tr.negIf(r.getTwo()).dither(freqRes, confRes, w2cSafe(eviMin)), nar, start, end, ss.getOne());
    // if (ss.getTwo() > 0) dyn.setCyclic(true);
    dyn.cause = cause();
    dyn.priSet(pri());
    if (Param.DEBUG_EXTRA)
        dyn.log("Dynamic");
    return dyn;
}
Also used : EviDensity(nars.task.EviDensity) Term(nars.term.Term) PreciseTruth(nars.truth.PreciseTruth) LongInterval(jcog.math.LongInterval) NALTask(nars.task.NALTask) Truth(nars.truth.Truth) PreciseTruth(nars.truth.PreciseTruth) Nullable(org.jetbrains.annotations.Nullable)

Example 2 with PreciseTruth

use of nars.truth.PreciseTruth in project narchy by automenta.

the class Revision method mergeTemporal.

/**
 * assumes:
 *          the tasks to be sorted in descending strength
 * the input minEvi corresponds to the absolute minimum accepted
 * evidence integral (evidence * time) for a point-like result (dtRange == 0)
 */
@Nullable
static Task mergeTemporal(float eviMinInteg, NAR nar, int results, TaskRegion... tt) {
    assert (tt.length > 1);
    Task first = tt[0].task();
    // TODO calculate the temporal density at the same time as this first part to avoid naively generating a sparse result afterward
    // TODO combine evidensity with the stamp calculation
    // TODO allow evidensity to skip a task in the array and proceed to the next without recurse
    LongHashSet evidence = new LongHashSet();
    int overlap = 0, totalEv = 0;
    int tasks = 0;
    boolean termSame = true;
    EviDensity density = new EviDensity();
    for (int i = 0; i < results; i++) {
        TaskRegion ri = tt[i];
        if (ri == null)
            continue;
        Task ti = ri.task();
        // assert (!t.isEternal());
        long[] ts = ti.stamp();
        totalEv += ts.length;
        int overlapsToAdd;
        if (tasks == 0) {
            overlapsToAdd = 0;
        } else {
            overlapsToAdd = Stamp.overlaps(evidence, ts);
            if (overlapsToAdd > 0) {
                if (totalEv > 0 && Param.overlapFactor(overlap + overlapsToAdd) < Float.MIN_NORMAL) {
                    /* current amount so far */
                    // would cause zero evidence, regardless of whatever truth is calculated later
                    tt[i] = null;
                    // skip this one
                    continue;
                }
            } else {
                if (termSame) {
                    Term termI = ti.term();
                    if ((i > 0) && !termI.equals(first.term())) {
                        if (tasks == 1 && termI.op() != CONJ) /* dont do CONJ now because it might produce an occurrence shift which isnt tracked yet */
                        {
                            // limit termpolation to max 2 tasks for now
                            // difference in terms
                            termSame = false;
                            // TODO loop dont recurse, just buffer the accumulated evidence changes to the end of the loop
                            tt = new TaskRegion[] { first, ri };
                            // cause the for-loop to end after this iteration
                            i = results;
                        // continue
                        } else {
                            // skip this term, it would conflict with the other 2+ terms which are already known to be the same
                            tt[i] = null;
                            // skip this one
                            continue;
                        }
                    }
                }
            }
        }
        density.add(ri);
        evidence.addAll(ts);
        if (tasks > 1)
            // because it may be compared against frequently
            evidence.compact();
        overlap += overlapsToAdd;
        tasks++;
    }
    if (tasks == 1) {
        // return the top one, nothing could be merged
        return first;
    }
    // dont settle for anything worse than the first (strongest) task by un-revised
    eviMinInteg = Math.max(first.eviInteg(), eviMinInteg);
    float overlapFactor = Param.overlapFactor(((float) overlap) / totalEv);
    if (overlapFactor < Float.MIN_NORMAL)
        return first;
    float densityFactor = density.factor();
    if (tasks != tt.length)
        tt = ArrayUtils.removeNulls(tt, Task[]::new);
    long start = density.unionStart;
    long end = density.unionEnd;
    long range = 1 + (end - start);
    Term content;
    float differenceFactor = 1f;
    if (!termSame) {
        Task second = tt[1].task();
        float diff = dtDiff(first.term(), second.term());
        if (!Float.isFinite(diff))
            // impossible
            return null;
        if (diff > 0)
            // proport
            differenceFactor = (float) Param.evi(1f, diff, Math.max(1, range));
        float e1 = first.eviInteg();
        float e2 = second.eviInteg();
        float firstProp = e1 / (e1 + e2);
        content = intermpolate(first.term(), second.term(), firstProp, nar);
        if (!Task.validTaskTerm(content))
            return first;
    } else {
        content = first.term();
    }
    int dur = nar.dur();
    Truth truth = new TruthPolation(start, end, dur, tt).truth(true);
    if (truth == null)
        return first;
    float factor = overlapFactor * differenceFactor * densityFactor;
    float eAdjusted = truth.evi() * factor;
    if ((eAdjusted * range) < eviMinInteg)
        return first;
    Task t = Task.tryTask(content, first.punc(), truth, (c, tr) -> {
        @Nullable PreciseTruth cTruth = tr.dither(nar, factor);
        if (cTruth == null)
            return null;
        return new NALTask(c, first.punc(), cTruth, nar.time(), start, end, Stamp.sample(Param.STAMP_CAPACITY, evidence, /* TODO account for relative evidence contributions */
        nar.random()));
    });
    if (t == null)
        return first;
    t.priSet(Priority.fund(Util.max((TaskRegion p) -> p.task().priElseZero(), tt), false, Tasked::task, tt));
    ((NALTask) t).cause = Cause.sample(Param.causeCapacity.intValue(), tt);
    if (Param.DEBUG)
        t.log("Temporal Merge");
    for (TaskRegion x : tt) {
        // forward to the revision
        x.task().meta("@", (k) -> t);
    }
    return t;
}
Also used : Task(nars.Task) Term(nars.term.Term) TaskRegion(nars.task.util.TaskRegion) LongHashSet(org.eclipse.collections.impl.set.mutable.primitive.LongHashSet) PreciseTruth(nars.truth.PreciseTruth) Truth(nars.truth.Truth) PreciseTruth(nars.truth.PreciseTruth) Nullable(org.jetbrains.annotations.Nullable) Nullable(org.jetbrains.annotations.Nullable)

Example 3 with PreciseTruth

use of nars.truth.PreciseTruth in project narchy by automenta.

the class TruthPolation method truth.

/**
 * blends any result with an eternal "background" contribution
 */
public Truth truth(@Nullable Task eternalTask) {
    Truth temporal = truth(true);
    Truth eternal = eternalTask != null ? eternalTask.truth() : null;
    if (eternal == null)
        return temporal;
    else if (temporal == null)
        return eternal;
    else {
        return Revision.revise(temporal, eternal);
    // float tempEvi = t.eviSum;
    // boolean someEvi = tempEvi > 0f;
    // if (topEternal != null) {
    // if (!someEvi) {
    // return new PreciseTruth(topEternal.truth()); //eternal the only authority
    // } else {
    // 
    // //long totalSpan = Math.max(1, t.spanEnd - t.spanStart);
    // long totalCovered = Math.max(1, t.rangeSum); //estimate
    // float temporalDensity = ((float) totalCovered) / Math.max(1, end - start);
    // float eviDecay = 1 / ((1 + tempEvi * temporalDensity));
    // 
    // float eteEvi = topEternal.evi();
    // 
    // t.accept(topEternal.freq(), eteEvi * eviDecay);
    // }
    // }
    // 
    // return !someEvi ? null : t.truth();
    }
}
Also used : Truth(nars.truth.Truth) PreciseTruth(nars.truth.PreciseTruth)

Example 4 with PreciseTruth

use of nars.truth.PreciseTruth in project narchy by automenta.

the class TruthletTask method truth.

@Nullable
public Truth truth(long when) {
    float[] tl = truthlet.truth(when);
    float f = tl[0];
    if (f != f)
        return null;
    float e = tl[1];
    if (e > 0)
        return new PreciseTruth(f, e, /* evi */
        false);
    else
        return null;
}
Also used : PreciseTruth(nars.truth.PreciseTruth) Nullable(org.jetbrains.annotations.Nullable)

Example 5 with PreciseTruth

use of nars.truth.PreciseTruth in project narchy by automenta.

the class Line1DCalibrate method main.

public static void main(String[] args) {
    Param.DEBUG = true;
    NAR n = NARS.threadSafe();
    // new STMTemporalLinkage(n, 2, false);
    n.time.dur(1);
    n.termVolumeMax.set(16);
    // n.beliefConfidence(0.9f);
    // n.goalConfidence(0.5f);
    // n.onCycle((nn) -> {
    // nn.stats(System.out);
    // });
    // n.truthResolution.setValue(0.05f);
    Line1DSimplest a = new Line1DSimplest() {

        // final FloatAveraged rewardAveraged = new FloatAveraged(()->super.act(), 10);
        @Override
        protected float act() {
            float r = super.act();
            System.out.println("reward: " + now + "\t^" + n2(i.floatValue()) + "\t@" + n2(o.floatValue()) + "\t\t= " + r);
            return r;
        }
    };
    // in time units
    float tHz = 0.05f;
    // in 0..1.0
    float yResolution = 0.1f;
    float periods = 16;
    // final int runtime = Math.round(periods / tHz);
    // Set.of(a.up.term(), a.down.term());
    Collection actions = a.actions.values();
    n.onTask(t -> {
        if (t instanceof DerivedTask) {
            if (t.isGoal()) {
                if (actions.contains(t.term())) {
                    float dir = new PreciseTruth(t.freq(), t.evi(a.nar().time(), a.nar().dur()), false).freq() - 0.5f;
                    // TEST POLARITY
                    float i = a.i.floatValue();
                    float o = a.o.floatValue();
                    float neededDir = (i - o);
                    boolean good = Math.signum(neededDir) == Math.signum(dir);
                    /*if (!good)*/
                    System.err.println(n4(dir) + "\t" + good + " " + i + " <-? " + o);
                    System.err.println(t.proof());
                    System.out.println();
                }
                if (t.isGoal())
                    System.err.println(t.proof());
            } else {
            // System.err.println(t.toString(n));
            }
        }
    });
    a.speed.set(yResolution);
    // a.up.resolution.setValue(yResolution);
    // a.down.resolution.setValue(yResolution);
    a.in.resolution(yResolution);
    a.curiosity.set(0.1f);
    // a.in.beliefs().capacity(0, 100, a.nar);
    // a.out.beliefs().capacity(0, 100, a.nar);
    // a.out.goals().capacity(0, 100, a.nar);
    // Line1DTrainer trainer = new Line1DTrainer(a);
    // new RLBooster(a, new HaiQAgent(), 5);
    // ImplicationBooster.implAccelerator(a);
    a.onFrame((z) -> {
        a.target(// Math.signum(Math.sin(a.nar.time() * tHz * 2 * PI) ) > 0 ? 1f : -1f
        Util.round((float) (0.5f + 0.5f * Math.sin(a.nar().time() * tHz * 2 * PI)), yResolution));
    // Util.pause(1);
    });
    // a.runCycles(runtime);
    // new Thread(() -> {
    // //NAgentX.chart(a);
    // int history = 800;
    // window(
    // row(
    // conceptPlot(a.nar, Lists.newArrayList(
    // () -> (float) a.i.floatValue(),
    // a.o,
    // //a.out.feedback.current!=null ? a.out.feedback.current.freq() : 0f,
    // () -> a.reward
    // //() -> a.rewardSum
    // )
    // ,
    // history),
    // col(
    // new Vis.EmotionPlot(history, a),
    // new ReflectionSurface<>(a),
    // Vis.beliefCharts(history,
    // Iterables.concat(a.sensors.keySet(), a.actions.keySet()), a.nar)
    // )
    // )
    // , 900, 900);
    // 
    // }).start();
    // n.startFPS(100);
    n.run(2000);
// n.tasks().forEach(x -> {
// if (x.isBelief() && x.op()==IMPL) {
// System.out.println(x.proof());
// }
// });
}
Also used : PreciseTruth(nars.truth.PreciseTruth) Line1DSimplest(nars.test.agent.Line1DSimplest) Collection(java.util.Collection) DerivedTask(nars.task.DerivedTask) NAR(nars.NAR)

Aggregations

PreciseTruth (nars.truth.PreciseTruth)10 Nullable (org.jetbrains.annotations.Nullable)8 Truth (nars.truth.Truth)6 Term (nars.term.Term)4 Task (nars.Task)3 NALTask (nars.task.NALTask)3 ITask (nars.task.ITask)2 TaskRegion (nars.task.util.TaskRegion)2 LongHashSet (org.eclipse.collections.impl.set.mutable.primitive.LongHashSet)2 NaN (java.lang.Float.NaN)1 Collection (java.util.Collection)1 Map (java.util.Map)1 Random (java.util.Random)1 BiConsumer (java.util.function.BiConsumer)1 Consumer (java.util.function.Consumer)1 IntConsumer (java.util.function.IntConsumer)1 IntPredicate (java.util.function.IntPredicate)1 Util (jcog.Util)1 Util.unitize (jcog.Util.unitize)1 FasterList (jcog.list.FasterList)1