Пример #1
0
        public void AnyVariableExpressionShouldMatch()
        {
            var variable = new DummyVariable("variable");
            var pattern  = ExpressionPattern.Variable <DummyInstruction>();

            Assert.True(pattern.Matches(new VariableExpression <DummyInstruction>(variable)));
        }
Пример #2
0
        public void InstructionWithOneStackArgumentShouldResultInAssignmentAndExpressionStatementWithArgument()
        {
            var cfg = ConstructAst(new[]
            {
                DummyInstruction.Push(0, 1),
                DummyInstruction.Pop(1, 1),
                DummyInstruction.Ret(2)
            });

            var variableCapture = new CaptureGroup("variable");

            var pattern = new SequencePattern <Statement <DummyInstruction> >(
                // stack_slot = push 1()
                StatementPattern
                .Assignment <DummyInstruction>()
                .WithExpression(ExpressionPattern.Instruction(new DummyInstructionPattern(DummyOpCode.Push)))
                .CaptureVariables(variableCapture),

                // pop(stack_slot)
                StatementPattern.Expression(ExpressionPattern
                                            .Instruction(new DummyInstructionPattern(DummyOpCode.Pop))
                                            .WithArguments(ExpressionPattern
                                                           .Variable <DummyInstruction>()
                                                           .CaptureVariable(variableCapture))),

                // ret()
                StatementPattern.Instruction(new DummyInstructionPattern(DummyOpCode.Ret))
                );

            var result = pattern.Match(cfg.Nodes[0].Contents.Instructions);

            Assert.True(result.IsSuccess);
            Assert.Single(result.Captures[variableCapture].Distinct());
        }
        public void TestComplexCapture()
        {
            var valueExpression = new InstructionExpression <DummyInstruction>(DummyInstruction.Push(0, 1),
                                                                               ArraySegment <Expression <DummyInstruction> > .Empty);

            var statement = new ExpressionStatement <DummyInstruction>(new InstructionExpression <DummyInstruction>(DummyInstruction.Ret(1), new List <Expression <DummyInstruction> >
            {
                valueExpression
            }));

            // Define capture group.
            var returnValueGroup = new CaptureGroup("returnValue");

            // Create ret(?) pattern.
            var pattern = StatementPattern.Expression(
                ExpressionPattern
                .Instruction(new DummyInstructionPattern(DummyOpCode.Ret))
                .WithArguments(
                    ExpressionPattern.Any <DummyInstruction>().CaptureAs(returnValueGroup)
                    )
                );

            // Match.
            var result = pattern.Match(statement);

            // Extract return expression node.
            var capturedObject = result.Captures[returnValueGroup][0];

            Assert.Same(valueExpression, capturedObject);
        }
        public void DifferentInstructionWithZeroArgumentsShouldNotMatch()
        {
            var pattern = ExpressionPattern.InstructionLiteral(1234);
            var input   = new InstructionExpression <int>(5678, ImmutableArray <Expression <int> > .Empty);

            Assert.False(pattern.Matches(input));
        }
        public void SameInstructionWithZeroArgumentsShouldMatch()
        {
            var pattern = ExpressionPattern.InstructionLiteral(1234);
            var input   = new InstructionExpression <int>(1234, ImmutableArray <Expression <int> > .Empty);

            Assert.True(pattern.Matches(input));
        }
Пример #6
0
        public void JoiningControlFlowPathsWithDifferentVariableVersionsShouldResultInPhiNode()
        {
            var variable = new DummyVariable("temp");

            var cfg = ConstructAst(new[]
            {
                DummyInstruction.Push(0, 1),
                DummyInstruction.JmpCond(1, 5),

                DummyInstruction.Push(2, 1),
                DummyInstruction.Set(3, variable),
                DummyInstruction.Jmp(4, 7),

                DummyInstruction.Push(5, 1),
                DummyInstruction.Set(6, variable),

                DummyInstruction.Get(7, variable),
                DummyInstruction.Pop(8, 1),
                DummyInstruction.Ret(9)
            });

            var phiSourcesCapture = new CaptureGroup("sources");
            var variablesCapture  = new CaptureGroup("variables");

            // temp_vx = set(?)
            var assignPattern = StatementPattern
                                .Assignment <DummyInstruction>()
                                .WithExpression(ExpressionPattern
                                                .Instruction(new DummyInstructionPattern(DummyOpCode.Set))
                                                .WithArguments(1))
                                .CaptureVariables(variablesCapture);

            // variable = phi(?, ?)
            var phiPattern = StatementPattern
                             .Phi <DummyInstruction>()
                             .WithSources(2)
                             .CaptureSources(phiSourcesCapture);

            var set1Result = assignPattern.FindFirstMatch(cfg.Nodes[2].Contents.Instructions);
            var set2Result = assignPattern.FindFirstMatch(cfg.Nodes[5].Contents.Instructions);
            var phiResult  = phiPattern.Match(cfg.Nodes[7].Contents.Header);

            Assert.True(set1Result.IsSuccess, "Node 2 was expected to contain an assignment statement.");
            Assert.True(set2Result.IsSuccess, "Node 5 was expected to contain an assignment statement.");
            Assert.True(phiResult.IsSuccess, "Node 7 was expected to start with a phi statement.");

            var sources = phiResult.Captures[phiSourcesCapture]
                          .Cast <VariableExpression <DummyInstruction> >()
                          .Select(s => s.Variable);

            var allVariables = new[]
            {
                (IVariable)set1Result.Captures[variablesCapture][0],
                (IVariable)set2Result.Captures[variablesCapture][0]
            };

            Assert.Equal(allVariables.ToHashSet(), sources.ToHashSet());
        }
Пример #7
0
        public void DifferentSpecificVariableShouldMatch()
        {
            var variable1 = new DummyVariable("variable1");
            var variable2 = new DummyVariable("variable2");

            var pattern = ExpressionPattern.Variable <DummyInstruction>(variable1);

            Assert.False(pattern.Matches(new VariableExpression <DummyInstruction>(variable2)));
        }
