Package COM.hugin.HAPI

The Hugin Java API consists of the COM.hugin.HAPI package.

See:
          Description

Interface Summary
ClassParseListener An implementation of the ClassParseListener interface must be used when one wants to call the parseClasses method of the ClassCollection class.
NumericDiscreteNode The NumericDiscreteNode interface declares the common methods for the NumberedDCNode, NumberedDDNode, IntervalDCNode, and IntervalDDNode classes.
ParseListener The ParseListener interface is a general interface for handling errors while parsing Hugin NET files, Hugin case files, Hugin data files, files of node names, and strings representing Expressions.
 

Class Summary
AbsExpression Expression class representing the abs operator.
AddExpression Expression class representing the + operator.
AggregateExpression Expression class representing the aggregate() operator.
AndExpression Expression class representing the and() function.
Attribute Attributes can be used to associate arbitrary data with a node or a NetworkModel (i.e., a Class or a Domain).
BetaDistribution Expression class representing the Beta distribution.
BinomialDistribution Expression class representing the Binomial distribution.
BooleanDCNode Boolean chance node.
BooleanDDNode Boolean decision node.
BooleanDFNode Boolean function node.
BooleanExpression A Boolean constant expression is used to compare state values of Boolean discrete chance or decision nodes.
CeilExpression Expression class representing the ceil operator.
Class Instances of the Class class represent object-oriented Bayesian networks and LIMIDs.
ClassCollection Classes are grouped into ClassCollections.
ClassList Lists of Classes are represented as ClassList's.
Clique Represents the cliques in the JunctionTree.
CliqueList Lists of Cliques are represented as CliqueList's.
CompositeExpression The ancestor class of all composite expression (for example arithmetic operators or standard distribution functions).
ConstantExpression The ancestor of all expression classes representing a constant (label, number, or Boolean).
ContinuousChanceNode Represents continuous chance nodes with (conditional) Gaussian distributions.
CosExpression Expression class representing the cos() function.
CoshExpression Expression class representing the cosh() function.
DataSet The DataSet class.
DefaultClassParseListener Provides a simple implementation of the ClassParseListener class.
DiscreteChanceNode The DiscreteChanceNode class.
DiscreteDecisionNode The DiscreteDecisionNode class.
DiscreteFunctionNode The DiscreteFunctionNode class.
DiscreteNode The DiscreteNode class.
DistributionDistribution Expression class representing the Distribution distribution.
DivideExpression Expression class representing the / operator.
Domain Instances of the Domain class represent Bayesian networks and LIMIDs in which you can propagate evidence and calculate updated beliefs and expected utilities.
Domain.Equilibrium The Equilibrium class represents the equilibrium state of this Domain.
Domain.EvidenceMode The EvidenceMode class represents the mode used for propagating evidence in this Domain.
Domain.TriangulationMethod The TriangulationMethod class represents the triangulation method used for this Domain.
EqualsExpression Expression class representing the == operator.
ExpExpression Expression class representing the exp() function.
ExponentialDistribution Expression class representing the Exponential distribution.
Expression Expression is the ancestor of all expression classes.
ExpressionList Lists of Expressions are represented as ExpressionList's.
FloorExpression Expression class representing the floor operator.
FunctionNode A FunctionNode represents a real-valued function.
GammaDistribution Expression class representing the Gamma distribution.
GeometricDistribution Expression class representing the Geometric distribution.
GreaterThanExpression Expression class representing the > operator.
GreaterThanOrEqualsExpression Expression class representing the >= operator.
IfExpression Expression class representing the if(cond-expr,true-expr,false-expr) function.
InstanceNode InstanceNodes are the key building block of object-oriented Bayesian networks and LIMIDs.
IntervalDCNode Interval discrete chance node.
IntervalDDNode Interval discrete decision node.
IntervalDFNode Interval discrete function node.
JunctionTree Thic class represents the JunctionTrees in the compiled domain.
JunctionTreeList Lists of JunctionTrees are represented as JunctionTreeLists.
LabelExpression A label constant expression is used to compare state labels of labelled discrete chance nodes or decision nodes.
LabelledDCNode Labelled discrete chance node.
LabelledDDNode Labelled discrete decision node.
LabelledDFNode Labelled discrete function node.
LessThanExpression Expression class representing the < operator.
LessThanOrEqualsExpression Expression class representing the <= operator.
Log10Expression Expression class representing the log10 function.
Log2Expression Expression class representing the log2 function.
LogExpression Expression class representing the log() function.
LogNormalDistribution Expression class representing the LogNormal distribution.
MaxExpression Expression class representing the max() function.
MinExpression Expression class representing the min() function.
Model A Model is a compact description of a table.
ModExpression Expression class representing the mod operator.
MultiplyExpression Expression class representing the * operator.
NegateExpression Expression class representing the unary - operator.
NegativeBinomialDistribution Expression class representing the Negative Binomial distribution.
NetworkModel The NetworkModel class is an abstract class with two subclasses: Domain and Class.
NetworkModel.Category The Category class is used to attach a category tag to the Nodes of Classes and Domains.
NetworkModel.Constraint The Constraint class is used to represent domain knowledge about a particular edge between a pair of nodes.
NetworkModel.Kind The Kind class is used to attach a sub-category tag to the chance and decision nodes of Classes and Domains.
Node Nodes are one of the fundamental objects used in the construction of Bayesian networks and LIMIDs.
NodeExpression An expression representing the value of a discrete chance node or decision node.
NodeList Lists of Nodes are represented as NodeList's.
NoisyOrDistribution Expression class representing the NoisyOr distribution.
NormalDistribution Expression class representing the Gaussian (Normal) distribution.
NotEqualsExpression Expression class representing the != operator.
NotExpression Expression class representing the Boolean not() function.
NumberedDCNode Numbered discrete chance node.
NumberedDDNode Numbered discrete decision node.
NumberedDFNode Numbered discrete function node.
NumberExpression A numeric constant expression is used to compare state value of numbered or interval discrete chance nodes or decision nodes.
OrExpression Expression class representing the Boolean or() function.
PERTDistribution Expression class representing the PERT distribution.
PoissonDistribution Expression class representing the Poisson distribution.
PowerExpression Expression class representing the ^ operator.
ProbabilityExpression Expression class representing the probability() operator.
QuantileExpression Expression class representing the quantile function.
SinExpression Expression class representing the sin() function.
SinhExpression Expression class representing the sinh() function.
SqrtExpression Expression class representing the sqrt() function.
StateIndexExpression Expression class representing the unary # operator.
SubtractExpression Expression class representing the binary - operator.
Table Hugin uses Tables for representing the conditional probability and utility potentials of individual Nodes, the probability and utility potentials on separators and Cliques of JunctionTrees, evidence potentials, etc.
TanExpression Expression class representing the tan() function.
TanhExpression Expression class representing the tanh() function.
TriangularDistribution Expression class representing the Triangular distribution.
TruncateExpression Expression class representing the truncate() operator.
UniformDistribution Expression class representing the Uniform distribution.
UtilityNode A UtilityNode represents a utility function.
VarianceExpression Expression class representing the variance function.
WeibullDistribution Expression class representing the Weibull distribution.
 

