[frames] | no frames]

# Class Factor

source code

Factors represent functions from a discrete product space to the reals

Typically used to construct discrete probability distributions with certain conditional independence properties

 Instance Methods

 __init__(self, variables=(), data=None, domain=None, new_domain_variables=None, must_be_new=False, check=False, convert=False) Initialise a Factor object source code
Float
 __getitem__(self, inst) Return value associated with the instantiation inst source code
Iterator
 __iter__(self) Iterates over the factors in a factor source code
Int
 __len__(self) Return the number of values in a factor source code

 __repr__(self) repr(x) source code
Float
 __setitem__(self, inst, val) Set value associated with the instantiation inst source code
String
 __str__(self) Pretty representation of a factor source code
Factor
 broadcast(self, variables) Alter self to be a function of variables source code
Factor
 copy(self, copy_domain=False) Return a 'copy' of a factor source code
Factor
 copy_rename(self, oldnew, copy_domain=False) Return a 'copy' of a factor, but using different variables source code
List
 data(self) Return a copy of the data in a Factor source code
Factor
 data_restrict(self, newvalues, keep_class=False) Alter a factor's data by effecting the restriction on variables given by newvalues source code
Factor
 data_extend(self, newvalues, keep_class=False) Alter a factor's data by introducting new values to a variable given by the dictionary newvalues source code
Factor
 demo_mult(self, other) Explicit string representation of multiplying self and other source code
Boolean
 differ(self, other, epsilon=0.0) Whether there are corresponding values in self and other differing by more than epsilon source code
Class of self
 drop_variable(self, variable, check_instd=True) Alter self by dropping variable source code
Class of self
 drop_variables(self, variables, check_instd=True) Alter self by dropping variables source code

 gui_buttons(self, gui, data_indices, tkc_variables) Return a frame of buttons to a GUI for manipulating a factor source code

 gui_display(self, parent, **config) Display a GUI widget for displaying a factor source code

 gui_edit(self, parent) Display a GUI widget for editing a factor source code
Frame or Tuple
 gui_main(self, parent, edit=True, varselect=False, **config) Return a Tkinter.Frame (and possibly other information) for displaying and editing a factor source code

 h_score(self, ess=1.0) Return h_score of factor with ESS = ess source code

 inc_from_rawdata(self, rawdata) Increment self with counts directly from rawdata source code

 inc_from_record(self, variables_info, record) Increment a data value in a factor from a data record source code
Tuple
 insts_data_tuple(self, keyfn=None) Return instantiations with values source code
Same as self
 map(self, fn, keep_class=False) Transform by an arity 1 function. source code
Class of self
 marginalise_away(self, variables) Alter self by marginalising away variables source code
CPT object
 makeCPT(self, child, cpt_check=True) Construct an CPT object from a factor source code
Factor
 normalised(self) Return a new factor with values proportional to those of self but which sum to one source code
String
 repr_nodomain(self) Return string representation but without domain source code
float
 z(self) Return the sum of the factor's values source code

 zero(self) Set all values for a factor to zero source code
List
 _data_broadcast(self, data, variables, n_extra) Broadcast data to make room for variables source code
List
 _data_marginalise(self, data, variables, to_sumout) Sum out variables to_sumout from data source code
List
 _data_restrict(self, variables, togo, newvalues, data) Alter data to effect the restriction given by newvalues source code
List
 _data_extend(self, variables, togo, newvalues, data) Alter data to effect the extension given by newvalues source code

 _factor_pointwise_op(self, other, op) Apply binary operation op to the factors self and other source code

 _gui_display_rows(self, gui_main, insts, data_indices, hrows) Add rows of joint instantiations and corresponding data values for each to a factor's main GUI source code
List
 _gui_edit_rows(self, gui_main, insts, data_indices, hrows) Add rows of joint instantiations and data entry widgets source code

 _gui_header(self, gui_main, variables, widget_type, firstcol=0, r=0, span=1) Add button or label headers to a factor's main GUI window source code

 _gui_tkc_done(self, win, data_indices, tkc_variables) Change a factor's data to be that contained in a list of lists of Tkinter.StringVar objects and destroy the window win source code

 _gui_tkc_get(self, data_indices, tkc_variables) Change a factor's data to be that contained in a list of lists of Tkinter.StringVar objects source code

 _gui_tkc_set(self, data_indices, tkc_variables) Set the data displayed by a list of lists of Tkinter.StringVar objects to be the factor's data source code
Tuple
 _header(self, variables=None) Return a format string and string of dashes suitable for creating a header for rows of instantiations of variables source code
Factor
 _pointwise_op(self, other, op, swapped=False) Apply binary operation op to the factor self and other. source code

