Search in sources :

Example 1 with Functor

use of nars.term.Functor in project narchy by automenta.

the class Builtin method registerFunctors.

public static void registerFunctors(NAR nar) {
    for (Concept t : Builtin.statik) {
        nar.on(t);
    }
    nar.on(Functor.f1("varIntro", (x) -> {
        Pair<Term, Map<Term, Term>> result = DepIndepVarIntroduction.the.apply(x, nar.random());
        return result != null ? result.getOne() : Null;
    }));
    nar.on(Functor.f1((Atom) $.the("termlinkRandom"), (Term t) -> {
        @Nullable Concept c = nar.conceptualize(t);
        if (c == null)
            return Null;
        @Nullable PriReference<Term> tl = c.termlinks().sample(nar.random());
        if (tl == null)
            return Null;
        return tl.get();
    }));
    // nar.on(Functor.f("service", (TermContainer c) ->
    // $.sete(
    // nar.services().map(
    // (e) ->
    // $.p(e, $.the(e.getValue().state())))
    // .toArray(Term[]::new)
    // )
    // ));
    /**
     * subterm, but specifically inside an ellipsis. otherwise pass through
     */
    nar.on(Functor.f("esubterm", (Subterms c) -> {
        Term x = c.sub(0, null);
        if (x == null)
            return Null;
        Term index = c.sub(1, Null);
        if (index == Null)
            return Null;
        int which;
        if (index != null) {
            if (index instanceof Variable)
                return Null;
            which = $.intValue(index, -1);
            if (which < 0) {
                return Null;
            }
        } else {
            // random
            which = nar.random().nextInt(x.subs());
        }
        return x.sub(which);
    }));
    nar.on(Functor.f2((Atom) $.the("without"), (Term container, Term content) -> Op.without(container, x -> x.equals(content), nar.random())));
    nar.on(Functor.f2((Atom) $.the("withoutPosOrNeg"), (Term container, Term content) -> Op.without(container, x -> x.unneg().equals(content), nar.random())));
    /**
     * TODO rename this to 'dropAnyCommutive'
     * remove an element from a commutive conjunction (or set), at random, and try re-creating
     * the compound. wont necessarily work in all situations.
     * TODO move the type restriction to another functor to wrap this
     *
     * this also filter a single variable (depvar) from being a result
     */
    nar.on(Functor.f1((Atom) $.the("dropAnySet"), (Term t) -> {
        Op oo = t.op();
        if (oo == INT) {
            if (t instanceof Int.IntRange) {
                // select random location in the int and split either up or down
                Int.IntRange i = (Int.IntRange) t;
                Random rng = nar.random();
                if (i.min + 1 == i.max) {
                    // arity=2
                    return Int.the(rng.nextBoolean() ? i.min : i.max);
                } else if (i.min + 2 == i.max) {
                    // arity=3
                    switch(rng.nextInt(4)) {
                        case 0:
                            return Int.the(i.min);
                        case 1:
                            return Int.range(i.min, i.min + 1);
                        case 2:
                            return Int.range(i.min + 1, i.min + 2);
                        case 3:
                            return Int.the(i.max);
                        default:
                            throw new UnsupportedOperationException();
                    }
                } else {
                    int split = // midpoint, deterministic
                    (i.max + i.min) / 2;
                    // rng.nextInt(i.max-i.min-2);
                    return (rng.nextBoolean()) ? Int.range(i.min, split + 1) : Int.range(split + 1, i.max);
                }
            }
            // cant drop int by itself
            return Null;
        }
        if (!oo.in(SETi.bit | SETe.bit | SECTi.bit | SECTe.bit))
            // returning the original value may cause feedback loop in callees expcting a change in value
            return Null;
        int size = t.subs();
        switch(size) {
            case 0:
                assert (false) : "empty set impossible here";
                return Null;
            case 1:
                return Null;
            /* can't shrink below one element */
            case 2:
                int n = nar.random().nextInt(2);
                return oo.the(t.sub(n));
            default:
                Term[] y = Terms.dropRandom(nar.random(), t.subterms());
                return oo.the(y);
        }
    }));
    /**
     * depvar cleaning from commutive conj
     */
    nar.on(Functor.f1((Atom) $.the("ifConjCommNoDepVars"), (Term t) -> {
        if (!t.hasAny(VAR_DEP))
            return t;
        Op oo = t.op();
        if (oo != CONJ)
            return t;
        SortedSet<Term> s = t.subterms().toSetSorted();
        if (!s.removeIf(x -> x.unneg().op() == VAR_DEP))
            return t;
        return CONJ.the(t.dt(), s);
    }));
    /**
     * drops a random contained event, whether at first layer or below
     */
    nar.on(Functor.f1((Atom) $.the("dropAnyEvent"), (Term t) -> {
        Op oo = t.op();
        if (oo != CONJ)
            // returning the original value may cause feedback loop in callees expcting a change in value
            return Null;
        FasterList<LongObjectPair<Term>> ee = Conj.eventList(t);
        ee.remove(nar.random().nextInt(ee.size()));
        return Conj.conj(ee);
    // }
    // if (r instanceof Variable /*&& r.op()!=VAR_DEP*/)
    // return Null; //HACK dont allow returning a variable as an event during decomposition HACK TODO make more careful and return the only result if one subterm is a non-returnable variable
    // return r;
    }));
    nar.on(Functor.f2((Atom) $.the("conjEvent"), (Term c, Term when) -> {
        if (c.op() != CONJ || !(when instanceof Atom))
            return Null;
        // extract earliest or latest &| timeslice of events
        throw new TODO();
    // if (c.dt() == DTERNAL || c.dt() == 0) {
    // return c.sub(nar.random().nextInt(c.subs())); //choose a subterm at random
    // }
    // assert (c.subs() == 2);
    // int target;
    // switch (when.toString()) {
    // case "early":
    // target = 0;
    // break;
    // case "late":
    // target = 1;
    // break;
    // default:
    // throw new UnsupportedOperationException();
    // }
    // if (c.dt() < 0)
    // target = 1 - target;
    // return c.sub(target);
    }));
    /**
     * similar to without() but special handling for CONJ sub-events
     */
    nar.on(Functor.f2((Atom) $.the("conjWithout"), (Term conj, Term event) -> {
        if (conj.op() != CONJ || conj.impossibleSubTerm(event))
            return Null;
        FasterList<LongObjectPair<Term>> events = Conj.eventList(conj);
        IntArrayList found = new IntArrayList(2);
        int es = events.size();
        assert (es > 1);
        for (int i = 0; i < es; i++) {
            if (event.equalsRoot(events.get(i).getTwo())) {
                found.add(i);
            }
        }
        int fs = found.size(), r;
        switch(fs) {
            case 0:
                return Null;
            case 1:
                r = found.get(0);
                break;
            default:
                r = found.get(nar.random().nextInt(fs));
                break;
        }
        events.remove(r);
        return Conj.conj(events);
    // } else {
    // return nullToNull(Op.without(conj, event::equalsRoot, nar.random()));
    // }
    }));
    /**
     * extracts only the events preceding the specified events
     */
    nar.on(Functor.f2((Atom) $.the("conjDropIfLatest"), (Term conj, Term event) -> Conj.conjDrop(conj, event, false)));
    nar.on(Functor.f2((Atom) $.the("conjDropIfEarliest"), (Term conj, Term event) -> Conj.conjDrop(conj, event, true)));
    nar.on(Functor.f1Concept("belief", nar, (c, n) -> $.quote(n.belief(c, n.time()))));
    nar.on(Functor.f1Concept("goal", nar, (c, n) -> $.quote(n.goal(c, n.time()))));
    nar.on(f0("self", nar::self));
    nar.on(Functor.f1("the", what -> {
        if (what instanceof Atom) {
            switch(what.toString()) {
                case "sys":
                    return $.p($.quote(nar.emotion.summary()), $.quote(nar.concepts.summary()), $.quote(nar.emotion.summary()), $.quote(nar.exe.toString()));
            }
        }
        Object x = nar.concept(what);
        if (x == null)
            x = what;
        return $.quote($.p($.quote(x.getClass().toString()), $.quote(x.toString())));
    }));
    // /** slice(<compound>,<selector>)
    // selector :-
    // a specific integer value index, from 0 to compound size
    // (a,b) pair of integers, a range of indices */
    nar.on(Functor.f("slice", (args) -> {
        if (args.subs() == 2) {
            Term x = args.sub(0);
            if (x.subs() > 0) {
                int len = x.subs();
                Term index = args.sub(1);
                Op o = index.op();
                if (o == INT) {
                    // specific index
                    int i = ((Int) index).id;
                    if (i >= 0 && i < len)
                        return x.sub(i);
                    else
                        return False;
                } else if (o == PROD && index.subs() == 2) {
                    Term start = (index).sub(0);
                    if (start.op() == INT) {
                        Term end = (index).sub(1);
                        if (end.op() == INT) {
                            int si = ((Int) start).id;
                            if (si >= 0 && si < len) {
                                int ei = ((Int) end).id;
                                if (ei >= 0 && ei <= len) {
                                    if (si == ei)
                                        return Op.EmptyProduct;
                                    if (si < ei) {
                                        return $.p(Arrays.copyOfRange(x.subterms().arrayClone(), si, ei));
                                    }
                                }
                            }
                            // TODO maybe reverse order will return reversed subproduct
                            return False;
                        }
                    }
                }
            }
        }
        return null;
    }));
}
Also used : Concept(nars.concept.Concept) Atom(nars.term.atom.Atom) java.util(java.util) MathFunc(nars.op.MathFunc) Subst(nars.op.Subst) Variable(nars.term.var.Variable) nars.op.data(nars.op.data) Functor.f0(nars.term.Functor.f0) Int(nars.term.atom.Int) Op(nars.Op) Conj(nars.term.compound.util.Conj) User(jcog.User) Texts(jcog.Texts) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Pair(org.eclipse.collections.api.tuple.Pair) Concept(nars.concept.Concept) LongObjectPair(org.eclipse.collections.api.tuple.primitive.LongObjectPair) Term(nars.term.Term) ScriptException(javax.script.ScriptException) DepIndepVarIntroduction(nars.op.DepIndepVarIntroduction) Opjects(nars.op.java.Opjects) IntArrayList(org.eclipse.collections.impl.list.mutable.primitive.IntArrayList) UnifiedMap(org.eclipse.collections.impl.map.mutable.UnifiedMap) Predicate(java.util.function.Predicate) FasterList(jcog.list.FasterList) Functor(nars.term.Functor) ListFunc(nars.op.ListFunc) Terms(nars.term.Terms) Nullable(org.jetbrains.annotations.Nullable) TODO(jcog.TODO) java.io(java.io) Subterms(nars.subterm.Subterms) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) PriReference(jcog.pri.PriReference) Operator(nars.concept.Operator) Subterms(nars.subterm.Subterms) Op(nars.Op) TODO(jcog.TODO) Variable(nars.term.var.Variable) FasterList(jcog.list.FasterList) Term(nars.term.Term) PriReference(jcog.pri.PriReference) Atom(nars.term.atom.Atom) Int(nars.term.atom.Int) IntArrayList(org.eclipse.collections.impl.list.mutable.primitive.IntArrayList) Pair(org.eclipse.collections.api.tuple.Pair) LongObjectPair(org.eclipse.collections.api.tuple.primitive.LongObjectPair)