Exception Summary
ExceptionArgumentNotAlive An ExceptionArgumentNotAlive exception is thrown when a method (or a constructor) is called with an argument that is not alive.
ExceptionBadKBFormat An ExceptionBadKBFormat exception is thrown when an attempt is made to open an invalid Hugin KB file.
ExceptionBadKBPassword An ExceptionBadKBPassword exception is thrown when an attempt is made to open a password protected Hugin KB file using an invalid password.
ExceptionBadKBType An ExceptionBadKBType exception is thrown when an attempt is made to open a Hugin KB (HKB) file of the wrong type for the operation used.
ExceptionBadKBVersion An ExceptionBadKBVersion exception is thrown when an attempt is made to open a Hugin KB file produced by an ancient (or a newer) version of the Hugin software.
ExceptionCaseStateTooLarge An ExceptionCaseStateTooLarge exception is thrown when a state index larger than 32767 is passed to the DiscreteNode.setCaseState method.
ExceptionCGEvidenceIncorporated An ExceptionCGEvidenceIncorporated exception is thrown when a conflict value is requested, and CG evidence has been propagated.
ExceptionCGLIMIDsNotSupported An ExceptionCGLIMIDsNotSupported exception is thrown when an attempt is made to construct a network containing both decision (or utility) and CG nodes.
ExceptionChainGraph An ExceptionChainGraph exception is thrown when a zero value is found in the normalizing potential of a chain graph block.
ExceptionCompressed An ExceptionCompressed exception is thrown when a method is called that does not support compressed domains.
ExceptionComputationFailed An ExceptionComputationFailed exception is thrown if a probability/density function or a function value in an Expression cannot be computed.
ExceptionCyclicFunctionalDependency An ExceptionCyclicFunctionalDependency exception is thrown when an attempt is made to create a link that would cause a cyclic dependency in the evaluation of function nodes.
ExceptionCyclicInstanceHierarchy An ExceptionCyclicInstanceHierarchy exception is thrown if an attempt is made to create a cycle in the hierarchical structure of an OOBN model.
ExceptionCyclicNetwork An ExceptionCyclicNetwork exception is thrown when an attempt is made to create a (directed) cycle in a network.
ExceptionDemo An ExceptionDemo exception is thrown if the Hugin software detects that the limits of the software have been exceeded.
ExceptionDivisionByZero An ExceptionDivisionByZero exception is thrown when an attempt is made to divide by zero while evaluating an Expression.
ExceptionEnumeration An ExceptionEnumeration exception is thrown when an invalid elimination sequence is passed to the Domain.triangulate(NodeList) method or the Domain.setInitialTriangulation(NodeList) method.
ExceptionError An ExceptionError exception is thrown if an internal error in the Hugin API is detected.
ExceptionExpiredLicense An ExceptionExpiredLicense exception is thrown if the Hugin software detects that the time limited license has expired.
ExceptionFastRetraction An ExceptionFastRetraction exception is thrown when logical relations in a probability distribution causes a fast-retraction propagation to fail.
ExceptionFunctionalDependency An ExceptionFunctionalDependency exception is thrown when a functional dependency between two non-real-valued function nodes has been detected.
ExceptionHugeArray An ExceptionHugeArray exception is thrown if Table.getData() detects that the size of the table is larger than Integer.MAX_VALUE.
ExceptionHugin The ExceptionHugin class is the base class of all exception classes in the Hugin Java API.
ExceptionIllegalBinding An ExceptionIllegalBinding exception is thrown if an actual input node is found to be incompatible with the formal input node, or multiple occurrences of the same parent are detected.
ExceptionInappropriateArguments An ExceptionInappropriateArguments exception is thrown if invalid arguments are passed to a standard mathematical or probability/density function in an Expression.
ExceptionInconsistencyOrUnderflow An ExceptionInconsistencyOrUnderflow exception is thrown when an attempt is made to propagate inconsistent evidence, or underflow has occurred.
ExceptionInsufficientStateRange An ExceptionInsufficientStateRange exception is thrown if the state range of a numeric node is found to be insufficient for a standard probability distribution.
ExceptionInvalidEvidence An ExceptionInvalidEvidence exception is thrown when an invalid evidence scenario is detected.
ExceptionInvalidExpression An ExceptionInvalidExpression exception is thrown if the table generator detects an invalid Expression.
ExceptionInvalidLicense An ExceptionInvalidLicense exception is thrown if the Hugin software could not find valid license data.
ExceptionInvalidName An ExceptionInvalidName exception is thrown when an attempt is made to assign an invalid name to some object.
ExceptionInvalidProbabilityPotential An ExceptionInvalidProbabilityPotential exception is thrown when a negative value or a zero-sum distribution is found in a probability potential.
ExceptionInvalidStateValues An ExceptionInvalidStateValues exception is thrown if the state values of a numeric node do not form an increasing sequence.
ExceptionIO An ExceptionIO exception is thrown when an error occurs during an input or an output operation.
ExceptionJNI An ExceptionJNI exception is thrown if an internal JNI error is detected.
ExceptionLocale An ExceptionLocale exception is thrown if the Hugin API native code could not establish the C locale.
ExceptionLowDensity An ExceptionLowDensity exception is thrown when the density of some CG evidence is too low to represent as a positive floating-point number.
ExceptionMemory An ExceptionMemory exception is thrown when Hugin runs out of memory while carrying out some operation (e.g., a compilation operation).
ExceptionNoEquilibrium An ExceptionNoEquilibrium exception is thrown when invalid junction tree potentials are detected.
ExceptionNormalization An ExceptionNormalization exception is thrown when an attempt is made to normalize with a zero (or underflowed) normalization constant.
ExceptionNotCompiled An ExceptionNotCompiled exception is thrown when a method is called that requires a compiled domain.
ExceptionNoValue An ExceptionNoValue exception is thrown when a case state/value is requested, but no value has been specified (or the previously specified value has become invalid).
ExceptionObjectNotAlive An ExceptionObjectNotAlive exception is thrown when a method is called on an object that is not alive.
ExceptionOverflow An ExceptionOverflow exception is thrown if overflow occurs during propagation.
ExceptionParse An ExceptionParse exception is thrown when a syntax error is detected while parsing a text file.
ExceptionRounding An ExceptionRounding exception is thrown when a potentially significant floating-point rounding error is detected.
ExceptionSizeTooLarge An ExceptionSizeTooLarge exception is thrown when the size of an object is requested, and the true size of the object cannot be represented.
ExceptionSyntax An ExceptionSyntax exception is thrown when a syntax error is detected while parsing an Expression specified as a String.
ExceptionTableTooLarge An ExceptionTableTooLarge exception is thrown if the Domain.compress() method detects that the compressed version of some non-clique table is too large.
ExceptionTwice An ExceptionTwice exception is thrown when an attempt is made to assign a name that is already in use to a node or a class.
ExceptionUsage An ExceptionUsage exception is thrown when a method (or a constructor) is called with an invalid argument (e.g., passing a NULL object to a method that expects a non-NULL argument).
ExceptionZeroVariance An ExceptionZeroVariance exception is thrown when a zero variance is detected during a conditioning operation.
 

