コード例 #1
0
    public BDDNode MakeIfThenElse(BDDNode ifNode, BDDNode thenNode, BDDNode elseNode)
    {
        // handle basic cases
        if (ifNode == BDDNode.True)
        {
            return(thenNode);
        }
        if (ifNode == BDDNode.False)
        {
            return(elseNode);
        }
        if (thenNode == BDDNode.True && elseNode == BDDNode.False)
        {
            return(ifNode);
        }
        if (thenNode.IsEquivalent(elseNode))
        {
            return(thenNode);
        }

        // splitting variable must be the topmost root
        int splitId = Min(ifNode.variableId, thenNode.variableId, elseNode.variableId);

        // create restricted nodes for both cases
        var high = Restrict(ifNode, thenNode, elseNode, splitId, true);
        var low  = Restrict(ifNode, thenNode, elseNode, splitId, false);

        return(MakeNode(splitId, high, low));
    }
コード例 #2
0
ファイル: BDDNode.cs プロジェクト: IrinaLen/SAT
 public BDDNode(int v, int i, BDDNode left, BDDNode right)
 {
     varId = v;
     id    = i;
     low   = left;
     high  = right;
 }
コード例 #3
0
        private BDDNode AddExceptions(Goal goal, BDDNode bddForRefinement)
        {
            foreach (var singleException in goal.Exceptions())
            {
                // Get the BDD for the countermeasure goal
                Goal cmGoal = singleException.ResolvingGoal();
                if (cmGoal == null)
                {
                    throw new ArgumentNullException($"Goal '{singleException.ResolvingGoalIdentifier}' not found.");
                }
                var bddForCountermeasure = GetObstructionSet(cmGoal);

                // Get the BDD for the sibling goal (i.e. remove the resolved obstacle)
                Obstacle obstacle           = singleException.Obstacle();
                var      obstacleVariableId = _mapping[obstacle];
                var      bddForPGprime      = _manager.Restrict(bddForRefinement, -1, obstacleVariableId);

                // Create a variable for the resolution
                var idx = _manager.CreateVariable();
                _mapping.Add(singleException, idx);
                _rmapping.Add(idx, singleException);

                var bddWhenIntegrated = _manager.Or(bddForPGprime, bddForCountermeasure);

                bddForRefinement = _manager.Create(idx, bddWhenIntegrated, bddForRefinement);
            }

            return(bddForRefinement);
        }
コード例 #4
0
        private static void Main()
        {
            List <string> files = new List <string>(Directory.GetFiles("examples")).Where(f => new Regex(@".*-ft.dot$").IsMatch(f)).ToList();

            foreach (string s in files.Take(1))
            {
                Console.WriteLine("Converting tree " + s);

                IFaultTreeCodec     codec = FaultTreeEncoderFactory.CreateFaultTreeCodec(s);
                FaultTree.FaultTree ft    = codec.Read(s);

                //ft = ft.deepCopy().replace(1, false).simplify();

                //IFaultTreeCodec xmlCodec = FaultTreeEncoderFactory.createFaultTreeCodec(FaultTreeFormat.FAULT_TREE_XML);
                //xmlCodec.write(ft, s + ".xml");

                BDDNode test = BDDFactory.GetComponentConnectionInstance().CreateBDD(ft);
                Console.WriteLine("Successfully converted tree");

                IBDDCodec bCodec = BDDEncoderFactory.CreateFaultTreeCodec(s + ".dot");
                bCodec.Write(new BinaryDecisionDiagram(test), s + ".dot");
            }
            Console.WriteLine("Finished construction");
            Console.ReadKey();
        }
コード例 #5
0
        public BDDNode GetObstructionSet(GoalRefinement refinement)
        {
            BDDNode acc = null;

            foreach (var child in refinement.SubGoals())
            {
                if (acc == null)
                {
                    acc = GetObstructionSet(child);
                }
                else
                {
                    var bDDNode = GetObstructionSet(child);
                    acc = _manager.Or(acc, bDDNode);
                }
            }
            foreach (var child in refinement.DomainHypotheses())
            {
                if (acc == null)
                {
                    acc = GetObstructionSet(child);
                }
                else
                {
                    var bDDNode = GetObstructionSet(child);
                    acc = _manager.Or(acc, bDDNode);
                }
            }
            return(acc);
        }
