예제 #1
0
        public static void CheckContradictionWIthModelsAndRulebase(GatheredBases bases)
        {
            foreach (Rule rule in bases.RuleBase.RulesList)
            {
                List <List <Rule> > differenceList;
                var tree = TreeOperations.ReturnComplexTreeAndDifferences(bases, rule, out differenceList);

                var askingConditions = TreeOperations.TreeToEnumerable
                                           (tree).Where(p => p.Askable);

                foreach (SimpleTree condition in askingConditions)
                {
                    IEnumerable <Model> models =
                        bases.ModelsBase.ModelList.Where(p => p.Conclusion == condition.rule.Conclusion);
                    if (models.Count() != 0)
                    {
                        // trzeba zebrać wszystkie warunki startowe
                        // jeszcze zrobić mały research

                        foreach (Model model in models)
                        {
                            var           list = new List <string>();
                            List <string> listOfStartedConditions = GatherStartConditions
                                                                        (model, bases, list);
                            //TODO:METODA sprzeczności w modelach
                            // z modelami relacyjnymi oraz modeli arytmetycznych z modelami arytmetycznymi
                            CheckContradictionBetweenRulesAndStartedConditions
                                (listOfStartedConditions, condition, model);
                            //  CheckContradictionBetweenModelsAndStartedConditions();
                            // CheckContradictionBetweenArithmeticModels();
                        }
                    }
                }
            }
        }
예제 #2
0
        public static void TreeTraversal()
        {
            TreeOperations treeOperations = new TreeOperations();
            var            Data           = new List <object> {
                5, 3, 7, 2, 4, 6, 8, 1, 9
            };

            treeOperations.PopulateBinarySearchTree(Data);
            Console.WriteLine("=========================================================================");
            var preOrderPath = treeOperations.RecursivePreOrderTraversal();

            DisplayPath(preOrderPath);
            preOrderPath = treeOperations.IterativePreOrderTraversal();
            DisplayPath(preOrderPath);
            Console.WriteLine("=========================================================================");
            var inOrderPath = treeOperations.RecursiveInOrderTraversal();

            DisplayPath(inOrderPath);
            inOrderPath = treeOperations.IterativeInOrderTraversal();
            DisplayPath(inOrderPath);
            Console.WriteLine("=========================================================================");
            var postOrderPath = treeOperations.RecursivePostOrderTraversal();

            DisplayPath(postOrderPath);
            postOrderPath = treeOperations.IterativePostOrderTraversal();
            DisplayPath(postOrderPath);
            Console.WriteLine("=========================================================================");
            Console.WriteLine("The Max Level for Leaf Node of The Tree is " + treeOperations.FindMaxLevel() + ".\nHierarchical representation is shown below: ");
            treeOperations.PrintHierarchy();
            Console.WriteLine("=========================================================================");
        }
예제 #3
0
        public static bool MethodForContradiction
            (GatheredBases bases, Rule ruleForCheck, int count, List <List <Rule> > differenceList, out SimpleTree tree)
        {
            tree = new SimpleTree {
                rule = ruleForCheck
            };
            IEnumerable <SimpleTree> parentWithoutChildren;

            int _number = 0;

            do
            {
                parentWithoutChildren = TreeOperations.TreeToEnumerable(tree).Where(p => p.Children.Count == 0).
                                        Where(p => p.Askable == false);

                foreach (SimpleTree parentWithoutChild in parentWithoutChildren)
                {
                    TreeOperations.ExpandBrunchOrMakeAskable(bases, parentWithoutChild, differenceList);
                    _number++;

                    if (_number == count)
                    {
                        return(false);  // method not finished tree after _number iterations
                    }  //TODO: ta pętla nie jest odporna na sprzeczność
                }
            } while (parentWithoutChildren.Count() != 0);

            return(true); // method finished tree and there is no contradiction
        }
        public void Sprawdzamy_Wnioskowania()
        {
            GatheredBases bases = new GatheredBases();
            RuleBase      rules = new RuleBase();
            Rule          r     = new Rule(1, "Wniosek", new List <string>()
            {
                "Wniosek1"
            }, true);
            Rule r1 = new Rule(2, "Wniosek1", new List <string>()
            {
                "Wniosek2"
            }, true);
            Rule r2 = new Rule(3, "Wniosek2", new List <string>()
            {
                "Wniosek3"
            }, true);
            Rule r22 = new Rule(5, "Wniosek2", new List <string>()
            {
                "Wniosek6"
            }, true);
            Rule r3 = new Rule(4, "Wniose3", new List <string>()
            {
                "Wniosek4"
            }, true);

            rules.RulesList.Add(r);
            rules.RulesList.Add(r1);
            rules.RulesList.Add(r2);
            rules.RulesList.Add(r3);
            rules.RulesList.Add(r22);
            bases.RuleBase = rules;
            TreeOperations.ReturnComplexTreeAndDifferences(bases, r);
            Assert.AreEqual(true, true);
        }
