Search in sources :

Example 1 with Term

use of nars.language.Term in project opennars by opennars.

the class PerceptionAccel method perceive.

public void perceive(DerivationContext nal) {
    // implement Peis idea here now
    // we start with length 2 compounds, and search for patterns which are one longer than the longest observed one
    boolean longest_result_derived_already = false;
    for (int Len = cur_maxlen + 1; Len >= 2; Len--) {
        // ok, this is the length we have to collect, measured from the end of event buffer
        // there is a interval term for every event
        Term[] relterms = new Term[2 * Len - 1];
        // measuring its distance to the next event, but for the last event this is obsolete
        // thus it are 2*Len-1] terms
        Task newEvent = eventbuffer.get(eventbuffer.size() - 1);
        TruthValue truth = newEvent.sentence.truth;
        Stamp st = new Stamp(nal.memory);
        ArrayList<Long> evBase = new ArrayList<Long>();
        int k = 0;
        for (int i = 0; i < Len; i++) {
            // we go till to the end of the event buffer
            int j = eventbuffer.size() - 1 - (Len - 1) + i;
            if (j < 0) {
                // but the mechanism already looks for length 2 patterns on the occurence of the first event
                break;
            }
            Task current = eventbuffer.get(j);
            for (long l : current.sentence.stamp.evidentialBase) {
                evBase.add(l);
            }
            relterms[k] = current.sentence.term;
            if (i != Len - 1) {
                // if its not the last one, then there is a next one for which we have to put an interval
                truth = TruthFunctions.deduction(truth, current.sentence.truth);
                Task next = eventbuffer.get(j + 1);
                relterms[k + 1] = new Interval(next.sentence.getOccurenceTime() - current.sentence.getOccurenceTime());
            }
            k += 2;
        }
        long[] evB = new long[evBase.size()];
        int u = 0;
        for (long l : evBase) {
            evB[u] = l;
            u++;
        }
        st.baseLength = evB.length;
        st.evidentialBase = evB;
        boolean eventBufferDidNotHaveSoMuchEvents = false;
        for (int i = 0; i < relterms.length; i++) {
            if (relterms[i] == null) {
                eventBufferDidNotHaveSoMuchEvents = true;
            }
        }
        if (eventBufferDidNotHaveSoMuchEvents) {
            continue;
        }
        // decide on the tense of &/ by looking if the first event happens parallel with the last one
        // Todo refine in 1.6.3 if we want to allow input of difference occurence time
        boolean after = newEvent.sentence.stamp.after(eventbuffer.get(eventbuffer.size() - 1 - (Len - 1)).sentence.stamp, Parameters.DURATION);
        // critical part: (not checked for correctness yet):
        // we now have to look at if the first half + the second half already exists as concept, before we add it
        Term[] firstHalf;
        Term[] secondHalf;
        if (relterms[Len - 1] instanceof Interval) {
            // the middle can be a interval, for example in case of a,+1,b , in which case we dont use it
            // so we skip the middle here
            firstHalf = new Term[Len - 1];
            // as well as here
            secondHalf = new Term[Len - 1];
            // make index mapping easier by counting
            int h = 0;
            for (int i = 0; i < Len - 1; i++) {
                firstHalf[i] = relterms[h];
                h++;
            }
            // we have to overjump the middle element this is why
            h += 1;
            for (int i = 0; i < Len - 1; i++) {
                secondHalf[i] = relterms[h];
                h++;
            }
        } else {
            // it is a event so its fine
            // 2*Len-1 in total
            firstHalf = new Term[Len];
            // but the middle is also used in the second one
            secondHalf = new Term[Len];
            // make index mapping easier by counting
            int h = 0;
            for (int i = 0; i < Len; i++) {
                firstHalf[i] = relterms[h];
                h++;
            }
            // we have to use the middle twice this is why
            h--;
            for (int i = 0; i < Len; i++) {
                secondHalf[i] = relterms[h];
                h++;
            }
        }
        Term firstC = Conjunction.make(firstHalf, after ? ORDER_FORWARD : ORDER_CONCURRENT);
        Term secondC = Conjunction.make(secondHalf, after ? ORDER_FORWARD : ORDER_CONCURRENT);
        Concept C1 = nal.memory.concept(firstC);
        Concept C2 = nal.memory.concept(secondC);
        if (C1 == null || C2 == null) {
            if (debugMechanism) {
                System.out.println("one didn't exist: " + firstC.toString() + " or " + secondC.toString());
            }
            // the components were not observed, so don't allow creating this compound
            continue;
        }
        if (C1.getPriority() < partConceptsPrioThreshold || C2.getPriority() < partConceptsPrioThreshold) {
            // too less priority
            continue;
        }
        Conjunction C = (Conjunction) Conjunction.make(relterms, after ? ORDER_FORWARD : ORDER_CONCURRENT);
        // importance "summation"
        Sentence S = new Sentence(C, Symbols.JUDGMENT_MARK, truth, st);
        Task T = new Task(S, new BudgetValue(BudgetFunctions.or(C1.getPriority(), C2.getPriority()), Parameters.DEFAULT_JUDGMENT_DURABILITY, truth), true);
        if (debugMechanism) {
            System.out.println("success: " + T.toString());
        }
        if (longest_result_derived_already) {
            T.setElemOfSequenceBuffer(false);
        }
        longest_result_derived_already = true;
        // lets make the new event the parent task, and derive it
        nal.derivedTask(T, false, false, false);
    }
}
Also used : Concept(nars.entity.Concept) BudgetValue(nars.entity.BudgetValue) Task(nars.entity.Task) Stamp(nars.entity.Stamp) ArrayList(java.util.ArrayList) Term(nars.language.Term) TruthValue(nars.entity.TruthValue) Conjunction(nars.language.Conjunction) Sentence(nars.entity.Sentence) Interval(nars.language.Interval)