Inherited from Variables.SubDomain: __add__, __div__, __iadd__, __idiv__, __imul__, __isub__, __mul__, __rdiv__, __rmul__, __sub__, inst2index, insts, insts_indices, marginalise_onto, sumout, table_size, uses_default_domain, variables, varvalues

Inherited from Variables.SubDomain (private): _decode_inst, _get_result_variables, _insts, _insts_indices

Inherited from Variables.Domain: add_domain_variable, add_domain_variables, add_domain_variables_from_rawdata, change_domain_variable, change_domain_variables, common_domain, known_variable, numvals, values

Inherited from object: __delattr__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __setattr__

 Static Methods

 _gui_select(button) Change the appearance of a button source code

 _gui_tkc_clear(tkc_variables) Clear the a list of lists of Entry widgets source code
 Instance Variables
List _data
A value for each joint instantiation of the factor's _variables

Inherited from Variables.SubDomain (private): _variables

Inherited from Variables.Domain (private): _domain, _instd, _numvals

 Properties

Inherited from object: __class__

 Method Details

### __init__(self, variables=(), data=None, domain=None, new_domain_variables=None, must_be_new=False, check=False, convert=False)(Constructor)

source code

Initialise a Factor object

Parameters:
• variables (Iterable) - Variables in the factor. variables can be any iterable object, e.g. a list, tuple, set or frozenset. If variables is a sequence (e.g. a list or tuple), then the order of the variables in this sequence is ignored.
• data (List, unless convert=True or None) - The numbers associated with the joint instantiations of the variables. If None, then a list of 1.0s of the right size is created. The ith value of data corresponds to the ith joint instanstiation of the variables. To understand how instantiations are ordered it may be enough to just print a factor and observe the ordering, but here is the formal definition.

Joint instantiations are ordered as follows: Each joint instantiation is a tuple of values: val0,val1, ... valn where valj is the value of the jth variable in this joint instantiation and where variables are ordered according to Python's standard ordering (i.e. lexicographically). The instantiations are then ordered just like any other collection of Python tuples: let tuple1 and tuple2 be two different tuples, and let k be the index of the first element where they differ, then tuple1 < tuple2 iff tuple1[k] < tuple2[k].

• new_domain_variables (Dict or None) - If not None, a dictionary containing a mapping from any new variables to their values.
• domain (Variables.Domain or None) - A domain for the model. If None the internal default domain is used.
• must_be_new (Boolean) - Whether domain variables in new_domain_variables have to be new
• check (Boolean) - Whether to check that (1) variables is of the right form, and (2) that each variable has an associated set of values and (3) that data is the right size and type.
• convert (Boolean) - If True, data is converted to a list.
Raises:
• TypeError - If check is set and convert is not set and data is of the wrong type.
• VariableError - If check is set and there is a variable in variables which does not have associated values. Or If a variable in new_domain_variables already exists with values different from its values in new_domain_variables; Or if must_be_new is set and the variable already exists.
• DataError - If check is set and data is the wrong size.
Overrides: object.__init__

### __getitem__(self, inst)(Indexing operator)

source code

Return value associated with the instantiation inst

inst is either a list/tuple of values, or a dictionary mapping variables to values, or a data index.

If a dictionary is used it can contain 'extra' keys which do not correspond to variables of self. These are just ignored.

Uses an internal dictionary which will be built if not already.

Parameters:
• inst (Tuple, List, Dictionary or Int) - Instantiation
Returns: Float
The value in self associated with inst
Raises:
• KeyError - If there is no joint instantiation inst.

### __iter__(self)

source code

Iterates over the factors in a factor

Returns: Iterator
Iterator over factor
Raises:
• ValueError - If self has no variables.

### __len__(self)(Length operator)

source code

Return the number of values in a factor

Returns: Int
The number of values in a factor

### __repr__(self)(Representation operator)

source code

repr(x)

Overrides: object.__repr__
(inherited documentation)

### __setitem__(self, inst, val)(Index assignment operator)

source code

Set value associated with the instantiation inst

inst is either a list/tuple of values, or a dictionary mapping variables to values, or a data index.

(Uses an internal dictionary which will be built if not already.)

Parameters:
• inst (Tuple, List, Dictionary or Int) - Instantiation
Returns: Float
The value in self associated with inst

### __str__(self)(Informal representation operator)

source code

Pretty representation of a factor

Returns: String
Pretty representation of a factor
Overrides: object.__str__

source code

Alter self to be a function of variables

Parameters:
• variables (Iterable) - New variables for self
Returns: Factor
Altered self
Raises:
• ValueError - If variables is not a superset of self's variables

