Search in sources :

Example 1 with Op

use of nars.Op in project narchy by automenta.

the class DefaultConceptBuilder method unroll.

@Nullable
static DynamicTruthModel unroll(Term t) {
    DynamicTruthModel dmt = null;
    final Subterms ts = t.subterms();
    switch(t.op()) {
        case INH:
            Term subj = ts.sub(0);
            Term pred = ts.sub(1);
            Op so = subj.op();
            Op po = pred.op();
            if (dmt == null) /*&& (so.atomic || so == PROD || so.isSet())*/
            {
                if ((po == Op.SECTi) || (po == Op.SECTe) || (po == DIFFi)) {
                    // (M --> P), (M --> S), notSet(S), notSet(P), neqCom(S,P) |- (M --> (P & S)), (Belief:Intersection)
                    // (M --> P), (M --> S), notSet(S), notSet(P), neqCom(S,P) |- (M --> (P | S)), (Belief:Union)
                    // (M --> P), (M --> S), notSet(S), notSet(P), neqCom(S,P) |- (M --> (P - S)), (Belief:Difference) //intensional
                    Compound cpred = (Compound) pred;
                    int s = cpred.subs();
                    Term[] x = new Term[s];
                    for (int i = 0; i < s; i++) {
                        Term y;
                        if (!validDynamicSubterm.test(y = INH.the(subj, cpred.sub(i))))
                            return null;
                        x[i] = y;
                    }
                    switch(po) {
                        case SECTi:
                            dmt = new DynamicTruthModel.Union(x);
                            break;
                        case SECTe:
                            dmt = new DynamicTruthModel.SectIntersection(x);
                            break;
                        case DIFFi:
                            dmt = new DynamicTruthModel.Difference(x[0], x[1]);
                            break;
                    }
                }
            /*else if (so.image) {
                        Compound img = (Compound) subj;
                        Term[] ee = new Term[img.size()];

                        int relation = img.dt();
                        int s = ee.length;
                        for (int j = 1, i = 0; i < s; ) {
                            if (j == relation)
                                ee[i++] = pred;
                            if (i < s)
                                ee[i++] = img.sub(j++);
                        }
                        Compound b = compoundOrNull(INH.the(DTERNAL, img.sub(0), $.p(ee)));
                        if (b != null)
                            dmt = new DynamicTruthModel.Identity(t, b);
                    }*/
            }
            if (dmt == null) /* && (po.atomic || po == PROD || po.isSet()) */
            {
                if ((so == Op.SECTi) || (so == Op.SECTe) || (so == Op.DIFFe)) // || (subj instanceof Int.IntRange) || (so == PROD && subj.OR(Int.IntRange.class::isInstance))
                {
                    // (P --> M), (S --> M), notSet(S), notSet(P), neqCom(S,P) |- ((S | P) --> M), (Belief:Intersection)
                    // (P --> M), (S --> M), notSet(S), notSet(P), neqCom(S,P) |- ((S & P) --> M), (Belief:Union)
                    // (P --> M), (S --> M), notSet(S), notSet(P), neqCom(S,P) |- ((P ~ S) --> M), (Belief:Difference) //extensional
                    Subterms subjsubs = subj.subterms();
                    int s = subjsubs.subs();
                    Term[] x = new Term[s];
                    for (int i = 0; i < s; i++) {
                        Term y;
                        // 
                        if (!validDynamicSubterm.test(y = INH.the(subjsubs.sub(i), pred)))
                            return null;
                        x[i] = y;
                    }
                    switch(so) {
                        // case PROD:
                        case SECTi:
                            dmt = new DynamicTruthModel.SectIntersection(x);
                            break;
                        case SECTe:
                            dmt = new DynamicTruthModel.Union(x);
                            break;
                        case DIFFe:
                            dmt = new DynamicTruthModel.Difference(x[0], x[1]);
                            break;
                    }
                }
            }
            break;
        case CONJ:
            // allow variables onlyif they are not themselves direct subterms of this
            if (validDynamicSubterms(ts)) {
                dmt = DynamicTruthModel.Intersection.ConjIntersection.the;
            }
            break;
        case DIFFe:
            // root DIFFe (not subj or pred of an inh)
            if (validDynamicSubterms(ts))
                dmt = new DynamicTruthModel.Difference(ts.arrayShared());
            break;
        case NEG:
            throw new RuntimeException("negation terms can not be conceptualized as something separate from that which they negate");
    }
    return dmt;
}
Also used : Subterms(nars.subterm.Subterms) Op(nars.Op) Compound(nars.term.Compound) Term(nars.term.Term) DynamicTruthModel(nars.concept.dynamic.DynamicTruthModel) Nullable(org.jetbrains.annotations.Nullable)

