Example #1
0
        // function prototype and some of the methode is like https://github.com/opennars/opennars/blob/4515f1d8e191a1f097859decc65153287d5979c5/nars_core/nars/inference/RuleTables.java#L73
        internal static void reason(
            ClassicalTaskLink taskLink,
            ClassicalTermLink beliefLink,
            DerivationContext ctx
            )
        {
            { // debugging
                int taskId   = taskLink.targetTask.name.term.getAtomicOrTerm;
                int beliefId = beliefLink.target.getAtomicOrTerm;

                if (taskId == 300002 && beliefId == 300004)
                {
                    int breakpointHere2 = 1;
                }
                else if (taskId == 300004 && beliefId == 300002)
                {
                    int breakpointHere2 = 1;
                }

                int breakpointHere1 = 1;
            }

            Memory memory = ctx.memory;

            memory.emotion.manageBusy(ctx);

            ClassicalTask     task         = ctx.currentTask;
            ClassicalSentence taskSentence = task.sentence;

            TermOrCompoundTermOrVariableReferer taskTerm   = taskSentence.term;
            TermOrCompoundTermOrVariableReferer beliefTerm = beliefLink.target;

            // commented because not jet translated
            //if (equalSubTermsInRespectToImageAndProduct(taskTerm, beliefTerm))
            //    return;

            ClassicalConcept beliefConcept = memory.translateTermToConcept(beliefTerm);

            ClassicalSentence belief = (beliefConcept != null) ? beliefConcept.getBelief(ctx, task) : null;

            ctx.currentBelief = belief;

            if (belief != null)
            {
                beliefTerm = belief.term; //because interval handling that differs on conceptual level


                // too restrictive, its checked for non-deductive inference rules in derivedTask (also for single prem)
                if (Stamp.checkBaseOverlap(task.sentence.stamp, belief.stamp))
                {
                    ctx.evidentalOverlap = true;
                    if (!task.sentence.stamp.isEternal || !belief.stamp.isEternal)
                    {
                        return; // only allow for eternal reasoning for now to prevent derived event floods
                    }
                    //return; // preparisons are made now to support this nicely
                }
                // comment out for recursive examples, this is for the future, it generates a lot of potentially useless tasks

                //ctx.emit(Events.BeliefReason.class, belief, beliefTerm, taskTerm, nal);

                if (LocalRules.match(task, belief, ctx))    // new tasks resulted from the match, so return
                {
                    return;
                }
            }

            // current belief and task may have changed, so set again:
            ctx.currentBelief = belief;
            ctx.currentTask   = task;

            // HACK< derivation must be made by combining compounds >
            if (!TermUtilities.isTermCompoundTerm(taskTerm) || !TermUtilities.isTermCompoundTerm(beliefTerm))
            {
                return;
            }

            // derive and create new tasks for the results
            {
                IList <TemporaryDerivedCompoundWithDecorationAndTruth> derivedCompoundTermsWithDecorationAndTruth = new List <TemporaryDerivedCompoundWithDecorationAndTruth>();
                bool insert = true;

                DeriverCaller.deriverCaller(
                    ctx.compoundAndTermContext,
                    ctx.compoundAndTermContext.translateToCompoundChecked(taskTerm),
                    ctx.compoundAndTermContext.translateToCompoundChecked(beliefTerm),
                    out derivedCompoundTermsWithDecorationAndTruth, insert);

                // translate derivedCompoundTermsWithDecorationAndTruth to tasks and add them
                // for this we have to call DerivationContext.doublePremiseTask() to generate the tasks
                foreach (var iDerivedWithDecorationAndTruth in derivedCompoundTermsWithDecorationAndTruth)
                {
                    TermOrCompoundTermOrVariableReferer content = iDerivedWithDecorationAndTruth.derivedCompoundWithDecoration.termReferer;

                    bool temporalInduction = false; // TODO< decide by rule? from the deriver? >
                    bool overlapAllowed    = false; // TODO< decide by rule? from the deriver? >

                    TruthValue truth = null;
                    truth = RuleTable.calcTruthDoublePremise(task.sentence.truth, belief.truth, iDerivedWithDecorationAndTruth.truthfunction);

                    ClassicalBudgetValue budget = new ClassicalBudgetValue(0.5f, 0.5f, 0.5f); // TODO< calculate budget by table >

                    ctx.doublePremiseTask(content,
                                          truth,
                                          budget,
                                          temporalInduction,
                                          overlapAllowed
                                          );
                }
            }
        }
 public override IDerivation Visit(AlternativeSet aAlternativeSet, DerivationContext aContext)
 {
     aAlternativeSet.Parent = (aContext as CyclesDetectContext).Parent;
     return(base.Visit(aAlternativeSet, aContext));
 }