コード例 #6
0
        protected Dictionary <string, bool> BuildThruthTable(BDDManager manager, BDDNode root)
        {
            var truth = new Dictionary <string, bool>();

            AddThruthValue("", root, truth, manager.N);
            return(truth);
        }
コード例 #7
0
        protected override double GetProbability(BDDNode node, SamplingVector samplingVector, Dictionary <BDDNode, double> cache = null)
        {
            if (node.IsOne)
            {
                return(1.0);
            }
            if (node.IsZero)
            {
                return(0.0);
            }

            if (cache == null)
            {
                cache = new Dictionary <BDDNode, double> ();
            }
            else if (cache.TryGetValue(node, out double cached))
            {
                return(cached);
            }

            if (_rmapping[node.Index] is PrimitiveRefineeParameter <double> c)
            {
                double value = GetProbability(node.Low, samplingVector, cache) * (1 - c.Value)
                               + GetProbability(node.High, samplingVector, cache) * c.Value;
                cache[node] = value;
                return(value);
            }
            else
            {
                return(base.GetProbability(node, samplingVector, cache));
            }
        }
コード例 #8
0
        private BDDNode CreateExpressionsFromBooleanNetwork(
            BDDManager manager,
            List <GeneLink> booleanNetwok,
            Dictionary <string, List <int> > availableFunctions,
            int depth,
            Dictionary <string, BDDNode> nodeStore)
        {
            var toDictionary = booleanNetwok.GroupBy(a => a.To);

            BDDNode seq = null;

            for (int i = 0; i < depth - 1; i++)
            {
                var ass = CreateFunctionApplication(manager, availableFunctions, toDictionary, i, nodeStore);

                if (seq == null)
                {
                    seq = ass;
                }
                else
                {
                    seq = manager.And(seq, ass);
                }
            }

            return(seq);
        }
コード例 #9
0
 public BDDNode(int id, int variableId, BDDNode high, BDDNode low)
 {
     this.id         = id;
     this.variableId = variableId;
     this.high       = high;
     this.low        = low;
 }
コード例 #10
0
        protected override double GetProbability(BDDNode node, SamplingVector samplingVector, Dictionary <BDDNode, double> cache = null)
        {
            if (node.IsOne)
            {
                return(1.0);
            }
            if (node.IsZero)
            {
                return(0.0);
            }

            if (cache == null)
            {
                cache = new Dictionary <BDDNode, double> ();
            }
            else if (cache.TryGetValue(node, out double cached))
            {
                return(cached);
            }

            if (_rmapping[node.Index] is GoalException exception)
            {
                var    v     = 0;
                double value = GetProbability(node.Low, samplingVector, cache) * (1 - v)
                               + GetProbability(node.High, samplingVector, cache) * v;
                cache[node] = value;
                return(value);
            }
            else
            {
                return(base.GetProbability(node, samplingVector, cache));
            }
        }
コード例 #11
0
        /// <summary>
        /// Write BDD to stream.
        /// </summary>
        /// <param name="bdd">
        /// The bdd.
        /// </param>
        /// <param name="stream">
        /// The stream.
        /// </param>
        public override void Write(BinaryDecisionDiagram bdd, FileStream stream)
        {
            using (var sw = new StreamWriter(stream, Encoding.UTF8, 65536))
            {
                sw.WriteLine("digraph G {");
                sw.WriteLine("0 [shape=box, label=\"0\", style=filled, shape=box, height=0.3, width=0.3];");
                sw.WriteLine("1 [shape=box, label=\"1\", style=filled, shape=box, height=0.3, width=0.3];");

                List <BDDNode> flat = BDDNode.Traverse(bdd.Root).ToList();
                flat = (from f in flat orderby f.Variable select f).Reverse().ToList();

                var fastAccess = new Dictionary <BDDNode, int>();
                for (int i = 0; i < flat.Count; i++)
                {
                    fastAccess.Add(flat[i], i);
                }

                for (int i = 2; i < flat.Count; i++)
                {
                    sw.WriteLine(i + " [label=\"" + flat[i].Variable + "\"];\n" + i + " -> " + fastAccess[flat[i].LowNode] + " [style=dotted];\n" + i + " -> " + fastAccess[flat[i].HighNode] + " [style=filled];");
                }

                sw.WriteLine("}");
            }
        }