Example 2 with Op

use of nars.Op in project narchy by automenta.

the class DynamicTruthBeliefTable method template.

@Nullable
protected Term template(long start, long end, Term template, NAR nar) {
    Op templateOp = template.op();
    if (this.term != null && templateOp != this.term.op())
        // template doesnt match this (quick op test)
        return null;
    int templateSubs = template.subs();
    assert (templateSubs > 1);
    boolean temporal = templateOp.temporal;
    if (temporal) {
        int d = template.dt();
        if (d == XTERNAL) {
            int e = matchDT(start, end, templateSubs > 2, nar);
            assert (e != XTERNAL);
            Term next = template.dt(e);
            if ((next.subs() < templateSubs || next.dt() == XTERNAL)) {
                /*if no dt can be calculated, return
                              0 or some non-zero value (ex: 1, end-start, etc) in case of repeating subterms. */
                int artificialDT;
                if (templateSubs == 2) {
                    if (start != end && end - start < Integer.MAX_VALUE) {
                        if (end != start) {
                            artificialDT = (int) (end - start);
                        } else {
                            artificialDT = (template.sub(0).unneg().equals(template.sub(1).unneg())) ? nar.dur() : // ok for simultaneous
                            0;
                        }
                    } else {
                        artificialDT = nar.dur();
                    }
                } else /*(if (templateSubs > 2)*/
                {
                    assert (templateSubs > 2);
                    // commutive conjunction
                    artificialDT = 0;
                }
                next = template.dt(artificialDT);
                if (next.subs() < templateSubs || next.dt() == XTERNAL) {
                    next = template;
                    if (next.subs() == 2) {
                        // possibly pulled an internal XTERNAL to the outside, so try artificializing this as well
                        int limit = 2;
                        int nextDT = XTERNAL;
                        do {
                            next = next.dt(artificialDT);
                            if (next instanceof Bool)
                                return null;
                        } while (limit-- > 0 && (nextDT = next.dt()) == XTERNAL);
                        if (nextDT == XTERNAL)
                            // give up
                            return null;
                    } else {
                        // create a random sequence of the terms, separated by artificial DT's
                        assert (templateOp == CONJ);
                        Term[] subs = template.subterms().arrayClone();
                        ArrayUtils.shuffle(subs, nar.random());
                        int dur = nar.dur();
                        next = subs[0];
                        for (int k = 1; k < subs.length; k++) {
                            next = Op.conjMerge(next, 0, subs[k], dur);
                            if (next instanceof Bool)
                                // it is probably possible to find another solution with a different shuffle
                                return null;
                        }
                    }
                }
            }
            template = next;
        }
    }
    return template;
}
Also used : Op(nars.Op) Bool(nars.term.atom.Bool) Term(nars.term.Term) Nullable(org.jetbrains.annotations.Nullable)

Example 3 with Op

use of nars.Op in project narchy by automenta.

the class Premise method match.

/**
 * resolve the most relevant belief of a given term/concept
 * <p>
 * patham9 project-eternalize
 * patham9 depending on 4 cases
 * patham9 https://github.com/opennars/opennars2/blob/a143162a559e55c456381a95530d00fee57037c4/src/nal/deriver/projection_eternalization.clj
 * sseehh__ ok ill add that in a bit
 * patham9 you need  project-eternalize-to
 * sseehh__ btw i disabled immediate eternalization entirely
 * patham9 so https://github.com/opennars/opennars2/blob/a143162a559e55c456381a95530d00fee57037c4/src/nal/deriver/projection_eternalization.clj#L31
 * patham9 especially try to understand the "temporal temporal" case
 * patham9 its using the result of higher confidence
 * <p>
 * returns ttl used, -1 if failed before starting
 *
 * @param matchTime - temporal focus control: determines when a matching belief or answer should be projected to
 */