예제 #5
0
        /// <summary>
        /// Given a set of instruction indices, returns the set of their lowest common ancestors.
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public IEnumerable <int> GetLCASet(IEnumerable <int> query)
        {
            List <int> result = new List <int>();

            TreeOperations.GetLCATree(query,
                                      new DelegatePropMap <int, int>(GetIDomIndex),
                                      0,
                                      new DelegatePropMap <int, int>(GetPostOrderIndex),
                                      new DelegatePropMap <int, int>((i, p) => { result.Add(p); }));
            return(result);
        }
예제 #6
0
        public static List <Rule> CheckOutsideContradiction(GatheredBases bases, bool reportIncluded)
        {
            var contradictedRules = new List <Rule>();

            foreach (Rule RuleI in bases.RuleBase.RulesList)
            {
                var differenceList = new List <List <Rule> >();
                int numberForCheck = 100;
                do
                {
                    var tree             = new SimpleTree();
                    var complexTreeValue = MethodForContradiction(bases, RuleI, numberForCheck, differenceList, out tree);

                    if (complexTreeValue == false)
                    {
                        IEnumerable <SimpleTree> currentEndOfTree =
                            TreeOperations.TreeToEnumerable(tree).Where(p => p.Children.Count == 0);

                        foreach (SimpleTree currentEnd in currentEndOfTree)
                        {
                            SimpleTree node         = currentEnd;
                            SimpleTree checkedValue = currentEnd;

                            while (node.Parent != null)
                            {
                                node.rule = node.Parent.rule;
                                if (checkedValue == node)
                                {
                                    if (reportIncluded)
                                    {
                                        MessageBox.Show(
                                            "W bazie występuje sprzeczność przejdź do dniagnoz bazy aby poznać szczegóły");

                                        reportIncluded = false; //TODO : tymczasowe rozwiązanie trzeba jakoś przerwać metodę
                                    }
                                    AddRuleToContradictionTable(contradictedRules, RuleI);

                                    break;
                                }
                            }
                        }

                        numberForCheck = numberForCheck * 2;
                        // in case that there is no contradiction but
                        // also tree is not finished number is double
                    }
                    else
                    {
                        break;
                    }
                } while (contradictedRules.Count == 0);
            }
            return(contradictedRules);
        }
예제 #7
0
    // Simple function for setting the tree of the agent.
    // All trees are defined by their rootnode: N_Root.
    public void SetTree(N_Root treeRoot, N_AgentNode.AgentType agent)
    {
        btRoot = treeRoot;
        // Find all agentnodes and set their agent to be this one.
        List <Node> agentNodes = TreeOperations.RetrieveNodesOfType(treeRoot, typeof(N_AgentNode));

        foreach (N_AgentNode n in agentNodes)
        {
            n.SetAgent(agent);
        }
    }
예제 #8
0
        public void BuildComplexTree_Check_If_Return_Key_And_Value_With_Good_Count()
        {
            method();

            var tree           = TreeOperations.ReturnComplexTreeAndDifferences(bases, rules.RulesList[1]);
            int treeCount      = TreeOperations.TreeToEnumerable(tree.Values.First()).Count();
            int dvideListCount = tree.Keys.Count;

            Assert.AreEqual(6, treeCount);// sześć elementow , cztery reguly
            Assert.AreEqual(1, dvideListCount);
        }
예제 #9
0
        public static void ReportAboutContradictionInRules(GatheredBases bases, ViewModel _viewModel)
        {
            int         i = 0;
            List <Rule> listWithContradiction = CheckOutsideContradiction(bases, false);

            foreach (Rule rule in listWithContradiction)
            {
                i += CheckSelfContradiction(rule);


                for (int count = 1; count < 1000; count++)  //TODO:nie powinno być stałej w pętli for
                {
                    var tree           = new SimpleTree();
                    var differenceList = new List <List <Rule> >();
                    MethodForContradiction(bases, rule, count, differenceList, out tree);

                    IEnumerable <SimpleTree> ListOfTreesElements =
                        TreeOperations.TreeToEnumerable(tree).Where(p => p.Children.Count == 0);

                    foreach (SimpleTree treeElement in ListOfTreesElements)
                    {
                        string     s          = "";
                        SimpleTree copyOfTree = treeElement;
                        if (treeElement.rule.NumberOfRule == rule.NumberOfRule)
                        {
                            i++;
                            bool boolValue = true;
                            while (copyOfTree.Parent.rule != rule)
                            {
                                if (boolValue == false)
                                {
                                    copyOfTree = copyOfTree.Parent;
                                }
                                boolValue = false;

                                s += copyOfTree.rule.NumberOfRule + "==>";
                            }
                            //TODO: Report aboyt contradiction
                            MessageBox.Show("Poprzez podstawienie następujących reguł otrzymasz sprzeczność zewnetrzną :" + s + "\n");
                            _viewModel.ButtonsLogic.ConclusionEnabled = false;
                            goto Res;
                        }
                    }
                }

                Res :;
            }
            if (i == 0)
            {
                MessageBox.Show("Nie wykryto sprzeczności w bazie reguł");
                _viewModel.ButtonsLogic.ConclusionEnabled = true;
            }
        }
