Exemple #1
0
        public static void SelectChoice_PrologKBChanges(object sender, SelectChoiceEventArgs_Old eventArgs)
        {
            ContentUnit selectedChoice = eventArgs.SelectedChoice;
            U_PrologKB  kb             = eventArgs.Blackboard.LookupSingleton <U_PrologKB>();

            // If there are any facts to retract, retract them
            if (selectedChoice.HasMetadataSlot(FactDeleteList_Prolog))
            {
                string[] deleteList = (string[])selectedChoice.Metadata[FactDeleteList_Prolog];
                foreach (string fact in deleteList)
                {
                    kb.Retract(fact);
                }
            }

            // If there are any facts to add, add them
            if (selectedChoice.HasMetadataSlot(FactAddList_Prolog))
            {
                string[] addList = (string[])selectedChoice.Metadata[FactAddList_Prolog];
                foreach (string fact in addList)
                {
                    kb.Assert(fact);
                }
            }
        }
        // Gathers the choices for the selected content unit, stores them on fields provided on this KS, and calls any calls any registered event handlers.
        internal override void Execute(IDictionary <string, object> boundVars)
        {
            ContentUnit selectedCU = (ContentUnit)boundVars[SelectedContentUnit];

            string textToDisplay = (string)selectedCU.Content[Text];

            ContentUnit[] choices = GetChoices(selectedCU);

            string[] choicesToDisplay;

            if (choices.Any())
            {
                int choiceCounter = 0;
                choicesToDisplay = new string[choices.Count()];
                foreach (ContentUnit choice in choices)
                {
                    choicesToDisplay[choiceCounter++] = (string)choice.Content[Text];
                }
            }
            else
            {
                // No choices. Create a 0 length string array so that callers don't have to worry about null checks.
                choicesToDisplay = new string[0];
            }

            // Remove the displayed SelectedContentUnit from the blackboard. Do this to indicate that we have processed the selectedCU.
            m_blackboard.RemoveUnit(selectedCU);

            // Construct event args and call the event handler.
            var eventArgs = new PresenterExecuteEventArgs(textToDisplay, choicesToDisplay, choices);

            OnExecute(eventArgs);
        }
        public void TestExecute_ReactiveChoicePresenter(IBlackboard blackboard, ContentUnit selectedCU, ContentUnit originalCU, ContentUnit[] choices)
        {
            blackboard.Clear();
            blackboard.AddUnit(selectedCU);
            blackboard.AddUnit(originalCU);
            blackboard.AddLink(originalCU, selectedCU, LinkTypes.L_SelectedContentUnit);

            foreach (ContentUnit choice in choices)
            {
                blackboard.AddUnit(choice);
                blackboard.AddLink(originalCU, choice, LinkTypes.L_Choice);
            }

            KS_Old_ReactiveChoicePresenter ks = new KS_Old_ReactiveChoicePresenter(blackboard);

            ks.PresenterExecute += GenerateEventHandler(selectedCU, choices, blackboard);

            var KSAs = ks.Precondition();

            int count = KSAs.Count();

            Assert.Equal(1, count);

            // Execute the activated choice presenter
            KSAs.ElementAt(0).Execute();
        }