@Nullable
public Derivation match(Derivation d, long[] focus, int matchTTL) {
    NAR n = d.nar;
    if (task == null || task.isDeleted()) {
        // }
        return null;
    }
    // n.conceptualize(task.term(), (c)->{});
    int dur = d.dur;
    Term beliefTerm = term();
    Term taskTerm = task.term();
    Term taskConcept = task.term().concept();
    final boolean[] beliefConceptCanAnswerTaskConcept = { false };
    boolean unifiedBelief = false;
    Op to = taskTerm.op();
    Op bo = beliefTerm.op();
    if (to == bo) {
        if (taskConcept.equals(beliefTerm.concept())) {
            beliefConceptCanAnswerTaskConcept[0] = true;
        } else {
            if ((bo.conceptualizable) && (beliefTerm.hasAny(var) || taskTerm.hasAny(var))) {
                Term _beliefTerm = beliefTerm;
                final Term[] unifiedBeliefTerm = new Term[] { null };
                UnifySubst u = new UnifySubst(/*null*/
                VAR_QUERY, n, (y) -> {
                    if (y.op().conceptualizable) {
                        y = y.normalize();
                        beliefConceptCanAnswerTaskConcept[0] = true;
                        if (!y.equals(_beliefTerm)) {
                            unifiedBeliefTerm[0] = y;
                            // stop
                            return false;
                        }
                    }
                    // keep going
                    return true;
                }, matchTTL);
                u.varSymmetric = true;
                u.varCommonalize = true;
                u.unify(taskTerm, beliefTerm, true);
                if (unifiedBeliefTerm[0] != null) {
                    beliefTerm = unifiedBeliefTerm[0];
                    unifiedBelief = true;
                }
            }
        }
    }
    // HACK ?? assert(beliefTerm.op()!=NEG);
    beliefTerm = beliefTerm.unneg();
    // QUESTION ANSWERING and TERMLINK -> TEMPORALIZED BELIEF TERM projection
    Task belief = null;
    // float timeFocus = n.timeFocus.floatValue();
    // int fRad = Math.round(Math.max(1,dur * timeFocus));
    final Concept beliefConcept = beliefTerm.op().conceptualizable ? // conceptualize in case of dynamic concepts
    n.conceptualize(beliefTerm) : null;
    if (beliefConcept != null) {
        if (!beliefTerm.hasVarQuery()) {
            // doesnt make sense to look for a belief in a term with query var, it will have none
            final BeliefTable bb = beliefConcept.beliefs();
            if (task.isQuestOrQuestion()) {
                if (beliefConceptCanAnswerTaskConcept[0]) {
                    final BeliefTable answerTable = (task.isGoal() || task.isQuest()) ? beliefConcept.goals() : bb;
                    // //see if belief unifies with task (in reverse of previous unify)
                    // if (questionTerm.varQuery() == 0 || (unify((Compound)beliefConcept.term(), questionTerm, nar) == null)) {
                    // 
                    // } else {
                    // 
                    // }
                    Task match = answerTable.answer(task.start(), task.end(), dur, task, beliefTerm, n, d::add);
                    if (match != null) {
                        assert (task.isQuest() || match.punc() == BELIEF) : "quest answered with a belief but should be a goal";
                        @Nullable Task answered = task.onAnswered(match, n);
                        if (answered != null) {
                            n.emotion.onAnswer(task, answered);
                        }
                        if (match.isBelief()) {
                            belief = match;
                        }
                    }
                }
            }
            if ((belief == null) && !bb.isEmpty()) {
                belief = bb.match(focus[0], focus[1], beliefTerm, n, taskConcept.equals(beliefConcept.term()) ? x -> !x.equals(task) : null);
            }
        }
        if (unifiedBelief) {
            Concept originalBeliefConcept = n.conceptualize(term());
            if (originalBeliefConcept != null)
                linkVariable(originalBeliefConcept, beliefConcept);
        }
    }
    if (belief != null) {
        // use the belief's actual possibly-temporalized term
        beliefTerm = belief.term().unneg();
    // if (belief.equals(task)) { //do not repeat the same task for belief
    // belief = null; //force structural transform; also prevents potential inductive feedback loop
    // }
    }
    if (beliefTerm instanceof Bool) {
        // logger.warn("{} produced Bool beliefTerm", this);
        return null;
    }
    if (!d.reset().proto(task, belief, beliefTerm))
        return null;
    return d;
}
Also used : Concept(nars.concept.Concept) Op(nars.Op) Task(nars.Task) Term(nars.term.Term) Bool(nars.term.atom.Bool) BeliefTable(nars.table.BeliefTable) UnifySubst(nars.term.subst.UnifySubst) NAR(nars.NAR) Nullable(org.jetbrains.annotations.Nullable) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with Op

