Attaching constraints to variables
Infer.NET provides a variety of constraints that can be applied to variables. For example:
constrains the random variable x to be positive. Built-in constraints include Positive, True, False, Equal and EqualRandom (see the full list of built-in constraints). Constraints can be combined with factors to produce more complex constraints. Here are some examples:
One of the most useful constraints is ConstrainEqualRandom. This constraint is an optimized version of ConstrainEqual that avoids the creation of an intermediate random variable. The lines
are mathematically equivalent to
but the ConstrainEqualRandom line leads to more efficient code since no intermediate random variable is created. Furthermore, ConstrainEqualRandom can be used in cases where there is no corresponding method on Variable to create a random variable with the desired distribution. Therefore you should try to use ConstrainEqualRandom whenever you find yourself writing ConstrainEqual lines like the above.
Similarly, if you find yourself writing
then try to replace this with
The second form avoids creating an intermediate random variable, making the code run faster and Infer.NET happier.
Under the hood
Under the hood, a call to Variable.ConstrainEqual is converted into a call to Variable.Constrain, as follows:
Similar to factor functions, the most general way of adding a constraint is:
which adds the constraint specified by MethodName to the arguments arg1, arg2 (which may be random variables, constants or parameters). Using this mechanism, you can define your own constraints.