Example 2 with Term

use of nars.language.Term in project opennars by opennars.

the class GlobalAnticipation method temporalPredictionsAdapt.

// check all predictive statements, match them with last events
public void temporalPredictionsAdapt(DerivationContext nal) {
    if (TEMPORAL_PREDICTION_FEEDBACK_ACCURACY_DIV == 0.0f) {
        return;
    }
    ArrayList<Task> lastEvents = new ArrayList<Task>();
    for (Task stmLast : stm) {
        lastEvents.add(stmLast);
    }
    if (lastEvents.isEmpty()) {
        return;
    }
    final long duration = Parameters.DURATION;
    ArrayList<Task> derivetasks = new ArrayList<Task>();
    for (final Task c : current_tasks) {
        // a =/> b or (&/ a1...an) =/> b
        boolean concurrent_conjunction = false;
        Term[] args = new Term[1];
        Implication imp = (Implication) c.sentence.term.clone();
        boolean concurrent_implication = imp.getTemporalOrder() == TemporalRules.ORDER_CONCURRENT;
        args[0] = imp.getSubject();
        if (imp.getSubject() instanceof Conjunction) {
            Conjunction conj = (Conjunction) imp.getSubject();
            if (!conj.isSpatial) {
                if (conj.temporalOrder == TemporalRules.ORDER_FORWARD || conj.temporalOrder == TemporalRules.ORDER_CONCURRENT) {
                    concurrent_conjunction = conj.temporalOrder == TemporalRules.ORDER_CONCURRENT;
                    // in case of &/ this are the terms
                    args = conj.term;
                }
            }
        }
        int i = 0;
        boolean matched = true;
        int off = 0;
        long expected_time = lastEvents.get(0).sentence.getOccurenceTime();
        for (i = 0; i < args.length; i++) {
            // handling of intervals:
            if (args[i] instanceof Interval) {
                if (!concurrent_conjunction) {
                    expected_time += ((Interval) args[i]).time;
                }
                off++;
                continue;
            }
            if (i - off >= lastEvents.size()) {
                break;
            }
            if (!Variables.hasSubstitute(Symbols.VAR_INDEPENDENT, args[i], lastEvents.get(i - off).sentence.term)) {
                // it didnt match, instead sth different unexpected happened
                // whether intermediate events should be tolerated or not was a important question when considering this,
                matched = false;
                // if it should be allowed, the sequential match does not matter only if the events come like predicted.
                break;
            } else {
                if (lastEvents.get(i - off).sentence.truth.getExpectation() <= 0.5f) {
                    // it matched according to sequence, but is its expectation bigger than 0.5? todo: decide how truth values of the expected events
                    // it didn't happen
                    matched = false;
                    break;
                }
                long occurence = lastEvents.get(i - off).sentence.getOccurenceTime();
                boolean right_in_time = Math.abs(occurence - expected_time) < ((double) duration) / TEMPORAL_PREDICTION_FEEDBACK_ACCURACY_DIV;
                if (!right_in_time) {
                    // it matched so far, but is the timing right or did it happen when not relevant anymore?
                    matched = false;
                    break;
                }
            }
            if (!concurrent_conjunction) {
                expected_time += duration;
            }
        }
        if (concurrent_conjunction && !concurrent_implication) {
            // implication is not concurrent
            // so here we have to add duration
            expected_time += duration;
        } else if (!concurrent_conjunction && concurrent_implication) {
            expected_time -= duration;
        }
        // ok it matched, is the consequence also right?
        if (matched && lastEvents.size() > args.length - off) {
            long occurence = lastEvents.get(args.length - off).sentence.getOccurenceTime();
            boolean right_in_time = Math.abs(occurence - expected_time) < ((double) duration) / TEMPORAL_PREDICTION_FEEDBACK_ACCURACY_DIV;
            if (right_in_time && Variables.hasSubstitute(Symbols.VAR_INDEPENDENT, imp.getPredicate(), lastEvents.get(args.length - off).sentence.term)) {
                // it matched and same consequence, so positive evidence
                // c.sentence.truth=TruthFunctions.revision(c.sentence.truth, new TruthValue(1.0f,Parameters.DEFAULT_JUDGMENT_CONFIDENCE));
                Sentence s2 = new Sentence(c.sentence.term.clone(), Symbols.JUDGMENT_MARK, new TruthValue(1.0f, Parameters.DEFAULT_JUDGMENT_CONFIDENCE), new Stamp(nal.memory));
                Task t = new Task(s2, new BudgetValue(Parameters.DEFAULT_JUDGMENT_PRIORITY, Parameters.DEFAULT_JUDGMENT_DURABILITY, s2.truth), true);
                derivetasks.add(t);
            } else {
                // it matched and other consequence, so negative evidence
                // c.sentence.truth=TruthFunctions.revision(c.sentence.truth, new TruthValue(0.0f,Parameters.DEFAULT_JUDGMENT_CONFIDENCE));
                Sentence s2 = new Sentence(c.sentence.term.clone(), Symbols.JUDGMENT_MARK, new TruthValue(0.0f, Parameters.DEFAULT_JUDGMENT_CONFIDENCE), new Stamp(nal.memory));
                Task t = new Task(s2, new BudgetValue(Parameters.DEFAULT_JUDGMENT_PRIORITY, Parameters.DEFAULT_JUDGMENT_DURABILITY, s2.truth), true);
                derivetasks.add(t);
            }
        // todo use derived task with revision instead
        }
    }
    for (Task t : derivetasks) {
        if (nal.derivedTask(t, false, false, false)) {
            boolean debug = true;
        }
    }
    ArrayList<Task> toDelete = new ArrayList<Task>();
    for (Task t : current_tasks) {
        Concept w = nal.memory.concept(t.sentence.term);
        if (w == null) {
            // concept does not exist anymore, delete
            toDelete.add(t);
        }
    }
    for (Task t : toDelete) {
        current_tasks.remove(t);
    }
}
Also used : BudgetValue(nars.entity.BudgetValue) Concept(nars.entity.Concept) Task(nars.entity.Task) Stamp(nars.entity.Stamp) ArrayList(java.util.ArrayList) Term(nars.language.Term) Implication(nars.language.Implication) TruthValue(nars.entity.TruthValue) Conjunction(nars.language.Conjunction) Sentence(nars.entity.Sentence) Interval(nars.language.Interval)

