Search in sources :

Example 41 with Sentence

use of nars.entity.Sentence in project opennars by opennars.

the class TextOutputHandler method getOutputString.

/**
 * generates a human-readable string from an output channel and signal
 */
public static String getOutputString(final Class channel, Object signal, final boolean showChannel, final boolean showStamp, final NAR nar, final StringBuilder buffer, float minPriority) {
    buffer.setLength(0);
    if (showChannel)
        buffer.append(channel.getSimpleName()).append(": ");
    if (channel == ERR.class) {
        if (signal instanceof Throwable) {
            Throwable e = (Throwable) signal;
            buffer.append(e.toString());
            /*if (showStackTrace)*/
            {
            // buffer.append(" ").append(Arrays.asList(e.getStackTrace()));
            }
        } else {
            buffer.append(signal.toString());
        }
    } else if ((channel == OUT.class) || (channel == IN.class) || (channel == ECHO.class) || (channel == EXE.class) || (channel == Answer.class) || (channel == ANTICIPATE.class) || (channel == DISAPPOINT.class) || (channel == CONFIRM.class)) {
        if (channel == CONFIRM.class) {
            buffer.append(signal.toString());
        }
        if (signal instanceof Task) {
            Task t = (Task) signal;
            if (t.getPriority() < minPriority)
                return null;
            if ((channel == ANTICIPATE.class) || (channel == DISAPPOINT.class)) {
                buffer.append(t.sentence.toString(nar, showStamp));
            } else if (channel == Answer.class) {
                // server / NARRun
                Task task = t;
                Sentence answer = task.getBestSolution();
                if (answer != null)
                    buffer.append(answer.toString(nar, showStamp));
                else
                    buffer.append(t.sentence.toString(nar, showStamp));
            } else
                buffer.append(t.sentence.toString(nar, showStamp));
        } else {
            buffer.append(signal.toString());
        }
    } else {
        buffer.append(signal.toString());
    }
    return Texts.unescape(buffer).toString();
}
Also used : Task(nars.entity.Task) EXE(nars.io.events.OutputHandler.EXE) IN(nars.io.events.OutputHandler.IN) Sentence(nars.entity.Sentence) OUT(nars.io.events.OutputHandler.OUT)

Example 42 with Sentence

use of nars.entity.Sentence in project opennars by opennars.

the class Counting method setEnabled.

@Override
public boolean setEnabled(NAR n, boolean enabled) {
    Memory memory = n.memory;
    if (obs == null) {
        obs = new EventObserver() {

            @Override
            public void event(Class event, Object[] a) {
                if ((event != Events.TaskDerive.class && event != Events.TaskAdd.class))
                    return;
                Task task = (Task) a[0];
                if (task.getPriority() < InternalExperience.MINIMUM_PRIORITY_TO_CREATE_WANT_BELIEVE_ETC) {
                    return;
                }
                if (task.sentence.punctuation == Symbols.JUDGMENT_MARK) {
                    // lets say we have <{...} --> M>.
                    if (task.sentence.term instanceof Inheritance) {
                        Inheritance inh = (Inheritance) task.sentence.term;
                        if (inh.getSubject() instanceof SetExt) {
                            SetExt set_term = (SetExt) inh.getSubject();
                            // this gets the cardinality of M
                            int cardinality = set_term.size();
                            // now create term <(*,M,cardinality) --> CARDINALITY>.
                            Term[] product_args = new Term[] { inh.getPredicate(), Term.get(cardinality) };
                            // TODO CARDINATLITY can be a static final instance shared by all
                            Term new_term = Inheritance.make(new Product(product_args), /* --> */
                            CARDINALITY);
                            if (new_term == null) {
                                // this usually happens when product_args contains the term CARDINALITY in which case it is an invalid Inheritance statement
                                return;
                            }
                            TruthValue truth = task.sentence.truth.clone();
                            Stamp stampi = task.sentence.stamp.clone();
                            Sentence j = new Sentence(new_term, Symbols.JUDGMENT_MARK, truth, stampi);
                            BudgetValue budg = task.budget.clone();
                            Task newTask = new Task(j, budg, true);
                            memory.addNewTask(newTask, "Derived (Cardinality)");
                        }
                    }
                }
            }
        };
    }
    memory.event.set(obs, enabled, Events.TaskDerive.class);
    return true;
}
Also used : BudgetValue(nars.entity.BudgetValue) Task(nars.entity.Task) Stamp(nars.entity.Stamp) Memory(nars.storage.Memory) Inheritance(nars.language.Inheritance) Product(nars.language.Product) Term(nars.language.Term) EventObserver(nars.io.events.EventEmitter.EventObserver) Events(nars.io.events.Events) TruthValue(nars.entity.TruthValue) SetExt(nars.language.SetExt) Sentence(nars.entity.Sentence)

