Package COM.hugin.HAPI

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

See:
          Description

Interface Summary
ClassParseListener An implementation of the ClassParseListener interface must used when one wants to call the parseClasses method of the ClassCollection class.
ExpressionParseListener An implementation of the ExpressionParseListener interface must used when one wants to parse Expressions, using the stringToExpression method of the Expression class.
NetParseListener An implementation of the NetParseListener interface must be used when one wants to call the Domain constructor.
ParseListener The ParseListener interface is a general interface for parsing Hugin NET files, Hugin case files, and strings representing Expressions.
 

Class Summary
AbsExpression Expression class representing the abs operator.
AddExpression Expression class representing the + 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 function.
BinomialDistribution Expression class representing the Binomial distribution function.
BooleanDCNode Boolean discrete chance node.
BooleanDDNode Boolean discrete decision 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 influence diagrams.
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.
DefaultClassParseListener Provides a simple implementation of the ClassParseListener class.
DiscreteChanceNode The discrete chance node.
DiscreteDecisionNode The discrete decision node.
DistributionDistribution Expression class representing the Distribution distribution function.
DivideExpression Expression class representing the / operator.
Domain Instances of the Domain class represent Bayesian networks and influence diagrams 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 function.
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.
GammaDistribution Expression class representing the Gamma distribution function.
GeometricDistribution Expression class representing the Geometric distribution function.
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 influence diagrams.
IntervalDCNode Interval discrete chance node.
IntervalDDNode Interval discrete decision node.
JunctionTree Thic class represents the JunctionTrees in the compiled domain.
JunctionTreeList Lists of JunctionTrees are represented as JunctionTreeList's.
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.
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.
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 function.
NetworkModel The NetworkModel class is an abstract class with two subclasses: Domain.java and Class.java.
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 possible domain knowledge about a particular edge between a pair of variables.
NetworkModel.Endian The Endian class is used to represent the byte-order used when saving a Hugin Knowledge Base (HKB) file.
NetworkModel.Kind The Kind class is used to attach a sub-category tag to the chance nodes of Classes and Domains.
Node Nodes are one of the fundamental objects used in the construction of Bayesian networks and influence diagrams.
NodeExpression An expression representing the value of a discrete chance node or decision node.
NodeList Lists of Nodes are represented as NodeList's.
NoisyOrExpression Expression class representing the NoisyOr() function.
NormalDistribution Expression class representing the Gaussian (Normal) distribution function.
NotEqualsExpression Expression class representing the != operator.
NotExpression Expression class representing the Boolean not() function.
NumberedDCNode Numbered discrete chance node.
NumberedDDNode Numbered discrete decision 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.
PoissonDistribution Expression class representing the Poisson distribution function.
PowerExpression Expression class representing the ^ operator.
SinExpression Expression class representing the sin() function.
SinhExpression Expression class representing the sinh() function.
SqrtExpression Expression class representing the sqrt() function.
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.
UniformDistribution Expression class representing the Uniform distribution function.
UtilityNode A UtilityNode represents a utility function.
WeibullDistribution Expression class representing the Weibull distribution function.
 