Exemple #4
0
        internal override void Execute(IDictionary <string, object> boundVars)
        {
            string targetContentUnitID = ((U_IDSelectRequest)boundVars[IDSelectRequest]).TargetContentUnitID;
            var    contentUnits        = from contentUnit in m_blackboard.LookupUnits <ContentUnit>()          // lookup content units
                                         where contentUnit.HasMetadataSlot(ContentUnitID)                      // where the content unit has an ID
                                         where contentUnit.Metadata[ContentUnitID].Equals(targetContentUnitID) // and the ID equals the target ID
                                         select contentUnit;

            //fixme: for the purposes of getting something running quickly, I'm doing the random selection among potentially multiple content units here.
            // However, this should be done as a pooling process with some other selector selecting from the pool.
            if (contentUnits.Any())
            {
                // One or more content units matching the ContentUnitID in the U_IDQuery were found.
                // fixme: if no matching content unit was found, perhaps the KS should post something indiciating the execution failed.
                // Or this could be done via tracing, with a KS that looks for tracing patterns, though this will require separate "failure patterns"
                // for each case. So probably better to have more general semantics for KSs to post success and failure into the trace.

                int         r        = m_rand.Next(contentUnits.Count());
                ContentUnit randUnit = contentUnits.ElementAt(r);

                // Need to store the selected content unit. Creating a new type to do this seems awkward (SelectedContentUnit).
                // Could do this with links: SelectedContentUnit link points at the correct CU. But what should it point from?
                // Default blackboard indexing always uses the type as the hashbucket. This is going to result in creating a zillion types.
                // Solution: Add another slot called SelectedContentUnit and add it to a copy of the selected content unit. Value of the new slot is null.

                // Selected content unit stored as a new ContentUnit with the SelectedContentUnit property set. It is linked back to the original content unit.
                ContentUnit newUnit = new ContentUnit(randUnit);
                newUnit.Metadata[SelectedContentUnit] = null;
                m_blackboard.AddUnit(newUnit);
                m_blackboard.AddLink(randUnit, newUnit, LinkTypes.L_SelectedContentUnit);
            }
            m_blackboard.RemoveUnit((IUnit)boundVars[IDSelectRequest]);
        }
        private EventHandler <PresenterExecuteEventArgs> GenerateEventHandler(ContentUnit selectedCU, ContentUnit[] choices, IBlackboard blackboard)
        {
            return((object sender, PresenterExecuteEventArgs eventArgs) =>
            {
                var presenterEventArgs = eventArgs as PresenterExecuteEventArgs;

                if (selectedCU != null)
                {
                    Assert.Equal(selectedCU.Content[Text], presenterEventArgs.TextToDisplay);
                    int numOfChoices = choices.Length;
                    Assert.Equal(numOfChoices, presenterEventArgs.Choices.Length);

                    foreach (ContentUnit choice in choices)
                    {
                        Assert.True(Array.Exists(presenterEventArgs.ChoicesToDisplay, element => element.Equals(choice.Content[Text])));
                    }
                }
                else
                {
                    Assert.Equal("", presenterEventArgs.TextToDisplay);
                }

                // Iterate through each of the choices selecting it and confirming that the correct U_IDSelectRequest is added.
                IChoicePresenter_Old cp = (IChoicePresenter_Old)sender;
                for (uint i = 0; i < presenterEventArgs.ChoicesToDisplay.Length; i++)
                {
                    cp.SelectChoice((ContentUnit[])presenterEventArgs.Choices, i);
                    U_IDSelectRequest idSelectRequest = blackboard.LookupSingleton <U_IDSelectRequest>();
                    Assert.True(idSelectRequest.TargetContentUnitID.Equals(choices[i].Metadata[TargetContentUnitID]));
                    blackboard.RemoveUnit(idSelectRequest); // Remove the U_IDSelect request before the next iteration.
                }
            });
        }
        public override void OnListItemClick(ListView l, View v, int position, long id)
        {
            ContentUnit cu     = ((ContentUnitAdapter)ListAdapter).GetItem(position);
            Intent      intent = new Intent(Activity, Java.Lang.Class.FromType(typeof(WebActivity)));

            intent.SetData(Android.Net.Uri.Parse(cu.URL));
            StartActivity(intent);
        }
        /*
         * Experiments with the following configuration:
         * Global Prolog KB stored on a knowledge unit.
         * Prolog query applicability tests associated with content units.
         */
        private static void AddPrologQueriesToContentUnits()
        {
            IBlackboard blackboard = new Blackboard();

#pragma warning disable CS0618 // Type or member is obsolete
            ContentUnit cu = new ContentUnit();
#pragma warning restore CS0618 // Type or member is obsolete

            // cu.Metadata[] =
        }
 private void TestUnits()
 {
     for (int i = 0; i < test_cnt; ++i)
     {
         ContentUnit cu = new ContentUnit()
         {
             header = "KEK lol #" + i, description = "SNOVA KEK omgwtf plsno", imgUrl = "http://vignette3.wikia.nocookie.net/animeandmangauniverse/images/e/e5/Kallen_Kozuki.jpg/revision/latest?cb=20120129132316.jpg"
         };
         cu.date = (i % 31).ToString() + ".12.0000";
         cu.URL  = "https://tjournal.ru/37885-v-saudovskoi-aravii-vipal-sneg";
         list_cu.Add(cu);
     }
 }
 /*
  * Given an array of choices and a 0-indexed choice selection, adds the appropriate query to the blackboard.
  */
 public void SelectChoice(ContentUnit[] choices, uint choiceMade)
 {
     if (choiceMade < choices.Length)
     {
         // Add a U_IDQuery to blackboard for the target content unit associated with the choice.
         ContentUnit selectedChoice = choices[choiceMade];
         m_blackboard.AddUnit(new U_IDSelectRequest((string)selectedChoice.Metadata[TargetContentUnitID]));
         SelectChoiceEventArgs eventArgs = new SelectChoiceEventArgs(selectedChoice, m_blackboard);
         OnSelectChoice(eventArgs);
     }
     else
     {
         throw new ArgumentOutOfRangeException(nameof(choiceMade), choiceMade, $"choiceMade must be between 0 and the number of choices - 1 {choices.Length - 1}");
     }
 }
        // fixme: TestSelectorPrecondition not passing. comment out for now and consider deleting if it doesn't make sense with the switch to ScheduledKnowledgeSources.
        //public static IEnumerable<object[]> Data_TestSelectorPrecondition()
        //{
        //    string inputPoolName = "inputPool";
        //    string outputPoolName = "outputPool";
        //    IBlackboard blackboard = new Blackboard();

        //    ContentUnit cuInputPool = new ContentUnit();
        //    cuInputPool.Metadata[ContentPool] = inputPoolName;

        //    ContentUnit cuDifferentPool = new ContentUnit();
        //    cuDifferentPool.Metadata[ContentPool] = "differentPool";

        //    ContentUnit cuNoPool = new ContentUnit();

        //    /* Structure of object[]:
        //     * IBlackboard: blackboard,
        //     * KnowledgeSource: KS whose precondition to test,
        //     * IUnit[]: array of KUs to add,
        //     * bool: whether there should be an activation
        //     */

        //    return new List<object[]>
        //    {
        //        // Empty blackboard
        //        new object[] {blackboard, new KS_ScheduledFilterSelector(blackboard, inputPoolName, outputPoolName), new IUnit[] { }, false },

        //        // Blackboard with content unit not in a pool
        //        new object[] {blackboard, new KS_ScheduledFilterSelector(blackboard, inputPoolName, outputPoolName), new IUnit[] { cuNoPool }, false },

        //        // Blackboard with content unit in a different pool
        //        new object[] {blackboard, new KS_ScheduledFilterSelector(blackboard, inputPoolName, outputPoolName), new IUnit[] { cuDifferentPool }, false },

        //        // Blackboard with content unit in input pool
        //        new object[] {blackboard, new KS_ScheduledFilterSelector(blackboard, inputPoolName, outputPoolName), new IUnit[] { cuInputPool }, true },

        //    };
        //}

        //[Theory]
        //[MemberData(nameof(Data_TestSelectorPrecondition))]
        //public void TestSelectorPrecondition(IBlackboard blackboard, ReactiveKnowledgeSource ks, IUnit[] unitsToAdd, bool activated)
        //{
        //    // Clear the blackboard so there aren't any KUs lying around.
        //    blackboard.Clear();

        //    // Add the units in unitsToAdd
        //    foreach (IUnit unitToAdd in unitsToAdd)
        //    {
        //        blackboard.AddUnit(unitToAdd);
        //    }

        //    // Call KnowledgeSource.Precondition() to get the activated KSs.
        //    IEnumerable<IKnowledgeSourceActivation> KSAs = ks.Precondition();


        //    // Check that the number of activated KSs equals the number we're expecting
        //    int count = KSAs.Count();
        //    if (activated)
        //    {
        //        Assert.Equal(1, count);
        //    }
        //    else
        //    {
        //        Assert.Equal(0, count);
        //    }

        //    // Run the preconditions again to verify that on a second running they don't activate any KSs.
        //    KSAs = ks.Precondition();
        //    count = KSAs.Count();
        //    Assert.Equal(0, count);
        //}


        public static IEnumerable <object[]> Data_TestObviationCondition()
        {
            IBlackboard blackboard = new Blackboard();
            ContentUnit selectedCU = new ContentUnit();

            selectedCU.Metadata[SelectedContentUnit] = null;

            /* Structure of object[]:
             * IBlackboard: blackboard,
             * KnowledgeSource: KS whose obviation condition to test,
             * IUnit[]: array of KUs to add,
             *
             */

            return(new List <object[]>
            {
                // KS_IDSelector, one matching unit
                new object[] { blackboard, new KS_Old_ReactiveIDSelector(blackboard), new IUnit[] { new U_IDSelectRequest("foo") } },

                // KS_IDSelector, multiple matching units
                new object[]
                {
                    blackboard, new KS_Old_ReactiveIDSelector(blackboard), new IUnit[]
                    {
                        new U_IDSelectRequest("foo"),
                        new U_IDSelectRequest("bar"),
                        new U_IDSelectRequest("baz")
                    }
                },

                // ChoicePresenter, one matching unit
                new object[] { blackboard, new KS_Old_ReactiveChoicePresenter(blackboard), new IUnit[] { new ContentUnit(selectedCU) } },

                // ChoicePresenter, multiple matching units
                new object[]
                {
                    blackboard, new KS_Old_ReactiveChoicePresenter(blackboard), new IUnit[]
                    {
                        new ContentUnit(selectedCU),
                        new ContentUnit(selectedCU),
                        new ContentUnit(selectedCU)
                    }
                },
            });
        }
        public static IEnumerable <object[]> Data_TestExecute_ReactiveChoicePresenter()
        {
            IBlackboard blackboard = new Blackboard();

            ContentUnit originalCU = new ContentUnit();

            originalCU.Metadata[ContentUnitID] = "foo";
            originalCU.Content[Text]           = "Here is a node with choices";

            ContentUnit selectedCU = new ContentUnit(originalCU);

            selectedCU.Metadata[SelectedContentUnit] = null;

            ContentUnit choice1 = new ContentUnit();

            choice1.Metadata[TargetContentUnitID] = "bar";
            choice1.Content[Text] = "Choice 1";

            ContentUnit choice2 = new ContentUnit();

            choice2.Metadata[TargetContentUnitID] = "baz";
            choice2.Content[Text] = "Choice 2";

            /* Structure of object[]:
             * IBlackboard: blackboard,
             * ContentUnit: the selected CU,
             * ContentUnit: the original CU (selected CU is an copy of this),
             * ContentUnit[]: array of choices (ContentUnits)
             */

            return(new List <object[]>
            {
                // Selected and original CU, no choices
                new object[] { blackboard, selectedCU, originalCU, new ContentUnit[] { } },

                // Selected and original CU, one choice
                new object[] { blackboard, selectedCU, originalCU, new ContentUnit[] { choice1 } },

                // Selected and original CU, two choices
                new object[] { blackboard, selectedCU, originalCU, new ContentUnit[] { choice1, choice2 } },
            });
        }
        /*
         * fixme: this doesn't work if there are multiple filter pools (see KS_ScheduledChoicePresenter for how to handle this.
         * Fix this when I've decided more definitively how I'm handling reactive KSs.
         */
        // Returns an Enumerable of choices. Choices are ContentUnits linked to this ContentUnit by Choice links.
        protected ContentUnit[] GetChoices(ContentUnit selectedCU)
        {
            // Gather the links of type L_SelectedContentUnit that have the SelectedContentUnit as one of the endpoints.
            var linkToOrigCU = from link in m_blackboard.LookupLinks(selectedCU)
                               where link.LinkType.Equals(LinkTypes.L_SelectedContentUnit)
                               select link;

            // There should be only one such link (ie. a SelectedContentUnit should only point to one originating unit).
            Debug.Assert(linkToOrigCU.Count() == 1);

            // Get the original content unit (originalCU)
            (IUnit originalCU, _, _) = linkToOrigCU.ElementAt(0);

            // Gather the choices connected to the originalCU.
            IEnumerable <ContentUnit> choices = from link in m_blackboard.LookupLinks(originalCU)
                                                where link.LinkType.Equals(LinkTypes.L_Choice)
                                                select(ContentUnit) link.Node;

            return(choices.ToArray());
        }