Example 3 with Term

use of nars.language.Term in project opennars by opennars.

the class ApplySubstituteTest method testApplySubstitute.

@Test
public void testApplySubstitute() throws Narsese.InvalidInputException {
    String abS = "<a --> b>";
    CompoundTerm ab = (CompoundTerm) np.parseTerm(abS);
    int originalComplexity = ab.getComplexity();
    String xyS = "<x --> y>";
    Term xy = np.parseTerm(xyS);
    Map<Term, Term> h = new HashMap();
    h.put(np.parseTerm("b"), xy);
    CompoundTerm c = ab.applySubstituteToCompound(h);
    assertTrue(c.getComplexity() > originalComplexity);
    // ab unmodified
    assertTrue(ab.name().toString().equals(abS));
    // c is actually different
    assertTrue(!c.name().equals(abS));
    assertTrue(!c.equals(ab));
}
Also used : CompoundTerm(nars.language.CompoundTerm) HashMap(java.util.HashMap) CompoundTerm(nars.language.CompoundTerm) Term(nars.language.Term) Test(org.junit.Test)

Example 4 with Term

use of nars.language.Term in project opennars by opennars.

the class ApplySubstituteTest method test2.

@Test
public void test2() throws Narsese.InvalidInputException {
    // substituting:  <(*,$1) --> num>.  with $1 ==> 0
    NAR n = new NAR();
    Map<Term, Term> h = new HashMap();
    h.put(np.parseTerm("$1"), np.parseTerm("0"));
    CompoundTerm c = ((CompoundTerm) np.parseTerm("<(*,$1) --> num>")).applySubstituteToCompound(h);
    assertTrue(c != null);
}
Also used : CompoundTerm(nars.language.CompoundTerm) HashMap(java.util.HashMap) CompoundTerm(nars.language.CompoundTerm) Term(nars.language.Term) NAR(nars.main.NAR) Test(org.junit.Test)