Example 2 with Functor

use of nars.term.Functor in project narchy by automenta.

the class NAR method stats.

/**
 * creates a snapshot statistics object
 * TODO extract a Method Object holding the snapshot stats with the instances created below as its fields
 */
public SortedMap<String, Object> stats() {
    LongSummaryStatistics beliefs = new LongSummaryStatistics();
    LongSummaryStatistics goals = new LongSummaryStatistics();
    LongSummaryStatistics questions = new LongSummaryStatistics();
    LongSummaryStatistics quests = new LongSummaryStatistics();
    Histogram termlinkCount = new Histogram(1);
    Histogram tasklinkCount = new Histogram(1);
    // Frequency complexity = new Frequency();
    HashBag clazz = new HashBag();
    HashBag policy = new HashBag();
    HashBag rootOp = new HashBag();
    ShortCountsHistogram volume = new ShortCountsHistogram(2);
    // AtomicInteger i = new AtomicInteger(0);
    // LongSummaryStatistics termlinksCap = new LongSummaryStatistics();
    // LongSummaryStatistics tasklinksCap = new LongSummaryStatistics();
    SortedMap<String, Object> x = new TreeMap();
    synchronized (exe) {
        concepts().filter(xx -> !(xx instanceof Functor)).forEach(c -> {
            // complexity.addValue(c.complexity());
            volume.recordValue(c.volume());
            rootOp.add(c.op());
            clazz.add(c.getClass().toString());
            ConceptState p = c.state();
            policy.add(p != null ? p.toString() : "null");
            // termlinksCap.accept(c.termlinks().capacity());
            termlinkCount.recordValue(c.termlinks().size());
            // tasklinksCap.accept(c.tasklinks().capacity());
            tasklinkCount.recordValue(c.tasklinks().size());
            beliefs.accept(c.beliefs().size());
            goals.accept(c.goals().size());
            questions.accept(c.questions().size());
            quests.accept(c.quests().size());
        });
        // x.put("time real", new Date());
        if (loop.isRunning()) {
            loop.stats("loop", x);
        }
        x.put("time", time());
        // x.put("term index", terms.summary());
        x.put("concept count", concepts.size());
    }
    x.put("belief count", ((double) beliefs.getSum()));
    x.put("goal count", ((double) goals.getSum()));
    Util.decode(tasklinkCount, "tasklink count", 4, x::put);
    // x.put("tasklink usage", ((double) tasklinkCount.getTotalCount()) / tasklinksCap.getSum());
    x.put("tasklink total", ((double) tasklinkCount.getTotalCount()));
    Util.decode(termlinkCount, "termlink count", 4, x::put);
    // x.put("termlink usage", ((double) termlinkCount.getTotalCount()) / termlinksCap.getSum());
    x.put("termlink total", ((double) termlinkCount.getTotalCount()));
    // DoubleSummaryStatistics pos = new DoubleSummaryStatistics();
    // DoubleSummaryStatistics neg = new DoubleSummaryStatistics();
    // causes.forEach(c -> pos.accept(c.pos()));
    // causes.forEach(c -> neg.accept(c.neg()));
    // x.put("value count", pos.getCount());
    // x.put("value pos mean", pos.getAverage());
    // x.put("value pos min", pos.getMin());
    // x.put("value pos max", pos.getMax());
    // x.put("value neg mean", neg.getAverage());
    // x.put("value neg min", neg.getMin());
    // x.put("value neg max", neg.getMax());
    // x.put("volume mean", volume.);
    // 
    // x.put("termLinksCapacity", termlinksCap);
    // x.put("taskLinksUsed", tasklinksUsed);
    // x.put("taskLinksCapacity", tasklinksCap);
    Util.toMap(policy, "concept state", x::put);
    Util.toMap(rootOp, "concept op", x::put);
    Util.decode(volume, "concept volume", 4, x::put);
    Util.toMap(clazz, "concept class", x::put);
    x.put("term cache (eternal)", Op.cache.summary());
    x.put("term cache (temporal)", Op.cacheTemporal.summary());
    return x;
}
Also used : Atom(nars.term.atom.Atom) Ansi(org.fusesource.jansi.Ansi) GZIPInputStream(java.util.zip.GZIPInputStream) Exec(nars.exe.Exec) ConceptBuilder(nars.concept.util.ConceptBuilder) MutableInteger(jcog.math.MutableInteger) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) ConceptState(nars.concept.util.ConceptState) Truth(nars.truth.Truth) HashBag(org.eclipse.collections.impl.bag.mutable.HashBag) Op(nars.Op) Topic(jcog.event.Topic) ListTopic(jcog.event.ListTopic) TaskConcept(nars.concept.TaskConcept) TruthFunctions.c2w(nars.truth.TruthFunctions.c2w) Term(nars.term.Term) Longs(com.google.common.primitives.Longs) TriConsumer(jcog.util.TriConsumer) ShortToObjectFunction(org.eclipse.collections.api.block.function.primitive.ShortToObjectFunction) Twin(org.eclipse.collections.api.tuple.Twin) Service(jcog.Service) PreciseTruth(nars.truth.PreciseTruth) Functor.f(nars.term.Functor.f) Util(jcog.Util) BeliefTable(nars.table.BeliefTable) Nullable(org.jetbrains.annotations.Nullable) Stream(java.util.stream.Stream) ConceptIndex(nars.index.term.ConceptIndex) GZIPOutputStream(java.util.zip.GZIPOutputStream) java.util.function(java.util.function) NotNull(org.jetbrains.annotations.NotNull) Operator(nars.concept.Operator) nars.control(nars.control) java.util(java.util) Tense(nars.time.Tense) Prioritized(jcog.pri.Prioritized) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ShortCountsHistogram(org.HdrHistogram.ShortCountsHistogram) ETERNAL(nars.time.Tense.ETERNAL) AtomicReference(java.util.concurrent.atomic.AtomicReference) InvalidTaskException(nars.task.util.InvalidTaskException) nars.$.$(nars.$.$) Pri(jcog.pri.Pri) On(jcog.event.On) Cycles(nars.util.Cycles) Pair(org.eclipse.collections.api.tuple.Pair) Concept(nars.concept.Concept) Time(nars.time.Time) Ansi.ansi(org.fusesource.jansi.Ansi.ansi) NarseseException(nars.Narsese.NarseseException) Logger(org.slf4j.Logger) FasterList(jcog.list.FasterList) Functor(nars.term.Functor) Cycler(jcog.exe.Cycler) ITask(nars.task.ITask) NALTask(nars.task.NALTask) Histogram(org.HdrHistogram.Histogram) ArrayIterator(jcog.util.ArrayIterator) java.io(java.io) Subterms(nars.subterm.Subterms) Atomic(nars.term.atom.Atomic) Termed(nars.term.Termed) Services(jcog.Services) HashBag(org.eclipse.collections.impl.bag.mutable.HashBag) ShortCountsHistogram(org.HdrHistogram.ShortCountsHistogram) Histogram(org.HdrHistogram.Histogram) ShortCountsHistogram(org.HdrHistogram.ShortCountsHistogram) ConceptIndex(nars.index.term.ConceptIndex) Functor(nars.term.Functor) ConceptState(nars.concept.util.ConceptState)

Aggregations

java.io (java.io)2 java.util (java.util)2 FasterList (jcog.list.FasterList)2 Op (nars.Op)2 Concept (nars.concept.Concept)2 Operator (nars.concept.Operator)2 Subterms (nars.subterm.Subterms)2 Functor (nars.term.Functor)2 Longs (com.google.common.primitives.Longs)1 URL (java.net.URL)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 java.util.function (java.util.function)1 Predicate (java.util.function.Predicate)1 Stream (java.util.stream.Stream)1 GZIPInputStream (java.util.zip.GZIPInputStream)1 GZIPOutputStream (java.util.zip.GZIPOutputStream)1 ScriptException (javax.script.ScriptException)1 Service (jcog.Service)1 Services (jcog.Services)1