Exemple #13
0
 public SelectChoiceEventArgs_Old(ContentUnit selectedChoice, IBlackboard blackboard)
 {
     SelectedChoice = selectedChoice;
     Blackboard     = blackboard;
 }
        public static IEnumerable <object[]> Data_TestPrecondition()
        {
            IBlackboard blackboard = new Blackboard();
            ContentUnit selectedCU = new ContentUnit();

            selectedCU.Metadata[SelectedContentUnit] = null;

            /* Structure of object[]:
             * IBlackboard: blackboard,
             * KnowledgeSource: KS whose precondition to test,
             * IUnit[]: array of KUs to add,
             * bool: whether KUs should be marked as previously matched by this KS,
             * int: number of activated KSs precondition should return,
             */

            return(new List <object[]>
            {
                // KS_IDSelector, empty blackboard
                new object[] { blackboard, new KS_Old_ReactiveIDSelector(blackboard), new IUnit[] { }, false, 0 },

                // KS_IDSelector, non-matching unit
                new object[] { blackboard, new KS_Old_ReactiveIDSelector(blackboard), new IUnit[] { new TestUnit1("foo") }, false, 0 },

                // KS_IDSelector, matching unit, previously matched
                new object[] { blackboard, new KS_Old_ReactiveIDSelector(blackboard), new IUnit[] { new U_IDSelectRequest("foo") }, true, 0 },

                // KS_IDSelector, matching unit, not previously matched
                new object[] { blackboard, new KS_Old_ReactiveIDSelector(blackboard), new IUnit[] { new U_IDSelectRequest("foo") }, false, 1 },

                // KS_IDSelector, multiple matching units, not previously matched
                new object[]
                {
                    blackboard, new KS_Old_ReactiveIDSelector(blackboard), new IUnit[]
                    {
                        new U_IDSelectRequest("foo"),
                        new U_IDSelectRequest("bar"),
                        new U_IDSelectRequest("baz")
                    },
                    false, 3
                },

                // ChoicePresenter, empty blackboard
                new object[] { blackboard, new KS_Old_ReactiveChoicePresenter(blackboard), new IUnit[] { }, false, 0 },

                // ConsoleChoiceSelector, non-matching unit
                new object[] { blackboard, new KS_Old_ReactiveChoicePresenter(blackboard), new IUnit[] { new TestUnit1("foo") }, false, 0 },

                // ChoicePresenter, matching unit, previously matched
                new object[] { blackboard, new KS_Old_ReactiveChoicePresenter(blackboard), new IUnit[] { new ContentUnit(selectedCU) }, true, 0 },

                // ChoicePresenter, matching unit, not previously matched
                new object[] { blackboard, new KS_Old_ReactiveChoicePresenter(blackboard), new IUnit[] { new ContentUnit(selectedCU) }, false, 1 },

                // ChoicePresenter, multiple matching units, not previously matched
                new object[]
                {
                    blackboard, new KS_Old_ReactiveChoicePresenter(blackboard), new IUnit[]
                    {
                        new ContentUnit(selectedCU),
                        new ContentUnit(selectedCU),
                        new ContentUnit(selectedCU)
                    },
                    false, 3
                },
            });
        }
        public static void Demo1_Slots_DefineCUs(IBlackboard blackboard)
        {
            ContentUnit start = new ContentUnit();

            start.Metadata[ContentUnitID] = "start";
            start.Content[Text]           = "You stand before an old wooden door.";

            ContentUnit start_Choice1 = new ContentUnit();

            start_Choice1.Metadata[TargetContentUnitID] = "open door";
            start_Choice1.Content[Text] = "Open the door";

            ContentUnit start_Choice2 = new ContentUnit();

            start_Choice2.Metadata[TargetContentUnitID] = "wait";
            start_Choice2.Content[Text] = "Wait";

            ContentUnit openDoor = new ContentUnit();

            openDoor.Metadata[ContentUnitID] = "open door";
            openDoor.Content[Text]           = "Opening the door, you step forth into adventure.";

            ContentUnit waited = new ContentUnit();

            waited.Metadata[ContentUnitID] = "wait";
            waited.Content[Text]           = "You wait fruitlessly in front the door.";

            ContentUnit waitedChoice1 = new ContentUnit();

            waitedChoice1.Metadata[TargetContentUnitID] = "waited again";
            waitedChoice1.Content[Text] = "Wait again";

            ContentUnit waitedChoice2 = new ContentUnit();

            waitedChoice2.Metadata[TargetContentUnitID] = "open door after waiting";
            waitedChoice2.Content[Text] = "Finally open the door";

            ContentUnit waitedAgain = new ContentUnit();

            waitedAgain.Metadata[ContentUnitID] = "waited again";
            waitedAgain.Content[Text]           = "Sunk in a deep malaise, you wait the rest of your life.";

            ContentUnit openDoorAfterWaiting = new ContentUnit();

            openDoorAfterWaiting.Metadata[ContentUnitID] = "open door after waiting";
            openDoorAfterWaiting.Content[Text]           = "Breaking through your reservations, you step forward into a life of adventure.";

            blackboard.AddUnit(start);
            blackboard.AddUnit(start_Choice1);
            blackboard.AddUnit(start_Choice2);
            blackboard.AddUnit(openDoor);
            blackboard.AddUnit(waited);
            blackboard.AddUnit(waitedChoice1);
            blackboard.AddUnit(waitedChoice2);
            blackboard.AddUnit(waitedAgain);
            blackboard.AddUnit(openDoorAfterWaiting);

            blackboard.AddLink(start, start_Choice1, LinkTypes.L_Choice);
            blackboard.AddLink(start, start_Choice2, LinkTypes.L_Choice);
            blackboard.AddLink(waited, waitedChoice1, LinkTypes.L_Choice);
            blackboard.AddLink(waited, waitedChoice2, LinkTypes.L_Choice);
        }