Package COM.hugin.HAPI Description

The Hugin Java API consists of the COM.hugin.HAPI package. These pages are meant as a help for developers programming against the Hugin Java API. Brief descriptions are included for all classes and their members. For more detailed descriptions, please consult the full documentation provided in the Hugin API Reference Manual. This manual is included in the Hugin software packages, but it can also be downloaded here.

This document contains the following:

General Information

The Hugin Java API contains a high performance inference engine that can be used as the core of knowledge based systems built using Bayesian networks or LIMIDs. Using probabilistic descriptions of causal relationships in an application domain, a knowledge engineer can build knowledge bases that model the domain. Given this description, the Hugin Decision Engine can perform fast and accurate reasoning.

The Hugin Java API is organized as an ordinary Java package. Classes and member methods are provided for tasks such as construction of networks, performing inference, etc. The Hugin Java API also provides an exception based mechanism for handling errors.

Object-Oriented Specification

The Hugin Java API provides a powerful object-orientation mechanism. Object-oriented specification of Bayesian networks and LIMIDs make it very easy to reuse models, to encapsulate submodels (providing a means for hierarchical model specification), and to perform model construction in a top-down fashion, a bottom-up fashion, or a mix of the two (allowing repeated changes of level of abstraction).

The classes Domain and Class both extend the abstract class NetworkModel, which contains constants and methods common to regular Bayesian networks/LIMIDs and object-oriented Bayesian networks/LIMIDs, respectively.

