def init(bn, tht, valcs, clqs, vclqixs): pots = [pot.Potential(clq, valcs) for clq in clqs] for v, (clqix, thtv) in enumerate(izip(vclqixs, tht)): clq = clqs[clqix] pots[clqix] *= vpot(v, bn, thtv, valcs) return pots
def sepot(self, jt, clqs, valcs): spots = {} for (x,y) in jt.edges(): svars = list(set(clqs[x]) & set(clqs[y])) svars.sort() spots[(x,y)] = pot.Potential(svars, valcs) return spots
def infer(insts): lhs = [pot.Potential([v], valcs) for v in xrange(len(vclqs))] for v, i in insts: if isinstance(i, int): newi = [0.0] * valcs(v) newi[i] = 1.0 i = newi insert_evidence(lhs, v, map(float, i), pots[vclqs[v]]) spots = sepot(jt, clqs, valcs) globprop(jt, pots, spots) dstrs = [] for v, clqix in enumerate(vclqs): cpot = pots[clqix] dstr = (cpot >> pot.Potential([v], valcs, 0.0)).normalize().p dstrs.append(dstr) return dstrs
def insert_evidence(self, vars, vals): if isinstance(dstr, int): val = dstr dstr = [0.0]*self.valcs(v) dstr[val] = 1.0 old_lhv = self.lhs[v] new_lhv = pot.Potential(old_lhv.vars, old_lhv.valcs) new_lhv.p = dstr[:] self.lhs[v] = new_lhv vpot = self.pots[self.vclqs[v]] vpot *= new_lhv / old_lhv
def vpot(v, bn, thtv, valcs): ps = utils.ops(v, bn) fam = ps + [v] fam.sort() vp = pot.Potential(fam, valcs) vix = fam.index(v) for fcfg in utils.cfgs(valcs(fam)): cfg = list(fcfg) vl = cfg.pop(vix) cfg = tuple(cfg) vp[fcfg] = thtv(tuple(cfg))[vl] return vp
def __init__(self, valcs, jt, clqs, pots, vclqs): # CONSTANTS self.valcs = valcs self.jt = jt self.clqs = clqs self.vclqs = vclqs self.nof_vars = len(vclqs) # AND WORK VARIABLES self.pots_ = pots self.spots_ = self.sepot(jt, clqs, valcs) self.lhs_ = [pot.Potential([v], valcs) for v in xrange(self.nof_vars)] self.reset()
def infer1(self,v, needs_propagation=True): if needs_propagation: self.globprop(self.jt, self.pots, self.spots) cpot = self.pots[self.vclqs[v]] return (cpot >> pot.Potential([v], self.valcs, 0.0)).normalize().p
def insert_evidence(lhs, v, p, vpot): old_lhv = lhs[v] new_lhv = pot.Potential(old_lhv.vars, old_lhv.valcs) new_lhv.p = p[:] vpot *= new_lhv / old_lhv lhs[v] = new_lhv