• Manual
  • HAPI Namespace
Show / Hide Table of Contents
  • General Information
  • Object-Oriented Specification
  • Memory Management
  • Error Handling
  • Using the Hugin C#/.NET Core API
  • Examples
    • Example 1: Load and Propagate
    • Example 2: Build and Propagate
    • Example 3: Sequential Learning
    • Example 4: Node naming scheme for OOBNs
  • Acknowledgements

Example 1: Load And Propagate

This first example is concerned with loading a Bayesian network or a LIMID. Once the Bayesian network or LIMID has been loaded, the corresponding domain is triangulated using the minimum fill-in-weight heuristic and the compilation process is completed. Next, the beliefs and utilities are printed. Finally, a HUGIN case file is entered and a propagation of evidence is performed and the new beliefs and utilities are printed.

Note that this program loads networks saved in a "flat" network format. The HUGIN GUI application saves in OOBN format by default.

# if X64
using size_t = System.UInt64;
using h_index_t = System.Int64;
# else
using size_t = System.UInt32;
using h_index_t = System.Int32;
# endif
# if H_DOUBLE
using h_number_t = System.Double;
# else
using h_number_t = System.Single;
# endif

using System;
using HAPI;

namespace Example
{
    public class LoadAndPropagate
    {
        /// <summary>
        /// This function parses the given NET file, compiles the network,
        /// and prints the prior beliefs and expected utilities of all
        /// nodes.  If a case file is given, the function loads the file,
        /// propagates the evidence, and prints the updated results.
        /// 
        /// If the network is a LIMID, we assume that we should compute
        /// policies for all decisions (rather than use the ones specified
        /// in the NET file).  Likewise, we update the policies when new
        /// evidence arrives.
        /// </summary>
        public static void LAP(String netName, String caseName)
        {
            try
            {
                ParseListener parseListener = new DefaultClassParseListener();
                Domain domain = new Domain(netName + ".net", parseListener);
                domain.OpenLogFile(netName + ".log");
                domain.Triangulate(Domain.TriangulationMethod.H_TM_BEST_GREEDY);
                domain.Compile();
                domain.CloseLogFile();

                bool hasUtilities = ContainsUtilities(domain.GetNodes());

                if (!hasUtilities)
                    Console.WriteLine("Prior beliefs:");
                else
                {
                    domain.UpdatePolicies();
                    Console.WriteLine("Overall expected utility: "
                                       + domain.GetExpectedUtility());
                    Console.WriteLine();
                    Console.WriteLine("Prior beliefs (and expected utilities):");
                }
                PrintBeliefsAndUtilities(domain);

                if (caseName != null)
                {
                    domain.ParseCase(caseName, parseListener);

                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("Propagating the evidence specified in \""
                                       + caseName + "\"");

                    domain.Propagate(Domain.Equilibrium.H_EQUILIBRIUM_SUM,
                                     Domain.EvidenceMode.H_EVIDENCE_MODE_NORMAL);

                    Console.WriteLine();
                    Console.WriteLine("P(evidence) = "
                                       + domain.GetNormalizationConstant());
                    Console.WriteLine();

                    if (!hasUtilities)
                        Console.WriteLine("Updated beliefs:");
                    else
                    {
                        domain.UpdatePolicies();
                        Console.WriteLine("Overall expected utility: "
                                           + domain.GetExpectedUtility());
                        Console.WriteLine();
                        Console.WriteLine("Updated beliefs (and expected utilities):");
                    }
                    PrintBeliefsAndUtilities(domain);
                }

                domain.Delete();
            }
            catch (ExceptionHugin e)
            {
                Console.WriteLine("Exception caught: " + e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("General exception: " + e.Message);
                Console.WriteLine(e.StackTrace.ToString());
            }
        }


        /// <summary>
        /// Print the beliefs and expected utilities of all nodes in the domain.
        /// </summary>
        public static void PrintBeliefsAndUtilities(Domain domain)
        {
            NodeList nodes = domain.GetNodes();
            bool hasUtilities = ContainsUtilities(nodes);
            foreach (Node node in nodes)
            {
                Console.WriteLine();
                Console.WriteLine(node.GetLabel() + " (" + node.GetName() + ")");

                if (node is UtilityNode)
                    Console.WriteLine("  - Expected utility: "
                                    + ((UtilityNode)node).GetExpectedUtility());
                else if (node is DiscreteNode)
                {
                    DiscreteNode dNode = (DiscreteNode)node;

                    for (size_t i = 0, n = dNode.GetNumberOfStates(); i < n; i++)
                    {
                        Console.WriteLine("  - " + dNode.GetStateLabel(i)
                                           + " " + dNode.GetBelief(i));
                        if (hasUtilities)
                            Console.WriteLine(" (" + dNode.GetExpectedUtility(i) + ")");
                        else
                            Console.WriteLine();
                    }
                }
                else if (node is FunctionNode)
                {
                    FunctionNode fNode = (FunctionNode)node;
                    try {
                        double value = fNode.GetValue();
                        Console.WriteLine("  - Function value : " + value);
                    } catch (ExceptionHugin) {
                        Console.WriteLine("  - Function value : N/A");
                    }
                }
                else
                {
                    ContinuousChanceNode ccNode = (ContinuousChanceNode)node;

                    Console.WriteLine("  - Mean : " + ccNode.GetMean());
                    Console.WriteLine("  - SD   : " + Math.Sqrt(ccNode.GetVariance()));
                }
            }
        }


        /// <summary>
        /// Are there utility nodes in the list?
        /// </summary>
        public static bool ContainsUtilities(NodeList list)
        {
            foreach (Node node in list)
                if (node is UtilityNode)
                    return true;

            return false;
        }


        /// <summary>
        /// Load a HUGIN NET file, compile the network, and print the
        /// results.  If a case file is specified, load it, propagate the
        /// evidence, and print the results.
        /// </summary>
        public static void Main(String[] args)
        {
            if (args.Length == 1)
                LAP(args[0], null);
            else if (args.Length == 2)
                LAP(args[0], args[1]);
            else
                Console.Error.WriteLine("Usage: <netName> [<caseName>]");
        }

    }
}
In this article
Back to top Copyright (C) 2019-2025 Hugin Expert A/S