コード例 #12
0
    /// <summary>restricts an if-then-else block</summary>
    private BDDNode Restrict(BDDNode ifNode, BDDNode thenNode, BDDNode elseNode, int variableId, bool variableValue)
    {
        var i = Restrict(ifNode, variableId, variableValue);
        var t = Restrict(thenNode, variableId, variableValue);
        var e = Restrict(elseNode, variableId, variableValue);

        return(MakeIfThenElse(i, t, e));
    }
コード例 #13
0
        public virtual BDDNode GetObstructionSet(Goal goal)
        {
            if (goalCache.ContainsKey(goal))
            {
                return(goalCache[goal]);
            }

            IEnumerable <GoalRefinement> refinements  = goal.Refinements();
            IEnumerable <Obstruction>    obstructions = goal.Obstructions();

            if ((refinements.Count() + obstructions.Count()) > 1)
            {
                throw new PropagationException(PropagationException.INVALID_MODEL + $". Check '{goal.Identifier}' for obstructions and refinements.");
            }

            var r = refinements.SingleOrDefault();

            if (r != null)
            {
                BDDNode acc = null;
                foreach (var child in goal.Exceptions())
                {
                    if (acc == null)
                    {
                        acc = GetObstructionSet(child);
                    }
                    else
                    {
                        var bDDNode = GetObstructionSet(child);
                        acc = _manager.Or(acc, bDDNode);
                    }
                }

                if (acc == null)
                {
                    acc = GetObstructionSet(r);
                }
                else
                {
                    var bDDNode = GetObstructionSet(r);
                    acc = _manager.Or(acc, bDDNode);
                }
                goalCache.Add(goal, acc);
                return(acc);
            }

            var o = obstructions.SingleOrDefault();

            if (o != null)
            {
                BDDNode bn = GetObstructionSet(o);
                goalCache.Add(goal, bn);
                return(bn);
            }

            goalCache.Add(goal, _manager.Zero);
            return(_manager.Zero);
        }
コード例 #14
0
        protected virtual double GetProbability(BDDNode node, SamplingVector samplingVector, Dictionary <BDDNode, double> cache = null)
        {
            if (node.IsOne)
            {
                return(1.0);
            }
            if (node.IsZero)
            {
                return(0.0);
            }

            if (cache == null)
            {
                cache = new Dictionary <BDDNode, double> ();
            }
            else if (cache.TryGetValue(node, out double cached))
            {
                return(cached);
            }

            if (_rmapping[node.Index] is Obstacle obstacle)
            {
                //Console.WriteLine("Probability for " + obstacle.Identifier);
                //Console.WriteLine("Obstacle resolved: " + obstacle.Resolved);
                var v = samplingVector.ContainsKey(obstacle.Identifier) & !obstacle.Resolved ?
                        samplingVector.Sample(obstacle) : 0;
                //Console.WriteLine(v);

                double value = GetProbability(node.Low, samplingVector, cache) * (1 - v)
                               + GetProbability(node.High, samplingVector, cache) * v;
                cache[node] = value;
                return(value);
            }
            else if (_rmapping[node.Index] is DomainProperty domProp)
            {
                var v = samplingVector.ContainsKey(domProp.Identifier) ?
                        samplingVector.Sample(domProp) : 0;

                double value = GetProbability(node.Low, samplingVector, cache) * (1 - v)
                               + GetProbability(node.High, samplingVector, cache) * v;
                cache[node] = value;
                return(value);
            }
            else if (_rmapping[node.Index] is DomainHypothesis domHyp)
            {
                var v = samplingVector.ContainsKey(domHyp.Identifier) ?
                        samplingVector.Sample(domHyp) : 0;

                double value = GetProbability(node.Low, samplingVector, cache) * (1 - v)
                               + GetProbability(node.High, samplingVector, cache) * v;
                cache[node] = value;
                return(value);
            }
            else
            {
                throw new NotImplementedException("Type " + _rmapping[node.Index].GetType() + " is not yet supported.");
            }
        }