예제 #10
0
        /// <summary>
        /// Backwards the conclude.
        /// </summary>
        /// <param name="checkedRule">The checked rule.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public bool BackwardConclude(Rule checkedRule)
        {
            //FindHelpfulAssets(checkedRule);
            var differenceList = new List <List <Rule> >();
            var tree           = TreeOperations.ReturnComplexTreeAndDifferences(_bases, checkedRule, out differenceList);

            var possibleTrees = TreeOperations.ReturnPossibleTrees(tree, differenceList);

            try
            {
                foreach (var onePossibility in possibleTrees) //flattering all possible configurations of conditions
                {
                    List <SimpleTree> askableTable = onePossibility.Where(var => var.Askable).ToList();
                    //If askable simple tree can be a model,condition of rule or condition of constrain

                    // sprawdzamy czy jest w bazie faktow
                    foreach (SimpleTree simpleTree in askableTable)
                    {
                        if (CheckIfStringIsFact(simpleTree.rule.Conclusion, _bases.FactBase.FactList))
                        {
                            simpleTree.ConclusionValue = true;
                        }
                    }

                    bool conclusionValue = CheckConclusionValueOrCountModel(askableTable);


                    if (conclusionValue)
                    {
                        MessageBox.Show("Hipoteza :" + checkedRule.Conclusion + " prawdziwa");
                        ShowAdviceGraphicOrSound(checkedRule);
                        CleanBase();
                        //TODO : trzeba wyzerowaæ bazy
                        return(true);
                    }
                }
                MessageBox.Show("Nie uda³o siê potwierdziæ wniosku regu³y " + checkedRule.NumberOfRule.ToString() + "\n" +
                                "Ze wzglêdu na za³o¿enie otwatrego œwiata hipoteza niepotwierdzona");
                CleanBase();
                return(false);
                //TODO : trzeba wyzerowaæ bazy
            }
            catch (ApplicationException ex)
            {
                CleanBase();
                MessageBox.Show("Wnioskowanie przerwane");
                _viewModel.ExceptionValue = false;
            }
            return(false);
        }
예제 #11
0
        /// <summary>
        /// Flatters the rule.
        /// </summary>
        /// <param name="flatteredRule">The flattered rule.</param>
        public string FlatterRule(Rule flatteredRule)
        {
            var    differenceList = new List <List <Rule> >();
            var    tree           = TreeOperations.ReturnComplexTreeAndDifferences(_bases, flatteredRule, out differenceList);
            var    possibleTrees  = TreeOperations.ReturnPossibleTrees(tree, differenceList);
            int    i = 0;
            string s = "";

            foreach (var possibleTree in possibleTrees)
            {
                // _viewModel.MainWindowText1+=
                s += GetFlatteredRuleDescription(possibleTree);
                i++;
            }
            return(s);
        }
예제 #12
0
        public static List <List <SimpleTree> > AllFlatteredRules(GatheredBases bases, Rule ruleForCheck)
        {
            List <List <SimpleTree> > allFlatteredRules = new List <List <SimpleTree> >();
            List <Rule> ruleList = ConclusionClass.FindRulesWithParticularConclusion
                                       (ruleForCheck.Conclusion, bases.RuleBase.RulesList);

            foreach (var r in ruleList)
            {
                List <List <Rule> > differencesList;
                var tree = TreeOperations.ReturnComplexTreeAndDifferences(
                    bases, r, out differencesList);
                List <List <SimpleTree> > possibleTrees = TreeOperations.ReturnPossibleTrees(tree,
                                                                                             differencesList);
                allFlatteredRules.AddRange(possibleTrees);
            }
            return(allFlatteredRules);
        }
