def test_issue_4(self): """ Patch for a dynamic method Ensures that the patch is working. https://code.google.com/p/pyswip/issues/detail?id=4 """ from pyswip import Prolog Prolog.dynamic('test_issue_4_d/1') Prolog.assertz('test_issue_4_d(test1)') Prolog.assertz('test_issue_4_d(test1)') Prolog.assertz('test_issue_4_d(test1)') Prolog.assertz('test_issue_4_d(test2)') results = list(Prolog.query('test_issue_4_d(X)')) self.assertEqual(len(results), 4) Prolog.retract('test_issue_4_d(test1)') results = list(Prolog.query('test_issue_4_d(X)')) self.assertEqual(len(results), 3) Prolog.retractall('test_issue_4_d(test1)') results = list(Prolog.query('test_issue_4_d(X)')) self.assertEqual(len(results), 1)
def api(): # instanciamos prolog prolog = Prolog() # obtenemos la peticion con los datos data = request.get_json() print(data) # consultamos nuestro archivo de prolog prolog.consult("engine.pl") prolog.assertz("persona(fs)") #vemos que conocimientos tiene el usuario y los agregamos # a la DB de prolog if data['linguistico'] > 0: # prolog.query("ling(A)."); prolog.assertz("persona(linguistico)") if data['mate'] > 0: # prolog.query("mate(A)."); prolog.assertz("persona(matematico)") if data['espacio'] > 0: # prolog.query("esp(A)."); prolog.assertz("persona(espacio)") if data['interpersonal'] > 0: # prolog.query("inte(A)."); prolog.assertz("persona(interpersonal)") if data['creativa'] > 0: # prolog.query("cre(A)."); prolog.assertz("persona(creativo)") carrera = [] # hacemos un query para ver si cumple con alguna carrera abogado = list(prolog.query("abogado(A)")) arquitecto = list(prolog.query("arquitecto(A)")) civil = list(prolog.query("civil(A)")) electronico = list(prolog.query("electronico(A)")) informatico = list(prolog.query("informatico(A)")) if len(abogado) > 0 and (abogado[0]["A"] == 1): carrera.append('abogado') if len(arquitecto) > 0 and (arquitecto[0]["A"] == 1): carrera.append('arquitecto') if len(civil) > 0 and (civil[0]["A"] == 1): carrera.append('civil') if len(electronico) > 0 and (electronico[0]["A"] == 1): carrera.append('electronico') if len(informatico) > 0 and (informatico[0]["A"] == 1): carrera.append('informatico') # prolog.query("retractall(persona(_))"); # prolog.query("purgar"); prolog.retractall("persona(_)") print(list(prolog.query('getConocimientos(A).'))) del prolog res = make_response(jsonify({"message": carrera}), 200) return res
class PrologHelper: def __init__(self): self.prolog = Prolog() self.prolog.consult("main.pl") self.question_dict = { "likes": "What describes your interests the most?", "lang_status": "Do you prefer an older, established language, or a new, innovative one?", "platform": "What platform do you plan on using?", "skill": "Do you want a challenge or an easier approach?", "paradigm": "Which programming paradigm do you prefer?", "lang_performance": "What do you value more, performance or expressiveness?", "lang_execution": "Do you prefer working with compiled or interpreted languages?" } self.question_dict_reverse = {key: value for (value, key) in self.question_dict.items()} self.tech_dict = { "react": "React - A JavaScript front-end web framework.", "angular": "Angular - A TypeScript front-end web framework.", "vue": "Vue - A JavaScript front-end web framework.", "css_js": "CSS and Javascript - basics of web development.", "bootstrap": "Bootstrap - Basic web UI framework.", "jquery": "jQuery - fast, small, feature-rich JavaScript library.", "django": "Django - powerful Python back-end framework.", "flask": "Flask - simple Python back-end framework.", "node": "Node.js - JavaScript back-end framework.", "rocket": "Rocket - Rust back-end framework.", "javafx": "JavaFX - Web application platform", "electron": "Electron - JavaScript desktop development platform.", "wpf": "Windows Presentation Foundation - desktop development for Windows", "asp": "ASP.NET - back-end web framework for .NET", "razor": "Razor - front-end web framework for .NET", "netcore": ".NET Core - back-end web framework for .NET", "pytorch": "PyTorch - Python machine learning toolkit", "tensorflow": "Tensorflow - low-level machine learning toolkit", "caffee": "Caffee - Python machine learning toolkit", "keras": "Keras - Python machine learning toolkit", "dl4j": "DL4J - Java machine learning toolkit", "unity": "Unity - C# game development framework", "unreal": "Unreal - C++ game development framework", "swift_ui": "SwiftUI - UI framework for iOS and Mac", "godot": "Godot - C++ game development framework", "cocoa": "Cocoa - Apple's macOS API", "emscripten": "Emscripten - C to WebAssembly toolchain", "neuroph": "Neuroph - open source Java framework for neural network creation", "spring": "Spring - Java web framework" } self.techs_proposed = [] def get_question_from_prolog(self): for q in self.prolog.query("question(Q)"): return self.question_dict[str(q["Q"])] def get_answers_from_prolog(self, question): question = self.question_dict_reverse[question] cmd = "answers({0}, A)".format(question) answers = [] for a in self.prolog.query(cmd): answers.append(str(a["A"])) return answers def save_answer_to_prolog(self, question, answer): print(question, answer) question = self.question_dict_reverse[question] cmd = "remember(yes, {0}, {1})".format(question, answer) self.prolog.assertz(cmd) def get_possible_techs(self): techs = [] for t in self.prolog.query("tech(X)"): techs.append(str(t["X"])) return techs def get_tech_description(self, tech): return self.tech_dict[tech] def reset_prolog_memory(self): self.prolog.retractall("remember(_,_,_)")
def valid_constraints(root: IView[NT], visibilities: List[Tuple[IAnchor[NT], IAnchor[NT]]], debug: bool = True) \ -> Generator[IConstraint, None, None]: """ Computes the valid constraint pairs (or singletons) for various types of constraint. """ outfile = "debug.pl" # Note: Prolog is a singleton! prolog = Prolog() try: with open(outfile, 'w') as dbfile: # Load static terms/predicates. with resources.path(__package__, 'logic.pl') as path: prolog.consult(str(path)) # Add dynamic terms/predicates. prolog.dynamic('view/1') prolog.dynamic('parent/2') prolog.dynamic('visible/2') for view in root: prolog.assertz(f"view('{view.name}')") if debug: dbfile.write(f"view('{view.name}').\n") for child in view.children: prolog.assertz(f"parent('{view.name}', '{child.name}')") if debug: dbfile.write( f"parent('{view.name}', '{child.name}').\n") for vis in visibilities: [a1, a2] = vis a1_term = f"anchor('{a1.view.name}', '{a1.attribute.value}')" a2_term = f"anchor('{a2.view.name}', '{a2.attribute.value}')" prolog.assertz(f"visible({a1_term}, {a2_term})") if debug: dbfile.write(f"visible({a1_term}, {a2_term}).\n") # todo: Post-process output? Necessary? # ops = [operator.le, operator.ge, operator.eq] ops = [operator.eq] for answer in prolog.query("aspect_ratio_size(V)"): v, = [answer[k] for k in ('V', )] yield ConstraintFactory.create( kind=ConstraintKind.SIZE_ASPECT_RATIO, x_id=AnchorID(v, Attribute('height')), y_id=AnchorID(v, Attribute('width')), op=operator.eq) for answer in prolog.query("absolute_size(V, A)"): v, a = [answer[k] for k in ('V', 'A')] for op in ops: yield ConstraintFactory.create( kind=ConstraintKind.SIZE_CONSTANT, x_id=None, y_id=AnchorID(v, Attribute(a)), op=op) for answer in prolog.query("parent_relative_size(V, A, W, B)"): v, a, w, b = [answer[k] for k in ('V', 'A', 'W', 'B')] yield ConstraintFactory.create(kind=ConstraintKind.SIZE_RATIO, x_id=AnchorID(v, Attribute(a)), y_id=AnchorID(w, Attribute(b)), op=operator.eq) for answer in prolog.query("spacing(V, A, W, B)"): v, a, w, b = [answer[k] for k in ('V', 'A', 'W', 'B')] for op in ops: yield ConstraintFactory.create( kind=ConstraintKind.POS_LTRB_OFFSET, x_id=AnchorID(v, Attribute(a)), y_id=AnchorID(w, Attribute(b)), op=op) for answer in prolog.query("alignment(V, A, W, B)"): v, a, w, b = [answer[k] for k in ('V', 'A', 'W', 'B')] for op in ops: yield ConstraintFactory.create( kind=ConstraintKind.POS_LTRB_OFFSET, x_id=AnchorID(v, Attribute(a)), y_id=AnchorID(w, Attribute(b)), op=op) finally: # Cleanup dynamic predicates to avoid subsequent calls running in a # polluted Prolog namespace. prolog.retractall('view(_)') prolog.retractall('parent(_,_)') prolog.retractall('visible(_,_)') pass
class PrologStateMachine(StateMachine): def __init__(self, description): self.prolog = Prolog() load_game_description(description) self.roles = set( [str(res['R']) for res in list(self.prolog.query("role(R)"))]) def get_initial_state(self): bases = [] bases_query = list(self.prolog.query("base(X)")) for bases_result in bases_query: name = str(bases_result["X"]) if len(list(self.prolog.query("init(" + name + ")"))) == 1: bases.append(Term(name)) return State(bases) def is_terminal(self, state): self.set_base_truths(state) result_length = len(list(self.prolog.query("terminal"))) return result_length >= 1 def get_goal_value(self, state, player): self.set_base_truths(state) return list(self.prolog.query("goal(" + player + ", N)"))[0]['N'] def get_legal_moves(self, state, player): self.set_base_truths(state) return [ str(result['A']) for result in list(self.prolog.query("legal(" + player + ", A)")) ] def get_legal_joint_moves(self, state): self.set_base_truths(state) legals_query = list(self.prolog.query("legal(R, A)")) joint_legals = {} for result in legals_query: role = str(result['R']) action = str(result['A']) if role in joint_legals: joint_legals[role].append(action) else: joint_legals[role] = [action] return joint_legals def get_next_state(self, state, moves): self.set_base_truths(state) self.prolog.retractall("does(R,A)") for role in moves: self.prolog.assertz("does(" + role + ", " + moves[role] + ")") return State( set([ Term(str(res['P'])) for res in list(self.prolog.query("next(P)")) ])) def get_next_states(self, state, moves=None): if moves == None: pass else: pass def set_base_truths(self, state): self.prolog.retractall("true(X)") for term in state.true_terms: if term.value: self.prolog.assertz("true(" + term.name + ")") def get_roles(self): return self.roles
class PrologGrammarEngine: """ This class is used to : - initialize a interface toward Prolog using pyswip - transform and load a grammar into the prolog engine - define methods to query the grammar This class must be instanciate ony one """ all_ready_initialize = False def __init__(self, path_to_methods_file: str): """ :param path_to_methods_file: path toward prolog knowledge base that contains the predicates used to query the grammar """ assert not PrologGrammarEngine.all_ready_initialize self.prolog = Prolog() self.prolog.consult(path_to_methods_file) # We keep in memory all the predicates that had been added to the prolog engine # in order to be able to remove them if needed self.current_predicates: List[str] = [] # We keep in memoery all the terminal symbol of the grammar # in order to not have to communicate each time with prolog # when we need to know if a symbol is terminal self.terminals: Set[str] = set() PrologGrammarEngine.all_ready_initialize = True def delete_grammar(self): """ Remove all the grammar predicates from the prolog engine """ for rule in self.current_predicates: self.prolog.retractall(rule) self.current_predicates = [] self.terminals = {} def retrieve_terminal(self): """ Load the terminal symbol in memory once for all """ answers = self.prolog.query("terminal(X)") self.terminals = {answer["X"] for answer in answers} def load_grammar(self, ntlk_str_grammar: str): """ Transform the grammar into prolog predicates and load it in the prolog engine """ self.current_predicates = parse_to_prolog(ntlk_str_grammar) for rule in self.current_predicates: self.prolog.assertz(rule) self.retrieve_terminal() def valid_children(self, symbols: List[str]) -> List[List[str]]: """ Given a derivation (list of terms), return all the valide children node. Ie: - all symbols string that can derivate from this derivation using only one rule - all symbols string from which a terminal leaf can be reached """ try: answer = next( self.prolog.query("all_valid_children([%s], X)" % join(symbols))) return format_term(answer["X"]) except StopIteration: return [] def leaf(self, symbols: List[str]) -> Union[List[str], None]: """ Given a derivation, return a random terminal leaf if it exists, None else """ answers = self.prolog.query("random_leaf([%s], X)" % join(symbols)) try: answer = next(answers) return format_term(answer["X"]) except StopIteration: return None def is_terminal(self, symbol: str) -> bool: """ return true is the symbol is terminal """ return symbol in self.terminals def set_random_seed(self, seed: int): """ set the random seed of prolog engine """ # WARNING - This does not seem to work ! self.prolog.assertz("set_random(seed(%d))" % seed)
class PrologPhoneChoiceAssistant(PhoneChoiceAssistant): _REQUIRE_TEMPLATE = "user_requirement({rule_key}, {value})" def __init__( self, rules_file: str, knowledge_base_file: str, ): super().__init__() self._prolog = Prolog() self._load_knowledge_base(knowledge_base_file) self._load_rules(rules_file) self._loaded_rules: Dict[RuleKey, Rule] = dict() def _load_rules( self, rules_file: str, ): self._prolog.consult(rules_file) def _load_knowledge_base( self, knowledge_base_file: str, ): self._prolog.consult(knowledge_base_file) def suggest(self) -> Set[Model]: models: Generator[Dict[str, bytes], None, None] = self._prolog.query("is_sufficient(Model)") models_list = [d["Model"].decode("utf-8") for d in models] return set(models_list) def battery_life(self, battery_life: BatteryLife): rule_key = "battery_life" self._require(rule_key, battery_life.name.lower()) def cpu_frequency(self, cpu_frequency: CPUFrequency): rule_key = "cpu_frequency" self._require(rule_key, cpu_frequency.name.lower()) def touch_screen(self): rule_key = "touch_screen" self._require(rule_key, RequiredFeature_String) def nfc(self): rule_key = "nfc" self._require(rule_key, RequiredFeature_String) def water_resistant(self): rule_key = "touch_screen" self._require(rule_key, RequiredFeature_String) def dual_sim(self): rule_key = "dual_sim" self._require(rule_key, RequiredFeature_String) def cpu_n_cores(self, cpu_n_cores: CpuNCores): rule_key = "cpu_n_cores" self._require(rule_key, cpu_n_cores.name.lower()) def back_camera_matrix(self, back_camera_matrix: BackCameraMatrix): rule_key = "back_camera_matrix" self._require(rule_key, back_camera_matrix.name.lower()) def front_camera_matrix(self, front_camera_matrix: FrontCameraMatrix): rule_key = "front_camera_matrix" self._require(rule_key, front_camera_matrix.name.lower()) def phone_for_business(self): rule_key = "phone_for_business" self._require(rule_key, RequiredFeature_String) def big_screen(self): rule_key = "big_screen" self._require(rule_key, RequiredFeature_String) def very_big_screen(self): rule_key = "very_big_screen" self._require(rule_key, RequiredFeature_String) def phone_for_teenager(self): rule_key = "phone_for_teenager" self._require(rule_key, RequiredFeature_String) def phone_to_listening_music(self): rule_key = "phone_to_listening_music" self._require(rule_key, RequiredFeature_String) def phone_for_social_media(self): rule_key = "phone_for_social_media" self._require(rule_key, RequiredFeature_String) def phone_to_play_games(self): rule_key = "phone_to_play_games" self._require(rule_key, RequiredFeature_String) def phone_to_make_photos(self): rule_key = "phone_to_make_photos" self._require(rule_key, RequiredFeature_String) def phone_for_trips(self): rule_key = "phone_for_trips" self._require(rule_key, RequiredFeature_String) def _require(self, rule_key: str, value: Any): previous_rule = self._loaded_rules.get(rule_key) if previous_rule: self._prolog.retract(previous_rule) new_rule = PrologPhoneChoiceAssistant._REQUIRE_TEMPLATE.format( rule_key=rule_key, value=value, ) print(new_rule) self._prolog.asserta(new_rule) self._loaded_rules[rule_key] = new_rule def clear_requirements(self): self._prolog.retractall("user_requirement(A,B)") self._loaded_rules = dict()
class RobotAgent(Agent): """ An agent with fixed initial wealth.""" def __init__(self, unique_id, model, type, tasks, fmap, boxes): super().__init__(unique_id, model) self.uid = unique_id self.type = type self.stuff = 0 self.fmap = fmap self.next = True self.tasks = tasks self.target = self.tasks.pop(0) # self.possible_steps = astar(fmap, self.pos, self.target) self.possible_steps = [] self.passed = [] self.renew = False self.createDB(boxes) def createDB(self, boxes): # create boxes' database self.swi = Prolog() for i in range(len(self.fmap)): for j in range(len(self.fmap)): if (self.fmap[i][j] == 1 ): self.swi.assertz('wall('+str((i,j))+')') for pos in boxes[1]: s = str(pos) self.swi.assertz('full('+s+')') def findPath(self): if self.renew: new_pos = self.model.grid.get_neighborhood( self.pos, True, False, 1) candi_pos = [x for x in new_pos if (not bool(list(self.swi.query( 'full('+str(x)+')'))) and not bool(list(self.swi.query( 'wall('+str(x)+')'))) )] if len(candi_pos) == 0: self.possible_steps = [] self.new = False return candi_path = [] for pos in candi_pos: candi_path.append(astar( self.fmap, pos, self.target)) self.possible_steps = candi_path.pop(0) for path in candi_path: if len(self.possible_steps) > len(path): self.possible_steps = path print("from ", self.possible_steps[0], "to ", self.possible_steps[-1]) self.renew = False if self.next: print("from ", self.pos, "to ", self.target) self.possible_steps = astar(self.fmap, self.pos, self.target) self.next = False def step(self): # The agent's step will go here. global task_over """ check if need to recompute a path when the agent meets a full box or plans to next box it needs to stay and recompute a path """ if task_over: return self.findPath() """ # if not got the end # if not box, go through # else check if box is empty # if it is empty , go through # else stay to recompute a path # else take stuff away, update database, # stay and prepare for next target """ x,y = next_pos = self.possible_steps[0] s = str(next_pos) if len(self.possible_steps)>1: if bool(list(self.swi.query('full('+s+')'))): print(s,"is full") self.renew = True else: # if bool(list(self.swi.query('go('+s+')'))): self.passed.append(self.possible_steps.pop(0)) self.model.grid.move_agent(self, next_pos) elif len(self.possible_steps) <= 1: if len(self.possible_steps) == 1: cellmates = self.model.grid.get_cell_list_contents([next_pos]) cellmates[0].stuff -= 1 self.stuff += 1 self.swi.retractall('full('+s+')') # if bool(list(self.swi.query('empty('+s+')'))): self.swi.assertz('empty('+s+')') self.passed.append(self.possible_steps.pop(0)) self.model.grid.move_agent(self, next_pos) print(self.passed) if len(self.tasks) == 0: self.swi.retractall('full(_)') self.swi.retractall('wall(_)') task_over = True else: self.target = self.tasks.pop(0) self.next = True
def question_finder(question, ans): p = Prolog() p.consult('/home/jordanhudgens/code/coderprofile/survey/knowledgebase.pl') # When placed on server, be sure to change this path!!!! # Question 1: Type of Projects Desired to Learn if question == "What type of projects do you want to learn how to build?": p.dynamic('projectdesired/1') ## To account for going back p.retractall('projectdesired(_)') ## To account for going back if ans == "iPhone App": p.assertz('projectdesired(iphoneapp)') if ans == "Android App": p.assertz('projectdesired(androidapp)') if ans == "Web Application": p.assertz('projectdesired(webapp)') if ans == "Front End Website Development": p.assertz('projectdesired(frontend)') if ans == "just programming": p.assertz('projectdesired(generalprogramming)') # Question 2: Budget if question == "What is your budget?": p.dynamic('budget/1') ## To account for going back p.retractall('budget(_)') ## To account for going back if ans == "$0": p.assertz('budget(0)') if ans == "$50-$250": p.assertz('budget(250)') if ans == "$251-$500": p.assertz('budget(500)') if ans == "$501-$1000": p.assertz('budget(1000)') if ans == "$1001-$1500": p.assertz('budget(1500)') if ans == "$1501+": p.assertz('budget(1000000)') # Question 3: Level of Education if question == "What is the highest level of education you've completed?": p.dynamic('education/1') ## To account for going back p.retractall('education(_)') ## To account for going back if ans == "High School": p.assertz('education(highschool)') if ans == "Associates": p.assertz('education(associates)') if ans == "Bachelors": p.assertz('education(bachelors)') if ans == "Graduate": p.assertz('education(graduate)') # Question 4: Programming Experience if question == "What programming experience do you have?": p.dynamic('experience/1') ## To account for going back p.retractall('experience(_)') ## To account for going back if ans == "None": p.assertz('experience(none)') if ans == "Low": p.assertz('experience(low)') if ans == "Intermediate": p.assertz('experience(intermediate)') if ans == "Extensive": p.assertz('experience(extensive)') # Question 5: Learning Priority if question == "What's more of a priority for you to learn?": p.dynamic('priority/1') ## To account for going back p.retractall('priority(_)') ## To account for going back if ans == "Theory of coding": p.assertz('priority(theory)') if ans == "Real life projects": p.assertz('priority(practical)') # Question 6: Employment Status if question == "Are you currently employed full time?": p.dynamic('employment/1') ## To account for going back p.retractall('employment(_)') ## To account for going back if ans == "Yes": p.assertz('employment(fulltime)') if ans == "No": p.assertz('employment(none)') # Question 7: Weekly Time Dedication if question == "How many hours can you dedicate to learning each week?": p.dynamic('hoursfree/1') ## To account for going back p.retractall('hoursfree(_)') ## To account for going back if ans == "5": p.assertz('hoursfree(5)') if ans == "6-10": p.assertz('hoursfree(10)') if ans == "11-20": p.assertz('hoursfree(20)') if ans == "21-30": p.assertz('hoursfree(30)') if ans == "31-40": p.assertz('hoursfree(40)') if ans == "40+": p.assertz('hoursfree(168)') # Question 8: Feature Driven Developer if question == "Do you like to see the potential features you're going to build before learning how to implement them?": p.dynamic('featuredriven/1') ## To account for going back p.retractall('featuredriven(_)') ## To account for going back if ans == "Yes (I prefer to watch first)": p.assertz('featuredriven(true)') if ans == "No (I want to start coding right away)": p.assertz('featuredriven(false)') # Question 9: Mentor Driven Developer if question == "Do you like working out problems with experts or do you prefer working out issues on your own?": p.dynamic('mentor/1') ## To account for going back p.retractall('mentor(_)') ## To account for going back if ans == "I would prefer to work with an expert": p.assertz('mentor(mentordriven)') if ans == "I like working issues out on my own": p.assertz('mentor(notmentordriven)') # Question 10: Audience if question == "What type of audience do you want to develop for? I want to build: ": p.dynamic('targetaudience/1') ## To account for going back p.retractall('targetaudience(_)') ## To account for going back if ans == "Business applications": p.assertz('targetaudience(business)') if ans == "Games": p.assertz('targetaudience(games)') if ans == "Social apps": p.assertz('targetaudience(socialapps)') if ans == "eCommerce": p.assertz('targetaudience(ecommerce)') if ans == "No audience - just programming theory": p.assertz('targetaudience(programmingtheory)') # Question 11: Competitive if question == "Does testing your coding skills against other developers appeal to you?": p.dynamic('competitive/1') ## To account for going back p.retractall('competitive(_)') ## To account for going back if ans == "Yes": p.assertz('competitive(iscompetitive)') if ans == "No": p.assertz('competitive(notcompetitive)') # Question 12: High Speed Internet Status if question == "Do you have access to high speed internet?": p.dynamic('highspeedinternet/1') ## To account for going back p.retractall('highspeedinternet(_)') ## To account for going back if ans == "Yes": p.assertz('highspeedinternet(highspeed)') if ans == "No": p.assertz('highspeedinternet(lowspeed)') # Question 13: Code Motivation if question == "Why do you want to learn to code?": p.dynamic('motivation/1') ## To account for going back p.retractall('motivation(_)') ## To account for going back if ans == "Build my own project": p.assertz('motivation(project)') if ans == "Learn a new hobby": p.assertz('motivation(hobby)') if ans == "Improve for my current job": p.assertz('motivation(job)') # Question 14: Machine Type if question == "What type of computer do you have to work on?": p.dynamic('machine/1') ## To account for going back p.retractall('machine(_)') ## To account for going back if ans == "Mac": p.assertz('machine(mac)') if ans == "Windows": p.assertz('machine(windows)') if ans == "Linux": p.assertz('machine(linux)') # Question 15: Timeframe for Learning if question == "What is your timeframe?": p.dynamic('timeframe/1') ## To account for going back p.retractall('timeframe(_)') ## To account for going back if ans == "< 30 days": p.assertz('timeframe(30)') if ans == "31-90 days": p.assertz('timeframe(90)') if ans == "91+ days": p.assertz('timeframe(365)')
class PrologConnector: def __init__(self): self.prolog = Prolog() @staticmethod def create_temp_file(code) -> str: # create temp file for Prolog code if 'connect_files' not in os.listdir(): # custom dir try: os.mkdir('connect_files') except PermissionError: raise PermissionError("Don't have permission for create a dir") with tempfile.NamedTemporaryFile('w', delete=False, suffix='.pro', dir='connect_files') as file: file.write(code) return file.name[file.name.rfind('\\') + 1::] def consult_code(self, code: str, delete=True): # consult Prolog code via temp file self.consult_file('connect_files/' + self.create_temp_file(code), delete) def consult_file(self, file_name: str, delete=False): self.prolog.consult(file_name) if delete: os.remove(file_name) # warning! can be broken if maxresult = -1 def get_n_ans(self, instructions: str, maxresult=1, **kwargs) -> [dict]: # query for prolog return self.prolog.query(instructions, maxresult=maxresult, **kwargs) def get_n_ans_new(self, instructions: str, maxresults=-1, solves=True) -> list: ' functors and items of predicates, variables' terms, vars, statements = self.parse_ins(instructions) vars_ans = [] if solves else {i[0]: [] for i in vars } # list/dict of variable values statements_ans = {} # list of statements if terms: q = Query(*terms) # make query while q.nextSolution() and maxresults: # find solutions maxresults -= 1 if solves: # append values vars_ans.append({k: v.value for k, v in vars}) else: for k, v in vars: if v.value not in vars_ans[k]: vars_ans[k].append(v.value) q.closeQuery() if statements: for statement in statements: statements_ans.update({statement[1]: call(statement[0])}) return vars_ans, statements_ans @staticmethod def parse_ins(instruction) -> list and list and list: if instruction[-1] != ';': instruction += ';' terms = [] # if need var(s) vars = [] statements = [] # if need True or False pnames = re.compile( r'\[.+\]|[\w\d]+') # find names(vars|lists|strings|ints) in atoms plist = re.compile(r'\[.+\]') # find list # find predirects for pred, atoms in re.findall(r'([^\(\)\,\s]+|\S)(\([^\)]+\))\;', instruction): names = pnames.findall(atoms) items = [] there_is_var = False for atom in names: atom = atom.strip() if atom[0].isupper(): # check for var any_var = Variable() # link to Prologs var items.append(any_var) vars.append((atom, any_var)) there_is_var = True elif atom.isdigit(): # check for int items.append(int(atom)) elif plist.search(atom): # check for list items.append(literal_eval(atom)) else: try: # check for float items.append(float(atom)) except ValueError: items.append(atom) if there_is_var: terms.append(Functor(pred, len(names))(*items)) else: statements.append((Functor(pred, len(names))(*items), pred + atoms)) return terms, vars, statements def make_req(self, command: str, solves=False, **kwargs): # with custom parameters 'for all solves of only 1 request(may be unused)' a = self.get_n_ans_new(command, solves=solves, **kwargs) # getting only 1 result if a[0]: return a[0] elif a[1]: for i in a[1].values(): return i else: return None def assert_code(self, ins: str): """ for assertion facts(the same as consult_code) """ for i in ins.split(';'): self.prolog.assertz(i) def retract_code(self, ins: str, all=False): g = ins.split(';') if all: for i in g: self.prolog.retractall(i) else: for i in g: self.prolog.retract(i)
class PrologConvertor(): def __init__(self): self.prolog = Prolog() self.prolog.consult(PROLOG_FILENAME) self.__retractall() def __retractall(self): self.prolog.retractall("selected_meals(X)") self.prolog.retractall("selected_breads(X)") self.prolog.retractall("selected_mains(X)") self.prolog.retractall("selected_veggies(X)") self.prolog.retractall("selected_sauces(X)") self.prolog.retractall("selected_topups(X)") self.prolog.retractall("selected_sides(X)") self.prolog.retractall("selected_drinks(X)") def all_options(self, category): res = list(self.prolog.query( "all_options({}, X)".format(category)))[0]["X"] return self.convert_res_to_list(res) def available_options(self, category): res = list( self.prolog.query("available_options({}, X)".format(category))) return res if res == [] else self.convert_res_to_list(res[0]["X"]) def selected_options(self, category): res = list( self.prolog.query("selected_options({}, X)".format(category))) return res if res == [] else self.convert_res_to_list(res[0]["X"]) def selectable_input_options(self, category): return list( set(self.available_options(category)) - set(self.selected_options(category))) def add_meal(self, X): self.prolog.assertz("selected_meals({})".format(X)) def add_bread(self, X): self.prolog.assertz("selected_breads({})".format(X)) def add_main(self, X): self.prolog.assertz("selected_mains({})".format(X)) def add_veggie(self, X): self.prolog.assertz("selected_veggies({})".format(X)) def add_sauce(self, X): self.prolog.assertz("selected_sauces({})".format(X)) def add_topup(self, X): self.prolog.assertz("selected_topups({})".format(X)) def add_side(self, X): self.prolog.assertz("selected_sides({})".format(X)) def add_drink(self, X): self.prolog.assertz("selected_drinks({})".format(X)) def convert_res_to_list(self, res): counter = 0 list_result = [] while (counter < len(res)): list_result.append(res[counter].value) counter += 1 return list_result
class CovidAIBrigde: """ Communicates directly with prolog scripts to return diagnosis """ def __init__(self, name, log=False): self.prolog = Prolog() self.patient_name = name.split(" ")[0].lower() self.log = log self.prolog.consult('covid.pl') def store_home_parish(self, parish): """ Store the patient current home parish Parameters: parish(list): What symptoms does the patients """ parish = parish.lower() if "st." in parish: parish = parish.split(" ") parish[0] = "saint" parish = "_".join(parish) query_string = f"from_parish({self.patient_name}, {parish})" self.prolog.asserta(query_string) if self.log: self.__log_function(query_string) def store_symptoms(self, symptoms): """ Store the patient symptoms Parameters: symptoms(list): What symptoms does the patients """ query_strings = [ f"has_symptom({self.patient_name}, '{symptom}')" for symptom in symptoms ] for query_string in query_strings: self.prolog.asserta(query_string) if self.log: for query_string in query_strings: self.__log_function(query_string) def store_temperature(self, temperature): """ Store the patient temperature Parameters: temperature(int): What is the patients temperature """ query_string = f"patient_temperature({self.patient_name}, {temperature})" self.prolog.asserta(query_string) if self.log: self.__log_function(query_string) def store_patient_activities(self, wm, t, s, p): """ Store the patient activities that could contribute to diagnosis Parameters: wm(str): Does the patient usually wear a mask t(str): Does the patient travel alot s(str): Does the patient sanitize regularly p(str): Does the patient go to parties """ query_string_mask = f"wears_mask({self.patient_name}, {wm.lower()})" query_string_travel = f"travels({self.patient_name}, {t.lower()})" query_string_sanitize = f"sanitizes({self.patient_name}, {s.lower()})" query_string_party = f"goes_parties({self.patient_name}, {p.lower()})" self.prolog.asserta(query_string_mask) self.prolog.asserta(query_string_travel) self.prolog.asserta(query_string_sanitize) self.prolog.asserta(query_string_party) if (self.log): self.__log_function(query_string_mask) self.__log_function(query_string_travel) self.__log_function(query_string_sanitize) self.__log_function(query_string_party) def diagnose(self): """ Diagnosis and returns a value for how much the chances this patient has covid """ results = list(self.prolog.query(f"has_covid({self.patient_name}, X)")) return results[0] def __log_function(self, string): """ prints out any string passed in with specific format """ print(f"I KNOW: {string}.") def memory_wipe(self): """ wipe information about patient from the agents memory """ # define predicate strings query_string_symptom = f"has_symptom({self.patient_name},_)" query_string_parish = f"from_parish({self.patient_name},_)" query_string_temp = f"patient_temperature({self.patient_name},_)" query_string_mask = f"wears_mask({self.patient_name},_)" query_string_travel = f"travels({self.patient_name},_)" query_string_sanitize = f"sanitizes({self.patient_name},_)" query_string_party = f"goes_parties({self.patient_name},_)" self.prolog.retractall(query_string_symptom) self.prolog.retract(query_string_parish) self.prolog.retract(query_string_temp) self.prolog.retract(query_string_mask) self.prolog.retract(query_string_travel) self.prolog.retract(query_string_sanitize) self.prolog.retract(query_string_party) def __open_db_connection(self): """ Open connection to database """ try: self.con = sqlite3.connect("covidAi.db") print("[Connection established]") except Error: print(Error) def __get_parish_statistics(self): cursorObj = self.con.cursor() cursorObj.execute("SELECT * FROM parishes") rows = list(cursorObj.fetchall()) return rows def update_knowledgebase(self): self.__open_db_connection() statistics = self.__get_parish_statistics() for (id, parish, chance) in statistics: parish_assersion = f"covid_cases({parish}, {chance})" print(parish_assersion) self.prolog.asserta(parish_assersion)