Example #3
0
 public override IDerivation Accept(DerivationContext aContext)
 {
     return(aContext.Visitor.Visit(this, aContext));
 }
        public override IDerivation Visit(PlaceHolderAssignPhrase aPlaceHolderAssignPhrase, DerivationContext aContext)
        {
            CyclesDetectContext context = aContext as CyclesDetectContext;

            aPlaceHolderAssignPhrase.Parent = context.Parent;
            CyclesDetectContext newContext = new CyclesDetectContext(aContext as CyclesDetectContext);

            newContext.Parent = aPlaceHolderAssignPhrase;
            return(base.Visit(aPlaceHolderAssignPhrase, newContext));
        }
 public override IDerivation Visit(Seqence aSeqence, DerivationContext aContext)
 {
     aSeqence.Parent = (aContext as CyclesDetectContext).Parent;
     return(base.Visit(aSeqence, aContext));
 }
Example #6
0
 public virtual IDerivation Accept(DerivationContext aContext)
 {
     return(aContext.Visitor.Visit(this, aContext));
 }
Example #7
0
        /**
         * Insert a TaskLink into the TaskLink bag for indirect processing
         *
         * /param taskLink The termLink to be inserted
         */
        public bool insertTaskLink(ClassicalTaskLink taskLink, DerivationContext nal)
        {
            ClassicalTask target = taskLink.targetTask;
            ClassicalTask ques   = taskLink.targetTask;

            // TODO< implement if variables are implemented >

            /* commented and not translated because variables not implemented
             * if((ques.sentence.isQuestion() || ques.sentence.isQuest()) && ques.getTerm().hasVarQuery()) { //ok query var, search
             *  boolean newAnswer = false;
             *
             *  for(TaskLink t : this.taskLinks) {
             *
             *      Term[] u = new Term[] { ques.getTerm(), t.getTerm() };
             *      if(!t.getTerm().hasVarQuery() && Variables.unify(Symbols.VAR_QUERY, u)) {
             *          Concept c = nal.memory.concept(t.getTerm());
             *          if(c != null && ques.sentence.isQuestion() && c.beliefs.size() > 0) {
             *              final Task taskAnswer = c.beliefs.get(0);
             *              if(taskAnswer!=null) {
             *                  newAnswer |= trySolution(taskAnswer.sentence, ques, nal, false); //order important here
             *              }
             *          }
             *          if(c != null && ques.sentence.isQuest() &&  c.desires.size() > 0) {
             *              final Task taskAnswer = c.desires.get(0);
             *              if(taskAnswer!=null) {
             *                  newAnswer |= trySolution(taskAnswer.sentence, ques, nal, false); //order important here
             *              }
             *          }
             *      }
             *  }
             *  if(newAnswer && ques.isInput()) {
             *      memory.emit(Events.Answer.class, ques, ques.getBestSolution());
             *  }
             * }*/

            // TODO< implement if variables are implemented >

            /* commented and not translated because variables not implemented
             * //belief side:
             * Task t = taskLink.getTarget();
             * if(t.sentence.isJudgment()) { //ok query var, search
             *  for(TaskLink quess: this.taskLinks) {
             *      ques = quess.getTarget();
             *      if((ques.sentence.isQuestion() || ques.sentence.isQuest()) && ques.getTerm().hasVarQuery()) {
             *          boolean newAnswer = false;
             *          Term[] u = new Term[] { ques.getTerm(), t.getTerm() };
             *          if(!t.getTerm().hasVarQuery() && Variables.unify(Symbols.VAR_QUERY, u)) {
             *              Concept c = nal.memory.concept(t.getTerm());
             *              if(c != null && ques.sentence.isQuestion() && c.beliefs.size() > 0) {
             *                  final Task taskAnswer = c.beliefs.get(0);
             *                  if(taskAnswer!=null) {
             *                      newAnswer |= trySolution(taskAnswer.sentence, ques, nal, false); //order important here
             *                  }
             *              }
             *              if(c != null && ques.sentence.isQuest() &&  c.desires.size() > 0) {
             *                  final Task taskAnswer = c.desires.get(0);
             *                  if(taskAnswer!=null) {
             *                      newAnswer |= trySolution(taskAnswer.sentence, ques, nal, false); //order important here
             *                  }
             *              }
             *          }
             *          if(newAnswer && ques.isInput()) {
             *              memory.emit(Events.Answer.class, ques, ques.getBestSolution());
             *          }
             *      }
             *  }
             * }
             */

            { // handle max per concept
                // if taskLinks already contain a certain amount of tasks with same content then one has to go
                bool              isEternal       = target.sentence.stamp.isEternal;
                int               nSameContent    = 0;
                float             lowest_priority = float.MaxValue;
                ClassicalTaskLink lowest          = null;
                foreach (ClassicalTaskLink tl in taskLinks)
                {
                    ClassicalSentence s = tl.targetTask.sentence;
                    if (s.term == taskLink.targetTask.sentence.term && s.stamp.isEternal == isEternal)
                    {
                        nSameContent++;                           // same content and occurrence-type, so count +1
                        if (tl.budget.priority < lowest_priority) //the current one has lower priority so save as lowest
                        {
                            lowest_priority = tl.budget.priority;
                            lowest          = tl;
                        }
                        if (nSameContent > Parameters.TASKLINK_PER_CONTENT)    // ok we reached the maximum so lets delete the lowest
                        {
                            taskLinks.takeElement(lowest);
                            // commented because events not implemented yet  memory.emit(TaskLinkRemove.class, lowest, this);
                            break;
                        }
                    }
                }
            }

            ClassicalTaskLink removed = taskLinks.putIn(taskLink);

            if (removed != null)
            {
                if (removed == taskLink)
                {
                    // commented because events not implemented yet memory.emit(TaskLinkRemove.class, taskLink, this);
                    return(false);
                }
                else
                {
                    // commented because events not implemented yet memory.emit(TaskLinkRemove.class, removed, this);
                }

                removed.wasDiscarded();
            }
            // commented because events not implemented yet memory.emit(TaskLinkAdd.class, taskLink, this);
            return(true);
        }