예제 #13
0
        public static void CreateMinimalBinarySearchTreeDemo()
        {
            Console.Write("Enter Length of Array: ");
            int arrayLength = int.Parse(Console.ReadLine());

            int[] array = new int[arrayLength];
            for (int i = 0; i < arrayLength; i++)
            {
                Console.Write(string.Format("Enter Data at {0} position in array: ", i));
                array[i] = int.Parse(Console.ReadLine());
            }

            TreeOperations treeOperations = new TreeOperations();

            treeOperations.Current = treeOperations.CreateMinimalBinarySearchTree(array, 0, arrayLength - 1);

            HelperUtil.DisplayList(treeOperations.IterativePreOrderTraversal());
            HelperUtil.DisplayList(treeOperations.IterativeInOrderTraversal());
            HelperUtil.DisplayList(treeOperations.IterativePostOrderTraversal());
        }
예제 #14
0
        public void Test_DFS()
        {
            TreeNode root = new TreeNode(1);

            root.AddLeaf(2);
            root.AddLeaf(3);
            root.Leafs.ElementAt(0).AddLeaf(4);
            root.Leafs.ElementAt(0).AddLeaf(5);
            root.Leafs.ElementAt(0).Leafs.ElementAt(0).AddLeaf(7);
            root.Leafs.ElementAt(1).AddLeaf(6);

            List <int> result = TreeOperations.DepthFirstTraversal(root);

            result.ElementAt(0).ShouldBe(1);
            result.ElementAt(1).ShouldBe(2);
            result.ElementAt(2).ShouldBe(4);
            result.ElementAt(3).ShouldBe(7);
            result.ElementAt(4).ShouldBe(5);
            result.ElementAt(5).ShouldBe(3);
            result.ElementAt(6).ShouldBe(6);
        }
예제 #15
0
    // Assign random mutations to the given tree.
    protected void Mutate(N_Root child)
    {
        // First, check if there'll be any mutation at all.
        float random = UnityEngine.Random.Range(0.0f, 1.0f);

        if (random < mutationRate)
        {
            List <Node> thresholds = TreeOperations.RetrieveNodesOfType(child, typeof(N_Threshold));
            List <Node> probNodes  = TreeOperations.RetrieveNodesOfType(child, typeof(N_ProbabilitySelector));

            // Randomise between whether to change thresholds or probabilities
            random = UnityEngine.Random.Range(0.0f, 1.0f);
            // If no probnode exists, change condition if there are any instead
            if ((random <= 0.25f && thresholds.Count > 0))
            {
                //Debug.Log("Changing threshold!");
                // Get random index within range of list
                int         index  = UnityEngine.Random.Range(0, thresholds.Count);
                N_Threshold thresh = thresholds[index] as N_Threshold;

                // Mutate threshold by random offset
                int offset = UnityEngine.Random.Range(minThresholdOffset, maxTresholdOffset);
                thresh.SetThreshold(thresh.Threshold + offset);
            }
            else if (random > 0.25f && random <= 0.5f && probNodes.Count > 0) // Adjust relative probabilities on a probability selector.
            {
                //Debug.Log("Changing prob!");
                // Get random index within range of list
                int index = UnityEngine.Random.Range(0, probNodes.Count);
                N_ProbabilitySelector probSelect = probNodes[index] as N_ProbabilitySelector;

                // Check so that the probablitySelector has any children.
                if (probSelect.GetChildren().Count <= 0)
                {
                    return;
                }

                // Calculate total probability and retrieve a relative offset based on it.
                float totalProb = 0.0f;
                foreach (Node n in probSelect.GetChildren())
                {
                    totalProb += probSelect.GetProbabilityWeight(n);
                }
                float offset = totalProb * (relativeProbabilityMutation / 100.0f);
                // Also, get a random sign to decide whether to substract or add offset
                // and a random index for which child to be changed.
                float randomSign       = Mathf.Sign(UnityEngine.Random.Range(-1.0f, 1.0f));
                int   randomChildIndex = UnityEngine.Random.Range(0, probSelect.GetChildren().Count);

                // Finally, offset the given childs probability by the random amount.
                probSelect.OffsetProbabilityWeight(probSelect.GetChildren()[randomChildIndex]
                                                   , offset * randomSign);
            }
            else if (random > 0.5f && random <= 0.75f) // Change subtree
            {
                //Debug.Log("Changing subtree!");
                List <Node>       subtrees    = TreeOperations.RetrieveSubtreeNodes(child);
                int               randomIndex = UnityEngine.Random.Range(0, subtrees.Count);
                Node              subtree     = subtrees[randomIndex];
                N_CompositionNode parentComp  = subtree.Parent as N_CompositionNode;

                // Get a random subtree index and replace its position in the tree with
                // a new randomized subtree instead.
                parentComp.ReplaceChild(subtree, RandomSubtree());
            }
            else if (random > 0.75f) // Change composition
            {
                //Debug.Log("Changing composition!");
                List <Node>       comps       = TreeOperations.RetrieveNodesOfType(child, typeof(N_CompositionNode));
                int               randomIndex = UnityEngine.Random.Range(0, comps.Count);
                N_CompositionNode replaceComp = comps[randomIndex] as N_CompositionNode;

                // If parent is null, this comp is the initial comp.
                if (replaceComp.Parent != null)
                {
                    Node        compParent = replaceComp.Parent;
                    List <Node> children   = replaceComp.GetChildren();

                    // Attach old comps children to the new one.
                    N_CompositionNode newComp = RandomComp();
                    // Make sure to keep structure of subtrees
                    if (replaceComp.IsSubtree)
                    {
                        newComp.IsSubtree = true;
                    }

                    foreach (Node c in children)
                    {
                        c.Parent = newComp;
                        newComp.AddLast(c);
                    }

                    // Reattach parent to the new comp
                    if (compParent.GetType().IsSubclassOf(typeof(N_CompositionNode)))
                    {
                        N_CompositionNode compParent_comp = compParent as N_CompositionNode;
                        compParent_comp.ReplaceChild(replaceComp, newComp);
                    }
                    else if (compParent.GetType().IsSubclassOf(typeof(N_Decorator)))
                    {
                        N_Decorator compParent_dec = compParent as N_Decorator;
                        compParent_dec.Child = newComp;
                    }
                }
            }
        }
    }
