def sampleGivenMB(self, v, state): MBval = Table(v.name, shape=v.nvalues) children = v.out_v index = {} for vert in v.family: # replaced [v]+list(v.in_v) index[vert.name] = state[vert.name] # index = {var.name:state} for var in v.family childrenAndIndex = [] for child in children: cindex = {} # family = a node and all its parents for cvert in child.family: # replaced [child]+list(child.in_v) # cvert is either a child or an uncle(parent of child) of v # cindex contains the state of all variables in the family # of a child of v cindex[cvert.name] = state[cvert.name] childrenAndIndex.append((child,cindex)) #OPTIMIZE: could vectorize this code for value in range(v.nvalues): index[v.name] = value # initialise each element of the distribution with the # conditional probability table values of the variable # Pr(v=i)=Pr(v=i|Pa(v)=index) # index is randomly selected at each iteration MBval[value] = v.distribution[index] ################################################## # this could be replaced by Table multiplication instead # of an element-wise multiplication # in that case we don't need all those index dictionnaries ################################################## for child,cindex in childrenAndIndex: cindex[v.name] = value MBval[value] *= child.distribution[cindex] MBval.normalize() ####################################### # added a sample() function in Distribution ####################################### return MBval.sample()