コード例 #15
0
 protected void CheckThruthTable(Dictionary <string, bool> matrix, BDDNode node)
 {
     foreach (var kv in matrix)
     {
         Dictionary <int, bool> interpretation = BuildInterpretation(kv.Key);
         bool value = EvaluateBDD(node, interpretation);
         Assert.AreEqual(matrix[kv.Key], value);
     }
 }
コード例 #16
0
            public Node(int index, int low, int high, BDDNode val, Node next)
            {
                this.index = index;
                this.low   = low;
                this.high  = high;

                this.val  = new WeakReference(val);
                this.next = next;
            }
コード例 #17
0
        /// <summary>
        /// Applies operation "op" to BDD "u1" and "u2"
        /// </summary>
        /// <param name="nodeFactory">
        /// The node factory.
        /// </param>
        /// <param name="op">
        /// The operation.
        /// </param>
        /// <param name="u1">
        /// The first BDD represented by root node.
        /// </param>
        /// <param name="u2">
        /// The second BDD represented by root node.
        /// </param>
        /// <returns>
        /// The <see cref="BDDNode"/>.
        /// </returns>
        private BDDNode Apply(BDDNodeFactory nodeFactory, BDDOperator op, BDDNode u1, BDDNode u2)
        {
            if (u1 == null)
            {
                return(u2);
            }

            var g = new Dictionary <Tuple <BDDNode, BDDNode>, BDDNode>();

            return(this.App(nodeFactory, op, g, u1, u2));
        }
コード例 #18
0
        /// <summary>
        /// Reduction rules for a ZBDD.
        /// </summary>
        /// <param name="node">The node to reduce.</param>
        /// <param name="result">The modified node.</param>
        /// <returns>If there was a reduction.</returns>
        public override bool Reduce(BDDNode node, out DDIndex result)
        {
            result = DDIndex.False;
            if (node.High.IsZero())
            {
                result = node.Low;
                return(true);
            }

            return(false);
        }
コード例 #19
0
        private void LogToDotFormat(BDDNode root, BDDManager manager, Dictionary <string, BDDNode> nodeStore)
        {
            Dictionary <BDDNode, string> reverseHash = nodeStore.ToDictionary(a => a.Value, a => a.Key);

            Func <BDDNode, string> labelFunction = node =>
                                                   reverseHash.ContainsKey(node)
                    ? reverseHash[node] + $"({node.Index})"
                    : $"({reverseHash.FirstOrDefault(a => a.Key.Index == node.Index).Value})";

            logger.Info("ROOT");
            logger.Info(manager.ToDot(root, show_all: false, labelFunction: labelFunction));
        }
コード例 #20
0
ファイル: BDDNode.cs プロジェクト: IrinaLen/SAT
 public static bool Eq(BDDNode t1, BDDNode t2)
 {
     if (t1 == null && t2 == null)
     {
         return(true);
     }
     if (t1 == null || t2 == null)
     {
         return(false);
     }
     return(t1.varId == t2.varId && t1.high == t2.high && t1.low == t2.low);
 }
コード例 #21
0
        void AddThruthValue(string key, BDDNode node, Dictionary <string, bool> matrix, int acc)
        {
            if (acc == 0)
            {
                Dictionary <int, bool> interpretation = BuildInterpretation(key);
                bool value = EvaluateBDD(node, interpretation);
                matrix.Add(key, value);
                return;
            }

            AddThruthValue(key + "0", node, matrix, acc - 1);
            AddThruthValue(key + "1", node, matrix, acc - 1);
        }
コード例 #22
0
 public virtual string ToDot(BDDNode node)
 {
     return(_manager.ToDot(node, (arg) => {
         if (_rmapping[arg.Index] is KAOSCoreElement kce)
         {
             return kce.FriendlyName;
         }
         else
         {
             return _rmapping[arg.Index].ToString();
         }
     }, false));
 }
コード例 #23
0
ファイル: BDDToDNF.cs プロジェクト: IrinaLen/SAT
 public BDDToDNF(BDDNode bdd)
 {
     ToDNF("", bdd);
     if (total == "")
     {
         if (bdd.GetId() == 0)
         {
             total = "тождественная ложь";
         }
         if (bdd.GetId() == 1)
         {
             total = "тождественния истина";
         }
     }
 }
