def get_speculative_worlds(self, takenMoves): potentialMovesByOthers = {} tempKb = self.copy() for i in takenMoves.keys(): if i == self._player: tempKb += Term('does', i, takenMoves[i].args[1]) potentialMovesByOthers[i] = { Term('thinks_move', self._player, Term('does', i, takenMoves[i].args[1])): 1 } else: potentialMovesByOthers[i] = self.query(\ [Term('thinks_move', self._player, \ Term('does', i, Var('_')))], kb=tempKb, prob_override=1) potentialMoveSequences = \ self._processMoveSequences(\ itertools.product(*[[(key, val) for (key, val) in potentialMovesByOthers[key].items()] \ for key in potentialMovesByOthers.keys()])) successorWorlds = [] for moves, seqProb in potentialMoveSequences: copyKb = tempKb.extend() for m in moves: copyKb += m nextState = map(lambda a: Term('ptrue', a.args[0]) if a.args[0].functor != "thinks" else a.args[0],\ self.query([Term('next', Var('_'))], kb=copyKb).keys()) potentialWorld = World(self._engine, self._baseModel, self._step + 1,\ seqProb*self._prob, set(nextState), self._player,None,) successorWorlds.append(potentialWorld) return set(successorWorlds)
def foreign_keys(a, b): args = list(a.args) bargs = list(b.args) lgg_args = [None] * len(args) lgg_bargs = [None] * len(bargs) x = 0 for i in range(len(args)): match = False for j in range(len(bargs)): if not isinstance(bargs[j], Var): if args[i] == bargs[j]: v = Var("X" + str(x)) x += 1 lgg_args[i] = v lgg_bargs[j] = v match = True break if not match: lgg_args[i] = Var("X" + str(x)) x += 1 for i in range(len(lgg_bargs)): if lgg_bargs[i] is None: lgg_bargs[i] = Var("X" + str(x)) x += 1 return Term("join", a.with_args(*lgg_args), b.with_args(*lgg_bargs))
def main(): mod = GDLIIIEngine('./examples/guess.gdliii', File_Format.PREFIX) res = {} for i in range(1, 11): res[i] = 0 res['lost'] = 0 #Choose a move for i in range(0, 1000): guesses = 0 mov = mod.get_legal_moves() mod.set_actions({'player': mov['player'][0]}) mod.update_step() while not mod.is_terminal(): mov = mod.get_legal_moves() pmoves = sorted(mov[PLAYER_NAME], key=lambda a: int(str(a.args[0]))) possible_nums = sorted( [a[1] for a in mod.query('player', Term('secret', Var('_')))], key=lambda a: int(str(a.args[0]))) num = int(str(possible_nums[round( len(possible_nums) / 2)].args[0])) - 1 mod.set_actions({'player': pmoves[num]}) mod.update_step() guesses += 1 result = mod.query('player', Term('secret', Var('_'))) if len(result) == 1: res[guesses] += 1 else: res['lost'] += 1 mod.undo_step(guesses + 1) print(f'Game {i} Complete') print(res)
def __getitem__(self, name): if name == '#': name = self._get_name(self.count) self.count += 1 return Var(name) else: return Var(name)
def getSuccessorWorlds(self, takenMoves): potentialMovesByOthers = {} tempKb = self.copy() for i in takenMoves.keys(): tempKb += Term('does', i, takenMoves[i].args[1]) if i == self._player: potentialMovesByOthers[i] = { Term('thinks_move', self._player, Term('does', i, takenMoves[i].args[1])): 1 } else: potentialMovesByOthers[i] = self.query(\ [Term('thinks_move', self._player, \ Term('does', i, Var('_')))], kb=tempKb) potentialMoveSequences = \ self._processMoveSequences(\ itertools.product(*[[(key, val) for (key, val) in potentialMovesByOthers[key].items()] \ for key in potentialMovesByOthers.keys()])) tkquery = self.query([Term('sees', self._player, Var('_'))], kb=tempKb).keys() tokens = list(map(lambda a: str(a.args[1]),tkquery)) tokens.sort() tkkey = "".join(tokens) worlds = {} for moves, seqProb in potentialMoveSequences: copyKb = tempKb.extend() for m in moves: copyKb += m potentialTokens = set(map(lambda a: a.args[1], self.query([Term('thinks', self._player, \ Term('sees', self._player, Var('_')))],kb=copyKb).keys())) move_id = list(map(lambda a: str(a.args[1]),moves)) move_id.sort() move_id = "".join(move_id) ptklist = list(map(lambda a: str(a.args[1]),potentialTokens)) ptklist.sort() ptkkey = "".join(ptklist) nextState = map(lambda a: Term('ptrue', a.args[0]) if a.args[0].functor != "thinks" else a.args[0],\ self.query([Term('next', Var('_'))], kb=copyKb).keys()) move_id = list(map(lambda a: str(a.args[1]),moves)) move_id.sort() move_id = "".join(move_id) ptklist = list(map(lambda a: str(a.args[1]),potentialTokens)) ptklist.sort() ptkkey = "".join(ptklist) potentialWorld = World(self._engine, self._baseModel, self._step + 1,\ seqProb*self._prob, set(nextState), self._player, ptkkey, move_id) if ptkkey not in worlds.keys(): worlds[ptkkey] = set() worlds[ptkkey].add(potentialWorld) return (worlds, tkkey)
def load(self, data): """Load the settings from a data file. Initializes language, target and examples. :param data: data file :type data: DataFile """ self.language.load(data) # for types and modes if self._target is None: try: target = data.query('learn', 1)[0] target_functor, target_arity = target[0].args except IndexError: raise KnownError('No target specification found!') else: target_functor, target_arity = self._target.functor, self._target.args[ 0] target_arguments = [ Var(chr(65 + i)) for i in range(0, int(target_arity)) ] self._target = Term(str(target_functor), *target_arguments) # Find examples: # if example_mode is closed, we will only use examples that are defined in the data # this includes facts labeled with probability 0.0 (i.e. negative example) # otherwise, the examples will consist of all combinations of values appearing in the data # (taking into account type information) example_mode = data.query(Term('example_mode'), 1) if example_mode and str(example_mode[0][0]) == 'auto': types = self.language.get_argument_types(self._target.functor, self._target.arity) values = [self.language.get_type_values(t) for t in types] self._examples = list(product(*values)) elif example_mode and str(example_mode[0][0]) == 'balance': # Balancing based on count only pos_examples = [ r for r in data.query(self._target.functor, self._target.arity) ] pos_count = len(pos_examples) # get no. of positive examples types = self.language.get_argument_types(self._target.functor, self._target.arity) values = [self.language.get_type_values(t) for t in types] from random import shuffle neg_examples = list(product(*values)) shuffle(neg_examples) logger = logging.getLogger(self._logger) logger.debug('Generated negative examples:') for ex in neg_examples[:pos_count]: logger.debug(Term(self._target(*ex).with_probability(0.0))) self._examples = pos_examples + neg_examples[:pos_count] else: self._examples = [ r for r in data.query(self._target.functor, self._target.arity) ] with Timer('Computing scores', logger=self._logger): self._scores_correct = self._compute_scores_correct()
def get_array_term(name, index, array): return Term( name, Constant(index), *[ Constant(array[j]) if array[j] is not None else Var("X" + str(j)) for j in range(len(array)) ])
def _generate_legal_moves(self): legalMoves = {} for player in self.worlds.keys(): legalMoves[player] = {} for world in self.worlds[player]: legalMoves[player] = world.query([Term('legal', player, Var('_'))]) break return legalMoves
def __get_possible_term_arguments_for(self, functor, argument_mode_indicators, variables_in_query_by_type: Dict[TypeName, List[Term]]): """ Returns the possible arguments of the term with the given functor and as arity the length of the given list of mode indicators. These arguments are generated using the modes of the term, unifying if necessary with the variables of the same type already in the query. :param functor: :param argument_mode_indicators: :param variables_in_query_by_type: :return: """ # INPUT e.g. 'parent', ['+', '+'], {person: A} # we will collect the possible arguments for the current functor in a list arguments = [] arity = len(argument_mode_indicators) # get the types of the arguments of the given predicate argument_types = self.get_argument_types(functor, arity) # type: TypeArguments # e.g parent/2 has argument types ['person', 'person'] # argument types are necessary for unification # a functor has multiple variables, # each with their own modes. # We have to consider each variable with its mode separately # There are three different modes for an argument: # '+': the variable must be unified with an existing variable # --> use an existing variable # '-': create a new variable, do not reuse an old one # 'c': insert a constant # NEW: '+-': the variable can be a new variable, OR it can be unified with an existing on # for each argument of functor: # check its mode # '+' --> add to arguments # a list of the variables in the rule with the same type as the current argument # e.g. arguments = [ ..., [X,Y], ...] # '-' --> add to arguments # a list containing 1 new Var # # 'c' --> add to arguments # a list of all possible constants for the type of the argument for index, (argmode, argtype) in enumerate(zip(argument_mode_indicators, argument_types)): if argmode == '+': # All possible variables of the given type #TODO: this is were key output file needs to be adapted arguments.append(variables_in_query_by_type.get(argtype, [])) elif argmode == '-': # A new variable arguments.append([Var('#')]) # what about adding a term a(X,X) where X is new? elif argmode == 'c': # Add a constant type = functor + '_' + str(index) arguments.append(self.get_type_values(type)) # arguments.append(self.get_type_values(argtype)) # pass else: raise ValueError("Unknown mode specifier '%s'" % argmode) return arguments
def test_test(self): model_string = "nn(fc,[X,Y],Z,[0,1]) :: a(X,Y,Z).\nb(X,Y,Z) :- a(X,Y,Z)." fc = FC(10, 2) net = Network(fc, 'fc', lambda a, b, c: Variable(torch.FloatTensor([0.2, 0.8]))) model = Model(model_string, [net]) query = Term('b', Constant("string with 's"), Constant(3), Var('X')) solution = model.solve(query, test=True) print(solution)
def getSuccessorWorlds(self, takenMoves): copyKb = self.copy() for i in takenMoves.keys(): copyKb += Term('does', i, takenMoves[i].args[1]) #Assumption: random player never has any thinks predicates nextState = map(lambda a: Term('ptrue', a.args[0]),\ self.query([Term('next', Var('_'))], kb=copyKb).keys()) return set([RandomWorld(self._engine, self._baseModel, self._step + 1,\ 1, set(nextState), self._player, [])])
def get_prediction_goal(self) -> Term: prediction_goal_term = Term(self.functor) nb_of_args = len(self.modes) arguments = [Var('#')] * nb_of_args prediction_goal_term = prediction_goal_term(*arguments) prediction_goal_term = prediction_goal_term.apply(TypeModeLanguage.ReplaceNew(0)) return prediction_goal_term
def main_loop(model): while(not model.terminal): playerMoves = tuple(model.getLegalMovesForPlayer(Constant(1))) randomMoves = tuple(model.getLegalMovesForPlayer(Constant(0))) model.submitAction(choice(playerMoves), Constant(1)) model.submitAction(choice(randomMoves), Constant(0)) model.applyActionsToModelAndUpdate() #For Monty Hall #print(model.query(Constant(1), Term('car', Var('_')))) #For guessing game print(model.query(Constant(1), Term('num', Var('_'))))
def apply_substitution_to_term(term: Term, substitution: Dict[str, Term]) -> Term: complete_substitution = {} # NOTE: all variables in the term need to be defined in the substitution for var in term.variables(): complete_substitution[var.name] = Var(var.name) complete_substitution.update(substitution) term_substitution = term.apply(complete_substitution) return term_substitution
def get_knows_for_worlds(self, worlds): preds = set() for w in worlds: dis_set = set() for p in w.query([Term('thinks', w._player, Var('_'))],prob_override=1): if p.functor == "thinks": tp = p.args[1] if tp.functor != "knows": dis_set.add(tp) if len(preds) == 0: preds = dis_set else: preds &= dis_set return preds
def generate_speculative_worlds(self, player, actions): knowsSet = set() total_new_worlds = {} newWorlds = set() for world in self.worlds[player]: (wd, truekey) = world.getSuccessorWorlds(actions) newWorlds = newWorlds.union(wd[truekey]) total_new_worlds[player] = self._normaliseProbability(newWorlds) #Find knowledge that is known across every state, this will derive the knows predicate res = [k for (k,v) in self.raw_query(player, Term('thinks', player, Var('_')), total_new_worlds).items() if v == 1] for p in res: t = Term('knows', p.args[0], p.args[1]) knowsSet.add(t) knowsSet.add(Term('thinks', player, t)) for w in total_new_worlds[player]: for p in knowsSet: w._preds.add(p) w._kb += p return GDLNode(total_new_worlds, self.game_data, self)
def __init__(self, data, language, target=None, logger=None, **kwargs): self._language = language if target is not None: try: t_func, t_arity = target.split('/') arguments = [] i = 0 while i < int(t_arity): arguments.append(Var(chr(65+i))) i += 1 target = Term(t_func, *arguments) except Exception: raise KnownError('Invalid target specification \'%s\'' % target) self._target = target self._examples = None self._logger = logger self._data = data self._scores_correct = None
from problog.logic import Constant, Var, Term, AnnotatedDisjunction from problog import get_evaluatable true = Term('true') ok = Term('ok') query = Term('query') p = PrologFile("Try.pl") x = [p] for i in range(0, 2): s = SimpleProgram() brand = Term('brand') ind = Term('ind') prop = Term('prop') query = Term('query') X = Var('X') ford = Term('ford') seat = Term('seat') suzuki = Term('suzuki') audi = Term('audi') fiat = Term('fiat') s = SimpleProgram() s += AnnotatedDisjunction([ prop(ind, brand, ford, p=0.222222222222222), prop(ind, brand, seat, p=0.222222222222222), prop(ind, brand, suzuki, p=0.222222222222222), prop(ind, brand, audi, p=0.222222222222222), prop(ind, brand, fiat, p=0.111111111111111) ], true) if i == 1: q = PrologFile("TryQuery.pl")
def __getitem__(self, key): return self.base.get(key, Var(key))
def __getitem__(self, key): if key == '_': self.cnt += 1 return Var('anon_%s' % self.cnt) else: return Var(key)
""" Definition of Terms, Constants and Vars used in the machine parts examples. """ from problog.logic import Term, Constant, Var # defining the terms sendback, fix, ok = \ Term('sendback'), Term('fix'), Term('ok') worn, replaceable, not_replaceable = \ Term('worn'), Term('replaceable'), Term('not_replaceable') p0, p1, class_ = \ Term('p0'), Term('p1'), Term('class') # defining the constants gear, engine, chain, wheel, control_unit = \ Constant('gear'), Constant('engine'), Constant('chain'), Constant('wheel'), Constant('control_unit') # defining the vars X = Var('X') Y = Var('Y') Z = Var('Z')
def query_transformation_digit(query): args0, _ = query.args return query(args0, Var('X'))
self._gdl_rep._randomIdentifier] is None: self._gdl_rep.submitAction( choice( tuple( self._gdl_rep.getLegalMovesForPlayer( self._gdl_rep._randomIdentifier))), self._gdl_rep._randomIdentifier) self._gdl_rep.applyActionsToModelAndUpdate() self._cur_step += 1 def is_terminal(self): return self._gdl_rep.terminal if __name__ == "__main__": mod = GDLIIIEngine('./examples/montyhall.gdliii', File_Format.INFIX) print(mod.player_names) print(mod.get_legal_moves()) mod.set_actions({'candidate': mod.get_legal_moves('candidate')[0]}) mod.update_step() print(mod.get_legal_moves()) mod.set_actions({'candidate': mod.get_legal_moves('candidate')[0]}) mod.update_step() print(mod.is_terminal()) print(mod.query('candidate', Term('car', Var("_")), 0)) print(mod.query('candidate', Term('car', Var("_")), 1)) mod.set_actions({'candidate': mod.get_legal_moves('candidate')[0]}) mod.update_step() print(mod.is_terminal()) print(mod.query('candidate', Term('car', Var("_"))))
def query_transformation_happens_at(query): args0, _, args2 = query.args return query(args0, Var('X'), args2)
def query_transformation_initiated_at(query): args0, args1 = query.args return query(args0(Var('X'), Var('Y')), args1)
def getLegalMoves(self, playerOfLegalMove): return set(map(lambda a: a.args[2], self.query([Term('thinks', self._player, Term('legal', playerOfLegalMove, Var('_')))]).keys()\ ))
ancestor(X,Y) :- parent(X,Y). ancestor(X,Y) :- ancestor(X,Z), parent(Z,Y). sibling(X,Y) :- parent(Z,X),parent(Z,Y), not(X=Y). cousin(X,Y) :- grandchild(X,Z), grandchild(Y,Z). uncle(X,Y) :- sibling(X,Z),parent(Z,Y),male(X). uncle(X,Y) :- married(X,Z),sibling(Z,P),parent(P,Y),male(X). aunt(X,Y) :- sibling(X,Z),parent(Z,Y),female(X). aunt(X,Y) :- married(X,Z),sibling(Z,P),parent(P,Y),female(X). dad(X,Y) :- parent(X,Y), male(X). mom(X,Y) :- parent(X,Y), female(X). query(parent(X,giacomo)). """) engine = DefaultEngine() db = engine.prepare( p) # This compiles the Prolog model into an internal format. # This step is optional, but it might be worthwhile if you # want to query the same model multiple times. query1 = Term('parent', [Var('X'), Constant('giacomo')]) results = engine.query(db, query1) r = get_evaluatable().create_from(p).evaluate() print(results) print(r)
# -*- coding: utf-8 -*- """ Created on Fri Jan 31 14:04:54 2020 @author: PasqualeDeMarinis """ from problog.program import SimpleProgram from problog.logic import Constant, Var, Term, AnnotatedDisjunction from problog import get_evaluatable coin, heads, tails, win, query = Term('coin'), Term('heads'), Term( 'tails'), Term('win'), Term('query') C = Var('C') p = SimpleProgram() p += coin(Constant('c1')) p += coin(Constant('c2')) p += AnnotatedDisjunction([heads(C, p=0.4), tails(C, p=0.6)], coin(C)) p += (win << heads(C)) p += query(coin(C)) r = get_evaluatable().create_from(p).evaluate() print(r)
def _generate_successor_worlds(self, actions): total_new_worlds = {} players_less_random = [_ for _ in self.game_data.players if _ != self.game_data.random_id] all_worlds = {} knowsSet = set() for i in players_less_random: all_worlds[i] = {} newWorlds = set() truekey = None for world in self.worlds[i]: (wd,truekey) = world.getSuccessorWorlds(actions) try: newWorlds = newWorlds.union(wd[truekey]) except: pass for m in wd.keys(): if m not in all_worlds[i].keys(): all_worlds[i][m] = set() all_worlds[i][m] = all_worlds[i][m].union(wd[m]) total_new_worlds[i] = self._normaliseProbability(newWorlds) #Find knowledge that is known across every state, this will derive the knows predicate res = [k for (k,v) in self.raw_query(i, Term('thinks', i, Var('_')), total_new_worlds).items() if v == 1 and k.args[1].functor != "legal"] for p in res: t = Term('knows', p.args[0], p.args[1]) knowsSet.add(t) for w in total_new_worlds[i]: for p in knowsSet: w._preds.add(Term('thinks', i, p)) w._kb += Term('thinks', i, p) for i in players_less_random: for w in total_new_worlds[i]: for p in knowsSet: w._preds.add(p) w._kb += p for i in players_less_random: #Get knowledge in every other state for m in all_worlds[i].keys(): if m != truekey: knows = self.get_knows_for_worlds(all_worlds[i][m]) for p in knows: for wm in all_worlds[i][m]: wm._preds.add(Term('knows', i,p)) #Generate Inferred knowledge kvworlds = {} for i in players_less_random: for w in total_new_worlds[i]: kvworlds[w] = [Term('thinks',i,p) for p in self.generate_inferred_knowledge(w,all_worlds)] for (w,k) in kvworlds.items(): for p in k: w._preds.add(p) w._kb += p knowsSet2 = set() #Generate new legal moves for i in players_less_random: res = [k for (k,v) in self.raw_query(i, Term('thinks', i, Var('_')), total_new_worlds).items() if v == 1 and k.args[1].functor == "legal"] for q in res: knowsSet2.add(Term('knows', i, q.args[1])) for i in players_less_random: for w in total_new_worlds[i]: for p in knowsSet2: w._preds.add(p) w._kb += Term(p) #Extra case, should only be one world in the random players collection if self.game_data.random_id in self.worlds.keys(): for w in self.worlds[self.game_data.random_id]: total_new_worlds[self.game_data.random_id] = set(w.getSuccessorWorlds(actions)) for w1 in total_new_worlds[self.game_data.random_id]: for p1 in knowsSet: w1._preds.add(p1) w1._kb += p1 for p2 in knowsSet2: w1._preds.add(p2) w1._kb += p2 break return GDLNode(total_new_worlds, self.game_data, self)
def _initialiseKB(self): self._kb = self._engine.prepare(self._baseModelFile) initialState = \ set(map(lambda a: Term('ptrue', a[0].args[0]), self._engine.ground_all(self._kb, queries=[Term('init',Var('_'))]).get_names())) players = \ set(map(lambda a: a[0], self._engine.ground_all(self._kb, queries=[Term('role',Var('_'))]).get_names())) #Not needed, but dont care to remove right now self._step = 0 playerWorldState = {} for playerNum in map(lambda a: a.args[0], players): knowledge = map(lambda a: Term('thinks', playerNum, a.args[0]), initialState) playerPreds = initialState.union(set(knowledge)) self._playerList.append(playerNum) #Each player starts with a single initial world if playerNum == self._randomIdentifier: #Random Specific world has no thinks predicates playerWorldState[playerNum] = [RandomWorld(self._engine, self._baseModelFile, self._step, 1, initialState, playerNum)] else: playerWorldState[playerNum] = [World(self._engine, self._baseModelFile, self._step, 1, playerPreds, playerNum)] return playerWorldState