### copy(self, copy_domain=False)

source code

Return a 'copy' of a factor

Parameters:
• copy_domain (Boolean) - If true self's domain is copied, otherwise the copy shares self's domain
Returns: Factor
The copy
Overrides: Variables.Domain.copy

### copy_rename(self, oldnew, copy_domain=False)

source code

Return a 'copy' of a factor, but using different variables

For each variable pair old -> new, either: 1) new is a known variable (see Variables.Domain.known_variable) with the same values as old or 2) new is a new variable; in which case it will be given the same values as old

Parameters:
• oldnew (Dictionary) - A mapping from old to new variables
• copy_domain (Boolean) - If true self's domain is copied, otherwise the copy shares self's domain
Returns: Factor
The copy

To Do: Implement efficiently

### data(self)

source code

Return a copy of the data in a Factor

Returns: List
A copy of the data in a Factor

### data_restrict(self, newvalues, keep_class=False)

source code

Alter a factor's data by effecting the restriction on variables given by newvalues

Note that this does not alter the factor's domain which has to therefore be done separately.

Parameters:
• newvalues (Dictionary) - Dictionary of the form {var1:values1,var2:values2..}. Each value of this dictionary must be an iterable. Values in an iterable which were not previously values of the corresponding variable are ignored. Variables which are not used in the factor are also ignored. Upon return each value in newvalues.values() will be a frozenset.
• keep_class (Boolean) - Object will become a Factor if false, otherwise class is unaltered.
Returns: Factor
self

### data_extend(self, newvalues, keep_class=False)

source code

Alter a factor's data by introducting new values to a variable given by the dictionary newvalues

Parameters:
• newvalues (Dictionary) - Dictionary of the form {var1:values1,var2:values2..}. Each value of this dictionary must be an iterable. Values in an iterable which were not previously values of the corresponding variable are ignored. Variables which are not used in the factor are also ignored. Upon return each value in newvalues.values() will be a frozenset.
• keep_class (Boolean) - Object will become a Factor if false, otherwise class is unaltered.
Returns: Factor
self

Author: Charles Blundell

### demo_mult(self, other)

source code

Explicit string representation of multiplying self and other

Resulting factor has strings such as '0.2 * 0.5' instead of numbers as values, so cannot be used for much else apart from displaying.

Parameters:
• other (Factor) - Factor on RHS of multiplication
Returns: Factor
Factor with strings as values

### differ(self, other, epsilon=0.0)

source code

Whether there are corresponding values in self and other differing by more than epsilon

Parameters:
• other (Factor) - Factor
• epsilon (Float) - Permissible difference
Returns: Boolean
Whether they differ
Raises:
• ValueError - If the two factors do not have the same number of data values.

### drop_variable(self, variable, check_instd=True)

source code

Alter self by dropping variable

Should only be used on a for a variable which is instantiated.

Parameters:
• variable (Immutable) - Variable to drop
• check_instd (Boolean) - Whether to check that it is safe to drop the variables
Returns: Class of self
The altered self
Overrides: Variables.SubDomain.drop_variable

### drop_variables(self, variables, check_instd=True)

source code

Alter self by dropping variables

Should only be used for variables which are instantiated.

variables is not altered. Variables in variables which are not in self's variables are ignored.

Parameters:
• variables (Sequence) - Variables to drop
• check_instd (Boolean) - Whether to check that it is safe to drop the variables
Returns: Class of self
The altered self
Overrides: Variables.SubDomain.drop_variables

### gui_buttons(self, gui, data_indices, tkc_variables)

source code

Return a frame of buttons to a GUI for manipulating a factor

Parameters:
• gui (Frame) - The GUI into which the buttons will be packed
• data_indices (List) - list of lists of indexes into a data list
• tkc_variables (List) - List of lists of Tkinter.StringVar objects corresponding to data_indices

### gui_display(self, parent, **config)

source code

Display a GUI widget for displaying a factor

Parameters:
• parent (Some suitable Tk object.) - A widget into which the GUI is placed.
• config (various) - Optional extra configuration options to control how GUI widget is displayed in parent.

### gui_edit(self, parent)

source code

Display a GUI widget for editing a factor

Parameters:
• parent (Some suitable Tk object.) - A widget into which the GUI is placed.

### gui_main(self, parent, edit=True, varselect=False, **config)

source code

Return a Tkinter.Frame (and possibly other information) for displaying and editing a factor

If edit=True then also return information needed for subsequent editing