コード例 #24
0
 public override string ToDot(BDDNode node)
 {
     return(_manager.ToDot(node, (arg) => {
         if (_rmapping[arg.Index] is PrimitiveRefineeParameter <double> e)
         {
             return $"Case [{e.Value}]";
         }
         else if (_rmapping[arg.Index] is KAOSCoreElement kce)
         {
             return kce.FriendlyName;
         }
         else
         {
             return _rmapping[arg.Index].ToString();
         }
     }, false));
 }
コード例 #25
0
 public override string ToDot(BDDNode node)
 {
     return(_manager.ToDot(node, (arg) => {
         if (_rmapping[arg.Index] is GoalException e)
         {
             return "Except " + e.ResolvingGoalIdentifier;
         }
         else if (_rmapping[arg.Index] is KAOSCoreElement kce)
         {
             return kce.FriendlyName;
         }
         else
         {
             return _rmapping[arg.Index].ToString();
         }
     }, false));
 }
コード例 #26
0
    public BDDNode MakeNode(int index, BDDNode high, BDDNode low)
    {
        // node already exists?
        // TODO Jonas: this is supposed to be an O(1) hash lookup
        var newNode = new BDDNode(nodes.Count, index, high, low);

        foreach (var node in nodes)
        {
            if (node.IsEquivalent(newNode))
            {
                return(node);
            }
        }

        // register new node
        nodes.Add(newNode);
        return(newNode);
    }
コード例 #27
0
        /// <summary>
        /// Private helper for BDD construction.
        /// </summary>
        /// <param name="ft">
        /// The ft.
        /// </param>
        /// <param name="nodeFactory">
        /// The node factory.
        /// </param>
        /// <returns>
        /// The <see cref="BDDNode"/>.
        /// </returns>
        private BDDNode CreateBDD(FaultTree.FaultTree ft, BDDNodeFactory nodeFactory)
        {
            int nextVariable = ft.Reduce(new MinTerminalTransformer());

            if (nextVariable == int.MaxValue)
            {
                // ft should consist of only terminal node
                return(nodeFactory.CreateNode(((FaultTreeLiteralNode)ft.Root).Value));
            }

            FaultTree.FaultTree high = ft.DeepCopy().Replace(nextVariable, true).Simplify();
            FaultTree.FaultTree low  = ft.DeepCopy().Replace(nextVariable, false).Simplify();

            BDDNode highNode = this.CreateBDD(high, nodeFactory);
            BDDNode lowNode  = this.CreateBDD(low, nodeFactory);

            return(nodeFactory.CreateNode(nextVariable, highNode, lowNode));
        }
コード例 #28
0
ファイル: OBDDTest.cs プロジェクト: lumpn/model-checking
    private static BDDNode AddTransition(OBDD obdd, BDDNode node, int index, int numBits, int offset)
    {
        for (int i = 0; i < numBits; i++)
        {
            int literal  = i * 2 + offset;
            var variable = obdd.MakeLiteral(literal);

            bool hasBit = (index & (1 << i)) != 0;
            if (!hasBit)
            {
                variable = obdd.MakeNot(variable);
            }

            node = obdd.MakeAnd(node, variable);
        }

        return(node);
    }
コード例 #29
0
    /// <summary>restricts a BDD by assigning a value to a variable</summary>
    public BDDNode Restrict(BDDNode node, int variableId, bool variableValue)
    {
        if (node.variableId > variableId)
        {
            // our node and all our children do not contain the variable
            return(node);
        }

        if (node.variableId < variableId)
        {
            // restrict children
            return(MakeNode(node.variableId, Restrict(node.high, variableId, variableValue), Restrict(node.low, variableId, variableValue)));
        }

        // restrict this node because it matches the variable
        var branch = variableValue ? node.high : node.low;

        return(Restrict(branch, variableId, variableValue));
    }
コード例 #30
0
ファイル: BDDToDNF.cs プロジェクト: IrinaLen/SAT
 private void ToDNF(string curConj, BDDNode node)
 {
     if (node.GetId() == 0)
     {
         return;
     }
     if (node.GetId() == 1)
     {
         if (total.Any())
         {
             total += " + " + curConj;
         }
         else
         {
             total += curConj;
         }
         return;
     }
     ToDNF(curConj + "X" + node.GetVarId() + "\"", node.GetLow());
     ToDNF(curConj + "X" + node.GetVarId(), node.GetHigh());
 }