Example 5 with Term

use of nars.language.Term in project opennars by opennars.

the class TermTest method testParseOperationInFunctionalForm.

@Test
public void testParseOperationInFunctionalForm() {
    Parameters.FUNCTIONAL_OPERATIONAL_FORMAT = true;
    NAR n = new NAR();
    Narsese p = new Narsese(n);
    try {
        Term x = p.parseTerm("wonder(a,b)");
        assertEquals(Operation.class, x.getClass());
        assertEquals("(^wonder,a,b)", x.toString());
    } catch (Narsese.InvalidInputException ex) {
        ex.printStackTrace();
        assertTrue(false);
    }
}
Also used : Narsese(nars.io.Narsese) CompoundTerm(nars.language.CompoundTerm) Term(nars.language.Term) NAR(nars.main.NAR) Test(org.junit.Test)

Aggregations

Term (nars.language.Term)109 CompoundTerm (nars.language.CompoundTerm)66 BudgetValue (nars.entity.BudgetValue)48 TruthValue (nars.entity.TruthValue)46 Sentence (nars.entity.Sentence)40 Task (nars.entity.Task)37 Statement (nars.language.Statement)28 Conjunction (nars.language.Conjunction)20 Inheritance (nars.language.Inheritance)19 Stamp (nars.entity.Stamp)17 Concept (nars.entity.Concept)14 Implication (nars.language.Implication)13 Product (nars.language.Product)11 NAR (nars.main.NAR)9 Interval (nars.language.Interval)8 Test (org.junit.Test)8 HashMap (java.util.HashMap)7 SetExt (nars.language.SetExt)7 SetInt (nars.language.SetInt)7 Variable (nars.language.Variable)7