Exemplo n.º 1
0
 public static List <Evidence> Extend(List <Evidence> list, BayesianNode node, bool value)
 {
     return(new List <Evidence>(list)
     {
         new Evidence(node, value)
     });
 }
Exemplo n.º 2
0
    public void MakeDecision()
    {
        // You can specify a list of evidence
        List <string> observations = new List <string> {
            "brave=" + GetIsBrave(),
            "enemy_amount=" + GetEnemyAmount(),
            "cover_type=" + GetCoverType()
        };

        // You can then use them to infer another variable in the network
        double[] fightDistribution = ve.Infer("fight", observations);
        bool     fight             = ve.PickOne(fightDistribution) == 0;

        // You can do chain interence based on previous inference results
        observations.Add("fight=" + fight);

        // The API functions are overloaded to fit your needs
        // e.g. you can use a less string-based approach if you want to do things programmatically
        BayesianNetwork network         = ve.GetNetwork();
        Proposition     braveProp       = network.FindNode("brave").Instantiate(GetIsBrave());
        Proposition     enemyAmountProp = network.FindNode("enemy_amount").Instantiate(GetEnemyAmount());
        Proposition     hasCoverProp    = network.FindNode("cover_type").Instantiate(GetCoverType());
        Proposition     fightProp       = network.FindNode("fight").Instantiate(fight.ToString());
        BayesianNode    runAwayNode     = ve.GetNetwork().FindNode("run_away");

        double[] runawayDistribution = ve.Infer(runAwayNode, braveProp, enemyAmountProp, hasCoverProp, fightProp);
        bool     runaway             = ve.PickOne(runawayDistribution) == runAwayNode.var.GetTokenIndex("True");

        // Since it is a bayesian network, you can infer any variables with partial or even no information
        ve.Infer("enemy_amount", "fight=True");
        ve.Infer("fight");

        if (enemyAmount.Equals("NoEnemy"))
        {
            decisionText.text = "Did not see any enemy.";
        }
        else if (fight)
        {
            decisionText.text = "The NPC decided to fight. ";
        }
        else if (!fight && runaway)
        {
            decisionText.text = "The NPC decided to run away.";
        }
        else
        {
            decisionText.text = "The NPC decided to wait for his chance.";
        }
        decisionText.text = "Decision made: " + decisionText.text;

        probabilityText.text = string.Format("true: {0}%\t\tfalse: {1}%\ntrue: {2}%\t\tfalse: {3}%",
                                             fightDistribution[0] * 100, fightDistribution[1] * 100, runawayDistribution[0] * 100, runawayDistribution[1] * 100);
    }
 public Evidence(BayesianNode node, bool report)
 {
     Node   = node;
     Report = report;
 }
Exemplo n.º 4
0
 public static List <BayesianNode> Rest(List <BayesianNode> list, BayesianNode first)
 {
     return(list.Where(n => n != first).ToList());
 }
Exemplo n.º 5
0
        private void computarProbabilidadesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControl1.SelectTab(0);
            try
            {
                if (CheckConsistency())
                {
                    //obtener la evidencia
                    if (flowChartViewer1.Charts.Count > 0 && Evidence.Count > 0)
                    {
                        GetEvidence();
                    }
                    //transformar el grafo del visor a un grafo de nodos bayesianos

                    var graph = new BayesianGraph();
                    //
                    var          dict = new Dictionary <BayesianNode, BayesianNodeChartElement>(flowChartViewer1.Charts.Count);
                    BayesianNode node;
                    var          dict2 = new Dictionary <BayesianNodeChartElement, BayesianNode>(flowChartViewer1.Charts.Count);

                    graph.Clear();

                    foreach (var item in flowChartViewer1.Charts.Cast <BayesianNodeChartElement>())
                    {
                        node = new BayesianNode(item.Parents.Count, item.Childs.Count(), item.States.Count,
                                                item.Parents.Select(x => x.States.Count).ToArray())
                        {
                            Probabilities = item.Condicional_Probabilities, Name = item.Name
                        };

                        dict.Add(node, item);
                        dict2.Add(item, node);
                        item.CreateConditionalProbabilities();


                        graph.AddVertex(node);
                    }
                    foreach (var bnodechart in flowChartViewer1.Charts.Cast <BayesianNodeChartElement>())
                    {
                        foreach (var child in bnodechart.Childs)
                        {
                            graph.AddEdge(dict2[bnodechart], dict2[child]);
                        }
                    }
                    //ejecutar el traspaso de mensajes en un poliarbol o en una red multiplemente conexa
                    progressBar1.Value = 5;
                    //if(MessageTransfer.ParalellStartNumber>graph.Count)
                    MessageTransfer.Increment += UpdateProgress;


                    if (graph.Arbol())
                    {
                        if (Evidence.Count > 0)
                        {
                            MessageTransfer.Message_Tranfer_Poliarbol(graph, Evidence[EvidenceIndex]);
                        }
                        else
                        {
                            MessageTransfer.Message_Tranfer_Poliarbol(graph);
                        }
                        foreach (var nodebayesian in graph)
                        {
                            dict[nodebayesian].SetConditionalProbabilities(nodebayesian.ConditionalProbability);
                        }
                    }
                    else
                    {
                        var markovnet = new MarkovNet(graph);
                        if (Evidence.Count > 0)
                        {
                            MessageTransfer.Message_Tranfer_Arbol_Union(markovnet, Evidence[EvidenceIndex]);
                        }
                        else
                        {
                            MessageTransfer.Message_Tranfer_Arbol_Union(markovnet);
                        }
                        foreach (var nodebayesian in markovnet.BayesianNet)
                        {
                            dict[nodebayesian].SetConditionalProbabilities(nodebayesian.ConditionalProbability);
                        }
                    }

                    timer1.Stop();
                    progressBar1.Value = 100;

                    Tests.Add(new BayesianTest()
                    {
                        Evidence      = Evidence[EvidenceIndex].Clone(),
                        Probabilities =
                            graph.Select(x => x.ConditionalProbability.Clone() as double[]).ToArray()
                    });
                    TestsIndex = Tests.Count - 1;
                    ShowConditionalProbabilities();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Hubo algun problema al calcular las probabilidades condicionales. " + ex.Message);
            }
        }