Пример #8
0
        public void PushingTwoValuesOnStackWithDifferentConsumers()
        {
            var cfg = ConstructAst(new[]
            {
                DummyInstruction.Push(0, 2),
                DummyInstruction.Pop(1, 1),
                DummyInstruction.Pop(2, 1),
                DummyInstruction.Ret(3)
            });

            var variableCapture   = new CaptureGroup("variable");
            var argumentsCapture1 = new CaptureGroup("argument1");
            var argumentsCapture2 = new CaptureGroup("argument2");

            var pattern = new SequencePattern <Statement <DummyInstruction> >(
                // stack_slot_1, stack_slot_2 = push 2()
                StatementPattern
                .Assignment <DummyInstruction>()
                .WithVariables(2)
                .CaptureVariables(variableCapture),

                // pop(?)
                StatementPattern.Expression(ExpressionPattern
                                            .Instruction <DummyInstruction>()
                                            .WithArguments(1)
                                            .CaptureArguments(argumentsCapture1)),

                // pop(?)
                StatementPattern.Expression(ExpressionPattern
                                            .Instruction <DummyInstruction>()
                                            .WithArguments(1)
                                            .CaptureArguments(argumentsCapture2)),

                // ret()
                StatementPattern.Instruction(new DummyInstructionPattern(DummyOpCode.Ret))
                );

            var result = pattern.Match(cfg.Nodes[0].Contents.Instructions);

            Assert.True(result.IsSuccess);

            var variables = result.Captures[variableCapture]
                            .Cast <IVariable>()
                            .ToArray();

            var argument1 = (VariableExpression <DummyInstruction>)result.Captures[argumentsCapture1][0];
            var argument2 = (VariableExpression <DummyInstruction>)result.Captures[argumentsCapture2][0];

            // Note: we expect the first pop statement to use the second variable that was pushed by the push instruction.
            Assert.Equal(variables[1], argument1.Variable);
            Assert.Equal(variables[0], argument2.Variable);
        }
        public static T TryParse(ParseContext ctx)
        {
            var parseContext = ctx.Clone(false);
            var parseResult  = ExpressionPattern.Parse(parseContext);

            if (!parseResult.IsSuccess)
            {
                return(null);
            }

            var literalExpression =
                parseResult.Matches.GetValue <SkriptBoolean.SkriptRepresentation?>(0) as
                Expression <SkriptBoolean.SkriptRepresentation?>;

            //Check if literal
            T expression = null;

            if (literalExpression?.GenericValue != null)
            {
                expression = new T
                {
                    Literal = literalExpression
                };
            }

            //No literal found. Attempt to get a conditional expression
            if (parseResult.Matches.GetValue <ConditionalExpression>(0) is ConditionalExpression conditionalExpression)
            {
                expression = new T
                {
                    Condition = conditionalExpression
                };
            }

            //Users can also use expressions that return a boolean. Try that
            if (parseResult.Matches.GetValue <SkriptExpression>(0) is SkriptExpression skriptExpression)
            {
                expression = new T
                {
                    Expression = skriptExpression
                };
            }

            if (expression != null)
            {
                ctx.ReadUntilPosition(parseContext.CurrentPosition);
            }

            return(expression);
        }
        public void SameInstructionWithDifferentArgumentCountShouldNotMatch()
        {
            var pattern = ExpressionPattern
                          .InstructionLiteral(1234)
                          .WithArguments(ExpressionPattern.Any <int>(), ExpressionPattern.Any <int>());

            var arguments = new List <Expression <int> >(2)
            {
                new InstructionExpression <int>(0, ImmutableArray <Expression <int> > .Empty),
            };

            var input = new InstructionExpression <int>(1234, arguments);

            Assert.False(pattern.Matches(input));
        }
        public void SameInstructionWithComplexMatchingArgumentsShouldNotMatch()
        {
            var pattern = ExpressionPattern
                          .InstructionLiteral(1234)
                          .WithArguments(
                ExpressionPattern.InstructionLiteral(1234) | ExpressionPattern.InstructionLiteral(5678),
                ExpressionPattern.Any <int>());

            var arguments = new List <Expression <int> >(2)
            {
                new InstructionExpression <int>(5678, ImmutableArray <Expression <int> > .Empty),
                new InstructionExpression <int>(1, ImmutableArray <Expression <int> > .Empty),
            };

            var input = new InstructionExpression <int>(1234, arguments);

            Assert.True(pattern.Matches(input));
        }
Пример #12
0
        public void PushingTwoValuesOnStackShouldResultInTwoVariablesAssigned()
        {
            var cfg = ConstructAst(new[]
            {
                DummyInstruction.Push(0, 2),
                DummyInstruction.Pop(1, 2),
                DummyInstruction.Ret(2)
            });

            var variableCapture  = new CaptureGroup("variable");
            var argumentsCapture = new CaptureGroup("argument");

            var pattern = new SequencePattern <Statement <DummyInstruction> >(
                // stack_slot_1, stack_slot_2 = push 2()
                StatementPattern
                .Assignment <DummyInstruction>()
                .WithVariables(2)
                .CaptureVariables(variableCapture),

                // pop(?, ?)
                StatementPattern.Expression(ExpressionPattern
                                            .Instruction <DummyInstruction>()
                                            .WithArguments(2)
                                            .CaptureArguments(argumentsCapture)),

                // ret()
                StatementPattern.Instruction(new DummyInstructionPattern(DummyOpCode.Ret))
                );

            var result = pattern.Match(cfg.Nodes[0].Contents.Instructions);

            Assert.True(result.IsSuccess);

            var variables = result.Captures[variableCapture]
                            .Cast <IVariable>()
                            .ToArray();

            var arguments = result.Captures[argumentsCapture]
                            .Cast <VariableExpression <DummyInstruction> >()
                            .Select(e => e.Variable)
                            .ToArray();

            Assert.Equal(variables, arguments);
        }
        public void InstructionWithAnyArgumentsShouldMatchIfInstructionIsEqual(bool sameInstruction, int argumentCount)
        {
            var pattern = ExpressionPattern
                          .InstructionLiteral(1234)
                          .WithAnyArguments();

            var arguments = new List <Expression <int> >(argumentCount);

            for (int i = 0; i < argumentCount; i++)
            {
                arguments.Add(new InstructionExpression <int>(0, ImmutableArray <Expression <int> > .Empty));
            }

            var input = new InstructionExpression <int>(sameInstruction ? 1234 : 5678, arguments);

            var result = pattern.Match(input);

            Assert.Equal(sameInstruction, result.IsSuccess);
        }
Пример #14
0
        public void JoiningPathsWithMultipleAssignmentsShouldOnlyUseLatestVersion()
        {
            var variable = new DummyVariable("temp");

            var cfg = ConstructAst(new[]
            {
                // if (cond) goto else:
                DummyInstruction.Push(0, 1),
                DummyInstruction.JmpCond(1, 7),

                // temp = some_value (not used).
                DummyInstruction.Push(2, 1),
                DummyInstruction.Set(3, variable),
                // temp = some_value (render previous value useless)
                DummyInstruction.Push(4, 1),
                DummyInstruction.Set(5, variable),

                // goto end
                DummyInstruction.Jmp(6, 9),

                // else:
                // temp = some_value
                DummyInstruction.Push(7, 1),
                DummyInstruction.Set(8, variable),

                // end:
                // pop(temp)
                DummyInstruction.Get(9, variable),
                DummyInstruction.Pop(10, 1),

                // return
                DummyInstruction.Ret(11)
            });

            var phiSourcesCapture = new CaptureGroup("sources");
            var variablesCapture  = new CaptureGroup("variables");

            // variable = phi(?, ?)
            var phiPattern = StatementPattern
                             .Phi <DummyInstruction>()
                             .WithSources(2)
                             .CaptureSources(phiSourcesCapture);

            // temp_vx = set(?)
            var assignPattern = StatementPattern
                                .Assignment <DummyInstruction>()
                                .WithExpression(ExpressionPattern
                                                .Instruction(new DummyInstructionPattern(DummyOpCode.Set))
                                                .WithArguments(1))
                                .CaptureVariables(variablesCapture);

            var assignment1Results = assignPattern
                                     .FindAllMatches(cfg.Nodes[7].Contents.Instructions)
                                     .ToArray();

            var assignment2Results = assignPattern
                                     .FindAllMatches(cfg.Nodes[2].Contents.Instructions)
                                     .ToArray();

            var phiResult = phiPattern.Match(cfg.Nodes[9].Contents.Header);

            Assert.True(assignment1Results.Length == 1, "Node 7 was expected to have one assignment to 'temp'.");
            Assert.True(assignment2Results.Length == 2, "Node 2 was expected to have two assignments to 'temp'.");
            Assert.True(phiResult.IsSuccess, "Node 9 was expected to start with a phi node with two sources.");

            var sources = phiResult.Captures[phiSourcesCapture]
                          .Cast <VariableExpression <DummyInstruction> >()
                          .Select(s => s.Variable);

            var allVariables = new[]
            {
                (IVariable)assignment1Results[0].Captures[variablesCapture][0],
                (IVariable)assignment2Results[1].Captures[variablesCapture][0]
            };

            Assert.Equal(allVariables.ToHashSet(), sources.ToHashSet());
        }
