def choose_subset(self, select_subset, encodingFile, timeout=30, usc=False, solve_limit="umax,umax", clingoctl=None): if clingo is None: raise ImportError() c = clingoctl aset = [sys.maxsize, False, [], None, []] def __on_model(model): #if len(model.cost) == 0: # return logger.debug("better answer set found: %s %s %s", model, model.cost, model.optimality_proven) aset[1] |= model.optimality_proven opt = model.cost[0] if len(model.cost) > 0 else 0 if opt <= aset[0]: if opt < aset[0]: aset[2] = [] aset[0] = opt answer_set = [safe_int(x) for x in str(model).translate(str.maketrans(dict.fromkeys("abs()"))).split(" ")] # might get "fake" duplicates :(, with different model.optimality_proven if answer_set not in aset[2][-1:]: aset[2].append(answer_set) with open(encodingFile,"r") as encoding: encodingContent = "".join(encoding.readlines()) # FIXME: use mutable string prog = encodingContent if clingoctl is None: c = clingo.Control() if usc: c.configuration.solver.opt_strategy = "usc,pmres,disjoint,stratify" c.configuration.solver.opt_usc_shrink = "min" c.configuration.solve.opt_mode = "opt" # c.configuration.solve.models = 0 c.configuration.solve.solve_limit = solve_limit for e in self._edges: prog += "edge({0},{1}).\n".format(e[0], e[1]) for p in self._nodes: prog += "p({0}).\n".format(p) # subset (buckets) of proj to select upon #for b in range(1, select_subset + 1, 1): prog += "b({0}).\n".format(select_subset) #print(prog) aset[3] = c c.add("prog{0}".format(select_subset), [], str(prog)) def solver(c, om): c.ground([("prog{0}".format(select_subset), [])]) self.grounded = True c.solve(on_model=om) t = threading.Thread(target=solver, args=(c, __on_model)) t.start() t.join(timeout) self.timeout = t.is_alive() c.interrupt() t.join() aset[1] |= c.statistics["summary"]["models"]["optimal"] > 0 aset[4] = c.statistics return aset
def solve( self, solver_setup, xml_files, dump=None, nmodels=0, timers=False, stats=False, tests=False, logic_programs=None, facts_only=False, ): """Given two corpora, determine if they are compatible by way of flattening header information into facts, and handing to a solver. """ # Ensure our files exist, and are provided in list form if not isinstance(xml_files, list): xml_files = [xml_files] for path in xml_files: if not os.path.exists(path): sys.exit("%s does not exist." % path) # logic programs to give to the solver logic_programs = logic_programs or [] if not isinstance(logic_programs, list): logic_programs = [logic_programs] timer = Timer() # Initialize the control object for the solver self.control = clingo.Control() self.control.configuration.solve.models = nmodels self.control.configuration.asp.trans_ext = "all" self.control.configuration.asp.eq = "5" self.control.configuration.configuration = "tweety" self.control.configuration.solve.parallel_mode = "2" self.control.configuration.solver.opt_strategy = "usc,one" # set up the problem -- this generates facts and rules self.assumptions = [] with self.control.backend() as backend: self.backend = backend solver_setup.setup(self, xml_files, tests=tests) if facts_only: return timer.phase("setup") # read in the main ASP program and display logic -- these are # handwritten, not generated, so we load them as resources parent_dir = os.path.dirname(__file__) import IPython IPython.embed() # self.control.load(os.path.join(parent_dir, 'compatible.lp')) # self.control.load(os.path.join(parent_dir, "display.lp")) timer.phase("load") # Grounding is the first step in the solve -- it turns our facts # and first-order logic rules into propositional logic. self.control.ground([("base", [])]) timer.phase("ground") # With a grounded program, we can run the solve. result = Result() models = [] # stable models if things go well cores = [] # unsatisfiable cores if they do not def on_model(model): models.append((model.cost, model.symbols(shown=True, terms=True))) solve_kwargs = {} # Won't work after this, need to write files # solve_kwargs = { # "assumptions": self.assumptions, # "on_model": on_model, # "on_core": cores.append, # } # if clingo_cffi: # solve_kwargs["on_unsat"] = cores.append # solve_result = self.control.solve(**solve_kwargs) # timer.phase("solve") # once done, construct the solve result # result.satisfiable = solve_result.satisfiable # def stringify(x): # if clingo_cffi: # # Clingo w/ CFFI will throw an exception on failure # try: # return x.string # except RuntimeError: # return str(x) # else: # return x.string or str(x) # if result.satisfiable: # min_cost, best_model = min(models) # tuples = [ # (sym.name, [stringify(a) for a in sym.arguments]) for sym in best_model # ] # result.answers.append((list(min_cost))) # elif cores: # symbols = dict((a.literal, a.symbol) for a in self.control.symbolic_atoms) # for core in cores: # core_symbols = [] # for atom in core: # sym = symbols[atom] # if sym.name == "rule": # sym = sym.arguments[0].string # core_symbols.append(sym) # result.cores.append(core_symbols) if timers: timer.write() print() if stats: print("Statistics:") pprint.pprint(self.control.statistics) return result
def largest_clique_asp(self, clingoctl=None, timeout=10, enum=True, usc=True, ground=False, prevent_k_hyperedge=3, solve_limit="umax,umax"): if clingo is None: raise ImportError() @curry def __on_model(aset, model): if len(model.cost) == 0: return # print model, model.cost, model.optimality_proven aset[1] |= model.optimality_proven opt = abs(model.cost[0]) if opt >= aset[0]: if opt > aset[0]: aset[2] = [] aset[0] = opt answer_set = [safe_int(x) for x in str(model).translate(None, "u()").split(" ")] # might get "fake" duplicates :(, with different model.optimality_proven if answer_set not in aset[2][-1:]: aset[2].append(answer_set) prog = MutableString() if clingoctl is None: c = clingo.Control() if usc: c.configuration.solver.opt_strategy = "usc,pmres,disjoint,stratify" c.configuration.solver.opt_usc_shrink = "min" c.configuration.solve.opt_mode = "optN" if enum else "opt" c.configuration.solve.models = 0 c.configuration.solve.solve_limit = solve_limit guess = MutableString() pos = 0 if len(self.__vertices) > 0: guess += "{" prog += "#maximize {" for u in self.__vertices: prog += " 1,u({0}):u({1}){2}".format(u, u, " }.\n" if pos == len(self.__vertices) - 1 else ";") guess += " u({0}){1}".format(u, " }.\n" if pos == len(self.__vertices) - 1 else ";") pos += 1 prog += "#show u/1.\n" prog += guess # has to be clique if len(self.__edges) > 0: if not ground: prog += ":- u(Y1), u(Y2), not a(Y1, Y2), Y1 < Y2.\n" prog += "a(Y1, Y2) :- e(X, Y1), e(X, Y2), Y1 < Y2.\n" for k, e in self.__edges.iteritems(): for v in e: prog += "e({0}, {1}).\n".format(k, v) else: adj = self.adj for u in self.__vertices: for v in self.__vertices: if u < v and v not in adj[u]: prog += ":- u({0}), u({1}).\n".format(u, v) else: c = clingoctl aset = [0, False, [], c, []] if len(self.__edges) == 0 or len(self.__vertices) == 0: return aset if not ground and len(self.__edges) > 0: prog += ":- " for i in xrange(0, prevent_k_hyperedge): if i > 0: prog += ", Y{0} < Y{1}, ".format(i - 1, i) prog += "e(X, Y{0}), u(Y{0})".format(i) prog += ".\n" # prog += ":- e(X, Y1), e(X, Y2), e(X, Y3), u(Y1), u(Y2), u(Y3), Y1 < Y2, Y2 < Y3." else: constr = set() for e in self.__edges.values(): if len(e) <= 2 or len(e) < prevent_k_hyperedge: continue # prevent 3 elements from the same edge sub = range(0, prevent_k_hyperedge) while True: # sub[0] <= len(e) - prevent_k_hyperedge: rule = [] pos = 0 # print sub, e for v in sub: rule.append(e[v]) pos += 1 rule = tuple(sorted(rule)) if rule not in constr: constr.add(rule) prog += ":- " + ", ".join(("u({0})".format(r) for r in rule)) + ".\n" if sub[0] == len(e) - prevent_k_hyperedge: break # next position for i in xrange(prevent_k_hyperedge - 1, -1, -1): if sub[i] < len(e) + (i - prevent_k_hyperedge): sub[i] += 1 for j in xrange(i + 1, prevent_k_hyperedge): sub[j] = sub[i] + (j - i) break # print "XX, ", self.__edges, self.__vertices # print(prog) c.add("prog{0}".format(prevent_k_hyperedge), [], str(prog)) def solver(c, om): c.ground([("prog{0}".format(prevent_k_hyperedge), [])]) # print "grounded" c.solve(on_model=om) t = threading.Thread(target=solver, args=(c, __on_model(aset))) t.start() t.join(timeout) c.interrupt() t.join() aset[1] |= c.statistics["summary"]["models"]["optimal"] > 0 aset[4] = c.statistics # print c.statistics return aset
def solve_sudoku_ASP(sudoku, k): """ Function that solves given sudoku list with ASP encoding. Edges correspond to undirected edge between cells in same row, column or k*k block. """ num_vertices = (k * k) * (k * k) # 81 for k = 3 # Nd array representation of sudoku graph = np.array(sudoku).reshape(num_vertices, 1) # Create 2d np array of vertice numbers of 0 until num_vertices-1 for edges vertices = np.arange(num_vertices).reshape(k * k, k * k) edges = get_edges(vertices, k) vertices = vertices.reshape(num_vertices, 1) # Number of possible values in sudoku which we refer to as numbers (nums/n) num_nums = k * k asp_code = "" # Encode our facts as predicates vertex/1, value/2 which is possible values # for each vertex and edges/2 for v in range(num_vertices): asp_code += """vertex(v{}).\n""".format(v) # If a cell contains u in input, cell in solution must contain u if graph[v].item() != 0: asp_code += """value(v{}, {}).\n""".format(v, graph[v].item()) else: for n1 in range(1, num_nums + 1): asp_code += """value(v{},{}).\n""".format(v, n1) for (v1, v2) in edges: asp_code += """edge(v{},v{}).\n""".format(v1, v2) # Universily quantified variables; number for each vertex, already filled # in value must also hold for n1 in range(1, num_nums + 1): asp_code += """num(V,{}) :- vertex(V), value(V, {})""".format(n1, n1) for n2 in range(1, num_nums + 1): if n1 != n2: asp_code += """, not num(V,{})""".format(n2) asp_code += """.\n""" # Each two different cells in same row,col,block must contain diff values asp_code += """:- edge(V1, V2), num(V1,N), num(V2,N).\n""" # Only interested in the number predicate asp_code += """#show num/2.\n""" control = clingo.Control() control.add("base", [], asp_code) control.ground([("base", [])]) def on_model(model): global output output = model.symbols(shown=True) control.configuration.solve.models = 1 answer = control.solve(on_model=on_model) if answer.satisfiable: # Fill in sudoku graph with answer for i in range(len(output)): v = int(str(output[i]).split(",")[0].split("v")[1]) n = int(str(output[i]).split(",")[-1][:-1]) graph[v] = n graph = graph.reshape(k * k, k * k).tolist() else: graph = None return graph
def main(): ## Global variables global models global number_constraints xor_constraints = 0 total_rounds = 0 current_state_key = 0 ## Parse input data args = parse_params() ## Check for input errors check_input(args) programs = [] for in_file in args.input: try: int(in_file) except ValueError: programs.append(in_file) #print args #print programs ## Create clingo object round_num = 1 while True: control = clingo.Control() control.cleanup() control.configuration.solve.models = 0 control.configuration.solve.opt_mode = "ignore" if args.stats: control.configuration.stats=1 for program in programs: control.load(program) control.ground([("base", [])]) if round_num == 1: if len(programs) > 1: print "Reading from %s ..."%programs[0] else: print "Reading from %s "%programs[0] if args.incremental: print "Incremental Solving..." else: print "Solving..." ## Initial solvinig... only solving call if not incremental or non iterative control.register_propagator(Propagator(args.s)) solve_result = control.solve(None, lambda model: models.append(model.symbols(shown=True))) ## If incremental flag is on if args.incremental and solve_result: ## Get info from round 1 if verbosity 0, 2 or 3 if args.incremental: ## Get xor constraints and solving rounds xor_constraints = Propagator.number_constraints total_rounds = Propagator.roundn if args.verbose != 1: print "round %s:"%total_rounds if args.verbose == 0 or args.verbose == 2: Models().print_state(Propagator.state) if args.verbose == 0 or args.verbose == 3: Models().print_aggregates(Propagator.state, Propagator.symbols) ## Get the last key from state current_state_key = len(Propagator.state[0].keys()) ## For round 2 or more while True: ## While True until the search space is cut enough if len(models) >= int(args.models)*2: del models[:] ## Additional solve calls for incremental xor solve_result = control.solve(None, lambda model: models.append(model.symbols(shown=True))) ## Get xor constraints and solving rounds xor_constraints += Propagator.number_constraints total_rounds = Propagator.roundn ## Update the last key from state current_state_key += 1 if args.verbose != 1: print "" print "round %s:"%total_rounds if args.verbose == 0 or args.verbose == 2: last_state = {} last_state[current_state_key] = Propagator.state[0][current_state_key] Models().print_state([last_state]) if args.verbose == 0 or args.verbose == 3: last_state = {} last_state[current_state_key] = Propagator.state[0][current_state_key] Models().print_aggregates([last_state], Propagator.symbols) else: break if args.iterative == False: #print "do not check sat!!!!!!!!" break elif args.iterative == True: if solve_result.satisfiable: print "total rounds: %s"%round_num break else: round_num+=1 if args.incremental and args.verbose != 1: print "" print "----------------------------------------------------------" print "----------------------------------------------------------" if args.incremental: print "total rounds: %s"%total_rounds print "total xor constraints used: %s"%xor_constraints else: print "xor constraints: %s"%Propagator.number_constraints state = Propagator.state symbols = Propagator.symbols if args.verbose == 0: Models().print_state(state) Models().print_aggregates(state, symbols) print "" Models().print_results(control, solve_result, args, models) elif args.verbose == 1: Models().print_results(control, solve_result, args, models) elif args.verbose == 2: Models().print_state(state) print "" Models().print_results(control, solve_result, args, models) elif args.verbose == 3: Models().print_aggregates(state, symbols) print "" Models().print_results(control, solve_result, args, models) if args.stats: Models().print_stats(control)
import sys import clingo import copy # options files, options, max_models = [], [], 1 for i in sys.argv[1:]: if i[0] == "-": options.append(i) elif i.isdigit(): max_models = i else: files.append(i) # guess guess = clingo.Control(options + ["0"]) for i in files: guess.load(i) guess.ground([("base", [])]) # check # check = copy.deepcopy(guess)? check = clingo.Control(["0", "--enum-mode=cautious"]) for i in files: check.load(i) check.ground([("base", [])]) # gather knowledge predicates and atoms k_preds, k_atoms = set(), [] for atom in guess.symbolic_atoms.by_signature("k", 1): k_preds.add((atom.symbol.arguments[0].name,
def run_with(self, filenames:[str]=(), inline:str='', programs:iter=(['base', ()],), options:list=[]): import clingo ctl = clingo.Control(options) main = Main(propagators=self, programs=programs, inline=inline, generator=True) return main(ctl)
def load_model(self, model_path=None): ctl = clingo.Control(message_limit=0) #ctl.configuration.configuration = 'tweety' ctl.load(model_path) self.model = ctl
def reset_grounder(self): self._str_model = '' self._control = clingo.Control() if self._parser_widget is not None: self._parser_widget.update()
def __init__(self, arguments=[], **kwargs): self.cmdline_arguments = arguments self.input = "" self.control = clingo.Control(arguments, **kwargs) self.__simple = True
for root, dirs, files in os.walk(directory): split_root = root.split("/") if len(split_root)!=7: continue env = split_root[2] app = split_root[3] cons = split_root[5] instance = split_root[6] automata_file_name =f"{app}_automata.lp" if not automata_file_name in files: print(f"No automata file for {root}") continue if app=="telingo": continue file_path = os.path.join(root, automata_file_name) ctl = clingo.Control([0]) ctl.load(file_path) ctl.load("../formula_to_automaton/size.lp") ctl.ground([('base',[])]) ctl.solve(on_model= lambda m: save(env,app,cons,instance,m)) # print(dirs) # print("") # for filename in files: # print(os.path.join(root, filename)) for env,val in results.items(): file_name_csv = f'results/tables/{env}/size.csv'.format(env) file_name_tex_csv = f'results/tables/{env}/size.tex'.format(env) os.makedirs(os.path.dirname(f'results/tables/{env}/size.csv'), exist_ok=True)
def solve(self): """ Creating the program object """ program_types = clingo.Control([]) program_dynamic = clingo.Control([]) """ We want to obtain ALL possible stable models """ program_types.configuration.solve.models = 0 program_dynamic.configuration.solve.models = 0 """ We initialize data structures """ action_list = [] fluent_list = [] initial_states = [] """ Reading from the input file """ try: program_types.load(self.file_name) except RuntimeError: return try: program_dynamic.load(self.file_name) except RuntimeError: raise RuntimeError """ We obtain fluents, actions and the initial state """ try: program_types.ground([('initial', []), ('types', [0]), ('static', [])]) except RuntimeError: raise RuntimeError models = program_types.solve(yield_=True) for element in models: initial_state = [] for atom in element.symbols(atoms=True): if 'action' in str(atom): action_list.append( clingo.Function( TFG.src.main.model.util.atomutils.obtain_dynamic( str(atom)))) elif 'fluent' in str(atom): fluent_list.append( clingo.Function( TFG.src.main.model.util.atomutils.obtain_dynamic( str(atom)))) elif ((clingo.Function(str(atom))) in fluent_list) or ( (clingo.Function(str(atom))) in action_list): initial_state.append(clingo.Function(str(atom))) initial_states.append(initial_state) if len(initial_states) > 1: print('Warning: several answer sets obtained as initial state') """ We add as external atoms all the possible fluents and actions """ for atom in fluent_list: program_dynamic.add('fluents', [], "#external" + " " + str(atom) + ".") for atom in action_list: program_dynamic.add('actions', [], "#external" + " " + str(atom) + ".") try: program_dynamic.ground([('fluents', []), ('actions', []), ('dynamic', [1]), ('static', []), ('final', [1])]) except RuntimeError: raise RuntimeError """ Delegates to its search algorithm """ self.search_algorithm.add_domain(program_dynamic) self.search_algorithm.search(initial_states[0], self.fringe, action_list, fluent_list, self.heuristic, self.bfs, self.states)
def learn_ini(self): buffer = [] rule_index = 1 for line in self.aspProgram.splitlines(): if line.startswith('@getWeight'): self.weightsDic[str(rule_index)] = { 'wIndex': rule_index, 'weight': 0, 'n': 0, 'nii': 0, 'atomName': str(line.split(' ')[1]).split('(')[0], 'gradient': [], } self.weightsDic[str(rule_index)]['weight'] += self.init_weight buffer.append( str(self.weightsDic[str(rule_index)]['weight']) + ' ' + ''.join(line.split(' ')[1:])) else: buffer.append(line) if "".join(line.split()) != "": rule_index += 1 for line in buffer: self.progranWithoutPlaceholder += line + "\n" # Done on creating weight file, and initializing dictionary content = processor.lpmln_to_asp_parser(self.progranWithoutPlaceholder) finalout = processor.asp_domain_2_asp_parser(content) warn_option = "--warn=none" thread_option = "-t 4" options = [warn_option, thread_option] sampling_control = clingo.Control(options) sampling_control.add("base", [], finalout) sampling_control.ground([("base", [])]) symbols = [atom.symbol for atom in sampling_control.symbolic_atoms] for s in symbols: for key, value in self.weightsDic.items(): if s.name == value['atomName']: value['n'] += 1 xorSampler = xor_constraint_drawer.xorSampler( self.xorMode, [finalout, self.evidence], self.clingoOptions) models = xorSampler.startDrawSample() if len(models) > 1: # randomly generate a index from models randomIndex = random.randint(0, len(models) - 1) model = models[randomIndex] else: model = models[0] finalModels = [] finalModels.append(model) for model in finalModels: for atom in model: if str(atom.name) == "unsat": idx = eval(str(atom.arguments[0])) for key, value in self.weightsDic.items(): if value['wIndex'] == idx: value['nii'] += 1
def solve_sudoku_ASP(sudoku, k): # First we create a list containing all the edges for all vertices in the sudoku length = len(sudoku) num_vertices = length**2 matrix = np.arange(num_vertices).reshape(length, length) # edges = {'squares':[], 'rows':[], 'columns':[]} edges = [] sudoku = np.array(sudoku).reshape(length * length) # The loop below fills the edges list with all edges in the sudoku for i in range(length): for j in range(length): # specify the current value i,j as the left-hand value for the edge tuple left = int(matrix[i][j] + 1) # iterate over values in the square col = j // k row = i // k rows = matrix[(row * k):(row * k + k)] box = [x[(col * k):(col * k + k)] for x in rows] for v in range(k): for w in range(k): right = int(box[v][w] + 1) # make sure that we're not assigning the current value as the right-hand vertix if (row * k + v, col * k + w) != (i, j): if (right, left) not in edges: edges.append((left, right)) # iterative over cells in row i, for g in range(length): right = int(matrix[i][g] + 1) if (i, g) != (i, j): if (right, left) not in edges: edges.append((left, right)) # iterate over cells in column j, for c in range(length): right = int(matrix[c][j] + 1) if (c, j) != (i, j): if (right, left) not in edges: # edges['columns'].append((left, right)) edges.append((left, right)) # We encode the graph in ASP asp_code = "" for i in range(1, num_vertices + 1): asp_code += '\n\tvertex(v{}).'.format(i) for (i, j) in edges: asp_code += '\n\tedge(v{},v{}).'.format(i, j) asp_code += '\n\t' for value in range(1, length + 1): rule = 'value(V,{}) :- vertex(V)'.format(value) for i in range(1, length + 1): if i != value: rule += ', not value(V,{})'.format(i) rule += '.' asp_code += """{}\n\t""".format(rule) # for value in range(1, length+1): # rule = 'value(V,{}) :- vertex(V), not color (V,2), not color (V,3)' # print_answer_sets(""" # choice(1..{}). # choose(X,a) :- not choose(X,b), choice(X). # choose(X,b) :- not choose(X,a), choice(X). # """.format(k)) for i in range(length**2): # if i == : # break if sudoku[i] != 0: val = sudoku[i] asp_code += '\n\tvalue(v{},{}) :- vertex(v{}).'.format( i + 1, val, i + 1) asp_code += """ :- edge(V1,V2), value(V1,C), value(V2,C). """ # asp_code += """ # value(v1,2) :- vertex(v1). # """ asp_code += """ #show value/2. """ # asp_code_2 = '' # # asp_code_2 += """ # vertex(v1). # vertex(v2). # vertex(v3). # vertex(v4). # edge(v1,v2). # edge(v1,v3). # edge(v2,v3). # edge(v2,v4). # edge(v3,v4). # """; # # asp_code_2 += """ # color(V,1) :- vertex(V), not color(V,2), not color(V,3). # color(V,2) :- vertex(V), not color(V,1), not color(V,3). # color(V,3) :- vertex(V), not color(V,1), not color(V,2). # """ # # asp_code_2 += """ # :- edge(V1,V2), color(V1,C), color(V2,C). # """ # # asp_code_2 += """ # #show color/2. # """ # # print(asp_code) # # print(asp_code_2) # print_answer_sets(asp_code) control = clingo.Control() control.add("base", [], asp_code) control.ground([("base", [])]) def on_model(model): model.symbols(shown=False) control.configuration.solve.models = 1 answer = control.solve(on_model=on_model) if answer.satisfiable: solution = [] with control.solve(yield_=True) as handle: for model in handle: # solution.append(model.symbols(shown=True)) for atom in model.symbols(shown=True): solution.append(str(atom)) solution.sort(key=lambda x: int(x.split(',')[0].split('(v')[-1])) result = np.ones(length**2, dtype=int) for i, vertex in enumerate(solution): res = vertex[:-1].split(',')[-1] res = int(res) result[i] = res result = result.reshape(length, length).tolist() return result else: return None
def main(): ## Parse input data args = parse_params() ## Check for input errors check_input(args) # Input data ## STFT parameters sr = 44100.0 # Sample Rate N = args.samples # FFT size or Number of Samples M = N # Window size H = int(M / 64) # Hop size B = args.erb # ERB Bands low_lim = 20 # centre freq. of lowest filter high_lim = sr / 2 # centre freq. of highest filter threshold = args.essential_threshold # Essential bands analyze = args.analyze # Extract audio features or use instances in dir s = args.s q = args.q benchmark = args.benchmarks solve = not benchmark ## ASP variables project = args.project #project name models = [] # answer sets tracks = [] tracks_duration = [] ## Read wav files from project print("Reading tracks...") for fl in os.listdir("projects/%s/" % project): if fl.endswith(".wav"): tracks.append(os.path.splitext(fl)[0]) if analyze: t = "projects/%s/%s.wav" % (project, os.path.splitext(fl)[0]) with contextlib.closing(wave.open(t, 'r')) as f: frames = f.getnframes() rate = f.getframerate() duration = frames / float(rate) tracks_duration.append(duration) if analyze: duration = int(round(max(tracks_duration))) print("Mixdown duration (secs): %s" % duration) ## create tracks instance lp ## get audio features and create each track_name.lp file file_params = "S%s_B%s_ET%s_MF%s" % (N, B, args.essential_threshold, args.masking_factor) ## Create clingo object and load instances ## Add arguments if solve: clingo_args = [ "--sign-def=rnd", "--sign-fix", "--rand-freq=1", "--seed=%s" % random.randint(0, 32767), "--restart-on-model", "--enum-mode=record" ] control = clingo.Control(clingo_args) ## Load eq.lp control.load("lp/eq.lp") ## for each track track_number = 1 frequencies = [] spectrums = [] erbs = [] filters = [] for track in tracks: if analyze: print(" Building instance: %s" % track) ## Get spectrum and signal size spectrum, len_signal = af.get_spectrum( "projects/%s/%s" % (project, track), sr, N, M, H) # Equivalent Rectangular Bandwidth erb_bands, bandwidths, frequencies, center_fr, filters = af.get_erb_bands( spectrum, len_signal, sr, B, low_lim, high_lim) # Save data for plotting spectrums.append(spectrum) erbs.append(erb_bands) # ASP instances instance = "projects/%s/%s.lp" % (project, track) if analyze: ## If not benchmark file = open(instance, "w") af.build_asp_instance(file, track_number, instance, erb_bands, threshold) file.close() if solve: control.load("projects/%s/%s.lp" % (project, track)) track_number += 1 # Build mixdown graphics if analyze: print("Building graphics...") af.build_graphics(frequencies, spectrums, "projects/%s" % (project), project, erbs, B, filters, tracks, False) ## Number of mixes if solve: control.configuration.solve.models = args.mixes ## Add masking factor control.add( "p", [], "#const masking_factor = %s." % int(args.masking_factor * 100)) ## Ground print("Grounding...") control.ground([("base", [])]) control.ground([("p", [])]) ## Solve if s >= 0: print("Propagator Registered for Sampling") control.register_propagator(Propagator(s, q)) print("Solving...") solve_result = control.solve( None, lambda model: models.append(model.symbols(shown=True))) if str(solve_result) == "SAT": print("%s, Exhausted: %s" % (solve_result, solve_result.exhausted)) print(models) print("") results_path = "%s/results/" % ("projects/%s" % (project)) dir = os.path.dirname(results_path) if not os.path.exists(dir): os.makedirs(dir) file = open("%s/plan_%s.txt" % (results_path, file_params), "w") for answer in models: answer_number = models.index(answer) + 1 print("Answer: %s" % answer_number) #Plan file.write("Answer: %s \n" % answer_number) eqs = af.parse_answer_sets_to_plan(file, tracks, answer, center_fr, bandwidths) file.write("\n") #Csound csound_file = "Answer_%s_mixdown_%s.csd" % (answer_number, file_params) file_csd = open("%s/%s" % (results_path, csound_file), "w") csd.create_header(file_csd, results_path, csound_file) for i in range(len(tracks)): if (i + 1) in eqs: ## Create csound instrument with EQs csd.create_instrument(file_csd, i + 1, eqs[(i + 1)]) else: ## Create csound instrument without EQ csd.create_instrument(file_csd, i + 1, None) # Csound Bridge between Orchestra and Scores csd.create_bridge(file_csd) # Csound Orchestra for i in range(len(tracks)): csd.create_orchestra(file_csd, (i + 1), tracks[i], duration) # Csound Footer csd.create_footer(file_csd) # Close file file_csd.close() # Render csound files #if args.normalize: # print("normalize tracks") csd.render(results_path, csound_file) print("") file.close() else: print( "No masking detected for the given values masking-factor and/or essential-threshold" ) if benchmark: ## Create a single file instance with the masking factor constant and with all the sub instances of the project print("Generating Benchmarks")
# ctr(I, K):- ctr(I-1, K), not_item(I). # :- ctr(u, K), K > m. # :- ctr(u, K), K < n. # ctr(0, 0). # """ ################################### asp_code += """binary(1..10). { choice(X): binary(X)}. #show choice/1.\n """ print(asp_code) control = clingo.Control() control.add("base", [], asp_code) control.ground([("base", [])]) def on_model(model): print(model.symbols(shown=True)) control.configuration.solve.models = 0 answer = control.solve(on_model=on_model) if answer.satisfiable: print("satisfiable:") else: print("unsatisfiable")
def __init__(self, args): self.control = clingo.Control() self.args = args self.numberOfMachines = 0 self.numberOfJobs = 0
def execute(pcontext, rewritten, facts, plugins, config): # prepare contexts that are for this program but not yet specific for a clasp solver process # (multiple clasp solvers are used for finding compatible sets and for checking FLP property) # preparing clasp context which does not hold concrete clasp information yet # (such information is added during propagation) ccontext = ClaspContext() # preparing evaluator for external atoms which needs to know the clasp context #eaeval = EAtomEvaluator(ccontext) eaeval = CachedEAtomEvaluator(ccontext) # find names of external atoms that advertises to do checks on a partial assignment partial_evaluation_eatoms = [ eatomname for eatomname, info in dlvhex.eatoms.items() if info.props.provides_partial ] # XXX we could filter here to reduce this set or we could decide to do no partial evaluation at all or we could do this differently for FLP checker and Compatible Set finder should_do_partial_evaluation_on = partial_evaluation_eatoms propagatorFactory = lambda name: ClingoPropagator(name, pcontext, ccontext, eaeval, should_do_partial_evaluation_on) if config.flpcheck == 'explicit': flp_checker_factory = flp.ExplicitFLPChecker else: assert(config.flpcheck == 'none') flp_checker_factory = flp.DummyFLPChecker flpchecker = flp_checker_factory(propagatorFactory) # TODO get settings from commandline cmdlineargs = [] if config.number != 1: cmdlineargs.append(str(config.number)) # just in case we need optimization cmdlineargs.append('--opt-mode=optN') cmdlineargs.append('--opt-strategy=usc,9') logging.info('sending nonground program to clingo control') cc = clingo.Control(cmdlineargs) sendprog = shp.shallowprint(rewritten) try: logging.debug('sending program ===\n'+sendprog+'\n===') cc.add('base', (), sendprog) except: raise Exception("error sending program ===\n"+sendprog+"\n=== to clingo:\n"+traceback.format_exc()) # preparing context for instantiation # (this class is specific to the gringo API) logging.info('grounding with gringo context') ccc = GringoContext(eaeval) flpchecker.attach(cc) cc.ground([('base',())], ccc) logging.info('preparing for search') # name of this propagator CSF = compatible set finder checkprop = propagatorFactory('CSF') cc.register_propagator(checkprop) mr = ModelReceiver(facts, config, flpchecker) logging.info('starting search') cc.solve(on_model=mr) # TODO return code for unsat/sat/opt? return 0
('fixed', len(ba.label) + 4, ba), ('fixed', len(bb.label) + 4, bb), sf ], 1) f = urwid.Frame(urwid.Filler(c.display), None, b, 'footer') palette = [ ('red', 'black', 'light red'), ('green', 'black', 'light green'), ('blue', 'black', 'light blue'), ] self.loop = urwid.MainLoop(f, palette) self.loop.run() c = clingo.Control() c.add("check", ["k"], "#external query(k).") for f in sys.argv[1:]: c.load(f) def make_on_model(field, stone, move, target): def on_model(m): for atom in m.symbols(atoms=True): if atom.name == "field" and len(atom.arguments) == 2: x, y = [n.number for n in atom.arguments] field.append((x, y)) elif atom.name == "stone" and len(atom.arguments) == 5: s, d, x, y, l = [(n.number if n.type == clingo.SymbolType.Number else str(n)) for n in atom.arguments]
def solve_planning_problem_using_ASP(planning_problem, t_max): """ Parameters: planning_problem (PlanningProblem): Planning problem for which a shortest plan is to be found. t_max (int): The upper bound on the length of plans to consider. Returns: (list(Expr)): A list of expressions (each of which specifies a ground action) that composes a shortest plan for planning_problem (if some plan of length at most t_max exists), and None otherwise. """ def encode_init_ASP(planning_problem, t_max): """ Method for encoding the initial statements into ASP input: planning problem in PDDL returns: planning problem in ASP encoding """ #encode t_max time steps asp_code = "" asp_code += "#const tMax={}.\n".format(t_max - 1) asp_code += "time(0..tMax).\n" #encode initial statements as state(T, init(x,y)) for T=0 #swapcase used to switch caps and lowercase for different representation #of variables and constants in DPPL vs ASP for init in planning_problem.initial: asp_code += "state(0, {}).\n".format(init.__repr__().swapcase()) return asp_code def encode_actions_ASP(planning_problem): """ Method for encoding the actions into ASP input: planning problem in PDDL returns: planning problem in ASP encoding """ asp_code = "" for action in planning_problem.actions: available_action = "available(Time, {}) :- not goal_saved(Time), time(Time)".format( action.__repr__().swapcase()) if not action.precond: available_action = available_action else: for prec in action.precond: if str( prec )[0] == '~': #check if a negation is present to alter rule to not state prec = expr(str(prec)[1:]) available_action += ", not state(Time, {})".format( prec.__repr__().swapcase()) else: available_action += ", state(Time, {})".format( prec.__repr__().swapcase()) fluent = "state(Time, S) :- time(Time), state(Time-1, S), chosen(Time-1, {})".format( action.__repr__().swapcase()) effect = "" for effects in action.effect: if str( effects )[0] == '~': #check if a negation is present to alter rule to not same fluent += ", S!={}".format(str(effects)[1:].swapcase()) else: effect += "state(Time, {}) :- time(Time), chosen(Time-1, {}). \n".format( effects.__repr__().swapcase(), action.__repr__().swapcase()) available_rule = "1{chosen(Time, A) : available(Time, A)}1 :- time(Time), available(Time, _). \n" asp_code += effect + fluent + ". \n" + available_action + ". \n" + available_rule return asp_code def encode_goals_ASP(planning_problem): """ Method for encoding the goals into ASP input: planning problem in PDDL returns: planning problem in ASP encoding """ asp_code = "" goallist = [] for goal in planning_problem.goals: if str( goal )[0] == '~': #check if a negation is present to alter rule to not state goal = expr(str(goal)[1:]) goallist += [ "not state(Time, {})".format(goal.__repr__().swapcase()) ] else: goallist += [ "state(Time, {})".format(goal.__repr__().swapcase()) ] #add all goal rules, constraints and optimizations asp_code += "goal(Time) :- " + "{}. \n".format(', '.join(goallist)) asp_code += "goal_saved(Time) :- goal(Time). \n" asp_code += "goal_saved(Time) :- time(Time), goal_saved(Time-1). \n" #constraint asp_code += ":- time(Time), not goal(_). \n" #optimization statement asp_code += "#minimize{Time : goal(Time)}. \n" #show the chosen in answer set asp_code += '#show chosen/2. \n' return asp_code def return_plan(sorted_model): """ Method to extract the planning from the model Probably not the best way to do it but could not fix it otherwise """ plan_length = len(sorted_model) #used to order list according to T in chose(T, A) plan = [None] * plan_length for plans in sorted_model: #find all words in the plan words = re.findall(r'\w+', plans) #extract action action = words[2].swapcase() #extract arguments arguments = [word.swapcase() for word in words[3:]] plan[int(words[1])] = action + "({})".format(', '.join(arguments)) return plan def on_model(model): """ check if optimal model, if optimal model, sort results and return planning """ if model.optimality_proven == True: model = [str(atom) for atom in model.symbols(shown=True)] model.sort() global planning planning = return_plan(model) #create the ASP encoding asp_code = "" asp_code += encode_init_ASP(planning_problem, t_max) asp_code += encode_actions_ASP(planning_problem) asp_code += encode_goals_ASP(planning_problem) #solve the ASP encoding control = clingo.Control() control.add("base", [], asp_code) control.ground([("base", [])]) #optimization statements, show 1 model control.configuration.solve.opt_mode = "optN" control.configuration.solve.models = 1 #need this to get planning back, must be another way to extract from clingo.model answer = control.solve(on_model=on_model) #return None if no plan else return planning return planning
def __init__(self, args): self.control = clingo.Control() self.args = args self.horizon = 0 self.objects = 0 self.end = None
def test_control_model_integration(self): spu = SymbolPredicateUnifier() @spu.register class Afact(Predicate): num1 = IntegerField() num2 = IntegerField() str1 = StringField() @spu.register class Bfact(Predicate): num1 = IntegerField() str1 = StringField() af1 = Afact(1, 10, "bbb") af2 = Afact(2, 20, "aaa") af3 = Afact(3, 20, "aaa") bf1 = Bfact(1, "aaa") bf2 = Bfact(2, "bbb") fb1 = FactBase() fb1.add([af1, af2, af3, bf1, bf2]) fb2 = None def on_model(model): nonlocal fb2 self.assertTrue(model.contains(af1)) self.assertTrue(model.contains(af1.raw)) self.assertTrue(model.model_.contains(af1.raw)) fb2 = model.facts(spu, atoms=True) # Check that the known attributes behave the same as the real model self.assertEqual(model.cost, model.model_.cost) self.assertEqual(model.number, model.model_.number) self.assertEqual(model.optimality_proven, model.model_.optimality_proven) self.assertEqual(model.thread_id, model.model_.thread_id) self.assertEqual(model.type, model.model_.type) # Note: the SolveControl object returned is created dynamically on # each call so will be different for both calls. So test that the # symbolic_atoms property is the same. sas1 = set(model.context.symbolic_atoms) sas2 = set(model.model_.context.symbolic_atoms) self.assertEqual(len(sas1), len(sas2)) # Test that clorm.clingo.Model produces the correct string self.assertEqual(str(model), str(model.model_)) self.assertEqual(repr(model), repr(model.model_)) # Use the orignal clingo.Control object so that we can test the wrapper call ctrlX_ = oclingo.Control() ctrl = cclingo.Control(control_=ctrlX_) ctrl.add_facts(fb1) ctrl.ground([("base", [])]) ctrl.solve(on_model=on_model) # Check that the known control attributes behave the same as the real control cfg1 = ctrl.configuration cfg2 = ctrl.control_.configuration self.assertEqual(len(cfg1), len(cfg2)) self.assertEqual(set(cfg1.keys), set(cfg2.keys)) sas1 = set(ctrl.symbolic_atoms) sas2 = set(ctrl.control_.symbolic_atoms) self.assertEqual(len(sas1), len(sas2)) self.assertEqual(ctrl.is_conflicting, ctrl.control_.is_conflicting) stat1 = ctrl.statistics stat2 = ctrl.control_.statistics self.assertEqual(len(stat1), len(stat2)) tas1 = ctrl.theory_atoms tas2 = ctrl.control_.theory_atoms self.assertEqual(len(list(tas1)), len(list(tas2))) # _control_add_facts works with both a list of facts (either # clorm.Predicate or clingo.Symbol instances) and a FactBase ctrl2 = Control() ctrl2.add_facts([af1, af2, af3.raw, bf1.raw, bf2]) safact1 = fb2.select(Afact).where(Afact.num1 == ph1_) safact2 = fb2.select(Afact).where(Afact.num1 < ph1_) self.assertEqual(safact1.get_unique(1), af1) self.assertEqual(safact1.get_unique(2), af2) self.assertEqual(safact1.get_unique(3), af3) self.assertEqual(set(list(safact2.get(1))), set([])) self.assertEqual(set(list(safact2.get(2))), set([af1])) self.assertEqual(set(list(safact2.get(3))), set([af1, af2])) self.assertEqual( fb2.select(Bfact).where(Bfact.str1 == "aaa").get_unique(), bf1) self.assertEqual( fb2.select(Bfact).where(Bfact.str1 == "bbb").get_unique(), bf2)
import clingo def mop(m: clingo.Model): av = set() for symbol in m.symbols(shown=True): # We expect atoms of the form `currentExecutable(move(X, Y)` # but we are only interested in the first argument `move(X, Y)` #av.add(str(symbol.arguments[0])) sym = str(symbol) av.add(sym) print(sorted(av)) def mip(m: clingo.Model): print(m) def mep(m: clingo.Model): mip(m) mop(m) ctr = clingo.Control() ctr.load("SimpleClingo.lp") #ctr.load("frozenLake4x4.lp") ctr.ground([("base", [])]) ctr.solve(on_model=mep)
def test_control_and_model_wrapper(self): # Test a control wrapper of a wrapper ctrl0 = oclingo.Control() ctrl1 = cclingo.Control(control_=ctrl0) ctrl2 = cclingo.Control(control_=ctrl1) ctrl2.ground([("base", [])]) with ctrl2.solve(yield_=True) as sh: tmp = [m.facts(unifier=[], atoms=True) for m in sh] self.assertEqual(len(tmp), 1) self.assertEqual(len(tmp[0]), 0) # Test a model wrapper ctrl = oclingo.Control() ctrl.ground([("base", [])]) with ctrl.solve(yield_=True) as sh: for n, m_ in enumerate(sh): self.assertEqual(n, 0) m = cclingo.Model(model=m_, unifier=[]) self.assertEqual(len(m.facts()), 0) # Test wrapping a bad object - missing attributes and functions # Missing ground function with self.assertRaises(AttributeError) as ctx: class Bad(object): def solve(self): pass bad = Bad() ctrl = cclingo.Control(control_=bad) check_errmsg("'Bad' object has no attribute 'ground'", ctx) # Missing solve function with self.assertRaises(AttributeError) as ctx: class Bad(object): def ground(self): pass bad = Bad() ctrl = cclingo.Control(control_=bad) check_errmsg("'Bad' object has no attribute 'solve'", ctx) # Ground is an attribute but not a function with self.assertRaises(AttributeError) as ctx: class Bad(object): def __init__(self): self.ground = 4 def solve(self): pass bad = Bad() ctrl = cclingo.Control(control_=bad) check_errmsg(("Wrapped object of type '{}' does not have a " "function 'ground()'").format(type(bad)), ctx) # Solve is an attribute but not a function with self.assertRaises(AttributeError) as ctx: class Bad(object): def __init__(self): self.solve = 4 def ground(self): pass bad = Bad() ctrl = cclingo.Control(control_=bad) check_errmsg(("Wrapped object of type '{}' does not have a " "function 'solve()'").format(type(bad)), ctx) # Model wrapper with no "symbols" function or attribute with self.assertRaises(AttributeError) as ctx: class Bad(object): def __init__(self): self.symbols = 2 bad = Bad() m = cclingo.Model(model=bad) check_errmsg(("Wrapped object of type '{}' does not have a " "function 'symbols()'").format(type(bad)), ctx) with self.assertRaises(AttributeError) as ctx: class Bad(object): def __init__(self): pass bad = Bad() m = cclingo.Model(model=bad) check_errmsg("'Bad' object has no attribute 'symbols'", ctx)
def learn(self, list_of_obs, num_of_samples=50, lr=0.01, thres=0.0001, max_iter=None, num_pretrain=5): time_init = time.time() check_continue = True # Step 1: Parameter Pre-training: we pretrain the parameters # so that it's easier to generate sample stable models assert type(num_pretrain) is int if num_pretrain >= 1: if self.args.verbosity >= 6: print( "\n#######################################################\nParameter Pre-training for {} iterations...\n#######################################################" .format(num_pretrain)) for iteration in range(num_pretrain): if self.args.verbosity >= 6: print( "\n#### Iteration {} for Pre-Training ####\nGenerating 1 stable model for each observation...\n" .format(iteration + 1)) dif = lr * self.gradients_multi_obs_by_one_sample(list_of_obs) self.parameters = (np.array(self.parameters) + dif).tolist() self.normalize_probs() if self.args.verbosity >= 6: print("After {} seconds of training (in total)".format( time.time() - time_init)) print("Current parameters: {}".format(self.parameters)) # For each observation, decide which observation uses learn exact or learn sample learn_obs_decider = [] for obs in list_of_obs: crl = clingo.Control(['0', "--warn=none"]) crl.add("base", [], self.pi_prime + obs) crl.ground([("base", [])]) with crl.solve(yield_=True) as handle: counter = 0 for m in handle: counter += 1 if counter == 2500: break if counter == 2500: learn_obs_decider.append('sample') else: learn_obs_decider.append('exact') if self.args.verbosity >= 6: print("Leraning from Observations Decider: ", learn_obs_decider) self.all_SM_under_obs = {} for i, method in enumerate(learn_obs_decider): if method == 'exact': self.all_SM_under_obs[i] = self.find_all_SM_under_obs( list_of_obs[i]) iteration = 1 while check_continue: if self.args.verbosity >= 4: print("\n#### Iteration {} ####".format(iteration)) old_parameters = np.array(self.parameters) check_continue = False total_dif = np.array([[0.0 for item in l] for l in self.parameters]) for i, obs in enumerate(list_of_obs): if learn_obs_decider[i] == 'sample': dif = lr * self.gradients_multi_obs_by_sampling( [obs], num=num_of_samples) else: dif = lr * self.gradients_one_obs(i) for ruleIdx, list_of_bools in enumerate(self.learnable): # 1st, we turn each gradient into [-0.2, 0.2] for atomIdx, b in enumerate(list_of_bools): if b == True: if dif[ruleIdx][atomIdx] > 0.2: dif[ruleIdx][atomIdx] = 0.2 elif dif[ruleIdx][atomIdx] < -0.2: dif[ruleIdx][atomIdx] = -0.2 total_dif += dif self.parameters = (np.array(self.parameters) + total_dif).tolist() self.normalize_probs() if self.args.verbosity >= 6: print("After {} seconds of training (in total)".format( time.time() - time_init)) print("Current parameters: {}".format(self.parameters)) # we termintate if the change of the parameters is lower than thres dif = np.array(self.parameters) - old_parameters dif = abs(max(dif.min(), dif.max(), key=abs)) if self.args.verbosity >= 6: print("Max change on probabilities: {}".format(dif)) iteration += 1 if dif > thres: check_continue = True if max_iter is not None: if iteration > max_iter: check_continue = False if self.args.verbosity >= 4: print("Final parameters: {}".format(self.parameters)) self.write_final_program()
def solve_sudoku_ASP(sudoku: List[List[int]], k: int) -> Union[List[List[int]], None]: """Solve a k-by-k block Sudoku puzzle by encoding it as an answer set programming (ASP) problem and using an ASP solver :param sudoku: A Sudoku puzzle represented as a list of lists. Values to be filled in are set to zero (0) :type sudoku: List[List[int]] :param k: Size of the Sudoku puzzle (a grid of k x k blocks) :type k: int :return: The solved sudoku puzzles as a list of lists or None if no solution is found. :rtype: Union[List[List[int]], None] """ ### ### Solution Notes ### ### Inspiration from the following references: ### - Chapter 3 of Answer Set Solving in Practice ### - 'block' helper function retrieved from the blog of Enrico Höschler: ### https://ddmler.github.io/asp/2018/07/10/answer-set-programming-sudoku-solver.html ### ### sudoku(R, C, V) denotes a sudoku cell at a row index (R) and column index (C) filled with value (V) ### ### There are n == k**2 such rows, columns, and values ### ### Rows and columns are indexed at zero (0). Values start at one (1) ### ### Constraints: ### - Cardinality and Choice: Each cell must have exactly one value in the domain [1,n] ### - Integrity: No cell in the same row may share a value ### - Integrity: No cell in the same column may share a value ### - Integrity: No cell in the same block may share a value solved_sudoku = copy(sudoku) grid_size = k**2 # Build a string where each line is the fact corresponding to a pre-filled cell facts = '' for row_index, column_index in get_cell_indices(k): value = solved_sudoku[row_index][column_index] if value != 0: facts += f'sudoku({row_index}, {column_index}, {value}).\n' # As noted above, this was inspired by Enrico Höschler's blog # The rule applies if two cells are in the same block same_block_rule = 'block(R1, C1, R2, C2) :- row(R1), row(R2), column(C1), column(C2), R1/k == R2/k, C1/k == C2/k.' # Constraints cell_uniqueness = '1{sudoku(R, C, V): value(V)}1 :- row(R) , column(C).' row_integrity = ':- sudoku(R, C1, V), sudoku(R, C2, V), C1 != C2.' column_uniqueness = ':- sudoku(R1, C, V), sudoku(R2, C, V), R1 != R2.' block_uniqueness = ':- sudoku(R1, C1, V), sudoku(R2, C2, V), block(R1, C1, R2, C2), R1 != R2, C1 != C2.' asp_program = f""" #const k = {k}. #const n = {grid_size}. row(0..n-1). column(0..n-1). value(1..n). {facts} {same_block_rule} {cell_uniqueness} {row_integrity} {column_uniqueness} {block_uniqueness} """ # Fill in the puzzle once an answer set is found def on_model(model): for atom in model.symbols(atoms=True): if atom.name == 'sudoku': row_index, column_index, value = atom.arguments solved_sudoku[row_index.number][column_index.number] = value.number # Encode and solve control = clingo.Control() control.add("base", [], asp_program) control.ground([("base", [])]) control.configuration.solve.models = 1 # we only need one feasible solution answer = control.solve(on_model=on_model) if not answer.satisfiable: return None return solved_sudoku
if self.trace: print(" NEXT: ", self.trace[0]["state"], self.trace[0]["thread_id"]) self.cv.notify_all() self.cv.release() def propagate(self, control, changes): self.run_trace(control, control.thread_id, "propagate") def check(self, control): self.run_trace(control, control.thread_id, "check") if __name__ == "__main__": ctl = clingo.Control(["-t3", "0"]) ctl.register_propagator(Retracer()) print("============ STEP 1 ============") ctl.add( "step1", [], """\ #theory cp { sum_term { }; &minimize/0 : sum_term, directive }. &minimize { x }. """) ctl.ground([("step1", [])]) n = 0 for m in ctl.solve(yield_=True):
#!/usr/bin/env python import clingo def om(m): print "Model: " + str(m.atoms()) #init prg=clingo.Control("0") prg.add("base",[],"{a}. b :- a. #external base_e.") prg.ground([("base",[])]) prg.assign_external(clingo.Function("base_e"), True) print prg.solve(om, None) #assert new_e1 print "?- assert new_e1." prg.add("ext1",[],"#external new_e1.") prg.ground([("ext1",[])]) prg.assign_external(clingo.Function("new_e1"), True) print prg.solve(om, None) #assert new_e2. print "?- assert new_e2." prg.add("ext2",[],"#external new_e2.") prg.ground([("ext2",[])]) prg.assign_external(clingo.Function("new_e2"), True) print prg.solve(om, None) #retract new_1. print "?- retract new_1." prg.release_external(clingo.Function("new_e1"))
import clingo cc = clingo.Control([]) cc.load("./simple.lp") solution = cc.solve() print(str(solution))
import sys def inject_one(val): return clingo.create_num(val.num() + val.num()) def inject_two(val): return [val, clingo.create_num(val.num() + val.num())] def on_model(m): print m c = clingo.Control(sys.argv) c.add( "base", [], "#external c. a :- c. a :- not b. b :- not a. r(@inject_one(2)). r(@inject_two(3)). #program p(k). q(k)." ) c.ground([("base", []), ("p", [clingo.create_num(17)])], sys.modules[__name__]) print c.solve(on_model=on_model) vals = [ clingo.create_id("p"), clingo.create_str("q"), clingo.create_num(42), clingo.Sup, clingo.Inf ] vals.append(clingo.create_fun("f", vals, True)) vals.append(clingo.create_fun("", vals)) print vals