from lib import * def weighted_sample(bn,e): #Initializing event to return and the weight x = {} w = 1.0 for node in bn.nodes: cur_evidence = None #Asserting whether current node is an evidence node for node_name in e.keys(): if node_name == node.name: cur_evidence = e[node_name] break if(cur_evidence): w = w * get_sample(node,cur_evidence) x[node.name] = cur_evidence else: #Since node is not an evidence node, only sample from it. x[node.name] = get_sample(node,None) #Resetting sample values for node in bn.nodes: node.current_sample = 0 return (x,w) def likelihood_weighting(X,e,bn,N): W = {} for value in X.values: W[value] = 0.0 for i in range(0,N): (x,w) = weighted_sample(bn,e) W[x[X.name]] += w #Normalizing val_sum = 0.0 for val in W.keys(): val_sum += W[val] for val in W.keys(): W[val] = W[val]/val_sum return W print likelihood_weighting(node_uw,{'S':'true','T':'true','W':'true'},b_network,10000)