Пример #15
0
    public void ReceiveExpression(Expression utterer, Expression utterance)
    {
        // Debug.Log(this.name + " is seeing '" + utterance + "'");
        if (this.model == null)
        {
            // Debug.Log("No associated model.");
            this.controller.placeExpression.Play();
            StartCoroutine(ShowSpeechBubble("questionMark"));
            return;
        }

        if (utterance.type.Equals(SemanticType.CONFORMITY_VALUE))
        {
            // if (name.Equals(new Phrase(Expression.THE,  new Phrase(Expression.POSSESS, new Phrase(Expression.THE, Expression.LOG), 1)))) {
            //     if (!model.Proves(new Phrase(Expression.KING, utterer))) {
            //         StartCoroutine(ShowSpeechBubble(Expression.REFUSE));
            //         return;
            //     }
            // }

            // TODO figure out conditions of refusal, etc.
            if (utterance.GetHead().Equals(Expression.CONTRACT))
            {
                if (!this.model.Proves(new Phrase(Expression.NOT, new Phrase(Expression.TRUSTWORTHY, utterer))))
                {
                    // TODO: check if utilities work out, and if you can uphold your end of the deal.
                    // For now, just accept by default
                    // uphold your end of the bargain
                    model.Add(new Phrase(Expression.BETTER, utterance.GetArg(1), Expression.NEUTRAL));
                    // model.AddUtility(utterance.GetArg(1), 10f);

                    // hold the other person to account
                    model.UpdateBelief(new Phrase(Expression.BOUND, utterer, utterance.GetArg(0)));

                    // // hold yourself to account??
                    // model.UpdateBelief(new Phrase(Expression.BOUND, utterer, utterance.GetArg(1)));

                    this.controller.combineSuccess.Play();
                    StartCoroutine(ShowSpeechBubble(new Phrase(Expression.ACCEPT)));

                    return;
                }

                this.controller.lowClick.Play();
                StartCoroutine(ShowSpeechBubble(Expression.REFUSE));

                return;
            }

            if (utterance.GetHead().Equals(Expression.WOULD))
            {
                if (this.model.Proves(new Phrase(Expression.NOT, new Phrase(Expression.TRUSTWORTHY, utterer))))
                {
                    this.controller.lowClick.Play();
                    StartCoroutine(ShowSpeechBubble(new Phrase(Expression.REFUSE)));

                    return;
                }

                this.controller.combineSuccess.Play();
                StartCoroutine(ShowSpeechBubble(Expression.ACCEPT));

                model.Add(new Phrase(Expression.BETTER, utterance.GetArg(0), Expression.NEUTRAL));
                model.decisionLock = false;
                // model.AddUtility(utterance.GetArg(0), 10f);

                return;
            }
        }

        if (utterance.type.Equals(SemanticType.ASSERTION))
        {
            Expression content = utterance.GetArg(0);
            // if (this.model.UpdateBelief(new Phrase(Expression.BELIEVE, utterer, content))) {
            if (this.model.UpdateBelief(content))
            {
                this.controller.combineSuccess.Play();
                StartCoroutine(ShowSpeechBubble(new Phrase(Expression.ASSERT, Expression.AFFIRM)));
            }
            else
            {
                this.controller.failure.Play();
                StartCoroutine(ShowSpeechBubble(new Phrase(Expression.ASSERT, Expression.DENY)));
            }
            return;
        }

        if (utterance.type.Equals(SemanticType.TRUTH_VALUE))
        {
            if (this.model.Proves(utterance))
            {
                this.controller.combineSuccess.Play();
                StartCoroutine(ShowSpeechBubble(new Phrase(Expression.ASSERT, Expression.AFFIRM)));
            }
            else if (this.model.Proves(new Phrase(Expression.NOT, utterance)))
            {
                this.controller.failure.Play();
                StartCoroutine(ShowSpeechBubble(new Phrase(Expression.ASSERT, Expression.DENY)));
            }
            else
            {
                this.controller.lowClick.Play();
                StartCoroutine(ShowSpeechBubble(new Phrase(Expression.ASSERT, new Phrase(Expression.OR, Expression.AFFIRM, Expression.DENY))));
            }
            return;
        }

        if (utterance.type.Equals(SemanticType.INDIVIDUAL))
        {
            // I imagine this will be an invitation to attend to the individual named
            // but I'll leave this as a kind of puzzlement for now.
            this.controller.placeExpression.Play();
            StartCoroutine(ShowSpeechBubble("query"));
            return;
        }

        SemanticType outputType = utterance.type.GetOutputType();

        if (outputType != null && outputType.Equals(SemanticType.TRUTH_VALUE))
        {
            IPattern[] args = new IPattern[utterance.GetNumArgs()];
            Dictionary <SemanticType, int> places = new Dictionary <SemanticType, int>();
            int counter = 0;
            for (int i = 0; i < utterance.GetNumArgs(); i++)
            {
                if (utterance.GetArg(i) == null)
                {
                    SemanticType argType = utterance.type.GetInputType(counter);

                    int place = 0;

                    if (places.ContainsKey(argType))
                    {
                        place = places[argType];
                    }
                    places[argType] = place + 1;

                    args[i] = new MetaVariable(argType, place);

                    counter++;
                }
                else
                {
                    args[i] = utterance.GetArg(i);
                }
            }
            // let's see if this doesn't break things.
            // might have to cycle through the utterance's open args.
            IPattern question = new ExpressionPattern(utterance.GetHead(), args);

            List <Dictionary <MetaVariable, Expression> > found = model.Find(false, new List <Expression>(), question);
            if (found != null)
            {
                List <IPattern> bound   = question.Bind(found);
                Expression[]    answers = new Expression[bound.Count];
                counter = 0;
                foreach (IPattern p in bound)
                {
                    Expression answer = new Phrase(Expression.ASSERT, p.ToExpression());
                    answers[counter] = answer;
                    counter++;
                }
                StartCoroutine(ShowSpeechBubbles(answers));
                return;
            }
        }

        // this leaves functions with e as output. Not sure what this would amount to.
        this.controller.placeExpression.Play();
        StartCoroutine(ShowSpeechBubble("query"));
    }