In addition to the usual nodes, an object-oriented Bayesian network or LIMID contains instance nodes, representing instances of other networks. In other words, an instance node represents a subnetwork. Of course, the network of which instances exist in other networks can itself contain instance nodes, whereby an object-oriented network can be viewed as a hierarchical description of a problem domain. Describing a network in a hierarchical fashion often makes the network much less cluttered, and thus provides a much better means of communicating ideas among knowledge engineers and users.

As systems often are composed of collections of identical or similar components, models of systems often contain repetitive patterns. The notion of instance nodes makes it very easy to construct multiple identical instances of a network fragment.

Memory Management

The Hugin Java API is comprised of two parts: a Java part and a native part written in C. Contrary to objects within the Java VM, native data objects are not automatically reclaimed (or "garbage collected") when a program stops referring to them. Therefore, some explicit memory management is needed in order to avoid memory leaks.

For example, when a Java Domain object is no longer needed, it should be deleted. Deleting a Domain object will cause all the native objects associated with the Domain object to be implicitly deleted: the native domain object, the native node objects, etc. At the same time all Java objects corresponding to those native objects are marked "dead" (that is, invoking methods on such objects will cause ExceptionObjectNotAlive exceptions). When the Java program stops referring to dead objects, the garbage collector can reclaim them.