Parameters:
• parent (Some suitable Tk object.) - The Frame's parent widget.
• edit (Boolean) - If set, the Frame will allow editing of the factor's data
• varselect (Boolean) - If set, the user can 'select' variables by clicking on their names
• config (Dictionary) - Other parameters for the frame
Returns: Frame or Tuple
If edit=False the frame widget. If edit=True a tuple (frame,data_indices, tkc_variables) where the latter two are both identically structured lists of lists; data_indices indexes into the factor's data and tkc_variables contains Tkinter.StringVar objects one for each data point

### h_score(self, ess=1.0)

source code

Return h_score of factor with ESS = ess

This is the log of the function called H in UAI08 paper.

Computes \sum_i log(\Gamma(n_i+lpha)/\Gamma(lpha)) where alpha = ess/(no. of values in self)

### inc_from_rawdata(self, rawdata)

source code

Increment self with counts directly from rawdata

OK for parameter fitting not for structure learning

Parameters:
• rawdata (Tuple) - A tuple like that returned by IO.read_csv.
Raises:
• IndexError - If self has a variable missing from rawdata

### inc_from_record(self, variables_info, record)

source code

Increment a data value in a factor from a data record

Parameters:
• variables_info (Sequence) - A sequence of which each element corresponds to a variable in self (variables in order). Each element is a pair (indx,step) where
1. indx is the index of the field in record corresponding

to the variable

1. step is the number of data values corresponding to any given

value of the variable

• record (Sequence) - A data record (such as produced via IO.read_csv)

### insts_data_tuple(self, keyfn=None)

source code

Return instantiations with values

Returns a tuple of pairs. Each pair is of the form (inst,val) each inst is a tuple giving a joint instantiation of the variables.

If key is not None, it should be a function which takes an (inst,val) object as input. The (inst,val) pairs are ordered according to the value of this function. For example key = f where def f(x): return x[1] orders by value

If {key} is None, the order is the default one. Lexicographically on inst.

Returns: Tuple
Instantiations with values ordered by value

### map(self, fn, keep_class=False)

source code

Transform by an arity 1 function. By default, self is forced to a Factor, since rarely will fn result in anything more specific. keep_class controls this behaviour.

Parameters:
• fn (function between values of an element of the object (e.g., Parameters.Factor values)) - An arity 1 function
• keep_class (Boolean (defaulting to False)) - Do not force self to be a Parameters.Factor
Returns: Same as self
Result of applying the function

### marginalise_away(self, variables)

source code

Alter self by marginalising away variables

variables is not altered. Variables in variables which are not in self's variables are ignored.

Parameters:
• variables (Sequence) - Variables to marginalise away
Returns: Class of self
The altered self

### makeCPT(self, child, cpt_check=True)

source code

Construct an CPT object from a factor

by just naming child as the child variable. Will raise an exception if the factor is not a CPT with child as the child

Parameters:
• child (tuple) - Variable of form (varname,(varvalue1,varvalue2,..))
Returns: CPT object
The CPT
Raises:
• CPTError - if the factor is not a CPT with child

### normalised(self)

source code

Return a new factor with values proportional to those of self but which sum to one

Returns: Factor
Normalised version of self

### repr_nodomain(self)

source code

Return string representation but without domain

Returns: String
String representation but without domain given

### z(self)

source code

Return the sum of the factor's values

Returns: float
Sum of the factor's values

source code

Broadcast data to make room for variables

Parameters:
• data (List) - A sublist of self's data corresponding to an instantiation of a prefix of self's ordered variables.
• variables (Sequence) - An ordered sequence of variables which is a superset of the suffix of self's ordered variables
• n_extra (Int) - How many variables in variables are not in the remaining suffix of self's variables
Returns: List
Raises:
• KeyError - If variables contains a variable which is not in self's values dictionary

### _data_marginalise(self, data, variables, to_sumout)

source code

Sum out variables to_sumout from data

Variables in to_sumout not in variables have no effect

Parameters:
• data (List) - Data
• variables (Sequence) - The (ordered) variables for data
• to_sumout (Set/frozenset) - Variables to sum out
Returns: List
Data with to_sumout variables summed out

### _data_restrict(self, variables, togo, newvalues, data)

source code

Alter data to effect the restriction given by newvalues

Parameters:
• variables (Sequence) - The (sorted) variables for data
• togo (Int) - How many restrictions remain to be done
• newvalues (Dictionary) - Mapping from some variables to a subset of their original values
• data (List) - The data to be restricted
Returns: List
The data with the restriction given by newvalues effected

### _data_extend(self, variables, togo, newvalues, data)

source code

Alter data to effect the extension given by newvalues

Parameters:
• variables (Sequence) - The (sorted) variables for data
• togo (Int) - How many extensions remain to be done
• newvalues (Dictionary) - Mapping from some variables to a subset of their original values
• data (List) - The data to be restricted
Returns: List
The data with the restriction given by newvalues effected