Пример #16
0
    protected IEnumerator Do(List <Expression> actionSequence)
    {
        actionInProgress = true;
        if (actionSequence == null)
        {
            actionInProgress = false;
            yield break;
        }

        // // UNCOMMENT BELOW TO PRINT OUT THE ACTION SEUQNECE
        // StringBuilder s = new StringBuilder();
        // foreach (Expression a in actionSequence) {
        //     s.Append(a);
        //     s.Append("; ");
        // }
        // Debug.Log(s.ToString());

        // TODO: make the next action in the sequence wait until the previous
        // action has been completed.
        foreach (Expression action in actionSequence)
        {
            if (!controller.is2D)
            {
                if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.AT, Expression.SELF, Expression.BOB))))
                {
                    GetComponent <NavMeshAgent>().destination = GameObject.Find("Bob").transform.position;

                    yield return(null);

                    while (GetComponent <NavMeshAgent>().remainingDistance > 1)
                    {
                        yield return(null);
                    }
                    this.model.UpdateBelief(
                        new Phrase(Expression.MAKE, Expression.SELF,
                                   new Phrase(Expression.AT, Expression.SELF, Expression.BOB)));

                    continue;
                }

                if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.AT, Expression.SELF, Expression.EVAN))))
                {
                    GetComponent <NavMeshAgent>().destination = GameObject.Find("Evan").transform.position;

                    yield return(null);

                    while (GetComponent <NavMeshAgent>().remainingDistance > 1)
                    {
                        yield return(null);
                    }

                    this.model.UpdateBelief(
                        new Phrase(Expression.MAKE, Expression.SELF,
                                   new Phrase(Expression.AT, Expression.SELF, Expression.EVAN)));

                    continue;
                }

                if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.AT, Expression.SELF, Expression.GOAL))))
                {
                    GetComponent <NavMeshAgent>().destination = GameObject.Find("Prize").transform.position;

                    yield return(null);

                    while (GetComponent <NavMeshAgent>().remainingDistance > 1)
                    {
                        yield return(null);
                    }

                    this.model.UpdateBelief(
                        new Phrase(Expression.MAKE, Expression.SELF,
                                   new Phrase(Expression.AT, Expression.SELF, Expression.GOAL)));

                    continue;
                }

                if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.AT, Expression.SELF, new Phrase(Expression.THE, Expression.DOOR)))))
                {
                    GetComponent <NavMeshAgent>().destination = GameObject.Find("Door").transform.position;

                    yield return(null);

                    while (GetComponent <NavMeshAgent>().remainingDistance > 1)
                    {
                        yield return(null);
                    }

                    continue;
                }

                if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.OPEN, new Phrase(Expression.THE, Expression.DOOR)))))
                {
                    controller.door.SetActive(false);
                    continue;
                }

                if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.CLOSED, new Phrase(Expression.THE, Expression.DOOR)))))
                {
                    controller.door.SetActive(true);
                    continue;
                }

                if (action.Equals(new Phrase(Expression.WOULD,
                                             new Phrase(Expression.NOT, new Phrase(Expression.POSSESS, Expression.SELF, Expression.RUBY)))))
                {
                    // Debug.Log("GIVE UP RUBY!!!");
                    continue;
                }
            }

            // StopCoroutine(GoTo("Bob"));
            // StopCoroutine(GoTo("Evan"));
            // StopCoroutine(GoTo("DoorFront"));

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.AT, Expression.SELF, Expression.BOB))))
            {
                yield return(StartCoroutine(GoTo("Bob")));

                // this.model.Add(new Phrase(Expression.AT, Expression.EVAN, Expression.BOB));
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.AT, Expression.SELF, Expression.EVAN))))
            {
                yield return(StartCoroutine(GoTo("Evan")));

                // this.model.Add(new Phrase(Expression.AT, Expression.EVAN, Expression.BOB));
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.AT, Expression.SELF, new Phrase(Expression.THE, Expression.DOOR)))))
            {
                yield return(StartCoroutine(GoTo("DoorFront")));

                this.model.UpdateBelief(new Phrase(Expression.MAKE, Expression.SELF, new Phrase(Expression.AT, Expression.SELF, new Phrase(Expression.THE, Expression.DOOR))));
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.AT, Expression.SELF, new Phrase(Expression.THE, Expression.COW)))))
            {
                yield return(StartCoroutine(GoTo("Cow")));

                this.model.UpdateBelief(new Phrase(Expression.MAKE, Expression.SELF, new Phrase(Expression.AT, Expression.SELF, new Phrase(Expression.THE, Expression.COW))));
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.AT, Expression.SELF, Expression.PLAYER))))
            {
                yield return(StartCoroutine(GoTo("Player(Clone)")));

                this.model.UpdateBelief(new Phrase(Expression.MAKE, Expression.SELF, new Phrase(Expression.AT, Expression.SELF, new Phrase(Expression.PLAYER))));
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.AT, Expression.SELF, new Phrase(Expression.THE, Expression.TREE)))))
            {
                yield return(StartCoroutine(GoTo("tree")));

                this.model.UpdateBelief(new Phrase(Expression.MAKE, Expression.SELF, new Phrase(Expression.AT, Expression.SELF, new Phrase(Expression.THE, Expression.TREE))));
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.AT, Expression.SELF, new Phrase(Expression.THE, Expression.LOG)))))
            {
                yield return(StartCoroutine(GoTo("log")));

                this.model.UpdateBelief(new Phrase(Expression.MAKE, Expression.SELF, new Phrase(Expression.AT, Expression.SELF, new Phrase(Expression.THE, Expression.LOG))));
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.AT, Expression.SELF, new Phrase(Expression.THE, new Phrase(Expression.POSSESS, new Phrase(Expression.THE, Expression.LOG), 1))))))
            {
                yield return(StartCoroutine(GoTo("Woodcutter")));

                this.model.UpdateBelief(new Phrase(Expression.MAKE, Expression.SELF, new Phrase(Expression.AT, Expression.SELF, new Phrase(Expression.THE, new Phrase(Expression.POSSESS, new Phrase(Expression.THE, Expression.LOG), 1)))));
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.EXISTS, new Phrase(Expression.THE, Expression.LOG)))))
            {
                GameObject.Find("tree").SetActive(false);
                controller.log.SetActive(true);
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.WEAR, Expression.SELF, new Phrase(Expression.THE, new Phrase(Expression.FAKE, Expression.CROWN))))))
            {
                this.model.UpdateBelief(new Phrase(Expression.MAKE,
                                                   Expression.SELF,
                                                   new Phrase(Expression.WEAR,
                                                              Expression.SELF,
                                                              new Phrase(Expression.THE, new Phrase(Expression.FAKE, Expression.CROWN)))));

                controller.fakeCrown.SetActive(true);
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.NOT, new Phrase(Expression.WEAR, Expression.SELF, new Phrase(Expression.THE, new Phrase(Expression.FAKE, Expression.CROWN)))))))
            {
                this.model.UpdateBelief(new Phrase(Expression.MAKE,
                                                   Expression.SELF,
                                                   new Phrase(Expression.NOT,
                                                              new Phrase(Expression.WEAR,
                                                                         Expression.SELF,
                                                                         new Phrase(Expression.THE, new Phrase(Expression.FAKE, Expression.CROWN))))));

                controller.fakeCrown.SetActive(false);
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.POSSESS, Expression.PLAYER, new Phrase(Expression.THE, new Phrase(Expression.FAKE, Expression.CROWN))))))
            {
                this.model.UpdateBelief(new Phrase(Expression.MAKE,
                                                   Expression.SELF,
                                                   new Phrase(Expression.NOT,
                                                              new Phrase(Expression.POSSESS,
                                                                         Expression.SELF,
                                                                         new Phrase(Expression.THE, new Phrase(Expression.FAKE, Expression.CROWN))))));

                this.model.UpdateBelief(new Phrase(Expression.MAKE,
                                                   Expression.SELF,
                                                   new Phrase(Expression.POSSESS,
                                                              Expression.PLAYER,
                                                              new Phrase(Expression.THE, new Phrase(Expression.FAKE, Expression.CROWN)))));

                GameObject player = GameObject.Find("Player(Clone)");

                controller.fakeCrown.transform.SetParent(player.transform);
                controller.fakeCrown.transform.position = new Vector3(player.transform.position.x, player.transform.position.y + 0.25f);
                Player playerScript = player.GetComponent <Player>();
                playerScript.currentWearObject = controller.fakeCrown;
                if (controller.fakeCrown.activeSelf)
                {
                    playerScript.isWearing = true;
                }

                continue;
            }

            // The second "if" clauses are commented out b/c without coroutines, they aren't activated in time.
            // TODO Uncomment when coroutine stuff is sorted out.

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.OPEN, new Phrase(Expression.THE, Expression.DOOR)))))
            {
                //     if (currentInteractObject != null && currentInteractObject.name.Equals("DoorFront")) {
                this.controller.lowClick.Play();
                GameObject.Find("Door").GetComponent <Door>().Open();
                // this.model.Remove(new Phrase(Expression.CLOSED, new Phrase(Expression.THE, Expression.DOOR)));
                this.model.UpdateBelief(new Phrase(Expression.MAKE, Expression.SELF, new Phrase(Expression.OPEN, new Phrase(Expression.THE, Expression.DOOR))));
                // ShowSpeechBubble(new Phrase(Expression.OPEN, new Phrase(Expression.THE, Expression.DOOR)));
                //     }
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.CLOSED, new Phrase(Expression.THE, Expression.DOOR)))))
            {
                //     if (currentInteractObject != null && currentInteractObject.name.Equals("DoorFront")) {
                this.controller.lowClick.Play();
                GameObject.Find("Door").GetComponent <Door>().Close();
                // this.model.Remove(new Phrase(Expression.OPEN, new Phrase(Expression.THE, Expression.DOOR)));
                this.model.UpdateBelief(new Phrase(Expression.MAKE, Expression.SELF, new Phrase(Expression.CLOSED, new Phrase(Expression.THE, Expression.DOOR))));
                // ShowSpeechBubble(new Phrase(Expression.CLOSED, new Phrase(Expression.THE, Expression.DOOR)));
                //     }
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.INTEND, Expression.EVAN, new Phrase(Expression.OPEN, new Phrase(Expression.THE, Expression.DOOR))))))
            {
                this.controller.placeExpression.Play();
                // the below code works with fromScratch, to a degree
                yield return(ShowSpeechBubble(new Phrase(Expression.WOULD, new Phrase(Expression.OPEN, new Phrase(Expression.THE, Expression.DOOR)))));

                // yield return ShowSpeechBubble("would");

                // yield return new WaitForSeconds(2.0f);
                GameObject.Find("Evan").GetComponent <NPC>().ReceiveExpression(this.name, new Phrase(Expression.WOULD, new Phrase(Expression.OPEN, new Phrase(Expression.THE, Expression.DOOR))));
                // this.model.Remove(new Phrase(Expression.INTEND, Expression.EVAN, new Phrase(Expression.CLOSED, new Phrase(Expression.THE, Expression.DOOR))));
                // this.model.Add(new Phrase(Expression.INTEND, Expression.EVAN, new Phrase(Expression.OPEN, new Phrase(Expression.THE, Expression.DOOR))));

                // this.model.Remove(new Phrase(Expression.CLOSED, new Phrase(Expression.THE, Expression.DOOR)));
                this.model.UpdateBelief(new Phrase(Expression.MAKE, Expression.SELF, new Phrase(Expression.OPEN, new Phrase(Expression.THE, Expression.DOOR))));

                // ShowSpeechBubble(new Phrase(Expression.INTEND, Expression.EVAN, new Phrase(Expression.OPEN, new Phrase(Expression.THE, Expression.DOOR))));
                continue;
            }

            if (action.Equals(new Phrase(Expression.WOULD, new Phrase(Expression.INTEND, Expression.EVAN, new Phrase(Expression.CLOSED, new Phrase(Expression.THE, Expression.DOOR))))))
            {
                this.controller.placeExpression.Play();
                yield return(ShowSpeechBubble(new Phrase(Expression.WOULD, new Phrase(Expression.CLOSED, new Phrase(Expression.THE, Expression.DOOR)))));

                // yield return ShowSpeechBubble("would");
                // yield return new WaitForSeconds(2.0f);
                GameObject.Find("Evan").GetComponent <NPC>().ReceiveExpression(this.name, new Phrase(Expression.WOULD, new Phrase(Expression.CLOSED, new Phrase(Expression.THE, Expression.DOOR))));
                // this.model.Remove(new Phrase(Expression.INTEND, Expression.EVAN, new Phrase(Expression.OPEN, new Phrase(Expression.THE, Expression.DOOR))));
                // this.model.Add(new Phrase(Expression.INTEND, Expression.EVAN, new Phrase(Expression.CLOSED, new Phrase(Expression.THE, Expression.DOOR))));

                // this.model.Remove(new Phrase(Expression.OPEN, new Phrase(Expression.THE, Expression.DOOR)));
                this.model.UpdateBelief(new Phrase(Expression.MAKE, Expression.SELF, new Phrase(Expression.CLOSED, new Phrase(Expression.THE, Expression.DOOR))));

                // ShowSpeechBubble(new Phrase(Expression.INTEND, Expression.EVAN, new Phrase(Expression.CLOSED, new Phrase(Expression.THE, Expression.DOOR))));
                continue;
            }

            MetaVariable xi0 = new MetaVariable(SemanticType.INDIVIDUAL, 0);
            MetaVariable xt0 = new MetaVariable(SemanticType.TRUTH_VALUE, 0);

            IPattern assertionSchema =
                new ExpressionPattern(Expression.WOULD,
                                      new ExpressionPattern(Expression.BELIEVE, xi0, xt0));

            List <Dictionary <MetaVariable, Expression> > assertionBinding = assertionSchema.GetBindings(action);

            if (assertionBinding != null)
            {
                Expression assertion = new Phrase(Expression.ASSERT, assertionBinding[0][xt0]);
                yield return(ShowSpeechBubble(assertion));

                Expression recipient = assertionBinding[0][xi0];

                if (recipient.Equals(Expression.BOB))
                {
                    GameObject.Find("Bob").GetComponent <NPC>().ReceiveExpression(this.name, assertion);
                }

                if (recipient.Equals(Expression.EVAN))
                {
                    GameObject.Find("Evan").GetComponent <NPC>().ReceiveExpression(this.name, assertion);
                }
            }

            MetaVariable xc0 = new MetaVariable(SemanticType.CONFORMITY_VALUE, 0);

            IPattern conformitySchema =
                new ExpressionPattern(Expression.WOULD,
                                      new ExpressionPattern(Expression.EXPRESS_CONFORMITY, Expression.SELF, xi0, xc0));

            List <Dictionary <MetaVariable, Expression> > conformityBinding = conformitySchema.GetBindings(action);

            if (conformityBinding != null)
            {
                Expression conformity = conformityBinding[0][xc0];
                yield return(ShowSpeechBubble(conformity));

                Expression recipient = conformityBinding[0][xi0];

                if (recipient.Equals(Expression.BOB))
                {
                    GameObject.Find("Bob").GetComponent <NPC>().ReceiveExpression(this.name, conformity);
                }

                if (recipient.Equals(Expression.EVAN))
                {
                    GameObject.Find("Evan").GetComponent <NPC>().ReceiveExpression(this.name, conformity);
                }

                if (recipient.Equals(new Phrase(Expression.THE, new Phrase(Expression.POSSESS, new Phrase(Expression.THE, Expression.LOG), 1))))
                {
                    GameObject.Find("Woodcutter").GetComponent <NPC>().ReceiveExpression(this.name, conformity);
                }

                this.model.UpdateBelief(new Phrase(Expression.MAKE, Expression.SELF,
                                                   new Phrase(Expression.EXPRESS_CONFORMITY, Expression.SELF, recipient, conformity)));
            }

            MetaVariable xi1 = new MetaVariable(SemanticType.INDIVIDUAL, 1);
            IPattern     possessionSchema =
                new ExpressionPattern(Expression.WOULD,
                                      new ExpressionPattern(Expression.POSSESS, xi0, xi1));

            List <Dictionary <MetaVariable, Expression> > possessionBinding = possessionSchema.GetBindings(action);

            if (possessionBinding != null)
            {
                Expression possessor = possessionBinding[0][xi0];
                Expression item      = possessionBinding[0][xi1];
                GameObject inventory = GameObject.Find(this.gameObject.name + "/Inventory");
                foreach (Transform t in inventory.GetComponentsInChildren <Transform>())
                {
                    if (t.gameObject.name.ToLower().Equals(item.ToString()))
                    {
                        t.gameObject.transform.SetParent(GameObject.Find(possessor.ToString() + "/Inventory").transform);
                        t.gameObject.transform.position = GameObject.Find(possessor.ToString() + "/Inventory").transform.position;
                        // t.position = new Vector3(5f, 1f, 0f);
                    }
                }

                this.model.UpdateBelief(new Phrase(Expression.MAKE, Expression.SELF, new Phrase(Expression.POSSESS, possessor, item)));
                // if () {

                // }
            }
        }
        // this.controller.combineSuccess.Play();
        // yield return ShowSpeechBubble("yes");
        model.ClearGoal();
        actionInProgress = false;
        yield return(true);
    }
