def prove_1_goal(self, goal_str, **args): r'''Proves goal_str with logic variables set to args. Returns the vars and plan for the first solution found. Raises knowledge_engine.CanNotProve if no solutions are found. Ugly setup to use the family_relations example. You can ignore this... :-( >>> source_dir = os.path.dirname(os.path.dirname(__file__)) >>> family_relations_dir = \ ... os.path.join(source_dir, 'examples/family_relations') >>> sys.path.insert(0, family_relations_dir) >>> from pyke import knowledge_engine >>> my_engine = knowledge_engine.engine(family_relations_dir) >>> my_engine.activate('bc_example') OK, here's the example! >>> vars, plan = \ ... my_engine.prove_1_goal( ... 'bc_example.how_related($person1, $person2, $how_related)', ... person1='bruce', ... person2='m_thomas') >>> print "bruce is related to m_thomas as", vars['how_related'] bruce is related to m_thomas as ('father', 'son') If you want more than one answer, see engine.prove_goal. ''' return goal.compile(goal_str).prove_1(self, **args)
def create_stackup(): fc_goal = goal.compile('pcb.needs_gnd_layer($net)') engine.reset() # Allows us to run tests multiple times. # Also runs all applicable forward-chaining rules. start_time = time.time() engine.activate('fc_pcb') #print "dumping facts..:" #engine.get_kb('pcb').dump_universal_facts() fc_end_time = time.time() fc_time = fc_end_time - start_time print "Requires neighboring gnd layer:" try: # In this case, the relationship is returned when you run the plan. with fc_goal.prove( engine\ ) \ as gen: for vars, plan in gen: print "%s" % (vars['net']) #print "%s is a suitable material for %s" % (vars['material'], vars['net']) except StandardError: # This converts stack frames of generated python functions back to the # .krb file. krb_traceback.print_exc() sys.exit(1)
def prove_goal(self, goal_str, **args): r'''Proves goal_str with logic variables set to args. This returns a context manager that you use in a with statement: Ugly setup to use the family_relations example. You can ignore this... :-( >>> source_dir = os.path.dirname(os.path.dirname(__file__)) >>> family_relations_dir = \ ... os.path.join(source_dir, 'examples/family_relations') >>> sys.path.insert(0, family_relations_dir) >>> from pyke import knowledge_engine >>> my_engine = knowledge_engine.engine(family_relations_dir) >>> my_engine.activate('bc_example') OK, here's the example! >>> with my_engine.prove_goal( ... 'family.how_related($person1, $person2, $how_related)', ... person1='bruce') as it: ... for vars, plan in it: ... print "bruce is related to", vars['person2'], "as", \ ... vars['how_related'] vars is a dictionary of all of the logic variables in the goal (without the '$') and their values. The plan is a callable python function. If you only want the first answer, see engine.prove_1_goal. ''' return goal.compile(goal_str).prove(self, **args)
def fc_test(coil_kind, external_diameter, width, status1=1, Flag='0'): fc_goal = goal.compile('coil_area.move_area($coil_kind,$area,$status)') try: with fc_goal.prove(engine, coil_kind=coil_kind, status=status1) as gen: for vars, plan in gen: # 读取数据库中库区的信息 # 当前库区的最大长度 Max_Length = select_data('UACS_STOCK_INFO', vars['area'])[0] # 当前库区的最大宽度 Max_Width = select_data('UACS_STOCK_INFO', vars['area'])[1] # 当前库区的库容率 Current_Ratio = select_data('UACS_STOCK_INFO', vars['area'])[2] # 计算该钢卷放入之后的库容率 Cal_Capacity = Current_Ratio + (external_diameter * width) / ( Max_Length * Max_Width) # print "若该钢卷放入%s区域,库容率为%f"%(vars['area'],Cal_Capacity) if Cal_Capacity < 1 and Flag == '0': print "%s should be played in %s" % (coil_kind, vars['area']) return vars['area'] if Cal_Capacity >= 1 or Flag == '1': if Flag == '1': print "the saddle of %s area is full" % (vars['area']) else: print "the %s area is full" % (vars['area']) status_n = status1 + 1 return fc_test(coil_kind, external_diameter, width, status1=status_n) return "null" except: print "something err" krb_traceback.print_exc() sys.exit()
def recommend_controlled_z(): fc_goal = goal.compile('pcb.needs_ctrl_z($net)') engine.reset() # Allows us to run tests multiple times. # Runs all applicable forward-chaining rules. engine.activate('fc_pcb') print "Requires controlled impedance tracewidth:" try: # In this case, the relationship is returned when you run the plan. with fc_goal.prove( engine\ ) \ as gen: for vars, plan in gen: print "%s" % (vars['net']) #print "%s is a suitable material for %s" % (vars['material'], vars['net']) except StandardError: # This converts stack frames of generated python functions back to the # .krb file. krb_traceback.print_exc() sys.exit(1)
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 print "doing proof" with fc_goal.prove(engine, person1=person1) as gen:
def _create_column(engine, table_name, col_name, type, null, key, default, extra): #null = null.upper() == 'YES' if not key: key = None if not default: default = None if not extra: extra = None _add_fact(engine, "column", (table_name, col_name, type, null, key, default, extra)) if col_name == 'id': _add_fact(engine, "primary_key", (table_name, (col_name,))) if col_name.endswith('_id'): to_table = col_name[:-3] _add_fact(engine, "many_to_1", (table_name, to_table, (col_name,), ('id',))) many_to_1 = goal.compile( 'schema.many_to_1($from_table, $to_table, $from_columns, $to_columns)') links_to = goal.compile( 'schema.links_to($depth, $from_table, $to_table, $joins)') many_to_1_to = goal.compile( 'schema.many_to_1($to_table, $end_table, $to_columns, $end_columns)') def _links_to(engine, depth): ans = False if depth == 1: with many_to_1.prove(engine) as gen1: for vars, bogus_plan in gen1: from_table, to_table, from_columns, to_columns = \ vars['from_table'], vars['to_table'], vars['from_columns'], \ vars['to_columns']
import contextlib as contextlib import sys as sys import time as time import random as random from pyke import knowledge_engine, krb_traceback, goal #!!!!! USE PYTHON 3 #!!!!! engine = knowledge_engine.engine(__file__) fc_init = goal.compile('famous.knownFor($person, $status)') fc_rules = goal.compile('famous.rules($person, $nation)') fc_real = goal.compile('famous.real($person)') fc_lighthair = goal.compile('famous.lighthair($person, $haircolor)') fc_gender = goal.compile('famous.gender($person, $gender)') fc_title = goal.compile('famous.title($person, $title)') fc_dictator = goal.compile('famous.dictator($person)') fc_allies = goal.compile('famous.friendly_with($person, $nation)') fc_skill = goal.compile('famous.famousFor($person, $skill)') fc_children = goal.compile('famous.children($person)') fc_race = goal.compile('famous.race($person, $race)') fc_disney = goal.compile('famous.disney($person)') fc_princess = goal.compile('famous.princess($person)') fc_comic = goal.compile('famous.comics($person)') fc_villain = goal.compile('famous.villain($person)') fc_lightsaber = goal.compile('famous.lightsaber($person)') eliminated_persons = [] init_persons = []
# -*- 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 = []
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)') reasonable_goal = goal.compile('facts.reasonable()') def single_reasonability_test(): """ Checks reasonability rules for a single instance """ engine.reset() start_time = time.time() engine.activate( 'reasonability') # Runs all applicable forward-chaining rules. fc_end_time = time.time() fc_time = fc_end_time - start_time
import contextlib import sys import time import random 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_init = goal.compile('leaders.rules($leader, $nation)') fc_continent = goal.compile('leaders.on_continent($leader, $continent)') fc_goal2 = goal.compile('leaders.gender($leader, $gender)') fc_goal3 = goal.compile('leaders.title($leader, $title)') fc_goal4 = goal.compile('leaders.dictator($leader)') fc_goal6 = goal.compile('leaders.friendly_with($leader, $nation)') eliminated_leaders = [] init_leaders = [] def kb_init(): curr_list = [] engine.reset() engine.activate('fc_rules') with fc_init.prove(engine) as gen: for vars, plan in gen: curr_list.append(vars['leader']) global init_leaders init_leaders = curr_list
#!/usr/bin/python # -*- encoding:utf-8 -*- """ @author: zhouning @file:driver.py @time:2018/5/7 10:54 https://blog.csdn.net/lawme/article/details/5378278 """ from pyke import knowledge_engine, goal if __name__ == '__main__': engine = knowledge_engine.engine(__file__) engine.activate("fc_related") # This is where the rules are run! engine.get_kb("family").dump_specific_facts() # print(engine.prove_1_goal('family1.son_of(thomas,$son)')) print(engine.prove_1_goal('family.father_son(hiram,$son,())')) fc_goal = goal.compile( 'family.how_related($person1, $person2, $relationship)') print("finish...")
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 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)
cell_with_highest_commonality = index2 temp = counter counter = 0 if (cell_with_highest_commonality != -1): print "The cell chosen is %d,%d, with commonality index as %d" % ( cell_with_highest_commonality / 9, cell_with_highest_commonality % 9, temp) return cell_with_highest_commonality if __name__ == "__main__": engine = knowledge_engine.engine(__file__) fc_goal = goal.compile('sudoku.status($iteration, $status_value)') ## These are the EASY SUDOKU puzzles unsolved_input = "89127456.6.31859..457639...5.641723.7429.381.31..26.5.93854.67.16479.32..7536149." # unsolved_input = "572138.4.4.6.59817....67..2.43725..61.5.43728..96.13.43.7.14..5218.9.473.54.72..1" # unsolved_input = "49.63..58.6.28...91....74.3.5.4..68..4.8693753..7.592.875.9...6..4576.32.321.8597" # unsolved_input = "..5.397.6.976851..6.2..45....35..47.2..86.931718.9326.53674.82..71.2.3..4.9.58617" ## These are the HARD SUDOKU puzzles # unsolved_input = ".......37.4.8......2......65..9..1..7........3.6..5..................91.....37..." # unsolved_input = "..62.8...3......4..........4...7.1..........2.5..3.6.8.......9.....5......86....." # unsolved_input = "......5......2...79.3.1....4857.....3....8.6....5......7......2..9...4......4..3." # This code creates a sudoku puxxle similar to the commented-out sudoku_puzzle found below sudoku_puzzle = [] for r in xrange(9):
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. ''' 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('leaders.on_continent($leader, $continent)') fc_goal2 = goal.compile('leaders.gender($leader, $gender)') def fc_test(continent = 'Europe'): ''' This function runs the forward-chaining example (fc_example.krb). ''' engine.reset() # Allows us to run tests multiple times. print("test1") start_time = time.time() engine.activate('fc_rules') # Runs all applicable forward-chaining rules. fc_end_time = time.time() fc_time = fc_end_time - start_time
from __future__ import with_statement import contextlib import sys from pyke import knowledge_engine, krb_traceback, goal engine = knowledge_engine.engine(__file__) goals = [ goal.compile('food.recipe_glycemic_load($recipe, $glycemic_load)'), goal.compile('food.recipe_saturated_fats($recipe, $saturated_fats)'), goal.compile('food.recipe_proteins($recipe, $proteins)'), goal.compile('food.recipe_fibers($recipe, $fibers)'), goal.compile('food.recipe_calories($recipe, $calories)'), ] def recipe_calculation_test(recipe='spaghetti'): engine.reset() engine.activate('calculation_expressions') print("\n Goals for " + recipe + ":") for goal in goals: process_goal(goal, recipe) def constraint_test(): engine.activate('constraint_expressions') print("\n All asserted facts:") engine.get_kb('food').dump_specific_facts() def process_goal(goal, recipe): with goal.prove(engine, recipe=recipe) as g: for vars, plan in g: print vars #engine.print_stats()