Author: Charles Blundell

### _factor_pointwise_op(self, other, op)

source code

Apply binary operation op to the factors self and other

Copies of self and other are 'broadcast' as necessary self is altered to contain the result. self and other will have identical values dictionaries after this method has been executed (Normally they already are identical).

Parameters:
• other (Factor) - Factor on the RHS of the operation
• op (Function object) - A binary operation which takes numeric arguments
Raises:
• VariableError - If self and other use a variable with different values in each one's values dictionary.

### _gui_display_rows(self, gui_main, insts, data_indices, hrows)

source code

Add rows of joint instantiations and corresponding data values for each to a factor's main GUI

Parameters:
• gui_main (Tkinter.Frame) - The GUI into which the rows will be added
• insts (Sequence (of sequences of strings)) - The joint instantiations (one for each row)
• data_indices (List) - list of lists of indexes into a data list
• hrows (Int) - Number of header rows, and thus the vertical offset for these rows

### _gui_edit_rows(self, gui_main, insts, data_indices, hrows)

source code

Add rows of joint instantiations and data entry widgets

Initialises widgets to show current data values

Parameters:
• gui_main (Tkinter.Frame) - The GUI into which the rows will be added
• insts (Sequence (of sequences of strings)) - The joint instantiations (one for each row)
• data_indices (List) - list of lists of indexes into a data list
• hrows (Int) - Number of header rows in gui_main, and thus the vertical offset for these rows
Returns: List
List of lists of Tkinter.StringVar objects corresponding to data_indices

### _gui_header(self, gui_main, variables, widget_type, firstcol=0, r=0, span=1)

source code

Buttons are bound to the _gui_select method.

Parameters:
• gui_main (Tkinter.Frame) - The main GUI window to which buttons/labels are to be added
• variables (Sequence) - Sequence of strings providing text for the labels/buttons
• widget_type (Tkinter.Button or Tkinter.Label Tkinter class object) - Either Tkinter.Button or Tkinter.Label
• firstcol (Int) - The column into which the first label/button goes
• r (Int) - The row for the buttons/labels
• span (Int) - The column span of each button/label

### _gui_select(button)Static Method

source code

Change the appearance of a button

Parameters:
• button (Tkinter.Button) - The button

### _gui_tkc_clear(tkc_variables)Static Method

source code

Clear the a list of lists of Entry widgets

Parameters:
• tkc_variables (List) - List of lists of Tkinter.StringVar objects, typically corresponding to factor data indices

### _gui_tkc_done(self, win, data_indices, tkc_variables)

source code

Change a factor's data to be that contained in a list of lists of Tkinter.StringVar objects and destroy the window win

Parameters:
• win (Suitable Tkinter object) - Window to destroy
• data_indices (List) - list of lists of indexes into a data list
• tkc_variables (List) - List of lists of Tkinter.StringVar objects corresponding to data_indices

### _gui_tkc_get(self, data_indices, tkc_variables)

source code

Change a factor's data to be that contained in a list of lists of Tkinter.StringVar objects

Parameters:
• data_indices (List) - list of lists of indexes into a data list
• tkc_variables (List) - List of lists of Tkinter.StringVar objects corresponding to data_indices

### _gui_tkc_set(self, data_indices, tkc_variables)

source code

Set the data displayed by a list of lists of Tkinter.StringVar objects to be the factor's data

Parameters:
• data_indices (List) - list of lists of indexes into a data list
• tkc_variables (List) - List of lists of Tkinter.StringVar objects corresponding to data_indices

source code

Return a format string and string of dashes suitable for creating a header for rows of instantiations of variables

Parameters:
• variables ((Ordered) sequence) - Variables for which a header is sought. If None then self's variables are used.
Returns: Tuple
The format string and string of dashes

### _pointwise_op(self, other, op, swapped=False)

source code

Apply binary operation op to the factor self and other. self is altered to contain the result

After this operation has been applied, self is always set to have class Factor, since if it were originally a CPT there is no guarantee that it still is one.

other may be a factor or a scalar

Parameters:
• other (Factor, Float or Int) - Factor on the RHS of the operation
• op (Function object) - A binary operation which takes numeric arguments
• swapped (Boolean) - If set and other is a number return other op self
Returns: Factor
self
Raises:
• VariableError - If self and other use a variable with different values in each one's values dictionary.
Overrides: Variables.SubDomain._pointwise_op

 Generated by Epydoc 3.0.1 on Thu Oct 15 15:34:12 2009 http://epydoc.sourceforge.net