Example #8
0
 public IDerivation Visit(IPhrase aPhr, DerivationContext aContext)
 {
     throw new ApplicationException("Should never be called");
 }
Example #9
0
        // does the emotion part of the trySolution function
        private static void trySolution_emotion(ClassicalSentence belief, ClassicalTask task, DerivationContext ctx)
        {
            ClassicalSentence problem = task.sentence;
            Memory            memory  = ctx.memory;

            ClassicalSentence oldBest = task.bestSolution;

            if (oldBest != null)
            {
                TemporalRules.EnumRateByConfidence rateByConfidence =
                    oldBest.term == belief.term ? TemporalRules.EnumRateByConfidence.YES : TemporalRules.EnumRateByConfidence.NO;

                float newQ = TemporalRules.solutionQuality(rateByConfidence, task, belief, memory, ctx.compoundAndTermContext);
                float oldQ = TemporalRules.solutionQuality(rateByConfidence, task, oldBest, memory, ctx.compoundAndTermContext);
                if (oldQ >= newQ)
                {
                    if (problem.isGoal)
                    {
                        memory.emotion.adjustHappy(oldQ, task.budget.priority, ctx);
                    }
                    //System.out.println("Unsolved: Solution of lesser quality");
                    //java memory.emit(Unsolved.class, task, belief, "Lower quality");
                    return;
                }
            }
        }
Example #10
0
 public virtual IDerivation Visit(ExprDouble aExpr, DerivationContext aContext)
 {
     return(aExpr);
 }
Example #11
0
 public virtual IDerivation Visit(Access aAccess, DerivationContext aContext)
 {
     return(aContext.ParentDerivation.FindDerivation(aAccess.ObjectName));
 }
Example #12
0
        public virtual IDerivation Visit(PlaceHolderAssignPhrase aPlaceHolderAssignPhrase, DerivationContext aContext)
        {
            IDerivation        lExpandList    = aPlaceHolderAssignPhrase.RightPhrase.Accept(aContext);
            List <IDerivation> lReplacePoints = PlaceHolders.GetList(aPlaceHolderAssignPhrase.Name);

            foreach (TextDerivation lPoint in lReplacePoints)
            {
                if (aPlaceHolderAssignPhrase.Add)
                {
                    lPoint.Text += lExpandList.ToString();
                }
                else
                {
                    lPoint.Text = lExpandList.ToString();
                }
            }
            return(lExpandList);
        }
Example #13
0
 public abstract IDerivation VisitInternal(AlternativeSet aAlternativeSet, DerivationContext aContext);
Example #14
0
        private tEdge addEdge(DerivationContext aContext, IPhrase aPhr, IPhrase aParent)
        {
            tGraph graph    = (aContext as BuildGraphContext).BuildingGraph;
            string fromName = "unk";
            string toName   = "unk";

            // determine fromName
            if (aParent == null)
            {
                fromName = aContext.Grammar.MainSymbol.CounterName;
                graph.ensureExistsNode(fromName, aContext.Grammar.MainSymbol.Text);
            }
            else
            {
                NonTerminal parentNt = aParent as NonTerminal;
                if (parentNt != null)
                {
                    fromName = parentNt.CounterName;
                    graph.ensureExistsNode(parentNt.CounterName, parentNt.Text);
                }
                else
                {
                    fromName = (aContext as BuildGraphContext).GeneratedToName;
                    Debug.Assert(!string.IsNullOrEmpty(fromName), "Не должно быть");
                }
            }
            // determine toName
            NonTerminal nonTerminal = aPhr as NonTerminal;
            Terminal    terminal    = aPhr as Terminal;

            if (nonTerminal != null)
            {
                toName = nonTerminal.CounterName;
                string text = nonTerminal.Text;
                if ((nonTerminal.CycicKind & CycicKind.SkippedAsSeen) > 0)
                {
                    text += " *";
                }
                graph.ensureExistsNode(toName, text);
            }
            else if (terminal != null)
            {
                string text = string.IsNullOrEmpty(terminal.Text) ? "e" : terminal.Text;
                tNode  n    = graph.addNonUniqueNode(text);
                toName             = n.Name;
                n.CustomAttributes = "term";
            }
            else
            {
                toName = graph.addNonUniqueNode(aPhr.ToString()).Name;
                //надо запомнить это в контексте
                (aContext as BuildGraphContext).GeneratedToName = toName;
            }
            tEdge e = graph.addEdge(fromName, toName);

            if (e == null)
            {
                Debug.WriteLine("не создалась дуга, потому что нет вершин");
            }
            return(e);
        }