def _pyke_kb_engine(): """Return the PyKE knowledge engine for CF->cube conversion.""" pyke_dir = os.path.join(os.path.dirname(__file__), '_pyke_rules') compile_dir = os.path.join(pyke_dir, 'compiled_krb') engine = None if os.path.exists(compile_dir): tmpvar = [os.path.getmtime(os.path.join(compile_dir, fname)) for fname in os.listdir(compile_dir) if not fname.startswith('_')] if tmpvar: oldest_pyke_compile_file = min(tmpvar) rule_age = os.path.getmtime( os.path.join(pyke_dir, _PYKE_RULE_BASE + '.krb')) if oldest_pyke_compile_file > rule_age: # Initialise the pyke inference engine. engine = knowledge_engine.engine( (None, 'iris.fileformats._pyke_rules.compiled_krb')) if engine is None: engine = knowledge_engine.engine(iris.fileformats._pyke_rules) return engine
def _pyke_kb_engine(): """Return the PyKE knowledge engine for CF->cube conversion.""" pyke_dir = os.path.join(os.path.dirname(__file__), '_pyke_rules') compile_dir = os.path.join(pyke_dir, 'compiled_krb') engine = None if os.path.exists(compile_dir): tmpvar = [os.path.getmtime(os.path.join(compile_dir, fname)) for fname in os.listdir(compile_dir) if not fname.startswith('_')] if tmpvar: oldest_pyke_compile_file = min(tmpvar) rule_age = os.path.getmtime( os.path.join(pyke_dir, _PYKE_RULE_BASE + '.krb')) if oldest_pyke_compile_file >= rule_age: # Initialise the pyke inference engine. engine = knowledge_engine.engine( (None, 'iris.fileformats._pyke_rules.compiled_krb')) if engine is None: engine = knowledge_engine.engine(iris.fileformats._pyke_rules) return engine
def myTest(): engine = knowledge_engine.engine(__file__) engine.activate('subway_rules') kb = engine.get_kb('subway') kb.dump_universal_facts() print("Specific facts are:") engine.get_kb('subway').dump_specific_facts() # all forward-chaining rules are run print("doing proof") try: stmt = 'subway.at_station(Airport)' # {} stmt = 'subway_rules.at_station($a)' # take_line($from, $line, $to) # stmt = 'subway_rules.take_line(Airport, $a, $b)' # stmt = 'subway_rules.connected(Airport, $b)' # stmt = 'subway_rules.half_sibling($af, $bf)' with engine.prove_goal(stmt) as gen: for variable, plan in gen: print(variable) # print("%s at_station" % (variable['a'])) except Exception: # This converts stack frames of generated python functions back to the # .krb file. krb_traceback.print_exc() sys.exit(1) print() print("done") engine.print_stats()
def _setup(self): _engine = knowledge_engine.engine((__file__, '.rules')) # add UNIT items as immutable facts (not affected by reset()) for unit_name, unit_idx in UNIT.items(): _engine.add_universal_fact('units', 'unit', (unit_name.lower(), unit_idx)) self._wrapped = _engine
def compile_krb(rb_name, generated_root_pkg, generated_root_dir, filename): engine = knowledge_engine.engine(('*direct*', compiler_bc)) try: fc_name = rb_name + '_fc.py' bc_name = rb_name + '_bc.py' plan_name = rb_name + '_plans.py' fc_path = os.path.join(generated_root_dir, fc_name) bc_path = os.path.join(generated_root_dir, bc_name) plan_path = os.path.join(generated_root_dir, plan_name) ast = krbparser.parse(krbparser, filename) #sys.stderr.write("got ast\n") # dump(ast) # sys.stderr.write('\n\n') engine.reset() engine.activate('compiler') (fc_lines, bc_lines, plan_lines), plan = \ engine.prove_1('compiler', 'compile', (generated_root_pkg, rb_name, ast), 3) krb_filename = to_relative(generated_root_dir, filename) ans = [] if fc_lines: sys.stderr.write("writing [%s]/%s\n" % (generated_root_pkg, os.path.basename(fc_path))) write_file(fc_lines + ( "", "Krb_filename = %r" % krb_filename, ), fc_path) ans.append(fc_name) elif os.path.lexists(fc_path): os.remove(fc_path) if bc_lines: sys.stderr.write("writing [%s]/%s\n" % (generated_root_pkg, os.path.basename(bc_path))) write_file(bc_lines + ( "", "Krb_filename = %r" % krb_filename, ), bc_path) ans.append(bc_name) elif os.path.lexists(bc_path): os.remove(bc_path) if plan_lines: sys.stderr.write("writing [%s]/%s\n" % (generated_root_pkg, os.path.basename(plan_path))) #sys.stderr.write("plan_lines:\n") #for line in plan_lines: # sys.stderr.write(" " + repr(line) + "\n") write_file(plan_lines + ( "", "Krb_filename = %r" % krb_filename, ), plan_path) ans.insert(len(ans) - 1, plan_name) # want this loaded before _bc elif os.path.lexists(plan_path): os.remove(plan_path) #sys.stderr.write("done!\n") return ans except: if os.path.lexists(fc_path): os.remove(fc_path) if os.path.lexists(bc_path): os.remove(bc_path) if os.path.lexists(plan_path): os.remove(plan_path) raise
def init(db_connection, trace_sql=False): global Engine, Db_connection, Db_cursor Engine = knowledge_engine.engine(sqlgen, __file__) Db_connection = db_connection Db_cursor = db_connection.cursor() if trace_sql: Db_cursor = trace_cursor(Db_cursor) return Engine
def compile_krb(rb_name, generated_root_pkg, generated_root_dir, filename): engine = knowledge_engine.engine(('*direct*', compiler_bc)) try: fc_name = rb_name + '_fc.py' bc_name = rb_name + '_bc.py' plan_name = rb_name + '_plans.py' fc_path = os.path.join(generated_root_dir, fc_name) bc_path = os.path.join(generated_root_dir, bc_name) plan_path = os.path.join(generated_root_dir, plan_name) ast = krbparser.parse(krbparser, filename) #sys.stderr.write("got ast\n") # dump(ast) # sys.stderr.write('\n\n') engine.reset() engine.activate('compiler') (fc_lines, bc_lines, plan_lines), plan = \ engine.prove_1('compiler', 'compile', (generated_root_pkg, rb_name, ast), 3) krb_filename = to_relative(generated_root_dir, filename) ans = [] if fc_lines: sys.stderr.write("writing [%s]/%s\n" % (generated_root_pkg, os.path.basename(fc_path))) write_file(fc_lines + ("", "Krb_filename = %r" % krb_filename,), fc_path) ans.append(fc_name) elif os.path.lexists(fc_path): os.remove(fc_path) if bc_lines: sys.stderr.write("writing [%s]/%s\n" % (generated_root_pkg, os.path.basename(bc_path))) write_file(bc_lines + ("", "Krb_filename = %r" % krb_filename,), bc_path) ans.append(bc_name) elif os.path.lexists(bc_path): os.remove(bc_path) if plan_lines: sys.stderr.write("writing [%s]/%s\n" % (generated_root_pkg, os.path.basename(plan_path))) #sys.stderr.write("plan_lines:\n") #for line in plan_lines: # sys.stderr.write(" " + repr(line) + "\n") write_file(plan_lines + ("", "Krb_filename = %r" % krb_filename,), plan_path) ans.insert(len(ans) - 1, plan_name) # want this loaded before _bc elif os.path.lexists(plan_path): os.remove(plan_path) #sys.stderr.write("done!\n") return ans except: if os.path.lexists(fc_path): os.remove(fc_path) if os.path.lexists(bc_path): os.remove(bc_path) if os.path.lexists(plan_path): os.remove(plan_path) raise
def test(kb, ke, arg): global Engine if Engine is None: Engine = knowledge_engine.engine(__file__) Engine.reset() Engine.activate('rules') try: Engine.prove_1(kb, ke, (arg,), 0) except knowledge_engine.CanNotProve: return raise AssertionError("test: expected CanNotProve exception")
def start(): """Initialize the rules engine with info from the database.""" #krb_path = config.get('krb_path') krb_path = os.getenv("PWD") # The argument to knowledge_engine.engine() must be a path to a place # where the process owner can write new files to, because the compiled # source files will be written there. print "initializing engine with "+str(krb_path) engine = knowledge_engine.engine(krb_path) return engine
def __init__(self, loc): """ Instantiates a new instance of the knowledge engine Args: loc: The directory which the knowledge bases to be loaded are located A package or directory may be passed """ self.engine = knowledge_engine.engine(loc) self.currentKB = None self.type = "knowledge" super(KnowledgeSystem, self).__init__(type)
def run(self): # Call parent build_ext.build_ext.run(self) # Add our new build dir to the start of the path to pick up the KE rules sys.path.insert(0, self.build_lib) # Compile the pyke rules from pyke import knowledge_engine import iris.fileformats._pyke_rules e = knowledge_engine.engine(iris.fileformats._pyke_rules)
def run(self): # Run the main build command first to make sure all the target # directories are in place. build_py.build_py.run(self) # Now build the std_names module. cmd = std_name_cmd(self.build_lib) self.spawn(cmd) # Compile the pyke rules with self.temporary_path(): # Compile the pyke rules from pyke import knowledge_engine import iris.fileformats._pyke_rules e = knowledge_engine.engine(iris.fileformats._pyke_rules)
def run(pantry, capacity): engine = knowledge_engine.engine(__file__) engine.activate("knapsack") max = 0 ans = None with engine.prove_goal( "knapsack.legal_knapsack($pantry, $capacity, $knapsack)", pantry=pantry, capacity=capacity ) as gen: for vars, no_plan in gen: knapsack = vars["knapsack"] calories = sum(map(lambda x: x[2], knapsack)) if calories > max: max = calories ans = knapsack return max, ans
def present_activities(self): if self.mode == "online": self.is_running = False elif self.mode == "offline": self.answer_list = [] for items in question_list1: for i in range(len(items.answer)): if items.answer[i] == True: self.answer_list.append( (items.question_num, self.INDEX_ANSWER_DICT[i])) for items in question_list2: for i in range(len(items.answer)): if items.answer[i] == True: self.answer_list.append( (items.question_num, self.INDEX_ANSWER_DICT[i])) engine = knowledge_engine.engine(__file__) engine.reset() engine.activate('category_rules') for answers in self.answer_list: engine.assert_('answer', 'question', answers) print("Facts gathered:") engine.get_kb('answer').dump_specific_facts() try: vars, plan = engine.prove_1_goal( 'category_rules.top2($category1, $category2)') print() print("Top 2 Activity Categories selected are: %s, %s" % (self.RBS_CATEGORIES_DICT[vars['category1']], self.RBS_CATEGORIES_DICT[vars['category2']])) print() except knowledge_engine.CanNotProve: krb_traceback.print_exc() self.user_preferences = list( (self.RBS_CATEGORIES_DICT[vars['category1']], self.RBS_CATEGORIES_DICT[vars['category2']])) selector_obj = Selector.city_selector() throwaway, self.cities_and_activities_results_list = selector_obj.find_matching_city( self.user_preferences) self.show_offline_result()
def run(pantry, capacity): engine = knowledge_engine.engine(__file__) engine.activate('knapsack') max = 0 ans = None with engine.prove_goal( 'knapsack.legal_knapsack($pantry, $capacity, $knapsack)', pantry=pantry, capacity=capacity) \ as gen: for vars, no_plan in gen: knapsack = vars['knapsack'] calories = sum([x[2] for x in knapsack]) if calories > max: max = calories ans = knapsack return max, ans
def __init__(self, size): """A universe is composed of agents, objects and facts which will be used for Pyke. For now, the locations for the universe are [0-size-1]. The universe has a knowledge engine which is then used by the agents of the universe for their own cognition phase.""" self.agents = [] self.objects = [] self.facts = [] self.locations = range(size) # Initialization of the knowledge engine self.ke = knowledge_engine.engine(__file__) self.all_satisfied = False # Adding the locations of the universe in the knowledge engine for location in self.locations: self.ke.add_universal_fact('universe', 'location', (location, ))
def __init__(self, size): """A universe is composed of agents, objects and facts which will be used for Pyke. For now, the locations for the universe are [0-size-1]. The universe has a knowledge engine which is then used by the agents of the universe for their own cognition phase.""" self.agents = [] self.objects = [] self.facts = [] self.locations = range(size) # Initialization of the knowledge engine self.ke = knowledge_engine.engine(__file__) self.all_satisfied = False # Adding the locations of the universe in the knowledge engine for location in self.locations: self.ke.add_universal_fact('universe', 'location', (location,))
def pick_form(request): engine = knowledge_engine.engine( (None, "pyke_test.knowledge_base.compiled_krb")) ask = DjangoAskModule(engine, request.session) engine.ask_module = ask # engine.activate("q_test") engine.activate("permits") engine.load_question_cache(request.session.get("q_cache", {})) if request.method == "POST": if not ask.record_answer(request.POST): form = ask.getForm() return render_to_response( "foo/simple_form.html", { "form": form, "title": "Identify Required Permits", "heading": "Answer the questions to identify the required permits" }) # Read last review message, if there is one. if request.session.has_key("last_review"): last_review = request.session["last_review"] del request.session["last_review"] else: last_review = None try: plan = engine.prove_1_goal( "permits.actions_require_summary($specieslist, $summary)", specieslist=request.session["species"]) request.session["q_cache"] = engine.get_question_cache() return display_plan(request, plan, last_review) except DjangoAsyncInterrupt: request.session["q_cache"] = engine.get_question_cache() form = ask.getForm() return render_to_response( "foo/simple_form.html", { "form": form, "title": "Identify Required Permits", "heading": "Answer the questions to identify the required permits", "intro_txt": last_review })
def which_package(packages, duration): # We are loading Pyke rules base we have defined in pricing.krb engine = knowledge_engine.engine((__file__, '.rules')) engine.activate('pricing') # Creating the facts base from the package list. for package in packages: engine.assert_('packages', 'package', (package,)) # Now, we have our rules and our facts, let's just prove that a package applies. try: vals, plans = engine.prove_1_goal('pricing.packages($type, $delta)', delta=duration) print vals['type'] # We cannot prove that any package applies therefore no package applies. except knowledge_engine.CanNotProve: print "No package applies" # Resetting the engine is needed to be able to apply a new fact base. engine.reset()
def prove_price(self, started_at, ended_at): engine = knowledge_engine.engine( (PerformanceOrigTest.__FILE__, '.rules')) engine.activate(self.kb_name) for day_amount, unit in self.prices: engine.assert_('prices', 'price', (unit, day_amount)) delta = ended_at - started_at vals, plans = engine.prove_1_goal( # pylint: disable=unused-variable '{}.pricing($type, $started_at, $ended_at, $delta)'.format( self.kb_name), started_at=started_at, ended_at=ended_at, delta=delta) unit = PACKAGES_UNIT[vals['type']] # pylint: disable=unused-variable engine.reset()
def myTest(): # knowledge_engine.debug = True engine = knowledge_engine.engine(__file__) # engine = knowledge_engine.engine() # engine.add_universal_fact('family', 'son_of', ('david', 'bruce')) # engine.get_kb('family').dump_universal_facts() # engine.get_kb('family').dump_specific_facts() # son_of('david', 'bruce') # engine.reset() engine.activate('example') kb = engine.get_kb('family') kb.dump_universal_facts() print("Specific facts are:") engine.get_kb('family').dump_specific_facts() # all forward-chaining rules are run print("doing proof") try: with engine.prove_goal('example.real_siblings($a, $b)') as gen: for variable, plan in gen: print("%s and %s" % (variable['a'], variable['b'])) except Exception: # This converts stack frames of generated python functions back to the # .krb file. krb_traceback.print_exc() sys.exit(1) print("doing second proof") try: with engine.prove_goal('example.half_sibling($a, $b)') as gen: for variable, plan in gen: print("%s, %s are half_siblings" % (variable['a'], variable['b'])) except Exception: # This converts stack frames of generated python functions back to the # .krb file. krb_traceback.print_exc() sys.exit(1) print() print("done") engine.print_stats()
def _pyke_rule_compile(): """Compile the PyKE rule base.""" from pyke import knowledge_engine import iris.fileformats._pyke_rules knowledge_engine.engine(iris.fileformats._pyke_rules)
def __init__(self, source_path=DEFAULT_SOURCE_PATH): self.engine = knowledge_engine.engine(source_path) self.engine.activate(RB_NAME) logging.info("Started knowledge base engine")
def launch_engine(): engine = knowledge_engine.engine(__file__) engine.reset() engine.activate('travelrules') return engine
def calculate(result): """Calculates the timings for straight and right turning directions and phases. Uses the input values returned from the HTML form. """ lanes = [] c = [] cars_str = [] cars_rt = [] if result['jlist'] == '4way': junctions = junc(lambda prompt: 4) #FETCHED VALUE FROM HTML pre = 'd' else: junctions = junc(lambda prompt: 3) pre = 'td' for i in range(1, junctions + 1): #print("For junction "+ str(i) +" ") engine = knowledge_engine.engine(".\pyke1") lanes_st = str_lane(lambda prompt: result[pre + str(i) + 'lanes'] ) #FETCHED VALUE FROM HTML cars = result[pre + str(i) + 'cars'].split(',') #print(cars) for j in range(0, int(lanes_st)): engine = knowledge_engine.engine(".\pyke1") temp1 = str_lane_cars( lambda prompt: int(cars[j])) #FETCHED VALUE FROM HTML c.append(temp1) cars_str.append(c) c = [] engine = knowledge_engine.engine(".\pyke1") r = rt_lane(lambda prompt: result[pre + str(i) + 'right'] ) #FETCHED VALUE FROM HTML if r != 0: engine = knowledge_engine.engine(".\pyke1") temp1 = rt_lane_cars(lambda prompt: result[pre + str(i) + 'right'] ) #FETCHED VALUE FROM HTML c.append(int(temp1)) cars_rt.append(c) c = [] lanes_rt = 1 else: lanes_rt = 0 c.append(0) cars_rt.append(c) c = [] lanes.append((lanes_st, lanes_rt)) m = 3.5 total_cars = [] for i in range(0, len(cars_str)): tc = sum(cars_str[i]) + sum(cars_rt[i]) total_cars.append(tc) st_time = [] #print(len(cars_str)) for i in range(0, len(cars_str)): max_cars = max(cars_str[i]) res = junction_rules(int(result[pre + str(i + 1) + 'lanes'])) #print(res) if res[0] == 'big': penalty = (sum([x for k, x in enumerate(total_cars) if k != i]) / ( sum([len(x) for k, x in enumerate(cars_str) if k != i]) + sum([ len(x) for k, x in enumerate(cars_rt) if k != i and x[0] != 0 ]))) bias = res[1] ts = (max_cars * m + bias) - penalty st_time.append(ts) elif res[0] == 'small': penalty = 5 bias = res[1] ts = (max_cars * m + bias) - penalty st_time.append(ts) rt_time = [] #print(st_time) if junctions == 3: print(junctions) tr = 0 i = 0 if st_time[i] < st_time[i + 1]: tr = cars_rt[i][0] * m rt_time.append(tr) elif st_time[i] >= st_time[i + 1] and cars_rt[i][0] * m != 0: if cars_rt[i][0] * m < st_time[i] - st_time[i + 1]: tr = st_time[i] - st_time[i + 1] else: tr = (cars_rt[i][0] - (st_time[i] - st_time[i + 1]) / m) * m rt_time.append(tr) print("Time Straight: ", round(max(st_time[0], st_time[1]), 2), "Time Right: ", round(rt_time[0], 2)) print("Time Straight: ", round(st_time[2], 2), "Time Right: ", round(0, 2)) return (st_time, rt_time, junctions) elif junctions == 4: print(junctions) for i in range(0, len(st_time), 2): tr = 0 max_rcars = max(cars_rt[i][0], cars_rt[i + 1][0]) if st_time[i] < st_time[i + 1]: tr = max_rcars * m rt_time.append(tr) elif st_time[i] >= st_time[i + 1] and cars_rt[i][0] * m != 0: if max_rcars * m < st_time[i] - st_time[i + 1]: tr = st_time[i] - st_time[i + 1] else: tr = (max_rcars - (st_time[i] - st_time[i + 1]) / m) * m rt_time.append(tr) print("Time Straight: %4.2f" % round(max(st_time[0], st_time[1]), 2), "Time Right: %4.2f" % round(rt_time[0])) print("Time Straight: %4.2f" % round(max(st_time[2], st_time[3]), 2), "Time Right: %4.2f" % round(rt_time[1])) return (st_time, rt_time, junctions)
def init(*args, **kws): global Engine, Did_init Engine = knowledge_engine.engine(*args, **kws) Did_init = True
Once the pyke engine is created, all the rule bases loaded and all the primary data established as universal facts; there are five functions that can be used to run each of the three rule bases: fc_test, bc_test, bc2_test, test and general. """ from __future__ import with_statement import contextlib import sys import time from pyke import knowledge_engine, krb_traceback, goal # Compile and load .krb files in same directory that I'm in (recursively). engine = knowledge_engine.engine(__file__) fc_goal = goal.compile("family.how_related($person1, $person2, $relationship)") def fc_test(person1="bruce"): """ This function runs the forward-chaining example (fc_example.krb). """ engine.reset() # Allows us to run tests multiple times. start_time = time.time() engine.activate("fc_example") # Runs all applicable forward-chaining rules. fc_end_time = time.time() fc_time = fc_end_time - start_time
if profile == 'LD': if not checkProfile.checkIfOWLLD(g)[0]: # raise Exception('Ontology not in OWL-LD!') # only removes blank nodes toRem = [] for t in g: if type(t[0]) == rdflib.term.BNode or type(t[1]) == rdflib.term.BNode or type (t[2]) == rdflib.term.BNode: toRem.append(t) for r in toRem: g.remove(r) # Assert facts in PyKE engine = knowledge_engine.engine('.') for t in t_set: engine.assert_('ontology', 'triple', t) # Run inference if profile == 'LD': engine.activate('fc_owlld') elif profile == 'RL': engine.activate('fc_owlrl') triples = engine.knowledge_bases['ontology'].entity_lists['triple'].case_specific_facts # Build set with inference results pyke_t_set = set()
from pyke import knowledge_engine as ke from pyke import contexts import os sus = ke.engine(__file__) sus.activate('regras') sus.get_kb('relacao') ## Contador das doenças: dengue, zika e chiku global_cont_dengue = 0 global_cont_zika = 0 global_cont_chiku = 0 ## Febre def febre(): global global_cont_dengue global global_cont_zika global global_cont_chiku print("Com respeito aos sintomas:") print("Qual o grau, e duração da febre:") print("1- Acima de 38ºC (4 a 7 dias)") print("2- Sem febre ou subfebril 38ºC (1-2 dias subfebril)") print("3- Febre alta maior que 38ºC (2-3 dias)") febre = int(input()) while (febre <= 0 or febre > 3): print("Insira uma opção válida (1 - 3): ") febre = int(input()) #Adiciona ao contador e relaciona a prova da biblioteca pyke if febre == 1:
def main(): my_engine = knowledge_engine.engine('bases') my_engine.activate('barman_r') start = 'Robot3' # Здесь задаётся начальная ситуация (описание возможных смотрите в файле barman_f) my_engine.assert_('barman_f', start, (True, )) if (start == 'Robot9'): final = True else: final = False if ((start == 'Robot5') or (start == 'Robot6') or (start == 'Robot7')): glasses = [1, 1, 1, 1] # Здесь задаётся вектор стаканов (для данных ситуаций все стаканы полны), # по желанию можно увеличить размер вектора (в зависимости от того сколько стаканов) else: glasses = [0, 0, 0, 0] # Здесь задаётся вектор стаканов для остальных ситуаций (0 - если стакан пуст, 1 - если заполнен) # по желанию можно увеличить размер вектора (в зависимости от того сколько стаканов) if not final: nGlasses = len(glasses) for i in range(nGlasses): if (glasses[i] == 0): if (start == 'Robot'): my_engine.prove_1_goal('barman_r.robot_grasp_shaker()')[1]( i) elif (start == 'Robot1'): my_engine.prove_1_goal('barman_r.robot_dispense()')[1](i) elif (start == 'Robot2'): my_engine.prove_1_goal('barman_r.robot_shake()')[1](i) else: break print('\n') glasses[i] = 1 break if ((start != 'Robot') and (start != 'Robot1')): my_engine.assert_('barman_f', 'Robot1', (True, )) for i in range(nGlasses): if (glasses[i] == 0): my_engine.prove_1_goal('barman_r.robot_dispense()')[1](i) print('\n') glasses[i] = 1 if ((start != 'Robot5') and (start != 'Robot6') and (start != 'Robot7')): if (start != 'Robot8'): my_engine.assert_('barman_f', 'Robot8', (True, )) my_engine.prove_1_goal('barman_r.robot_put_shaker()')[1](0) elif (start == 'Robot6'): my_engine.assert_('barman_f', 'Robot5', (True, )) my_engine.prove_1_goal('barman_r.robot_give_glass()')[1](0) elif (start == 'Robot5'): my_engine.prove_1_goal('barman_r.robot_grasp_glass()')[1](0) else: my_engine.assert_('barman_f', 'Robot5', (True, )) my_engine.prove_1_goal('barman_r.robot_grasp_glass()')[1](0) print('\n') for i in range(1, nGlasses): my_engine.prove_1_goal('barman_r.robot_grasp_glass()')[1](i) print('\n') my_engine.assert_('barman_f', 'Robot9', (True, )) my_engine.prove_1_goal('barman_r.final()')[1]() else: my_engine.prove_1_goal('barman_r.final()')[1]()
def run(): global Robot, Building_center engine = knowledge_engine.engine(__file__) Robot = robot_simulator.start() # Add the following universal facts: # # layout.board(width, height) # layout.building(left, top, right, bottom) # layout.building_center(x, y) # layout.car(width, height) # layout.car_logical_center(x_offset, y_offset) # layout.range_finder(width, length) # layout.safety_factor(safety_factor) # layout.track(left, top, right, bottom) # layout.direction(cc|ccw) # layout.waypoint(x, y) engine.add_universal_fact('layout', 'board', (robot_simulator.Width, robot_simulator.Height)) corners = left, top, right, bottom = \ robot_simulator.Building.left, \ robot_simulator.Building.top, \ robot_simulator.Building.right, \ robot_simulator.Building.bottom print "building corners", corners engine.add_universal_fact('layout', 'building', corners) Building_center = robot_simulator.Building.center engine.add_universal_fact('layout', 'building_center', Building_center) engine.add_universal_fact('layout', 'car', Robot.car.rect[2:]) engine.add_universal_fact('layout', 'car_logical_center', Robot.car.logical_center) engine.add_universal_fact('layout', 'range_finder', Robot.rf.rect[2:]) safety_factor = max(Robot.car.rect.size) + 5 engine.add_universal_fact('layout', 'safety_factor', (safety_factor,)) track = (left - safety_factor, top - safety_factor, right + safety_factor, bottom + safety_factor) print "track", track engine.add_universal_fact('layout', 'track', track) initial_direction = direction(Robot.heading) print "initial_direction", initial_direction engine.add_universal_fact('layout', 'direction', (initial_direction,)) engine.add_universal_fact('layout', 'waypoint', (track[0], track[1])) engine.add_universal_fact('layout', 'waypoint', (track[0], track[3])) engine.add_universal_fact('layout', 'waypoint', (track[2], track[1])) engine.add_universal_fact('layout', 'waypoint', (track[2], track[3])) engine.add_universal_fact('layout', 'waypoint', Robot.position) for step in itertools.count(): x, y = Robot.position print "Robot position %d, %d" % Robot.position engine.add_universal_fact('history', 'position', (step, x, y)) print "Robot heading %d" % Robot.heading engine.add_universal_fact('history', 'heading', (step, Robot.heading)) engine.add_universal_fact('history', 'car_radial', (step, heading(Building_center, Robot.position))) engine.reset() engine.activate('rules') print "proving step", step try: vars, _ = engine.prove_1_goal('rules.get_plan($step, $plan)', step=step) except: krb_traceback.print_exc() sys.exit(1) plan = vars['plan'] if plan is None: print "Success!" break ans = plan() print "plan done, Robot at (%d, %d)" % Robot.position engine.add_universal_fact('history', 'result', (step, ans))
def init(*args, **kws): global Engine, Did_init Engine = knowledge_engine.engine(*args, **kws) Did_init = True
def run(): engine = knowledge_engine.engine(__file__) engine.activate('backup') vars, plan = engine.prove_1_goal('backup.top($ans)') print vars['ans']
def pyke_load_engine(): global engine engine = knowledge_engine.engine((__file__, '.rules'))
from flask import request from flask import render_template from pyeasyga import pyeasyga import numpy as np import numpy.random as random import os abspath = os.path.abspath("app.py") dname = os.path.dirname(abspath) os.chdir(dname) # Rule Based Timing Assignment #................................................................................. engine = knowledge_engine.engine(".\pyke1") def junc(infunc=engine.prove_1_goal): """Determines the type of junction based on the number of directions at the junction """ junctions = infunc('try.junction_number($num)') return junctions def str_lane(infunc=engine.prove_1_goal): """Determine the number of straight lanes """ st_lanes = infunc('try.junction_number($num)') return st_lanes
def init(*paths): global Engine Engine = knowledge_engine.engine(*paths)
def __init__(self): self.engine = knowledge_engine.engine(__file__) self.engine.activate('bc_odrl') self.odrl_factory = odrl()
except knowledge_engine.CanNotProve: if i + 1 < df.shape[0]: check_disease(df.iloc[i + 1, 0], i + 1) else: pass if __name__ == "__main__": df = pd.read_csv('./trimmed_dataset.csv', encoding='utf-8') RULE_FILE = create_bc_rules(df) try: shutil.rmtree('./compiled_krb') except: pass my_engine = knowledge_engine.engine('./knowledgebase') my_engine.ask_module = ask_tty my_engine.reset() print('''\n\n*****Welcome to Medical Diagnosis System****** I am your personal Diagnosis Expert System. Please answer the following questions''' ) my_engine.activate('ask_rules') my_engine.activate(RULE_FILE) vals, plans = my_engine.prove_1_goal(f"ask_rules.get_name($name)") print(vals['name']) # vals, plans = my_engine.prove_1_goal(f"ask_rules.get_age($age)") # print(vals['age'])
def mk_engine(*paths): if isinstance(self.paths, types.StringTypes): self.paths = (self.paths,) return knowledge_engine.engine(*paths)
def _pyke_rule_compile(): """Compile the PyKE rule base.""" from pyke import knowledge_engine import iris.fileformats._pyke_rules knowledge_engine.engine(iris.fileformats._pyke_rules)
def process_dicom_file(dicom_file): phi_rule = list() undef_rule = list() # extract dicom dataset try: logging.info("process_dicom_file: " + dicom_file) dataset = dicom.read_file(dicom_file) except: logging.error("process_dicom_file: file open error: " + dicom_file) return 1, 'file_not_found', 'none', 'none' tags_total = len(dataset) tags_blank = 0 tags_nokey = 0 tags_isphi = 0 tags_nophi = 0 engine = knowledge_engine.engine(__file__) engine.reset() goal_isphi = goal.compile('dicom_file.isphi_tag($tag)') goal_nokey = goal.compile('dicom_file.nokey_tag($tag)') goal_blank = goal.compile('dicom_file.blank_tag($tag)') goal_nophi = goal.compile('dicom_file.nophi_tag($tag)') # extract tag and value from dicom file and add as pyke specific fact for data_element in dataset: tag = str(data_element.tag).lower() tag = tag.replace(", ", ",") val = str(data_element.value) val = val.rstrip().lstrip() engine.add_case_specific_fact('dicom_file', 'attribute_is', (tag, val)) engine.activate('cad_pyke_dicom') # engine.get_kb('dicom_file').dump_specific_facts() with goal_isphi.prove(engine) as gen: for vars, plan in gen: tags_isphi += 1 phi_rule.append(vars['tag']) with goal_nokey.prove(engine) as gen: for vars, plan in gen: tags_nokey += 1 undef_rule.append(vars['tag']) with goal_blank.prove(engine) as gen: for vars, plan in gen: tags_blank += 1 with goal_nophi.prove(engine) as gen: for vars, plan in gen: tags_nophi += 1 # error if tag counts don't match if tags_total != (tags_blank + tags_nokey + tags_isphi + tags_nophi): logging.error("process_dicom_file: tag count mismatch," + " total:" + str(tags_total) + " blank:" + str(tags_blank) + " nokey:" + str(tags_nokey) + " isphi:" + str(tags_isphi) + " nophi:" + str(tags_nophi)) return 2, 'indeterminate', 'none', 'none' # construct return parameters if tags_isphi == 0 and tags_nokey == 0: status = "not_phi" else: status = "is_phi" # we are done, print status and reason logging.info("process_dicom_file: status: " + status) logging.info("process_dicom_file: reason: tag counts -" + " total:" + str(tags_total) + " blank:" + str(tags_blank) + " nokey:" + str(tags_nokey) + " isphi:" + str(tags_isphi) + " nophi:" + str(tags_nophi)) return 0, status, str(phi_rule), str(undef_rule)
#!/usr/local/bin/python # -*- coding: utf-8 -*- from pyke import knowledge_engine import pdir engine = knowledge_engine.engine('/Users/William/Programming/PyKE/test/kbtest') engine.activate('rule') engine.get_kb('knowledge').dump_specific_facts() res, _ = engine.prove_1_goal('knowledge.master(liaoyinan, $language)') print(res)
from __future__ import with_statement import contextlib import sys import time import os from pyke import knowledge_engine, krb_traceback, goal # Compile and load .krb files in same directory that I'm in (recursively). #engine = knowledge_engine.engine(__file__) engine = knowledge_engine.engine(os.getcwd()) fc_goal = goal.compile('fb_checkin.updated_sample_size($node,$value)') def fc_test(node=7030): ''' This function runs the forward-chaining example (animalia.krb). ''' engine.reset() # Allows us to run tests multiple times. start_time = time.time() engine.activate( 'fb_checkin_fc') # Runs all applicable forward-chaining rules. fc_end_time = time.time() fc_time = fc_end_time - start_time print "doing proof" with fc_goal.prove(engine, node=node) as gen: #print "gen1:",gen print "train-test-split:", node
def run(): engine = knowledge_engine.engine(__file__) engine.activate('backup') vars, plan = engine.prove_1_goal('backup.top($ans)') print vars['ans']
# -*- coding: utf-8 -*- """ Created on Thu Sep 5 15:54:57 2019 @author: kartik """ from pyke import knowledge_engine from pyke import goal engine = knowledge_engine.engine(".\pyke") jn = goal.compile('try.junction_number($num)') #a = my_goal.prove_1(engine) #a = engine.prove_1_goal('try.junction_category($lanes)') #print(a[0]['lanes']) #b = engine.prove_1_goal('try.junction_number($num)') #print(b[0]['num']) #junctions = int(input("Enter the number of junctions: ")) temp = engine.prove_1_goal('try.junction_number($num)') junctions = temp[0]['num'] lanes = [] c = [] cars_str = [] cars_rt = []
# driver.py from __future__ import with_statement import sys from pyke import knowledge_engine from pyke import krb_traceback engine = knowledge_engine.engine(__file__) def bc_test(client="client1"): engine.reset() try: engine.activate('bc_functions') with engine.prove_goal('bc_functions.findB($client)', client=client) as gen: for k, v in gen: print("iter") print(k) print(v()) print("----") except: krb_traceback.print_exc() sys.exit(1)
def main(): my_engine = knowledge_engine.engine(__file__) return