def to_funset(self): """ Converts the list of logical networks to a set of `gringo.Fun`_ instances Returns ------- set Representation of all networks as a set of `gringo.Fun`_ instances .. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun """ fs = set((gringo.Fun("variable", [var]) for var in self.hg.nodes)) formulas = set() for network in self: formulas = formulas.union(it.imap(lambda (_, f): f, network.formulas_iter())) formulas = pd.Series(list(formulas)) for i, network in enumerate(self): for v, f in network.formulas_iter(): fs.add(gringo.Fun("formula", [i, v, formulas[formulas == f].index[0]])) for formula_idx, formula in formulas.iteritems(): for clause in formula: clause_idx = self.hg.clauses_idx[clause] fs.add(gringo.Fun("dnf", [formula_idx, clause_idx])) for variable, sign in clause: fs.add(gringo.Fun("clause", [clause_idx, variable, sign])) return fs
def main(prg): imin = get(prg.get_const("imin"), 1) imax = get(prg.get_const("imax"), 100) istop = get(prg.get_const("istop"), "SAT") step = 0 prg.ground([("base", [])]) ret = prg.solve(on_model = __on_model) while ((imax is None or step < imax) and (step == 0 or step < imin or ( (istop == "SAT" and ret != gringo.SolveResult.SAT) or (istop == "UNSAT" and ret != gringo.SolveResult.UNSAT) or (istop == "UNKNOWN" and ret != gringo.SolveResult.UNKNOWN)))): # print "=== Add cumulative rules to program" print "=== Set cumulative(" + str(step) + ")" prg.ground([("step", [step])]) # print "=== Set external query(" + str(step) + ") to be true " prg.assign_external(gringo.Fun("query", [step]), True) ret = prg.solve(on_model = __on_model) # print "=== Release external query(" + str(step) + ") " prg.release_external(gringo.Fun("query", [step])) if ret == gringo.SolveResult.SAT: print "=== Found solution " break step = step+1
def solutions(self, on_model, on_model_weight=None, limit=0, force_weight=None): control = self.default_control("0") do_subsets = self.opts.family == "subset" \ or (self.opts.family =="mincard" and self.opts.mincard_tolerance) minsize = None self.setup_opt(control) control.ground([("base", [])]) control.load(aspf("show.lp")) control.ground([("show", [])]) start = time.time() if self.nodataset: force_weight = 0 if force_weight is None: control.assign_external(gringo.Fun("tolerance"),False) dbg("# start initial solving") opt = [] res = control.solve(None, lambda model: opt.append(model.optimization())) dbg("# initial solve took %s" % (time.time()-start)) optimizations = opt.pop() dbg("# optimizations = %s" % optimizations) weight = optimizations[0] if self.do_mincard: minsize = optimizations[1] if weight > 0 and on_model_weight is not None: dbg("# model has weight, changing enumeration mode") for sample in self.solution_samples(): on_model_weight(sample) return control.assign_external(gringo.Fun("tolerance"),True) else: weight = force_weight dbg("# force weight = %d" % weight) self.setup_weight(control, weight) self.setup_card(control, minsize) control.conf.solve.opt_mode = "ignore" control.conf.solve.project = 1 # ???? control.conf.solve.models = limit # ???? #print control.conf.solver[0].keys() if do_subsets: control.conf.solve.enum_mode = "domRec" control.conf.solver[0].heuristic = "Domain" control.conf.solver[0].dom_mod = "5,16" start = time.time() dbg("# begin enumeration") res = control.solve(None, on_model) dbg("# enumeration took %s" % (time.time()-start))
def to_funset(self): """ Converts the hypergraph to a set of `gringo.Fun`_ instances Returns ------- set Representation of the hypergraph as a set of `gringo.Fun`_ instances .. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun """ fs = set() for i, n in self.nodes.iteritems(): fs.add(gringo.Fun('node', [n, i])) for j, i in self.hyper.iteritems(): fs.add( gringo.Fun( 'hyper', [i, j, len(self.edges[self.edges.hyper_idx == j])])) for j, v, s in self.edges.itertuples(index=False): fs.add(gringo.Fun('edge', [j, v, s])) return fs
def __next(self): assert (self.__horizon < 30) self.__prg.assign_external(gringo.Fun("horizon", [self.__horizon]), False) self.__horizon += 1 self.__prg.ground([("trans", [self.__horizon]), ("check", [self.__horizon]), ("state", [self.__horizon])]) self.__prg.assign_external(gringo.Fun("horizon", [self.__horizon]), True)
def start(self, step): parts = [] parts.append(("check", [step])) if step > 0: self.__prg.release_external(gringo.Fun("query", [step - 1])) parts.append(("step", [step])) self.__prg.cleanup_domains() else: parts.append(("base", [])) self.__prg.ground(parts) self.__prg.assign_external(gringo.Fun("query", [step]), True) self.__future = self.__prg.solve_async(on_finish=self.on_finish)
def start(self, board): self.__assign = [] for robot, (x, y) in board.pos.items(): self.__assign.append( gringo.Fun("pos", [gringo.Fun(robot), x + 1, y + 1, 0])) self.__assign.append( gringo.Fun("target", [ gringo.Fun(board.current_target[0]), board.current_target[2] + 1, board.current_target[3] + 1 ])) for x in self.__assign: self.__prg.assign_external(x, True) self.__solution = None self.__future = self.__prg.solve_async(on_model=self.__on_model)
def to_funset(self): fs = funset(self.setup) clampings = [] for exp in sorted(self.experiments.values(), key=lambda e: e.id): i = exp.id literals = [Literal(node, sign) for node, sign in \ exp.mutations.items()] clampings.append(Clamping(literals)) for time, obs in exp.dobs.items(): for var, dval in obs.items(): fs.add(gringo.Fun('obs', [i, time, var, dval])) clampings = ClampingList(clampings) fs.update(clampings.to_funset("exp")) fs.add(gringo.Fun('dfactor', [self.dfactor])) return fs
def to_funset(self, index, name="clamped"): """ Converts the clamping to a set of `gringo.Fun`_ object instances Parameters ---------- index : int An external identifier to associate several clampings together in ASP name : str A function name for the clamping Returns ------- set The set of `gringo.Fun`_ object instances .. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun """ fs = set() for var, sign in self: fs.add(gringo.Fun(name, [index, var, sign])) return fs
def to_funset(self, lname="clamping", cname="clamped"): """ Converts the list of clampings to a set of `gringo.Fun`_ instances Parameters ---------- lname : str Predicate name for the clamping id cname : str Predicate name for the clamped variable Returns ------- set Representation of all clampings as a set of `gringo.Fun`_ instances .. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun """ fs = set() for i, clamping in enumerate(self): fs.add(gringo.Fun(lname, [i])) fs = fs.union(clamping.to_funset(i, cname)) return fs
def to_funset(self, discrete): """ Converts the dataset to a set of `gringo.Fun`_ instances Parameters ---------- discrete : callable A discretization function Returns ------- set Representation of the dataset as a set of `gringo.Fun`_ instances .. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun """ fs = self.clampings.to_funset("exp") fs = fs.union(self.setup.to_funset()) for i, row in self.readouts.iterrows(): for var, val in row.iteritems(): if not np.isnan(val): fs.add(gringo.Fun('obs', [i, var, discrete(val)])) return fs
def to_funset(self): """ Converts the experimental setup to a set of `gringo.Fun`_ object instances Returns ------- set The set of `gringo.Fun`_ object instances .. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun """ fs = set((gringo.Fun('stimulus', [str(var)]) for var in self.stimuli)) fs = fs.union((gringo.Fun('inhibitor', [str(var)]) for var in self.inhibitors)) fs = fs.union((gringo.Fun('readout', [str(var)]) for var in self.readouts)) return fs
def __init__(self, horizon=0): self.__horizon = horizon self.__prg = gringo.Control(['-t4']) self.__future = None self.__solution = None self.__assign = [] self.__prg.load("board.lp") self.__prg.load("robots.lp") parts = [("base", []), ("check", [0]), ("state", [0])] for t in range(1, self.__horizon + 1): parts.extend([("trans", [t]), ("check", [t]), ("state", [t])]) self.__prg.ground(parts) self.__prg.assign_external(gringo.Fun("horizon", [self.__horizon]), True)
def domain_of_networks(networks, hypergraph, dataset): fs = funset(networks) domain = ["1{%s}1." % ("; ".join(["model(%d)" % i for i in range(len(networks))]))] formulas = set() for network in networks: formulas = formulas.union(it.imap(lambda (_, f): f, network.formulas_iter())) formulas = pd.Series(list(formulas)) for i, network in enumerate(networks): for v, f in network.formulas_iter(): f= gringo.Fun("formula", [v, formulas[formulas == f].index[0]]) domain.append("%s :- model(%d)." % (f,i)) return "%s%s\n" % (fs.to_str(), "\n".join(domain))
def __init__(self, networks, setup, candidates=None): self.networks = networks self.setup = setup self.candidates = candidates self.designs = [] fs = networks.to_funset().union(setup.to_funset()) if candidates: fs = fs.union(self.candidates.to_funset("listing", "listed")) fs.add(gringo.Fun("mode", [2])) else: fs.add(gringo.Fun("mode", [1])) self.instance = ". ".join(map(str, fs)) + ". #show clamped/3." root = os.path.dirname(__file__) self.encodings = { 'design': os.path.join(root, 'encodings/design/idesign.lp') } self.__optimum__ = None self.stats = {'time_optimum': None, 'time_enumeration': None} self._logger = logging.getLogger("caspo")
def domain_of_networks(networks): hg = networks.hg domain = [ "1{%s}1." % ("; ".join(["model(%d)" % i for i in range(len(networks))])) ] for i, network in enumerate(networks): m = gringo.Fun("model", [i]) for v, formula in network.formulas_iter(): variable = hg.nodes[hg.nodes == v].index[0] f = gringo.Fun("formula", [v, variable]) domain.append("%s :- model(%d)." % (f, i)) for clause in formula: clause_idx = hg.clauses_idx[clause] d = gringo.Fun("dnf", [variable, clause_idx]) domain.append("%s :- %s." % (d, m)) for variable, sign in clause: c = gringo.Fun("clause", [clause_idx, variable, sign]) domain.append("%s :- %s." % (c, m)) return "%s\n" % "\n".join(domain)
def __init__(self, networks, scenarios): self.networks = networks self.scenarios = scenarios self.strategies = core.ClampingList() fs = networks.to_funset().union(scenarios.to_funset()) for v in it.ifilter(lambda n: n not in scenarios.exclude, networks.hg.nodes): fs.add(gringo.Fun("candidate", [v])) self.instance = ". ".join(map(str, fs)) + ". #show intervention/2." root = os.path.dirname(__file__) self.encodings = { 'control': os.path.join(root, 'encodings/control/encoding.lp') } self.stats = { 'time_optimum': None, 'time_enumeration': None } self._strategies = None self._logger = logging.getLogger("caspo")
def __init__(self, graph, dataset, length, discrete, factor): self.graph = graph self.dataset = dataset self.length = length self.factor = factor self.discrete = partial(self.__getattribute__(discrete), factor) self.hypergraph = core.HyperGraph.from_graph(self.graph, length) fs = self.dataset.to_funset(self.discrete).union( self.hypergraph.to_funset()) fs.add(gringo.Fun('dfactor', [self.factor])) self.instance = ". ".join(map(str, fs)) + ". #show dnf/2." self.optimum = None self.networks = core.LogicalNetworkList.from_hypergraph( self.hypergraph) root = os.path.dirname(__file__) self.encodings = { 'guess': os.path.join(root, 'encodings/learn/guess.lp'), 'fixpoint': os.path.join(root, 'encodings/learn/fixpoint.lp'), 'rss': os.path.join(root, 'encodings/learn/residual.lp'), 'opt': os.path.join(root, 'encodings/learn/optimization.lp'), 'enum': os.path.join(root, 'encodings/learn/enumeration.lp'), 'random': os.path.join(root, 'encodings/learn/random.lp') } self.stats = { 'time_optimum': None, 'time_enumeration': None, 'optimum_mse': None, 'optimum_size': None } self._last = None self._logger = logging.getLogger("caspo")
def sample(self, control, first, weight=None, minsize=None): if first: #control.conf.solve.opt_mode = "opt" self.setup_opt(control) control.ground([("base", [])]) control.load(aspf("show.lp")) control.ground([("show", [])]) control.assign_external(gringo.Fun("tolerance"),False) else: if weight: self.setup_weight(control, weight) if minsize: self.setup_card(control, minsize) control.conf.solve.opt_mode = "ignore" control.conf.solve.models = 1 models = [] res = control.solve(None, lambda model: models.append(ASPSample(self.opts, model))) if models: model = models.pop() return model
def solutions(self, on_model, on_model_weight=None, limit=0, force_weight=None): control = self.default_control("0") do_mincard = self.opts.family == "mincard" \ or self.opts.force_size is not None do_subsets = self.opts.family == "subset" \ or (self.opts.family =="mincard" and self.opts.mincard_tolerance) control.load(aspf("minimizeWeightOnly.lp")) if do_mincard: control.load(aspf("minimizeSizeOnly.lp")) control.ground([("base", [])]) control.load(aspf("show.lp")) control.ground([("show", [])]) #****Flavio**** start = time.time() if force_weight is None: control.assign_external(gringo.Fun("tolerance"), False) dbg("# start initial solving") opt = [] res = control.solve(None, lambda model: opt.append(model.optimization())) dbg("# initial solve took %s" % (time.time() - start)) optimizations = opt.pop() dbg("# optimizations = %s" % optimizations) weight = optimizations[0] if do_mincard: minsize = optimizations[1] if weight > 0 and on_model_weight is not None: for sample in self.solution_samples(): on_model_weight(sample) return control.assign_external(gringo.Fun("tolerance"), True) else: weight = force_weight dbg("# force weight = %d" % weight) max_weight = weight + self.opts.weight_tolerance control.add( "minWeight", [], ":- not " + str(weight) + " #sum {Erg,E,T,S : measured(E,T,S,V), not guessed(E,T,S,V), toGuess(E,T,S), obs(E,T,S,M), Erg=50-M, M < 50;" + " Erg,E,T,S : measured(E,T,S,V), not guessed(E,T,S,V), toGuess(E,T,S), obs(E,T,S,M), Erg=M-49, M >= 50} " + str(max_weight) + " .") control.ground([("minWeight", [])]) control.conf.solve.opt_mode = "ignore" control.conf.solve.project = 1 # ???? control.conf.solve.models = limit # ???? #print control.conf.solver[0].keys() if do_mincard: if self.opts.force_size: maxsize = self.opts.force_size else: maxsize = minsize + self.opts.mincard_tolerance control.add( "minSize", [], ":- not " + str(minsize) + " #sum {L,I,J : dnf(I,J) , hyper(I,J,L)} " + str(maxsize) + ".") control.ground([("minSize", [])]) if do_subsets: control.conf.solve.enum_mode = "domRec" control.conf.solver[0].heuristic = "Domain" control.conf.solver[0].dom_mod = "5,16" start = time.time() dbg("# begin enumeration") res = control.solve(None, on_model) dbg("# enumeration took %s" % (time.time() - start))
for atom in m.atoms(gringo.Model.ATOMS): if atom.name() == "field" and len(atom.args()) == 2: x, y = atom.args() field.append((x, y)) elif atom.name() == "stone" and len(atom.args()) == 5: s, d, x, y, l = atom.args() stone.append((str(s), str(d), x, y, l)) elif atom.name() == "move" and len(atom.args()) == 4: t, s, d, xy = atom.args() move.setdefault(t, []).append((str(s), str(d), xy)) elif atom.name() == "target" and len(atom.args()) == 3: s, x, y = atom.args() target.append((str(s), x, y)) return False return on_model t, field, stone, move, target = 0, [], [], {}, [] on_model = make_on_model(field, stone, move, target) c.ground([("base", [])]) while True: t += 1 c.ground([("step", [t])]) c.ground([("check", [t])]) c.release_external(gringo.Fun("query", [t-1])) c.assign_external(gringo.Fun("query", [t]), True) if c.solve(None, on_model) == gringo.SolveResult.SAT: break MainWindow().run(Plan(field, stone, target, move))
def main(prg): global w global curr_sample global max_num_iteration global isStableModelVar global sample_attempt global query_count global queries global domain global atoms2count # queries = raw_input('Queries?(Separated with Comma; No space) ').split(',') queries = "founders" # domain_filename = raw_input('Domain File? ') domain_filename = "/home/apradhan/proj/fact_checking/LPmln/company_founder/evidence/7company_founder_domain.txt" domain_file = open(domain_filename, 'r') for line in domain_file: if len(line) <= 2: continue parts = line.split(' ') instances = parts[1].split('&') for inst in instances: domain.append(gringo.Fun(parts[0], [eval(arg) for arg in inst.split(';')])) if parts[0] in queries: for inst in instances: query_count[gringo.Fun(parts[0], [eval(arg) for arg in inst.split(';')])] = 0 print 'domain', domain print 'query atoms', query_count.keys() iter_count = 0 random.seed() sample_count = 1 # Generate First Sampling by MAP inference prg.ground([('base', [])]) prg.solve([], getSample) curr_sample = sample_attempt # Main Loop for _ in range(max_num_iteration): curr_weight = w print 'Sample ',sample_count,': ',curr_sample print 'Weight: ' + str(w) print "Query Count: ", query_count for atom in atoms2count: query_count[atom] += 1 # Generate next sample by randomly flipping atoms while True: sample_attempt = [] for r in curr_sample: sample_attempt.append(r) ridx = random.randint(0, len(sample_attempt)-1) sample_attempt[ridx] = (sample_attempt[ridx][0], not sample_attempt[ridx][1]) isStableModelVar = False prg.solve(sample_attempt, getSample) if isStableModelVar: new_weight = w r = random.random() if r < new_weight / curr_weight: curr_sample = sample_attempt else: sample_attempt = curr_sample prg.solve(sample_attempt, getSample) sample_count += 1 break # Compute new marginal probabilities for atom in query_count: print atom, ": ", float(query_count[atom])/float(sample_count)
#help(gringo) control = gringo.Control( ["--conf=trendy", "--stats", "0", "--opt-strat=usc"]) #print_conf(control.conf, "") control.load("guessBN.lp") control.load(encoding) control.load("minimizeWeightOnly.lp") control.load("normalize.lp") # control.load("../../Benchmarks/nets_to_test/1/asp/pkn.lp") control.load(os.path.join(path, pkn)) control.load(os.path.join(path, i)) control.ground([("base", [])]) control.load("show.lp") control.ground([("show", [])]) control.assign_external(gringo.Fun("tolerance"), False) start = time.time() res = control.solve(None, on_model_opt) #print("Finding the minimal model: " + str(time.time()-start)) print(optimizations, end=',') print(str(time.time() - start), end=',') control.assign_external(gringo.Fun("tolerance"), True) control.add( "minWeight", [], ":- not " + str(optimizations[0]) + " #sum {Erg,E,T,S : measured(E,T,S,V), not guessed(E,T,S,V), toGuess(E,T,S), obs(E,T,S,M), Erg=50-M, M < 50;" + " Erg,E,T,S : measured(E,T,S,V), not guessed(E,T,S,V), toGuess(E,T,S), obs(E,T,S,M), Erg=M-49, M >= 50} "
def design(self, max_stimuli=-1, max_inhibitors=-1, max_experiments=10, relax=False, configure=None): """ Finds all optimal experimental designs using up to :attr:`max_experiments` experiments, such that each experiment has up to :attr:`max_stimuli` stimuli and :attr:`max_inhibitors` inhibitors. Each optimal experimental design is appended in the attribute :attr:`designs` as an instance of :class:`caspo.core.clamping.ClampingList`. Example:: >>> from caspo import core, design >>> networks = core.LogicalNetworkList.from_csv('behaviors.csv') >>> setup = core.Setup.from_json('setup.json') >>> designer = design.Designer(networks, setup) >>> designer.design(3, 2) >>> for i,d in enumerate(designer.designs): ... f = 'design-%s' % i ... d.to_csv(f, stimuli=self.setup.stimuli, inhibitors=self.setup.inhibitors) Parameters ---------- max_stimuli : int Maximum number of stimuli per experiment max_inhibitors : int Maximum number of inhibitors per experiment max_experiments : int Maximum number of experiments per design relax : boolean Whether to relax the full-pairwise networks discrimination (True) or not (False). If relax equals True, the number of experiments per design is fixed to :attr:`max_experiments` configure : callable Callable object responsible of setting clingo configuration """ self.designs = [] args = [ '-c maxstimuli=%s' % max_stimuli, '-c maxinhibitors=%s' % max_inhibitors, '-Wno-atom-undefined' ] clingo = gringo.Control(args) clingo.conf.solve.opt_mode = 'optN' if configure is not None: configure(clingo.conf) clingo.add("base", [], self.instance) clingo.load(self.encodings['design']) clingo.ground([("base", [])]) if relax: parts = [("step", [step]) for step in xrange(1, max_experiments + 1)] parts.append(("diff", [max_experiments + 1])) clingo.ground(parts) ret = clingo.solve(on_model=self.__save__) else: step, ret = 0, gringo.SolveResult.UNKNOWN while step <= max_experiments and ret != gringo.SolveResult.SAT: parts = [] parts.append(("check", [step])) if step > 0: clingo.release_external(gringo.Fun("query", [step - 1])) parts.append(("step", [step])) clingo.cleanup_domains() clingo.ground(parts) clingo.assign_external(gringo.Fun("query", [step]), True) ret, step = clingo.solve(on_model=self.__save__), step + 1 self.stats['time_optimum'] = clingo.stats['time_solve'] self.stats['time_enumeration'] = clingo.stats['time_total'] self._logger.info("%s optimal experimental designs found in %.4fs", len(self.designs), self.stats['time_enumeration'])
def to_funset(self): fs = funset() fs.update([gringo.Fun("fp", [self.id, n, v]) \ for (n,v) in self.state.items()]) return fs
curr_sample = None sample_attempt = None max_num_iteration = 1000 isStableModelVar = False evidenceIsStableModel = False weights = pickle.load(open(tmp_weights_file, 'r')) evid_obj = pickle.load(open(tmp_evidence_file, 'r')) lr = pickle.load(open(tmp_lr_file, 'r')) #weights = {} #weights[1] = 1 #evidence = [(gringo.Fun('q', [1]), True), (gringo.Fun('p', [1]), False)] evidence = [] for r in evid_obj: evidence.append((gringo.Fun(r[0], r[1]), r[2])) def getWeight(rule_id): global weights print str(weights[rule_id]) return str(weights[rule_id]) def main(prg): global mis global w global weights global curr_sample global max_num_iteration global numUnsat
print("solve something") c = gringo.Control(["0"]) c.add("base", [], "1{a;b;p(@test2())}.") c.ground("base", []) with c.iterSolve() as it: for m in it: print m print("solve something different") d = gringo.Control(["0"]) d.add("base", [], "1{b;c;p(@test3())}.") d.ground("base", []) with d.iterSolve() as it: for m in it: print m print "do it once" test() print "do it twice" test() print "do it thrice" test() print "time to stop this" a = gringo.Inf() b = gringo.Sup() c = gringo.Fun("a", [a, b]) d = gringo.Inf() e = gringo.Inf()
def main(prg): global w global curr_sample global max_num_iteration global isStableModelVar global sample_attempt global query_count global queries global domain global atoms2count with open('lpmln-learning/code/query_domain.txt') as f: content = f.readlines() queries = content[0].split(',') queries = [query.rstrip() for query in queries] print queries domain_filename = content[2] resource = ast.literal_eval(content[1]) resource = ['"' + res + '"' for res in resource] # print resource # queries, domain_filename = get_inputs() # queries = raw_input('Queries?(Separated with Comma; No space) ').split(',') # domain_filename = raw_input('Domain File? ') domain_file = open(domain_filename, 'r') for line in domain_file: if len(line) <= 2: continue parts = line.split('~') instances = parts[1].split('&') # print parts[0] # print instances for inst in instances: domain.append( gringo.Fun(parts[0], [eval(arg) for arg in inst.split(';')])) if parts[0] in queries: for inst in instances: query_count[gringo.Fun(parts[0], [eval(arg) for arg in inst.split(';')])] = 0 # print 'domain', domain # print 'query atoms', query_count.keys() iter_count = 0 random.seed() sample_count = 0 # Generate First Sampling by MAP inference prg.ground([('base', [])]) prg.solve([], getSample) curr_sample = sample_attempt # Main Loop for _ in range(max_num_iteration): timeout = time.time() + 60 * 2 curr_weight = w # print 'Sample ',sample_count,': ',curr_sample # print 'Weight: ' + str(w) # print "Query Count: ", query_count for atom in atoms2count: query_count[atom] += 1 # Generate next sample by randomly flipping atoms i = 0 while True: time.sleep(.0000001) i += 1 break_time = timeout - time.time() print i, break_time sample_attempt = [] for r in curr_sample: sample_attempt.append(r) ridx = random.randint(0, len(sample_attempt) - 1) sample_attempt[ridx] = (sample_attempt[ridx][0], not sample_attempt[ridx][1]) isStableModelVar = False prg.solve(sample_attempt, getSample) if isStableModelVar: new_weight = w r = random.random() if r < new_weight / curr_weight: curr_sample = sample_attempt else: sample_attempt = curr_sample prg.solve(sample_attempt, getSample) sample_count += 1 break if break_time < 0: print "timing out" break if break_time < 0: print "timing out" break # Compute new marginal probabilities output = [] compare_prob = [None] * 2 label = "Null" for atom in query_count: try: atom_str = str(atom).encode('utf-8') entities = re.findall(r'\".*?\"', atom_str) if resource[0] == entities[0] and resource[1] == entities[1]: prob = float(query_count[atom]) / float(sample_count) print atom, ": ", prob if 'neg' in atom_str: compare_prob[0] = prob else: compare_prob[1] = prob output.append(str(atom) + ": " + str(round(prob, 2))) except: pass label = get_label(compare_prob) with open('lpmln-learning/code/lpmln_prob.txt', 'w') as the_file: the_file.write(str(output).encode('utf-8')) the_file.write(';' + str(label))