Пример #17
0
 public void VisitExpressionPattern(ExpressionPattern exprPattern)
 {
     throw new NotImplementedException();
 }
Пример #18
0
    // returns the set of sentences that prove expr, if any.
    // returns NULL if this model doesn't prove expr.
    // TODO: for planning, need to sequence and compare
    // costs from multiple paths
    public HashSet <Expression> GetBasis(bool plan, Expression expr, List <Expression> suppositions)
    {
        if (this.loopCounter > 100)
        {
            return(null);
        }

        IPattern secondOrderAttitudePattern =
            new ExpressionPattern(new MetaVariable(SemanticType.INDIVIDUAL_TRUTH_RELATION, 0),
                                  new MetaVariable(SemanticType.INDIVIDUAL, 0),
                                  new ExpressionPattern(new MetaVariable(SemanticType.INDIVIDUAL_TRUTH_RELATION, 1),
                                                        new MetaVariable(SemanticType.INDIVIDUAL, 1),
                                                        new MetaVariable(SemanticType.TRUTH_VALUE, 0)));

        if (secondOrderAttitudePattern.Matches(expr))
        {
            return(null);
        }

        // if it's a plan instead of a proof or vice versa,
        // we need to reset
        if (isLastPlan != plan)
        {
            triedExpressions.Clear();
        }
        isLastPlan = plan;

        // BEGIN: checking to see if suppositions match.
        // If they we need to reset our tried proofs.
        foreach (Expression supposition in suppositions)
        {
            if (!this.lastSuppositions.Contains(supposition))
            {
                triedExpressions.Clear();
            }
        }

        foreach (Expression supposition in this.lastSuppositions)
        {
            if (!suppositions.Contains(supposition))
            {
                triedExpressions.Clear();
            }
        }

        // END supposition check

        HashSet <Expression> basis = new HashSet <Expression>();

        if (suppositions.Contains(expr))
        {
            return(basis);
        }

        // BASE CASES
        if (triedExpressions.ContainsKey(expr))
        {
            return(triedExpressions[expr]);
        }

        triedExpressions.Add(expr, null);
        this.loopCounter++;

        if (this.Contains(expr))
        {
            basis.Add(expr);
            triedExpressions[expr] = basis;
            return(basis);
        }

        // no inference with WOULD yet TODO add that
        if (!expr.type.Equals(SemanticType.TRUTH_VALUE))
        {
            return(null);
        }

        if (this.Contains(new Phrase(Expression.NOT, expr)))
        {
            return(null);
        }

        MetaVariable xt0 = new MetaVariable(SemanticType.TRUTH_VALUE, 0);

        // MODUS PONENS: checking to see if anything in the model satisifies
        // X, X -> expr
        IPattern consequentPattern =
            new ExpressionPattern(Expression.IF, xt0, expr);

        foreach (Expression e in GetAll())
        {
            List <Dictionary <MetaVariable, Expression> > antecedents = consequentPattern.GetBindings(e);
            if (antecedents == null)
            {
                continue;
            }
            Expression           antecedent      = antecedents[0][xt0];
            HashSet <Expression> antecedentBasis = GetBasis(plan, antecedent, suppositions);
            if (antecedentBasis != null)
            {
                antecedentBasis.Add(new Phrase(Expression.IF, antecedent, expr));
                triedExpressions[expr] = antecedentBasis;
                return(antecedentBasis);
            }
        }

        // END MODUS PONENS

        // UNIVERSAL ELIMINATION
        MetaVariable xp0 = new MetaVariable(SemanticType.PREDICATE, 0);
        MetaVariable xi0 = new MetaVariable(SemanticType.INDIVIDUAL, 0);
        IPattern     predicatePattern =
            new ExpressionPattern(xp0, xi0);

        List <Dictionary <MetaVariable, Expression> > decomposition = predicatePattern.GetBindings(expr);

        if (decomposition != null)
        {
            foreach (Dictionary <MetaVariable, Expression> binding in decomposition)
            {
                Expression subject   = binding[xi0];
                Expression predicate = binding[xp0];

                IPattern universalPattern =
                    new ExpressionPattern(Expression.ALL, xp0, predicate);

                foreach (Expression e in GetAll())
                {
                    List <Dictionary <MetaVariable, Expression> > domains =
                        universalPattern.GetBindings(e);

                    if (domains == null)
                    {
                        continue;
                    }

                    Expression           domain      = domains[0][xp0];
                    HashSet <Expression> domainBasis = GetBasis(plan, new Phrase(domain, subject), suppositions);
                    if (domainBasis != null)
                    {
                        domainBasis.Add(new Phrase(Expression.ALL, domain, predicate));
                        triedExpressions[expr] = domainBasis;
                        return(domainBasis);
                    }
                }
            }
        }

        // END UNIVERSAL ELIMINATION

        // TRANSITIVITY OF BETTER
        MetaVariable xt1           = new MetaVariable(SemanticType.TRUTH_VALUE, 1);
        IPattern     betterPattern = new ExpressionPattern(Expression.BETTER, xt0, xt1);

        List <Dictionary <MetaVariable, Expression> > preferands = betterPattern.GetBindings(expr);

        if (preferands != null)
        {
            Expression better = preferands[0][xt0];
            Expression worse  = preferands[0][xt1];

            foreach (Expression p in preferables)
            {
                HashSet <Expression> betterBasis =
                    GetBasis(plan, new Phrase(Expression.BETTER, better, p), suppositions);

                if (betterBasis != null)
                {
                    HashSet <Expression> worseBasis =
                        GetBasis(plan, new Phrase(Expression.BETTER, p, worse), suppositions);

                    if (worseBasis != null)
                    {
                        HashSet <Expression> transitiveBasis = new HashSet <Expression>();
                        foreach (Expression b in betterBasis)
                        {
                            transitiveBasis.Add(b);
                        }
                        foreach (Expression b in worseBasis)
                        {
                            transitiveBasis.Add(b);
                        }
                        return(transitiveBasis);
                    }
                }
            }
        }
        // END TRANSITIVITY OF BETTER

        // TRANSITIVITY OF AS_GOOD_AS
        IPattern asGoodAsPattern = new ExpressionPattern(Expression.AS_GOOD_AS, xt0, xt1);

        preferands = asGoodAsPattern.GetBindings(expr);

        if (preferands != null)
        {
            Expression first  = preferands[0][xt0];
            Expression second = preferands[0][xt1];

            foreach (Expression p in preferables)
            {
                HashSet <Expression> firstBasis =
                    GetBasis(plan, new Phrase(Expression.AS_GOOD_AS, first, p), suppositions);

                if (firstBasis != null)
                {
                    HashSet <Expression> secondBasis =
                        GetBasis(plan, new Phrase(Expression.AS_GOOD_AS, p, second), suppositions);

                    if (secondBasis != null)
                    {
                        HashSet <Expression> transitiveBasis = new HashSet <Expression>();
                        foreach (Expression b in firstBasis)
                        {
                            transitiveBasis.Add(b);
                        }
                        foreach (Expression b in secondBasis)
                        {
                            transitiveBasis.Add(b);
                        }
                        return(transitiveBasis);
                    }
                }
            }
        }
        // END TRANSITIVITY OF AS_GOOD_AS

        // BOUND
        IPattern trustworthyPattern =
            new ExpressionPattern(Expression.NOT, new ExpressionPattern(Expression.TRUSTWORTHY, xi0));

        List <Dictionary <MetaVariable, Expression> > promiser = trustworthyPattern.GetBindings(expr);

        if (promiser != null)
        {
            IPattern promisePattern = new ExpressionPattern(Expression.BOUND, promiser[0][xi0], xt0);

            foreach (Expression e in GetAll())
            {
                List <Dictionary <MetaVariable, Expression> > promises = promisePattern.GetBindings(e);
                if (promises == null)
                {
                    continue;
                }
                Expression           promise      = promises[0][xt0];
                HashSet <Expression> promiseBasis = GetBasis(plan, new Phrase(Expression.NOT, promise));
                if (promiseBasis != null)
                {
                    basis.Add(new Phrase(Expression.BOUND, promiser[0][xi0], promise));
                    basis.Add(new Phrase(Expression.NOT, promise));
                    triedExpressions[expr] = basis;
                    return(basis);
                }
            }
        }

        // END BOUND

        // CONDITIIONAL PROOF
        // MetaVariable xt1 = new MetaVariable(SemanticType.TRUTH_VALUE, 1);

        IPattern conditionalPattern = new ExpressionPattern(Expression.IF, xt0, xt1);
        List <Dictionary <MetaVariable, Expression> > conditionalBindings = conditionalPattern.GetBindings(expr);

        if (conditionalBindings != null)
        {
            return(GetBasis(plan, conditionalBindings[0][xt1], ImAdd(conditionalBindings[0][xt0], suppositions)));
        }

        // END CONDITIONAL PROOF

        // BELIEF
        // if the model proves X, it also proves believes(self, X)
        IPattern selfBeliefPattern = new ExpressionPattern(Expression.BELIEVE, Expression.SELF, xt0);
        List <Dictionary <MetaVariable, Expression> > selfBeliefBindings = selfBeliefPattern.GetBindings(expr);

        if (selfBeliefBindings != null)
        {
            HashSet <Expression> contentBasis = GetBasis(false, selfBeliefBindings[0][xt0], suppositions);
            triedExpressions[expr] = contentBasis;
            return(contentBasis);
        }
        // END BELIEF

        // LACK OF BELIEF
        // if the model fails to prove X, it proves ~believes(self, X)
        // NOTE this isn't the same as believes(self, ~X)
        IPattern notSelfBeliefPattern = new ExpressionPattern(Expression.NOT, selfBeliefPattern);
        List <Dictionary <MetaVariable, Expression> > notSelfBeliefBindings = notSelfBeliefPattern.GetBindings(expr);

        if (notSelfBeliefBindings != null)
        {
            if (GetBasis(false, notSelfBeliefBindings[0][xt0], suppositions) == null)
            {
                basis.Add(expr);
                triedExpressions[expr] = basis;
                return(basis);
            }
        }
        // END LACK OF BELIEF

        // RECURSIVE CASES
        foreach (SubstitutionRule sr in this.substitutionRules)
        {
            List <SubstitutionRule.Result> admissibleSubstitutions = sr.Substitute(this, plan, suppositions, expr);

            if (admissibleSubstitutions == null)
            {
                continue;
            }

            foreach (SubstitutionRule.Result conjunctSubstitution in admissibleSubstitutions)
            {
                basis.Clear();
                bool proved = true;

                List <IPattern> toFindList = new List <IPattern>();

                foreach (IPattern p in conjunctSubstitution.positives)
                {
                    Expression e = p.ToExpression();
                    if (e == null)
                    {
                        toFindList.Add(p);
                    }
                    else
                    {
                        HashSet <Expression> subBasis = this.GetBasis(plan, e, suppositions);
                        if (subBasis == null)
                        {
                            proved = false;
                            break;
                        }
                        else
                        {
                            foreach (Expression b in subBasis)
                            {
                                basis.Add(b);
                            }
                        }
                    }
                }

                if (!proved)
                {
                    continue;
                }

                foreach (IPattern p in conjunctSubstitution.negatives)
                {
                    if (p == null)
                    {
                        continue;
                    }
                    Expression e = p.ToExpression();
                    if (e == null)
                    {
                        toFindList.Add(new ExpressionPattern(Expression.NOT, p));
                    }
                    else
                    {
                        HashSet <Expression> subBasis = this.GetBasis(plan, new Phrase(Expression.NOT, e), suppositions);
                        if (subBasis == null)
                        {
                            proved = false;
                            break;
                        }
                        else
                        {
                            foreach (Expression b in subBasis)
                            {
                                basis.Add(b);
                            }
                        }
                    }
                }

                foreach (IPattern p in conjunctSubstitution.assumptions)
                {
                    if (p == null)
                    {
                        continue;
                    }
                    Expression e = p.ToExpression();
                    if (e != null)
                    {
                        if (Contains(new Phrase(Expression.NOT, e)))
                        {
                            proved = false;
                            break;
                        }
                    }
                }

                if (!proved)
                {
                    continue;
                }

                if (toFindList.Count == 0)
                {
                    if (proved)
                    {
                        foreach (IPattern p in conjunctSubstitution.assumptions)
                        {
                            Expression e = p.ToExpression();
                            basis.Add(e);
                        }
                        triedExpressions[expr] = basis;
                        return(basis);
                    }
                }
                else
                {
                    IPattern[] toFindArray = new IPattern[toFindList.Count];

                    int counter = 0;
                    foreach (IPattern p in toFindList)
                    {
                        if (p != null)
                        {
                            toFindArray[counter] = p;
                            counter++;
                        }
                    }

                    // TODO: find a way for Find() or something else to RECURSIVELY prove
                    // the potential bindings for use
                    List <Dictionary <MetaVariable, Expression> > bindings      = Find(plan, suppositions, toFindArray);
                    Dictionary <MetaVariable, Expression>         provedBinding = null;
                    if (bindings != null)
                    {
                        foreach (Dictionary <MetaVariable, Expression> binding in bindings)
                        {
                            foreach (IPattern p in toFindList)
                            {
                                Expression fullyBound = p.Bind(binding).ToExpression();
                                if (fullyBound == null)
                                {
                                    proved = false;
                                    break;
                                }
                                HashSet <Expression> subBasis = GetBasis(plan, fullyBound, suppositions);
                                if (subBasis == null)
                                {
                                    proved = false;
                                    break;
                                }
                                else
                                {
                                    provedBinding = binding;
                                    foreach (Expression b in subBasis)
                                    {
                                        basis.Add(b);
                                    }
                                }
                            }
                            if (!proved)
                            {
                                break;
                            }
                        }

                        foreach (IPattern p in conjunctSubstitution.assumptions)
                        {
                            Expression fullyBound = p.Bind(provedBinding).ToExpression();
                            basis.Add(fullyBound);
                        }
                        return(basis);
                    }
                }
            }
        }
        // ACTIONS
        if (plan)
        {
            // Check to see if this expression is actionable.
            HashSet <Expression> abilityBasis = GetBasis(plan, new Phrase(Expression.ABLE, Expression.SELF, expr), suppositions);
            if (abilityBasis != null)
            {
                abilityBasis.Add(new Phrase(Expression.WOULD, expr));
                return(abilityBasis);
            }

            // check if anyone else is able to make the expr true.
            // SPECIAL PURPOSE: this can be handled generally but
            // will involve a more efficient algorithm.
            IPattern otherAbilityPattern = new ExpressionPattern(Expression.ABLE, xi0, expr);
            foreach (Expression e in GetAll())
            {
                List <Dictionary <MetaVariable, Expression> > otherAbilityBinding = otherAbilityPattern.GetBindings(e);
                if (otherAbilityBinding == null)
                {
                    continue;
                }

                // we've found another person who can do what we want
                Expression other = otherAbilityBinding[0][xi0];

                // if they don't mind helping, just request it
                if (GetBasis(false,
                             new Phrase(Expression.NOT, new Phrase(Expression.PREFER, other, Expression.NEUTRAL, expr)), suppositions) != null)
                {
                    HashSet <Expression> expressBasis = GetBasis(true,
                                                                 new Phrase(Expression.EXPRESS_CONFORMITY,
                                                                            Expression.SELF, other, new Phrase(Expression.WOULD, expr)),
                                                                 suppositions);
                    triedExpressions[expr] = expressBasis;
                    return(expressBasis);
                }

                // otherwise, we'll need to make an offer.
                // TODO: jot down algorithm here.
                foreach (Expression e2 in GetAll())
                {
                    // TODO
                }
            }
        }
        // END  ACTIONS
        return(null);
    }
