def main(): numQueries = 0 queries = [] numTruths = 0 truths = [] with open("./input.txt") as inp: line = inp.readline() # First line is always the number of queries numQueries = int(line) # n queries for i in range(numQueries): line = inp.readline() queries.append(line.strip()) line = inp.readline() # This is followed by the number of truths numTruths = int(line) for i in range(numTruths): line = inp.readline() truths.append(line.strip()) kb = KnowledgeBase(truths) results = [] for q in queries: lit = Literal(q, len(truths) + 1) lit.negate() result = kb.proveByResolution2([lit], 0) print("{}: {}".format(q, result)) results.append(str(result).upper()) with open('./output.txt', 'w') as op: op.write('\n'.join([r for r in results]))
def __init__(self, board): self.board = board self.kb = KnowledgeBase() self.alive = True self.win = False self.d = 'E' self.arrows = 1 self.score = 0 # x,y are the 'printed' coordinates, starting at 1,1 # i,j are the 'actual' coordinates, starting at len - 1, 0 self.x = self.y = 1 self.i = len(self.board.grid) - 1 self.j = 0 # check to see if we started in the goal state self.kb.write(self) if self.board.percepts[self.i][self.j]['Glitter']: self.win = True
def __init__(self, session, corpus_dir, knbase_dir, result_dir, result_file): """ Args: session: The TensorFlow session. corpus_dir: Name of the folder storing corpus files and vocab information. knbase_dir: Name of the folder storing data files for the knowledge base. result_dir: The folder containing the trained result files. result_file: The file name of the trained model. """ self.session = session # Prepare data and hyper parameters print("# Prepare dataset placeholder and hyper parameters ...") tokenized_data = TokenizedData(corpus_dir=corpus_dir, training=False) self.knowledge_base = KnowledgeBase() self.knowledge_base.load_knbase(knbase_dir) self.session_data = SessionData() self.hparams = tokenized_data.hparams self.src_placeholder = tf.placeholder(shape=[None], dtype=tf.string) src_dataset = tf.data.Dataset.from_tensor_slices(self.src_placeholder) self.infer_batch = tokenized_data.get_inference_batch(src_dataset) # Create model print("# Creating inference model ...") self.model = ModelCreator(training=False, tokenized_data=tokenized_data, batch_input=self.infer_batch) # Restore model weights print("# Restoring model weights ...") self.model.saver.restore(session, os.path.join(result_dir, result_file)) self.session.run(tf.tables_initializer())
def fol_fc_ask(kb, alpha): res = set() while True: new_facts = set() for rule in KnowledgeBase.getRule(): count_premises = rule.count_premises() facts = kb.getFact() premises = itertools.permutations(facts, count_premises) for tuple_premises in premises: premises_ = [premise for premise in tuple_premises] theta = unify(rule.premise, premises_, Substitution()) if not theta: continue new_fact = rule.get_conclusion() theta.SUBST(new_fact) if new_fact not in new_facts and new_fact not in kb.getFact(): new_facts.add(new_fact) phi = unify(new_fact, alpha, Substitution()) if phi: if phi.empty(): for f in new_facts: kb.appendFact(f) res.add('true') return res res.add(phi) if not new_facts: if not res: res.add('false') return res for f in new_facts: kb.appendFact(f)
class Player(object): def __init__(self, board): self.board = board self.kb = KnowledgeBase() self.alive = True self.win = False self.d = 'E' self.arrows = 1 self.score = 0 # x,y are the 'printed' coordinates, starting at 1,1 # i,j are the 'actual' coordinates, starting at len - 1, 0 self.x = self.y = 1 self.i = len(self.board.grid) - 1 self.j = 0 # check to see if we started in the goal state self.kb.write(self) if self.board.percepts[self.i][self.j]['Glitter']: self.win = True def print_location(self): print("You are in room [{}, {}] of the cave. Facing {}".format( self.x, self.y, self.direction())) def print_percepts(self): percepts = [ k.upper() for k, v in self.board.percepts[self.i][self.j].items() if v ] p = " and a ".join(percepts) if p: print('There is a {} in here!'.format(p)) def forward(self): # get next tile, increment x,y,i,j, check for bump move = self.possible_moves().get(self.d) if move: self.move(*move) else: print('BUMP!!! You hit a wall!') def left(self): ''' turn player left ''' cycle = ['N', 'W', 'S', 'E', 'N'] i = cycle.index(self.d) + 1 self.d = cycle[i] def right(self): ''' turn player right ''' cycle = ['N', 'E', 'S', 'W', 'N'] i = cycle.index(self.d) + 1 self.d = cycle[i] def execute(self, command): if command == 'L': self.left() elif command == 'R': self.right() elif command == 'F': self.forward() elif command == 'S': if self.arrows > 0: hit = self.shoot() if not hit: print('You missed! {} arrows remaining'.format( self.arrows)) else: print('You have no arrows left!') def shoot(self): ''' returns True if player had an arrow and hit the wumpus. ''' self.arrows -= 1 self.score -= 10 candidates = [] dummy_player = deepcopy(self) move = dummy_player.possible_moves().get(dummy_player.d) while move: candidates.append(move[:2]) dummy_player.i, dummy_player.j, dummy_player.x, \ dummy_player.y = move move = dummy_player.possible_moves().get(dummy_player.d) for x, y in candidates: if self.board.grid[x][y] == 'W': self.scream() self.score += 500 return True return False def scream(self): print("You hear a SCREAM!!! The Wumpus is dead!") def possible_moves(self): i, j, x, y = self.i, self.j, self.x, self.y directions = ('N', 'S', 'W', 'E') candidates = [(i - 1, j, x, y + 1), (i + 1, j, x, y - 1), (i, j - 1, x - 1, y), (i, j + 1, x + 1, y)] candidates = [c if (c[0] > -1 and c[0] < len(self.board.grid) and \ c[1] > -1 and c[1] < len(self.board.grid)) else None for c in candidates] return {d: c for d, c in zip(directions, candidates)} def move(self, i, j, x, y): ''' update player information. only call move() after validating the move ''' self.i, self.j, self.x, self.y = i, j, x, y self.score -= 1 self.kb.write(self) if self.board.grid[i][j] == 'W': print("You were eaten by the Wumpus. Sorry. -1000 Points") self.alive = False elif self.board.grid[i][j] == 'P': print("You fell into a pit. Sorry. -1000 Points") self.alive = False if not self.alive: self.score -= 1000 if self.board.percepts[i][j]['Glitter']: self.score += 1000 self.win = True def prompt(self): return "What would you like to do? Please enter command [R,L,F,S]:\n> " def direction(self): return { 'E': 'EAST', 'W': 'WEST', 'S': 'SOUTH', 'N': 'NORTH', }.get(self.d)
class Player(object): def __init__(self, board): self.board = board self.kb = KnowledgeBase() self.alive = True self.win = False self.d = 'E' self.arrows = 1 self.score = 0 # x,y are the 'printed' coordinates, starting at 1,1 # i,j are the 'actual' coordinates, starting at len - 1, 0 self.x = self.y = 1 self.i = len(self.board.grid) - 1 self.j = 0 # check to see if we started in the goal state self.kb.write(self) if self.board.percepts[self.i][self.j]['Glitter']: self.win = True def print_location(self): print("You are in room [{}, {}] of the cave. Facing {}".format( self.x, self.y, self.direction())) def print_percepts(self): percepts = [k.upper() for k,v in self.board.percepts[self.i][self.j].items() if v] p = " and a ".join(percepts) if p: print('There is a {} in here!'.format(p)) def forward(self): # get next tile, increment x,y,i,j, check for bump move = self.possible_moves().get(self.d) if move: self.move(*move) else: print('BUMP!!! You hit a wall!') def left(self): ''' turn player left ''' cycle = ['N', 'W', 'S', 'E', 'N'] i = cycle.index(self.d) + 1 self.d = cycle[i] def right(self): ''' turn player right ''' cycle = ['N', 'E', 'S', 'W', 'N'] i = cycle.index(self.d) + 1 self.d = cycle[i] def execute(self, command): if command == 'L': self.left() elif command == 'R': self.right() elif command == 'F': self.forward() elif command == 'S': if self.arrows > 0: hit = self.shoot() if not hit: print('You missed! {} arrows remaining'.format(self.arrows)) else: print('You have no arrows left!') def shoot(self): ''' returns True if player had an arrow and hit the wumpus. ''' self.arrows -= 1 self.score -= 10 candidates = [] dummy_player = deepcopy(self) move = dummy_player.possible_moves().get(dummy_player.d) while move: candidates.append(move[:2]) dummy_player.i, dummy_player.j, dummy_player.x, \ dummy_player.y = move move = dummy_player.possible_moves().get(dummy_player.d) for x,y in candidates: if self.board.grid[x][y] == 'W': self.scream() self.score += 500 return True return False def scream(self): print("You hear a SCREAM!!! The Wumpus is dead!") def possible_moves(self): i,j,x,y = self.i, self.j, self.x, self.y directions = ('N', 'S', 'W', 'E') candidates = [(i-1, j, x, y+1), (i+1, j, x, y-1), (i, j-1, x-1, y), (i, j+1, x+1, y) ] candidates = [c if (c[0] > -1 and c[0] < len(self.board.grid) and \ c[1] > -1 and c[1] < len(self.board.grid)) else None for c in candidates] return { d:c for d,c in zip(directions,candidates) } def move(self, i,j,x,y): ''' update player information. only call move() after validating the move ''' self.i, self.j, self.x, self.y = i,j,x,y self.score -= 1 self.kb.write(self) if self.board.grid[i][j] == 'W': print("You were eaten by the Wumpus. Sorry. -1000 Points") self.alive = False elif self.board.grid[i][j] == 'P': print("You fell into a pit. Sorry. -1000 Points") self.alive = False if not self.alive: self.score -= 1000 if self.board.percepts[i][j]['Glitter']: self.score += 1000 self.win = True def prompt(self): return "What would you like to do? Please enter command [R,L,F,S]:\n> " def direction(self): return { 'E': 'EAST', 'W': 'WEST', 'S': 'SOUTH', 'N': 'NORTH', }.get(self.d)
class BotPredictor(object): def __init__(self, session, corpus_dir, knbase_dir, result_dir, result_file): """ Args: session: The TensorFlow session. corpus_dir: Name of the folder storing corpus files and vocab information. knbase_dir: Name of the folder storing data files for the knowledge base. result_dir: The folder containing the trained result files. result_file: The file name of the trained model. """ self.session = session # Prepare data and hyper parameters print("# Prepare dataset placeholder and hyper parameters ...") tokenized_data = TokenizedData(corpus_dir=corpus_dir, training=False) self.knowledge_base = KnowledgeBase() self.knowledge_base.load_knbase(knbase_dir) self.session_data = SessionData() self.hparams = tokenized_data.hparams self.src_placeholder = tf.placeholder(shape=[None], dtype=tf.string) src_dataset = tf.data.Dataset.from_tensor_slices(self.src_placeholder) self.infer_batch = tokenized_data.get_inference_batch(src_dataset) # Create model print("# Creating inference model ...") self.model = ModelCreator(training=False, tokenized_data=tokenized_data, batch_input=self.infer_batch) # Restore model weights print("# Restoring model weights ...") self.model.saver.restore(session, os.path.join(result_dir, result_file)) self.session.run(tf.tables_initializer()) def predict(self, session_id, question, html_format=False): chat_session = self.session_data.get_session(session_id) chat_session.before_prediction() # Reset before each prediction if question.strip() == '': answer = "Don't you want to say something to me?" chat_session.after_prediction(question, answer) return answer pat_matched, new_sentence, para_list = check_patterns_and_replace( question) for pre_time in range(2): tokens = nltk.word_tokenize(new_sentence.lower()) tmp_sentence = [' '.join(tokens[:]).strip()] self.session.run(self.infer_batch.initializer, feed_dict={self.src_placeholder: tmp_sentence}) outputs, _ = self.model.infer(self.session) if self.hparams.beam_width > 0: outputs = outputs[0] eos_token = self.hparams.eos_token.encode("utf-8") outputs = outputs.tolist()[0] if eos_token in outputs: outputs = outputs[:outputs.index(eos_token)] if pat_matched and pre_time == 0: out_sentence, if_func_val = self._get_final_output( outputs, chat_session, para_list=para_list, html_format=html_format) if if_func_val: chat_session.after_prediction(question, out_sentence) return out_sentence else: new_sentence = question else: out_sentence, _ = self._get_final_output( outputs, chat_session, html_format=html_format) chat_session.after_prediction(question, out_sentence) return out_sentence def _get_final_output(self, sentence, chat_session, para_list=None, html_format=False): sentence = b' '.join(sentence).decode('utf-8') if sentence == '': return "I don't know what to say.", False if_func_val = False last_word = None word_list = [] for word in sentence.split(' '): word = word.strip() if not word: continue if word.startswith('_func_val_'): if_func_val = True word = call_function(word[10:], knowledge_base=self.knowledge_base, chat_session=chat_session, para_list=para_list, html_format=html_format) if word is None or word == '': continue else: if word in self.knowledge_base.upper_words: word = self.knowledge_base.upper_words[word] if (last_word is None or last_word in ['.', '!', '?']) and not word[0].isupper(): word = word.capitalize() if not word.startswith('\'') and word != 'n\'t' \ and (word[0] not in string.punctuation or word in ['(', '[', '{', '``', '$']) \ and last_word not in ['(', '[', '{', '``', '$']: word = ' ' + word word_list.append(word) last_word = word return ''.join(word_list).strip(), if_func_val
def update_RDF(map_base, map_id, map_source, annotations, update_knowledgebase=False): map_dir = os.path.join(map_base, map_id) # RDF generation if update_knowledgebase: kb_path = os.path.join(map_base, 'KnowledgeBase.sqlite') print('Knowledge base: ', kb_path, (not os.path.exists(kb_path))) graph = KnowledgeBase(kb_path, create=(not os.path.exists(kb_path))) else: graph = rdflib.Graph() # graph.namespace_manager = NS.SCICRUNCH_NS # namespaces_dict = NS.namespaces_dict() ## Only really need rdf: obo: fma: FMA: RO: UBERON: ILX: flatmap: ## See https://github.com/RDFLib/rdflib/issues/794 # namespaces_dict = { 'FMA': rdflib.namespace.Namespace('http://purl.org/sig/ont/fma/fma'), 'ILX': rdflib.namespace.Namespace('http://uri.interlex.org/base/ilx_'), 'NCBITaxon': rdflib.namespace.Namespace( 'http://purl.obolibrary.org/obo/NCBITaxon_'), 'RO': rdflib.namespace.Namespace('http://purl.obolibrary.org/obo/RO_'), 'UBERON': rdflib.namespace.Namespace('http://purl.obolibrary.org/obo/UBERON_'), 'fma': rdflib.namespace.Namespace('http://purl.org/sig/ont/fma/'), 'ilx': rdflib.namespace.Namespace('http://uri.interlex.org/'), 'obo': rdflib.namespace.Namespace('http://purl.obolibrary.org/obo/'), } for pfx, ns in namespaces_dict.items(): graph.bind(pfx, ns, override=True) FLATMAP_NS = rdflib.namespace.Namespace( 'http://celldl.org/ontologies/flatmap/') graph.bind('flatmap', FLATMAP_NS, override=True) map_uri = rdflib.URIRef(map_source) for object_id, metadata in annotations.items(): if 'error' in metadata: print('Error in {} layer: {}: {}'.format(metadata['layer'], metadata['error'], metadata['annotation'])) continue layer_urls = UrlMaker(map_source, metadata['layer']) annotation = metadata['annotation'] properties = Parser.annotation(annotation) feature_id = properties.get('id') feature_uri = layer_urls.url(feature_id) graph.remove((feature_uri, None, None)) feature_class = None route = {'source': '', 'via': [], 'target': ''} for key, value in properties.items(): if key == 'models': prop = namespaces_dict['RO']['0003301'] (prefix, local) = value.split(':', 1) graph.add((feature_uri, prop, namespaces_dict[prefix][local])) elif key == 'node': feature_class = FLATMAP_NS['Node'] graph.add((feature_uri, FLATMAP_NS['nodeClass'], FLATMAP_NS[value[0]])) elif key == 'edge': feature_class = FLATMAP_NS['Edge'] if len(value) < 2: raise ValueError( 'Edge must have a source and target: {}'.format( annotation)) route['source'] = value[0] route['target'] = value[-1] route['via'] = value[1:-1] elif key in ['source', 'via', 'target']: if feature_class is None: feature_class = FLATMAP_NS['Edge'] elif feature_class != FLATMAP_NS['Edge']: raise ValueError( 'Only edges can be routed: {}'.format(annotation)) if key in ['source', 'target']: route[key] = value[0] else: route['via'].extend(value) if feature_class is None: feature_class = FLATMAP_NS['Node'] # Assume we have a Node elif feature_class == FLATMAP_NS['Edge']: if route['source']: graph.add((feature_uri, FLATMAP_NS['source'], layer_urls.url(route['source']))) if route['target']: graph.add((feature_uri, FLATMAP_NS['target'], layer_urls.url(route['target']))) for via in route['via']: graph.add( (feature_uri, FLATMAP_NS['via'], layer_urls.url(via))) graph.add((feature_uri, FLATMAP_NS['map'], map_uri)) graph.add((feature_uri, rdflib.namespace.RDF['type'], feature_class)) with open(os.path.join(map_dir, 'annotations.ttl'), 'w') as turtle: # Don't set `base=map_uri` until RDFLib 5.0 and then use `explicit_base=True` # See https://github.com/RDFLib/rdflib/issues/559 turtle.write(graph.serialize(format='turtle').decode('utf-8')) graph.close()
import argparse import sys import re from fact import Fact from rule import Rule from knowledgebase import KnowledgeBase from resolution import resolution_search from backwardchaining import BackwardChaining from fol_fc_ask import fol_fc_ask class Inferring(Enum): FORWARD = 0 BACKWARD = 1 RESOLUTION = 2 knowledgeBase = KnowledgeBase() infertype = -1 parser = argparse.ArgumentParser(description="Simple Prolog Implementation.") parser.add_argument("files", nargs='*', metavar='file', type=str) parser.add_argument("--infertype", nargs=1, default=Inferring.BACKWARD.value, type=int, metavar='i', help="{}: forward; {}: backward; {}: resolution".format(Inferring.FORWARD.value, Inferring.BACKWARD.value, Inferring.RESOLUTION.value)) def process(file, isInput = False): global knowledgeBase, infertype cmds = [] while True: if isInput: sys.stdout.write('? ' if len(cmds) == 0 else '| ') sys.stdout.flush() line = file.readline() if line == "": break