Exception Summary
ExceptionArgumentNotAlive The ExceptionArgumentNotAlive class...
ExceptionBadFile The ExceptionBadFile class...
ExceptionBadVersion The ExceptionBadVersion class...
ExceptionCGEvidenceIncorporated The ExceptionCGEvidenceIncorporated class...
ExceptionCGInfluenceDiagramsNotSupported The ExceptionCGInfluenceDiagramsNotSupported class...
ExceptionChainGraph The ExceptionChainGraph class...
ExceptionCompressed The ExceptionCompressed class...
ExceptionComputationFailed The ExceptionComputationFailed class...
ExceptionCyclicInstanceHierarchy The ExceptionCyclicInstanceHierarchy class...
ExceptionCyclicNetwork The ExceptionCyclicNetwork class...
ExceptionDecisionOrder The ExceptionDecisionOrder class...
ExceptionDemo The ExceptionDemo class...
ExceptionDivisionByZero The ExceptionDivisionByZero class...
ExceptionEnumeration The ExceptionEnumeration class...
ExceptionError The ExceptionError class...
ExceptionExpiredLicense The ExceptionExpiredLicense class...
ExceptionFastRetraction The ExceptionFastRetraction class...
ExceptionFormat The ExceptionFormat class...
ExceptionHugeArray The ExceptionHugeArray class...
ExceptionHugin The ExceptionHugin class.
ExceptionIllegalBinding The ExceptionIllegalBinding class...
ExceptionInappropriateArguments The ExceptionInappropriateArguments class...
ExceptionInconsistencyOrUnderflow The ExceptionInconsistencyOrUnderflow class...
ExceptionInsufficientStateRange The ExceptionInsufficientStateRange class...
ExceptionInvalidExpression The ExceptionExpression class...
ExceptionInvalidLicense The ExceptionInvalidLicense class...
ExceptionInvalidName The ExceptionInvalidName class...
ExceptionInvalidPassword The ExceptionInvalidPassword class...
ExceptionInvalidStateValues The ExceptionInvalidStateValues class...
ExceptionIO The ExceptionIO class...
ExceptionJNI The ExceptionJNI class...
ExceptionLocale The ExceptionLocale class...
ExceptionLowDensity The ExceptionLowDensity class...
ExceptionMemory The ExceptionMemory class...
ExceptionNegativeProbability The ExceptionNegativeProbability class...
ExceptionNoEquilibrium The ExceptionNoEquilibrium class...
ExceptionNormalization The ExceptionNormalization class...
ExceptionNotCompiled The ExceptionNotCompiled class...
ExceptionNoValue The ExceptionNoValue class...
ExceptionObjectNotAlive The ExceptionObjectNotAlive class...
ExceptionOverflow The ExceptionOverflow class...
ExceptionParse The ExceptionParse class...
ExceptionRounding The ExceptionRounding class...
ExceptionSizeTooLarge The ExceptionSizeTooLarge class...
ExceptionSyntax The ExceptionSyntax class...
ExceptionTableTooLarge The ExceptionTableTooLarge class...
ExceptionTwice The ExceptionTwice class...
ExceptionUsage The ExceptionUsage class...
ExceptionZeroSum The ExceptionZeroSum class...
ExceptionZeroVariance The ExceptionZeroVariance class...
 

Package COM.hugin.HAPI Description

The Hugin Java API 6.3 consists of the COM.hugin.HAPI package. These pages are meant as a help for developers programming against the Hugin Java API 6.3. Short descriptions can be found for all classes and their members. However, additional information might be relevant for different tasks. In such cases, the Hugin API 6.3 Reference Manual will be a good place to look. It contains detailed documentation of the Hugin C API 6.3, which is the basis of the COM.hugin.HAPI package. The Hugin API 6.3 Reference Manual can be downloaded from Hugin Expert A/S - Documentation. This document contains the following:

General Information

The Hugin Java API 6.3 contains a high performance inference engine that can be used as the core of knowledge based systems built using Bayesian networks or influence diagrams. 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 6.3 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 6.3 also provides an exception based mechanism for handling errors.

Object-Oriented Specification

The Hugin API 6.3 provides a powerful objection-orientation mechanism. Object-oriented specification of Bayesian networks and influence diagrams 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 contain constants and methods common to regular Bayesian networks (and influence diagrams) and object-oriented Bayesian networks (and influence diagrams), respectively.

In addition to the usual nodes, an object-oriented Bayesian network or influence diagram 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.

Examples

The next two examples describe how the Hugin Java API can be used to manipulate Bayesian networks and influence diagrams.

Example 1

This first example is concerned with loading a Bayesian network or an influence diagram. Once the Bayesian network or influence diagram has been loaded, the corresponding domain is triangulated using the minimum fill-in-weight heuristic and the compilation process is completed. Next, the members of each clique of the junction tree(s) are printed on standard output. Finally, a propagation of evidence is performed and the resulting posterior marginals are printed on standard output.
import COM.hugin.HAPI.*;
import java.util.ListIterator;

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 + ".net", this);
	}
	catch (ExceptionHugin e) {
	    System.out.println("Parsing failed: " + e.getMessage());
	}
    }
}

class LAP {

    static MyParseListener parseListener = new MyParseListener();

    /**
     * Load a Bayesian network, compile it, and propagate evidence.
     */
    public LAP(String fileName) {
        try {
	    ClassCollection cc = new ClassCollection();
	    cc.parseClasses(fileName + ".net", parseListener);
	    // Unfold the Class to a Domain that can be compiled and
	    // used for inference, etc.
            Domain domain = cc.getClassByName(fileName).createDomain();

            domain.openLogFile(fileName + ".log");

            domain.triangulate(Domain.H_TM_FILL_IN_WEIGHT);
            domain.compile();

            printJunctionTrees(domain.getJunctionTrees());

            domain.propagate(Domain.H_EQUILIBRIUM_SUM,
                             Domain.H_EVIDENCE_MODE_NORMAL);

            printNodeMarginals(domain);
            domain.closeLogFile();

            domain.save(fileName + ".hkb", Domain.H_ENDIAN_HOST);            
        }
        catch (ExceptionHugin e) {
            System.out.println("Exception caught:");
            System.out.println(e.getMessage());
        }
        catch (Exception e) {
            System.out.println("General exception:");
            System.out.println(e.getMessage());
        }
    }