Exemplo n.º 6
0
 public Query(BayesianNode node, bool question)
 {
     Node     = node;
     Question = question;
 }
Exemplo n.º 7
0
    /// <summary>
    /// Se le llama al inicio de la escena
    /// Se le llama cada vez que se pulsa un toogle o se desliza el slider
    /// </summary>
    public void MakeDecision()
    {
        ////Lista con las observaciones de la escena
        //List<string> observations = new List<string> {
        //    "brave=" + GetIsBrave(),
        //    "enemy_amount=" + GetEnemyAmount(),
        //    "cover_type=" + GetCoverType()
        //};
        ///*EJEMPLO: [brave=True, enemy_amount= 3, cover_type=Full_cover] */
        ////Usamos la lista para inferir otra variable en la red
        ////Calculamos la probabilidad de luchar en función de la observación
        //double[] fightDistribution = ve.Infer("fight", observations);

        ////Obtenemos si lucha o no
        //bool fight = ve.PickOne(fightDistribution) == 0;

        ////Añadimos si lucha o no a la lista de observaciones para tenerlo en cuenta para las siguientes inferencias
        //observations.Add("fight=" + fight);

        // The API functions are overloaded to fit your needs
        // e.g. you can use a less string-based approach if you want to do things programmatically
        //Creamos la red de decisión
        BayesianNetwork network = ve.GetNetwork();

        //Obtenemos referencia a todas las proposiciones y las crea con los valores observables
        Proposition braveProp       = network.FindNode("brave").Instantiate(GetIsBrave());
        Proposition enemyAmountProp = network.FindNode("enemy_amount").Instantiate(GetEnemyAmount());
        Proposition hasCoverProp    = network.FindNode("cover_type").Instantiate(GetCoverType());

        BayesianNode fightNode = ve.GetNetwork().FindNode("fight");

        double[] fightDistribution = ve.Infer(fightNode, braveProp, enemyAmountProp, hasCoverProp);
        bool     fight             = ve.PickOne(fightDistribution) == fightNode.var.GetTokenIndex("True");

        //Obtenemos la referencia a la proposición creada
        Proposition fightProp = network.FindNode("fight").Instantiate(fight.ToString());

        //Inferimos el nuevo nodo y tomamos una decisión
        BayesianNode runAwayNode = ve.GetNetwork().FindNode("run_away");

        double[] runawayDistribution = ve.Infer(runAwayNode, braveProp, enemyAmountProp, hasCoverProp, fightProp);
        bool     runaway             = ve.PickOne(runawayDistribution) == runAwayNode.var.GetTokenIndex("True");

        //Se puede inferir todo lo que quieras con información parcial o sin información
        ve.Infer("enemy_amount", "fight=True");
        ve.Infer("fight");

        //Escribir la decisión en función de lo que nos salga del coñete
        if (enemyAmount.Equals("NoEnemy"))
        {
            decisionText.text = "Did not see any enemy.";
        }
        else if (fight)
        {
            decisionText.text = "The NPC decided to fight. ";
        }
        else if (!fight && runaway)
        {
            decisionText.text = "The NPC decided to run away.";
        }
        else
        {
            decisionText.text = "The NPC decided to wait for his chance.";
        }

        decisionText.text = "Decision made: " + decisionText.text;

        probabilityText.text = string.Format("true: {0}%\t\tfalse: {1}%\ntrue: {2}%\t\tfalse: {3}%",
                                             fightDistribution[0] * 100, fightDistribution[1] * 100, runawayDistribution[0] * 100, runawayDistribution[1] * 100);
    }