Only objects that are not "owned" by other objects require explicit deletion. (For example, nodes are owned by a Domain or a Class object; a Class object is owned by a ClassCollection object; etc.) An object owned by another object is automatically deleted when its owner is deleted.

The following objects are not owned by other objects and must therefore be explicitly deleted in the Java code:

Error Handling

Several types of errors can occur when using a class or member method from the Hugin Java API. These errors can be the result of errors in the application program, of running out of memory, of corrupted data files, etc.

As a general principle, the Hugin Java API will try to recover from any error as well as possible. The API will then inform the application program of the problem and take no further action. It is then up to the application program to take the appropriate action.

When a member method fails, the data structures will always be left in a consistent state. Moreover, unless otherwise stated explicitly for a particular method, this state can be assumed identical to the state before the failed API call.

To communicate errors to the user of the Hugin Java API, the API defines a set of exception classes. All exception classes are subclasses of ExceptionHugin.

Examples

The following examples show how the Hugin Java API can be used to manipulate belief networks and LIMIDs.

Example 1

This example shows how to load a belief network or a LIMID specified as a (non-OOBN) NET file: A Domain object is constructed from the NET file. The domain is then triangulated using the "best greedy" heuristic, and the compilation process is completed. The (prior) beliefs and expected utilities (if the network is a LIMID) are then printed. If a case file is given, the file is loaded, the evidence is propagated, and the updated results are printed.
/* Copyright (C) 1991-2012 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   .  */
/* This header is separate from features.h so that the compiler can
   include it implicitly at the start of every compilation.  It must
   not itself include  or any other header that includes
    because the implicit include comes before any feature
   test macros that may be defined in a source file before it first
   explicitly includes a system header.  GCC knows the name of this
   header in order to preinclude it.  */
/* We do support the IEC 559 math functionality, real and complex.  */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
   Unicode 6.0.  */
/* We do not support C11 .  */
import COM.hugin.HAPI.*;
class LoadAndPropagate
{
    /**
     * 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.
     */
    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.H_TM_BEST_GREEDY);
            domain.compile();
            domain.closeLogFile();
            boolean hasUtilities = containsUtilities (domain.getNodes());
            if (!hasUtilities)
                System.out.println ("Prior beliefs:");
            else {
                domain.updatePolicies();
                System.out.println ("Overall expected utility: "
                                    + domain.getExpectedUtility());
                System.out.println ();
                System.out.println ("Prior beliefs (and expected utilities):");
            }
            printBeliefsAndUtilities (domain);
            if (caseName != null) {
                domain.parseCase (caseName, parseListener);
                System.out.println ();
                System.out.println ();
                System.out.println ("Propagating the evidence specified in \""
                                    + caseName + "\"");
                domain.propagate (Domain.H_EQUILIBRIUM_SUM,
                                  Domain.H_EVIDENCE_MODE_NORMAL);
                System.out.println ();
                System.out.println ("P(evidence) = "
                                    + domain.getNormalizationConstant());
                System.out.println ();
                if (!hasUtilities)
                    System.out.println ("Updated beliefs:");
                else {
                    domain.updatePolicies();
                    System.out.println ("Overall expected utility: "
                                        + domain.getExpectedUtility());
                    System.out.println ();
                    System.out.println ("Updated beliefs (and expected utilities):");
                }
                printBeliefsAndUtilities (domain);
            }
            domain.delete();
        } catch (ExceptionHugin e) {
            System.out.println ("Exception caught: " + e.getMessage());
        } catch (Exception e) {
            System.out.println ("General exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     * Print the beliefs and expected utilities of all nodes in the domain.
     */
    public static void printBeliefsAndUtilities (Domain domain)
        throws ExceptionHugin
    {
        NodeList nodes = domain.getNodes();
        boolean hasUtilities = containsUtilities (nodes);
        java.util.ListIterator it = nodes.listIterator();
        while (it.hasNext()) {
            Node node = (Node) it.next();
            System.out.println ();
            System.out.println (node.getLabel() + " (" + node.getName() + ")");
            if (node instanceof UtilityNode)
                System.out.println ("  - Expected utility: "
                                    + ((UtilityNode) node).getExpectedUtility());
            else if (node instanceof FunctionNode)
                try {
                    System.out.println ("  - Value: "
                                        + ((FunctionNode) node).getValue());
                } catch (ExceptionHugin e) {
                    System.out.println ("  - Value: N/A");
                }
            else if (node instanceof DiscreteNode) {
                DiscreteNode dNode = (DiscreteNode) node;
                for (int i = 0, n = (int) dNode.getNumberOfStates(); i < n; i++) {
                    System.out.print ("  - " + dNode.getStateLabel (i)
                                      + " " + dNode.getBelief (i));
                    if (hasUtilities)
                        System.out.println (" (" + dNode.getExpectedUtility (i) + ")");
                    else
                        System.out.println();
                }
            } else {
                ContinuousChanceNode ccNode = (ContinuousChanceNode) node;
                System.out.println ("  - Mean : " + ccNode.getMean());
                System.out.println ("  - SD   : " + Math.sqrt (ccNode.getVariance()));
            }
        }
    }
    /**
     * Are there utility nodes in the list?
     */
    public static boolean containsUtilities (NodeList list)
    {
        java.util.ListIterator it = list.listIterator();
        while (it.hasNext())
            if (it.next() instanceof UtilityNode)
                return true;
        return false;
    }
    /**
     * 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.
     */
    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
            System.err.println ("Usage: <netName> [<caseName>]");
    }
}