Example 43 with Sentence

use of nars.entity.Sentence in project opennars by opennars.

the class InternalExperience method beliefReason.

/**
 * used in full internal experience mode only
 */
protected void beliefReason(Sentence belief, Term beliefTerm, Term taskTerm, DerivationContext nal) {
    Memory memory = nal.memory;
    if (Memory.randomNumber.nextDouble() < INTERNAL_EXPERIENCE_RARE_PROBABILITY) {
        // the operators which dont have a innate belief
        // also get a chance to reveal its effects to the system this way
        Operator op = memory.getOperator(nonInnateBeliefOperators[Memory.randomNumber.nextInt(nonInnateBeliefOperators.length)]);
        Product prod = new Product(new Term[] { belief.term });
        if (op != null && prod != null) {
            Term new_term = Inheritance.make(prod, op);
            Sentence sentence = new Sentence(new_term, Symbols.GOAL_MARK, // a naming convension
            new TruthValue(1, Parameters.DEFAULT_JUDGMENT_CONFIDENCE), new Stamp(memory));
            float quality = BudgetFunctions.truthToQuality(sentence.truth);
            BudgetValue budget = new BudgetValue(Parameters.DEFAULT_GOAL_PRIORITY * INTERNAL_EXPERIENCE_PRIORITY_MUL, Parameters.DEFAULT_GOAL_DURABILITY * INTERNAL_EXPERIENCE_DURABILITY_MUL, quality);
            Task newTask = new Task(sentence, budget, true);
            nal.derivedTask(newTask, false, false, false);
        }
    }
    if (beliefTerm instanceof Implication && Memory.randomNumber.nextDouble() <= INTERNAL_EXPERIENCE_PROBABILITY) {
        Implication imp = (Implication) beliefTerm;
        if (imp.getTemporalOrder() == TemporalRules.ORDER_FORWARD) {
            // 1. check if its (&/,term,+i1,...,+in) =/> anticipateTerm form:
            boolean valid = true;
            if (imp.getSubject() instanceof Conjunction) {
                Conjunction conj = (Conjunction) imp.getSubject();
                if (!conj.term[0].equals(taskTerm)) {
                    // the expected needed term is not included
                    valid = false;
                }
                for (int i = 1; i < conj.term.length; i++) {
                    if (!(conj.term[i] instanceof Interval)) {
                        valid = false;
                        break;
                    }
                }
            } else {
                if (!imp.getSubject().equals(taskTerm)) {
                    valid = false;
                }
            }
            if (valid) {
                Operator op = memory.getOperator("^anticipate");
                if (op == null)
                    throw new RuntimeException(this + " requires ^anticipate operator");
                Product args = new Product(new Term[] { imp.getPredicate() });
                Term new_term = Operation.make(args, op);
                Sentence sentence = new Sentence(new_term, Symbols.GOAL_MARK, // a naming convension
                new TruthValue(1, Parameters.DEFAULT_JUDGMENT_CONFIDENCE), new Stamp(memory));
                float quality = BudgetFunctions.truthToQuality(sentence.truth);
                BudgetValue budget = new BudgetValue(Parameters.DEFAULT_GOAL_PRIORITY * INTERNAL_EXPERIENCE_PRIORITY_MUL, Parameters.DEFAULT_GOAL_DURABILITY * INTERNAL_EXPERIENCE_DURABILITY_MUL, quality);
                Task newTask = new Task(sentence, budget, true);
                nal.derivedTask(newTask, false, false, false);
            }
        }
    }
}
Also used : Operator(nars.operator.Operator) BudgetValue(nars.entity.BudgetValue) Task(nars.entity.Task) Stamp(nars.entity.Stamp) Memory(nars.storage.Memory) Product(nars.language.Product) 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 44 with Sentence