    /**
     * Print the cliques of the junction tree(s).
     */
    public void printJunctionTrees(JunctionTreeList list) {
        ListIterator jtit = list.listIterator(), cliqueit=null;
        
        System.out.println("Cliques : ");
        
        try {
            while (jtit.hasNext()) {
                cliqueit = ((JunctionTree)(jtit.next())).getCliques().listIterator();
                while (cliqueit.hasNext()) 
                    printNodes(((Clique)(cliqueit.next())).getMembers());
                }
            System.out.println();
        }
        catch (ExceptionHugin e) {
            System.out.println("Exception caught:");
            System.out.println(e.getMessage());
        }
    }

    /**
     * Print the marginal distribution of each variable in the domain.
     */
    public void printNodeMarginals(Domain domain) {
        try {
            Node node;
            ListIterator it = domain.getNodes().listIterator();
            while(it.hasNext()) {
                node = (Node)it.next();
                System.out.println(node.getLabel() + "(" + node.getName() + ")");
                if (node.getCategory() == Domain.H_CATEGORY_CHANCE) {
                    if (node.getKind() == Domain.H_KIND_CONTINUOUS) {
                        System.out.println("-Mean    : " +
                                           ((ContinuousChanceNode)node).getMean());
                        System.out.println("-Variance: " +
                                           ((ContinuousChanceNode)node).getVariance());
                    }
                    else if (node.getKind() == Domain.H_KIND_DISCRETE)
                        for (int i = 0; i < ((DiscreteChanceNode)node).getNumberOfStates(); i++)
                            System.out.println("-" +
                                               ((DiscreteChanceNode)node).getStateLabel(i) +
                                               " " +
                                               ((DiscreteChanceNode)node).getBelief(i));
                }
                else if (node.getCategory() == Domain.H_CATEGORY_DECISION)
                    for (int i = 0; i < ((DiscreteDecisionNode)node).getNumberOfStates(); i++)
                        System.out.println("-" +
                                           ((DiscreteDecisionNode)node).getStateLabel(i) +
                                           " " +
                                           ((DiscreteDecisionNode)node).getExpectedUtility(i));
            }
        }
        catch (ExceptionHugin e) {
            System.out.println("Exception caught:");
            System.out.println(e.getMessage());
        }
    }

    /**
     * Print the name of each node in the list.
     */
    static void printNodes(NodeList list) {
        try {
            Node node;
            ListIterator it = list.listIterator();
            while(it.hasNext()) {
                node = (Node)it.next();
                System.out.print(node.getName() + " ");
            }
            System.out.println();
        }
        catch (ExceptionHugin e) {
            System.out.println("Exception caught:");
            System.out.println(e.getMessage());
        }
    }
}

/**
 * Load a Hugin net file and perform a single propagation of
 * evidence.  Print the results.
 */
class LoadAndPropagate {
    static public void main(String args[]) {
        new LAP(args[0]);
    }
}

Example 2

The second example describes how a Bayesian network can be constructed using the Hugin Java API. The Bayesian network constructed 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 to a NET specification file and an initial propagation is performed. Finally, the marginals of the nodes are printed on standard output.
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();
            DiscreteChanceNode node;
            
            while(it.hasNext()) {
                node = (DiscreteChanceNode)it.next();
                System.out.println(node.getLabel());
                for (int i = 0; i < ((DiscreteChanceNode)node).getNumberOfStates(); i++)
                    System.out.println("-" + 
                                       node.getStateLabel(i) +
                                       " " +
                                       node.getBelief(i));
            }
        }
        catch (ExceptionHugin e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * Construct 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.Endian
NetworkModel.Kind

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

Class Classes
Class

ClassCollection Classes
ClassCollection

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

Junction Tree Classes
Clique
JunctionTree

Table Classes
Table

Model Classes
Model

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

Distribution Classes
BetaDistribution
BinomialDistribution
DistributionDistribution
ExponentialDistribution
GammaDistribution
GeometricDistribution
NegativeBinomialDistribution
NormalDistribution
PoissonDistribution
UniformDistribution
WeibullDistribution

List Classes
ClassList
CliqueList
ExpressionList
JunctionTreeList
NodeList

Parser Interfaces
ExpressionParseListener
ParseListener

Parser Classes
DefaultParseListener

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.

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.