예제 #16
0
    // Combine parents and create two new children based on them
    protected void Combine(out Genome child0, out Genome child1, Genome parent0, Genome parent1)
    {
        Node subtree0, subtree1 = null;
        // First, check if there'll be any combination/crossover.
        float random = UnityEngine.Random.Range(0.0f, 1.0f);

        if (random < combinationRate)
        {
            List <Node> subtrees0 = TreeOperations.RetrieveSubtreeNodes(parent0.RootNode);
            List <Node> subtrees1 = TreeOperations.RetrieveSubtreeNodes(parent1.RootNode);

            // Select to random subtrees...
            int randomIndex = UnityEngine.Random.Range(0, subtrees0.Count);
            subtree0    = subtrees0[randomIndex];
            randomIndex = UnityEngine.Random.Range(0, subtrees1.Count);
            subtree1    = subtrees1[randomIndex];

            // Swap subtrees between 0 and 1.
            if (subtree0.Parent.GetType().IsSubclassOf(typeof(N_CompositionNode)))
            {
                N_CompositionNode comp0 = subtree0.Parent as N_CompositionNode;
                comp0.ReplaceChild(subtree0, StaticMethods.DeepCopy <Node>(subtree1));
            }

            // Swap subtrees between 1 and 0.
            if (subtree1.Parent.GetType().IsSubclassOf(typeof(N_CompositionNode)))
            {
                N_CompositionNode comp1 = subtree1.Parent as N_CompositionNode;
                comp1.ReplaceChild(subtree1, StaticMethods.DeepCopy <Node>(subtree0));
            }

            #region Old Combination
            //// Get initial comp of parent 0
            //N_CompositionNode comp0 = parent0.RootNode.Child as N_CompositionNode;
            //// Fetch a random subtree from the parent's subtrees
            //int randomIndex = UnityEngine.Random.Range(0, comp0.GetChildren().Count);
            //subtree0 = comp0.GetChildren()[randomIndex];

            //// Get initial comp of parent 1
            //N_CompositionNode comp1 = parent1.RootNode.Child as N_CompositionNode;
            //// Fetch a random subtree from the parent's subtrees
            //randomIndex = UnityEngine.Random.Range(0, comp1.GetChildren().Count);
            //subtree1 = comp1.GetChildren()[randomIndex];

            //// Swap subtrees between 0 and 1.
            //if (subtree0.Parent.GetType().IsSubclassOf(typeof(N_CompositionNode)))
            //{
            //    comp0.ReplaceChild(subtree0, StaticMethods.DeepCopy<Node>(subtree1));
            //}

            //// Swap subtrees between 1 and 0.
            //if (subtree1.Parent.GetType().IsSubclassOf(typeof(N_CompositionNode)))
            //{
            //    comp1.ReplaceChild(subtree1, StaticMethods.DeepCopy<Node>(subtree0));
            //}
            #endregion
        }

        // Regardless of combination, assign the children to be the parents. (combined or not)
        child0 = parent0;
        child1 = parent1;
    }