This class represents a factorized representation of a conditional probability distribution table. It contains the attributes *inputvertex*, *inputbn*, *vals*, *scope*, *stride*, and *card*, and the methods *multiplyfactor*, *sumout*, *reducefactor*, and *copy*.
| 30 | import sys |
| 31 | |
| 32 | class TableCPDFactor(object): |
| 33 | ''' |
| 34 | This class represents a factorized representation of a conditional probability distribution table. It contains the attributes *inputvertex*, *inputbn*, *vals*, *scope*, *stride*, and *card*, and the methods *multiplyfactor*, *sumout*, *reducefactor*, and *copy*. |
| 35 | |
| 36 | ''' |
| 37 | |
| 38 | def __init__(self, vertex, bn): |
| 39 | ''' |
| 40 | This class is constructed with a :doc:`DiscreteBayesianNetwork <discretebayesiannetwork>` instance and a *vertex* name as arguments. First it stores these inputs in *inputvertex* and *inputbn*. Then, it creates a factorized representation of *vertex*, storing the values in *vals*, the names of the variables involved in *scope* the cardinality of each of these variables in *card* and the stride of each of these variables in *stride*. |
| 41 | |
| 42 | ''' |
| 43 | self.inputvertex = vertex |
| 44 | '''The name of the vertex.''' |
| 45 | self.inputbn = bn |
| 46 | '''The :doc:`DiscreteBayesianNetwork <discretebayesiannetwork>` instance that the vertex lives in.''' |
| 47 | |
| 48 | result = dict( vals = [], stride = dict(), card = [], scope = []) |
| 49 | root = bn.Vdata[vertex]["cprob"] |
| 50 | |
| 51 | # add values |
| 52 | def explore(_dict, key, depth, totaldepth): |
| 53 | if depth == totaldepth: |
| 54 | for x in _dict[str(key)]: |
| 55 | result["vals"].append(x) |
| 56 | return |
| 57 | else: |
| 58 | for val in bn.Vdata[bn.Vdata[vertex]["parents"][depth]]["vals"]: |
| 59 | ckey = key[:] |
| 60 | ckey.append(str(val)) |
| 61 | explore(_dict, ckey, depth+1, totaldepth) |
| 62 | |
| 63 | if not bn.Vdata[vertex]["parents"]: |
| 64 | result["vals"] = bn.Vdata[vertex]["cprob"] |
| 65 | else: |
| 66 | td = len(bn.Vdata[vertex]["parents"]) |
| 67 | explore(root, [], 0, td) |
| 68 | |
| 69 | # add cardinalities |
| 70 | result["card"].append(bn.Vdata[vertex]["numoutcomes"]) |
| 71 | if (bn.Vdata[vertex]["parents"] != None): |
| 72 | for parent in reversed(bn.Vdata[vertex]["parents"]): |
| 73 | result["card"].append(bn.Vdata[parent]["numoutcomes"]) |
| 74 | |
| 75 | # add scope |
| 76 | result["scope"].append(vertex) |
| 77 | if (bn.Vdata[vertex]["parents"] != None): |
| 78 | for parent in reversed(bn.Vdata[vertex]["parents"]): |
| 79 | result["scope"].append(parent) |
| 80 | |
| 81 | |
| 82 | # add strides |
| 83 | stride = 1 |
| 84 | result["stride"] = dict() |
| 85 | for x in range(len(result["scope"])): |
| 86 | result["stride"][result["scope"][x]] = (stride) |
| 87 | stride *= bn.Vdata[result["scope"][x]]["numoutcomes"] |
| 88 | |
| 89 | self.vals = result["vals"] |