Example 2

The code in the first example assumed that the network was specified as a non-OOBN NET file. If the network is specified as an OOBN model, the loading process becomes more complicated. The following code assumes that a class is stored as a single file with the name of the file formed by adding the extension ".oobn" to the name of the class.
/* Copyright (C) 1991-2012 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   .  */
/* This header is separate from features.h so that the compiler can
   include it implicitly at the start of every compilation.  It must
   not itself include  or any other header that includes
    because the implicit include comes before any feature
   test macros that may be defined in a source file before it first
   explicitly includes a system header.  GCC knows the name of this
   header in order to preinclude it.  */
/* We do support the IEC 559 math functionality, real and complex.  */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
   Unicode 6.0.  */
/* We do not support C11 .  */
import COM.hugin.HAPI.*;
class MyParseListener implements ClassParseListener
{
    public void parseError (int line, String msg)
    {
        System.out.println ("Parse error in line " + line + ": " + msg);
    }
    public void insertClass (String className, ClassCollection cc)
    {
        try {
            cc.parseClasses (className + ".oobn", this);
        } catch (ExceptionHugin e) {
            System.out.println ("Parsing failed: " + e.getMessage());
        }
    }
}
class OOBN
{
    /**
     * Load the class "className" (and all classes instantiated in
     * that class, recursively).  Then "unfold" the class to a Domain
     * that can be used for inference.
     */
    public OOBN (String className)
    {
        try {
            ClassCollection cc = new ClassCollection();
            MyParseListener parseListener = new MyParseListener();
            cc.parseClasses (className + ".oobn", parseListener);
            // Unfold the Class to a Domain that can be compiled and
            // used for inference, etc.
            COM.hugin.HAPI.Class main = cc.getClassByName (className);
            if (main == null)
                System.out.println ("Class not found: " + className);
            else {
                Domain domain = main.createDomain();
                // Use the domain for inference, etc. (omitted)
                domain.delete();
            }
            cc.delete();
        } catch (ExceptionHugin e) {
            System.out.println ("Exception caught: " + e.getMessage());
        } catch (Exception e) {
            System.out.println ("General exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Example 3

This example describes how a belief network can be constructed using the Hugin Java API. The network consists of three numbered nodes. Two of the nodes take on values 0, 1, and 2. The third node is the sum of the two other nodes. Once the Bayesian network is constructed, the network is saved as a NET specification file, and an initial propagation is performed. Finally, the marginals of the nodes are printed on standard output.
/* Copyright (C) 1991-2012 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   .  */
/* This header is separate from features.h so that the compiler can
   include it implicitly at the start of every compilation.  It must
   not itself include  or any other header that includes
    because the implicit include comes before any feature
   test macros that may be defined in a source file before it first
   explicitly includes a system header.  GCC knows the name of this
   header in order to preinclude it.  */
/* We do support the IEC 559 math functionality, real and complex.  */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
   Unicode 6.0.  */
/* We do not support C11 .  */
import COM.hugin.HAPI.*;
import java.awt.event.*;
import java.util.ListIterator;
import java.awt.geom.Point2D;
class BAP
{
    protected Domain domain;
    /**
     * Build a Bayesian network and propagate evidence.
     */
    public BAP ()
    {
        try {
            domain = new Domain ();
            buildNetwork ();
            domain.saveAsNet ("builddomain.net");
            domain.compile ();
            propagateEvidenceInNetwork ();
        }
        catch (ExceptionHugin e) {
            System.out.println (e.getMessage ());
        }
    }
    /**
     * Propagate evidence in domain.
     */
    protected void propagateEvidenceInNetwork ()
    {
        try {
            domain.propagate (Domain.H_EQUILIBRIUM_SUM,
                              Domain.H_EVIDENCE_MODE_NORMAL);
            printNodeMarginals (domain);
        }
        catch (ExceptionHugin e) {
            System.out.println (e.getMessage ());
        }
    }
    /**
     * print node marginals.
     */
    protected void printNodeMarginals (Domain d)
    {
        try {
            ListIterator it = domain.getNodes ().listIterator ();
            while (it.hasNext ())
            {
                DiscreteChanceNode node = (DiscreteChanceNode) it.next ();
                System.out.println (node.getLabel ());
                for (int i = 0, n = node.getNumberOfStates (); i < n; i++)
                    System.out.println ("-" + node.getStateLabel (i)
                                        + " " + node.getBelief (i));
            }
        }
        catch (ExceptionHugin e) {
            System.out.println (e.getMessage ());
        }
    }
    /**
     * Constructs numbered discrete chance node.
     */
    protected NumberedDCNode constructNDC (String label, String name, int n)
    {
        try {
            NumberedDCNode node = new NumberedDCNode (domain);
            node.setNumberOfStates (n);
            for (int i = 0; i < n; i++)
                node.setStateValue (i, i);
            for (int i = 0; i < n; i++)
                node.setStateLabel (i, (new Integer (i)).toString ());
            node.setLabel (label);
            node.setName (name);
            return node;
        }
        catch (ExceptionHugin e) {
            System.out.println (e.getMessage ());
        }
        return null;
    }
    /**
     * Build the structure.
     */
    protected void buildStructure
        (NumberedDCNode A, NumberedDCNode B, NumberedDCNode C)
    {
        try {
            C.addParent (A);
            C.addParent (B);
            A.setPosition (new Point2D.Double (100, 200));
            B.setPosition (new Point2D.Double (200, 200));
            C.setPosition (new Point2D.Double (150, 50));
        }
        catch (ExceptionHugin e) {
            System.out.println (e.getMessage ());
        }
    }
    /**
     * Expression for C
     */
    protected void buildExpressionForC
        (NumberedDCNode A, NumberedDCNode B, NumberedDCNode C)
    {
        try {
            NodeList modelNodes = new NodeList ();
            Model model = new Model (C, modelNodes);
            NodeExpression exprA = new NodeExpression (A);
            NodeExpression exprB = new NodeExpression (B);
            AddExpression exprC = new AddExpression (exprA, exprB);
            model.setExpression (0, exprC);
        }
        catch (ExceptionHugin e) {
            System.out.println (e.getMessage ());
        }
    }
    /**
     * Specify the prior distribution of A and B.
     */
    protected void specifyDistributions (NumberedDCNode A, NumberedDCNode B)
    {
        try {
            Table table;
            table = A.getTable ();
            double [] data = new double[3];
            data[0] = 0.1;
            data[1] = 0.2;
            data[2] = 0.7;
            table.setData (data);
            table = B.getTable ();
            table.setDataItem (0, 0.2);
            table.setDataItem (1, 0.2);
            table.setDataItem (2, 0.6);
        }
        catch (ExceptionHugin e) {
            System.out.println (e.getMessage ());
        }
    }
    /**
     * Build the Bayesian network.
     */
    protected void buildNetwork ()
    {
        try {
            domain.setNodeSize (new Point2D.Double (50, 30));
            NumberedDCNode A = constructNDC ("A", "A", 3);
            NumberedDCNode B = constructNDC ("B", "B", 3);
            NumberedDCNode C = constructNDC ("C", "C", 5);
            buildStructure (A, B, C);
            buildExpressionForC (A, B, C);
            specifyDistributions (A, B);
        }
        catch (ExceptionHugin e) {
            System.out.println (e.getMessage ());
        }
    }
}
/**
 * Build a Bayesian network and perform a propagation of evidence.
 * Print the results.
 */
class BuildAndPropagate
{
    static public void main (String args[])
    {
        new BAP ();
    }
}

Classes and Constants

The Hugin Java API uses various classes for representing Class objects, Domain objects, Node objects, Table objects, Clique objects, Junction Tree objects, Error Code objects, etc. A class summary is given above.

The classes are (sorted according to category):

NetworkModel Classes
NetworkModel
NetworkModel.Category
NetworkModel.Kind

Domain Classes
Domain
Domain.Equilibrium
Domain.EvidenceMode
Domain.TriangulationMethod

Class Classes
Class

ClassCollection Classes
ClassCollection

Node Classes
BooleanDCNode
BooleanDDNode
ContinuousChanceNode
DiscreteChanceNode
DiscreteDecisionNode
DiscreteNode
FunctionNode
InstanceNode
IntervalDCNode
IntervalDDNode
LabelledDCNode
LabelledDDNode
Node
NumberedDCNode
NumberedDDNode
UtilityNode

Junction Tree Classes
Clique
JunctionTree

Table Classes
Table

Model Classes
Model

Expression Classes
AbsExpression
AddExpression
AggregateExpression
AndExpression
BooleanExpression
CeilExpression
CompositeExpression
ConstantExpression
CosExpression
CoshExpression
DivideExpression
EqualsExpression
ExpExpression
Expression
FloorExpression
GreaterThanExpression
GreaterThanOrEqualsExpression
IfExpression
LabelExpression
LessThanExpression
LessThanOrEqualsExpression
LogExpression
Log2Expression
Log10Expression
MaxExpression
MinExpression
ModExpression
MultiplyExpression
NegateExpression
NodeExpression
NotEqualsExpression
NotExpression
NumberExpression
OrExpression
PowerExpression
ProbabilityExpression
SinExpression
SinhExpression
SqrtExpression
StateIndexExpression
SubtractExpression
TanExpression
TanhExpression
TruncateExpression

Distribution Classes
BetaDistribution
BinomialDistribution
DistributionDistribution
ExponentialDistribution
GammaDistribution
GeometricDistribution
LogNormalDistribution
NegativeBinomialDistribution
NoisyOrDistribution
NormalDistribution
PERTDistribution
PoissonDistribution
TriangularDistribution
UniformDistribution
WeibullDistribution

List Classes
ClassList
CliqueList
ExpressionList
JunctionTreeList
NodeList

Parser Interfaces
ClassParseListener
ParseListener

Parser Classes
DefaultClassParseListener

Attribute Classes
Attribute


The Hugin C API uses a number of enumeration types. Some examples: The type h_triangulation_method_t defines the possible triangulation methods used during compilation, etc. These types are in the Hugin Java API defined as inner classes in the NetworkModel and the Domain classes.

Acknowledgements

Hugin Expert A/S has participated in a number of projects funded by the European Union. Some projects have also received funding from Innovation Fund Denmark. See www.hugin.com/index.php/acknowledgments for the complete list of projects.

The development of the functionality concerning the real-valued FunctionNode type (introduced in Hugin 7.3) has been sponsored by Danish mortgage credit institution Nykredit Realkredit (www.nykredit.dk).

The development of the functionality concerning the DiscreteFunctionNode type as well as the AggregateExpression and ProbabilityExpression operators (introduced in Hugin 7.7) has been sponsored by the research project "Operational risk in banking and finance." The project is dedicated to strengthening management of operational risk in the banking and finance sector, including developing Basel II compliant operational risk measurement and management tools in accordance with the Advanced Measurement Approach (AMA). The project is financed by the University of Stavanger and a consortium of Norwegian banks consisting of Sparebank 1 SR-Bank, Sparebank 1 SNN, Sparebank 1 SMN, Sparebanken Hedmark, and Sparebank 1 Oslo and Akershus.