use of nars.Op in project narchy by automenta.

the class SubIfUnify method apply.

@Override
public Term apply(/*@NotNull*/
Subterms a) {
    // parse parameters
    boolean strict = false;
    @Nullable Op op = null;
    // TODO compile at function construction time
    boolean force = false;
    int pp = a.subs();
    for (int p = 3; p < pp; p++) {
        Term ai = a.sub(p);
        if (ai.equals(Subst.STRICT))
            strict = true;
        else if (ai.equals(INDEP_VAR)) {
        // ;in this cases also dependent var elimination is fine!
        // 
        // (let [[mode check-var-type] (if (= var-symbol "$")
        // [:ind #(or (= % 'ind-var) (= % 'dep-var))]
        // [:dep #(= % 'dep-var)])
        // op = VAR_INDEP;
        } else if (ai.equals(DEP_VAR)) {
            op = VAR_DEP;
        } else if (ai.equals(Subst.FORCE))
            force = true;
        else
            throw new UnsupportedOperationException("unrecognized parameter: " + ai);
    }
    /**
     * term being transformed if x unifies with y
     */
    Term c = a.sub(0);
    // if (input instanceof Bool)return Null;
    // if (input == Null) return Null;
    Term x = a.sub(1);
    // if (x == Null) return Null;
    Term y = a.sub(2);
    if (x.equalsRoot(y)) {
        // unification would occurr but no changes would result
        return strict ? Null : c;
    }
    Term output;
    if (c.equals(x)) {
        // input equals X so it is entirely replaced by 'y'
        output = y;
    } else {
        boolean tryUnify = (op == null && x.hasAny(Op.VariableBits)) || (op != null && x.hasAny(op));
        if (!tryUnify) /* && mustSubstitute()*/
        {
            // no change
            output = null;
        } else {
            SubUnify su = new MySubUnify(op, strict);
            output = su.tryMatch(c, x, y);
            parent.use(parent.ttl - su.ttl);
        }
        if (output == null) {
            if (!force) {
                return Null;
            } else {
                // force: apply substitution even if un-unifiable
                output = c.replace(x, y);
                if (output == null)
                    return Null;
            }
        }
    }
    return (strict && c.equals(output)) ? Null : output;
}
Also used : Op(nars.Op) SubUnify(nars.term.subst.SubUnify) Term(nars.term.Term) Nullable(org.jetbrains.annotations.Nullable)

Example 5 with Op

use of nars.Op in project narchy by automenta.

the class TermKey method writeCompoundSeq.

// static void writeStringBytes(DataOutput out, String s) throws IOException {
// out.write(bytes(s));
// }
static void writeCompoundSeq(DataOutput out, Compound c, boolean includeTemporal) throws IOException {
    out.writeByte('(');
    writeTermContainerSeq(out, c.subterms(), includeTemporal);
    out.writeByte(')');
    /*@NotNull*/
    Op o = c.op();
    // put operator last
    out.writeByte(o.id);
    if (includeTemporal && o.temporal) {
        out.writeInt(c.dt());
    }
}
Also used : Op(nars.Op)

Aggregations

Op (nars.Op)36 Term (nars.term.Term)13 Subterms (nars.subterm.Subterms)11 Nullable (org.jetbrains.annotations.Nullable)8 Atomic (nars.term.atom.Atomic)4 Test (org.junit.jupiter.api.Test)4 FasterList (jcog.list.FasterList)3 NAR (nars.NAR)3 Termed (nars.term.Termed)3 Atom (nars.term.atom.Atom)3 Bool (nars.term.atom.Bool)3 Pair (org.eclipse.collections.api.tuple.Pair)3 NotNull (org.jetbrains.annotations.NotNull)3 java.io (java.io)2 java.util (java.util)2 List (java.util.List)2 Map (java.util.Map)2 Stream (java.util.stream.Stream)2 nars.$ (nars.$)2 Concept (nars.concept.Concept)2