use of nars.entity.Sentence in project opennars by opennars.

the class Memory method executedTask.

/**
 * ExecutedTask called in Operator.call
 *
 * @param operation The operation just executed
 */
public void executedTask(final Operation operation, TruthValue truth) {
    Task opTask = operation.getTask();
    // logic.TASK_EXECUTED.commit(opTask.budget.getPriority());
    Stamp stamp = new Stamp(this, Tense.Present);
    Sentence sentence = new Sentence(operation, Symbols.JUDGMENT_MARK, truth, stamp);
    Task task = new Task(sentence, new BudgetValue(Parameters.DEFAULT_FEEDBACK_PRIORITY, Parameters.DEFAULT_FEEDBACK_DURABILITY, truthToQuality(sentence.getTruth())), true);
    task.setElemOfSequenceBuffer(true);
    addNewTask(task, "Executed");
}
Also used : BudgetValue(nars.entity.BudgetValue) Task(nars.entity.Task) Stamp(nars.entity.Stamp) Sentence(nars.entity.Sentence)

Example 45 with Sentence

use of nars.entity.Sentence in project opennars by opennars.

the class Predict_NARS_Core method main.

public static void main(String[] args) throws Narsese.InvalidInputException, InterruptedException {
    Parameters.DEBUG = false;
    int duration = 4;
    float freq = 1.0f / duration * 0.03f;
    double discretization = 10;
    n = new NAR();
    n.param.noiseLevel.set(0);
    Random rnd = new Random();
    n.on(TaskImmediateProcess.class, new TaskImmediateProcess() {

        @Override
        public void onProcessed(Task t, DerivationContext n) {
            // return;
            if (t.sentence.getOccurenceTime() >= n.memory.time() && t.sentence.truth.getExpectation() > 0.5) {
                Term term = t.getTerm();
                int time = (int) t.sentence.getOccurenceTime() / thinkInterval;
                /*if(positionTruthExp.containsKey(time)) {
                        if(positionTruthExp.get(time) > t.sentence.truth.getExpectation()) {
                            return;
                        }
                    }*/
                int value = -1;
                String ts = term.toString();
            // Prediction(t.sentence, ts, time);
            }
        }
    });
    TreeMLData observed = new TreeMLData("value", Color.WHITE).setRange(0, 1f);
    // predictions = new TreeMLData[(int)discretization];
    predicted = new TreeMLData("seen", Color.WHITE).setRange(0, 1f);
    // for (int i = 0; i < predictions.length; i++) {
    // predictions[i] = new TreeMLData("Pred" + i,
    // Color.getHSBColor(0.25f + i / 4f, 0.85f, 0.85f));
    // }
    pred = (LineChart) new LineChart(predicted).thickness(16f).height(128).drawOverlapped();
    TimelineVis tc = new TimelineVis(pred, new LineChart(observed).thickness(16f).height(128).drawOverlapped());
    new NWindow("_", new PCanvas(tc)).show(800, 800, true);
    n.cycles((int) discretization * 4);
    NARSwing.themeInvert();
    new NARSwing(n);
    ChangedTextInput chg = new ChangedTextInput(n);
    int k = 0;
    String lastInput = "";
    boolean pause = false;
    HashSet<String> qus = new HashSet<String>();
    int truecnt = 0;
    String saved = "";
    int lastOrival = 0;
    while (true) {
        int steps = 40;
        int h = 0;
        do {
            truecnt++;
            if (truecnt % 100 == 0) {
            // qus.clear();
            }
            for (int i = 0; i < thinkInterval; i++) {
                n.cycles(1);
            }
            Thread.sleep(10);
            h++;
            int repeat = 500;
            signal = (float) Math.sin(freq * (k / 2 % 500) - Math.PI / 2) * 0.5f + 0.5f;
            int time = (int) (n.time() / thinkInterval);
            int val2 = (int) (((int) (((signal) * discretization)) * (10.0 / discretization)));
            // System.out.println("observed "+val);
            int tmp = val2;
            if (!pause && val2 != lastOrival) {
                float noise_amp = 0.5f;
                // noise
                val2 += (rnd.nextDouble() * noise_amp * 0.5f - noise_amp * 0.25f);
            }
            lastOrival = tmp;
            final int val = val2;
            lastInput = "<{" + val + "} --> value>. :|:";
            if (k % repeat == 0 && k != 0) {
                pause = true;
                // new run
                n.memory.seq_current.clear();
            }
            if (!pause && !saved.isEmpty()) {
                chg.set(saved);
                saved = "";
            }
            observed.add((int) time, val / 10.0);
            int curval = val;
            if (QUAnswers.containsKey(val)) {
                curval = QUAnswers.get(val);
            }
            int curtime = time;
            int hh = 0;
            // QUAnswers.put(8, 0); //end to start link is fixed
            while (QUAnswers.containsKey(curval)) {
                int shift = QUShift.get(curval) / thinkInterval;
                for (int i = 0; i < shift; i++) {
                    predicted.add((int) curtime + i, (curval) / 10.0);
                    pred.customColor.put(curtime + i, Color.RED.getRGB());
                    pred.customColor.put(curtime + i + 1, Color.RED.getRGB());
                }
                curtime = curtime + shift;
                curval = QUAnswers.get(curval);
                if (curval == 0) {
                    break;
                }
                hh++;
                if (hh > discretization * 2) {
                    break;
                }
            }
            // if(!positionTruthExp.containsKey(time)) { //keep pred line up to date
            // but don't overwrite predictions
            predicted.add((int) time, val / 10.0);
            if (true) {
                chg.set(lastInput);
                if (!pause) {
                } else {
                    saved = lastInput;
                }
                // n.addInput(lastInput);
                String S = "<(&/," + "<{" + val + "} --> value>,?I1) =/> ?what>";
                if (!qus.contains(S)) {
                    // n.addInput(S);
                    AnswerHandler cur = new AnswerHandler() {

                        @Override
                        public void onSolution(Sentence belief) {
                            // System.out.println("solution: " + belief);
                            System.out.println(belief);
                            String rpart = belief.toString().split("=/>")[1];
                            Prediction(belief, rpart, -1, val);
                        }
                    };
                    try {
                        // if(truecnt%10 == 0) {
                        qus.add(S);
                        n.askNow(S, cur);
                    // }
                    } catch (Narsese.InvalidInputException ex) {
                        Logger.getLogger(Predict_NARS_Core.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            if (h > 20) {
                pause = false;
            }
        } while (pause);
        k += steps;
    }
}
Also used : Task(nars.entity.Task) ChangedTextInput(nars.lab.ioutils.ChangedTextInput) NWindow(automenta.vivisect.swing.NWindow) Narsese(nars.io.Narsese) AnswerHandler(nars.io.events.AnswerHandler) TimelineVis(automenta.vivisect.timeline.TimelineVis) Random(java.util.Random) TreeMLData(automenta.vivisect.TreeMLData) PCanvas(automenta.vivisect.swing.PCanvas) Sentence(nars.entity.Sentence) HashSet(java.util.HashSet) Term(nars.language.Term) DerivationContext(nars.control.DerivationContext) TaskImmediateProcess(nars.io.events.Events.TaskImmediateProcess) NARSwing(nars.gui.NARSwing) NAR(nars.main.NAR) LineChart(automenta.vivisect.timeline.LineChart)

Aggregations

Sentence (nars.entity.Sentence)70 Task (nars.entity.Task)54 Term (nars.language.Term)40 BudgetValue (nars.entity.BudgetValue)39 TruthValue (nars.entity.TruthValue)39 Stamp (nars.entity.Stamp)25 CompoundTerm (nars.language.CompoundTerm)24 Statement (nars.language.Statement)13 Conjunction (nars.language.Conjunction)11 Concept (nars.entity.Concept)10 Implication (nars.language.Implication)10 Inheritance (nars.language.Inheritance)8 Interval (nars.language.Interval)8 ArrayList (java.util.ArrayList)6 Equivalence (nars.language.Equivalence)6 HashMap (java.util.HashMap)5 AnswerHandler (nars.io.events.AnswerHandler)5 NARSwing (nars.gui.NARSwing)4 Narsese (nars.io.Narsese)4 Product (nars.language.Product)4