Пример #19
0
 public void VisitExpressionPattern(ExpressionPattern exprPattern)
 {
     exprPattern.Expression.AcceptWalker(this);
 }
Пример #20
0
    // public void SetUtility(Expression expr, float utility) {
    //     this.utilities[expr] = utility;
    // }

    // OIT 1, NIT 2, OE 3, Inf 4, OCT 5, OP 6, NCT 7, NE 8, NP 9, B 10
    public int EstimatePlausibility(Expression e, bool isNew)
    {
        MetaVariable xi0 = new MetaVariable(SemanticType.INDIVIDUAL, 0);
        MetaVariable xt0 = new MetaVariable(SemanticType.TRUTH_VALUE, 0);
        IPattern     perceptionPattern  = new ExpressionPattern(Expression.PERCEIVE, Expression.SELF, xt0);
        IPattern     testimonyPattern   = new ExpressionPattern(Expression.BELIEVE, xi0, xt0);
        IPattern     expectationPattern = new ExpressionPattern(Expression.MAKE, Expression.SELF, xt0);

        List <Dictionary <MetaVariable, Expression> > bindings = perceptionPattern.GetBindings(e);

        if (bindings != null)
        {
            if (isNew)
            {
                return(9);
            }
            else
            {
                return(6);
            }
        }

        bindings = testimonyPattern.GetBindings(e);
        if (bindings != null)
        {
            bool isCredible = true; // this.Proves(new Phrase(Expression.CREDIBLE, bindings[0][xi0]));
            if (isCredible)
            {
                if (isNew)
                {
                    return(7);
                }
                return(5);
            }
            else
            {
                if (isNew)
                {
                    return(2);
                }
                return(1);
            }
        }

        bindings = expectationPattern.GetBindings(e);
        if (bindings != null)
        {
            if (isNew)
            {
                return(8);
            }
            return(3);
        }

        if (this.Contains(e))
        {
            return(10);
        }

        if (e.Equals(new Word(SemanticType.TRUTH_VALUE, "example")))
        {
            return(4);
        }

        if (e.Equals(new Phrase(Expression.NOT, new Word(SemanticType.TRUTH_VALUE, "example"))))
        {
            return(5);
        }

        return(4);
    }