def _time_shift_forward(self, active_pm, script, backward=False): """ Next situation synthesis :param active_pm: meaning of active situation :param script: meaning of active action :param backward: planning style :return: """ next_situation = Sign(st.SIT_PREFIX + str(st.SIT_COUNTER)) self.world_model[next_situation.name] = next_situation pm = next_situation.add_meaning() st.SIT_COUNTER += 1 copied = {} for event in active_pm.cause: for es in self._applicable_events(script, effect=backward): if event.resonate('meaning', es): break else: pm.add_event(event.copy(pm, 'meaning', 'meaning', copied)) for event in self._applicable_events(script, effect=not backward): pm.add_event(event.copy(pm, 'meaning', 'meaning', copied)) pm = pm.copy('meaning', 'image') global_situation = self.world_model['situation'] global_cm = global_situation.add_image() connector = global_cm.add_feature(pm) next_situation.add_out_image(connector) return pm
def create_situation(name, predicates): sign = Sign(name) signif = sign.add_significance() for pred in predicates: connector = signif.add_feature(pred.significances[1]) pred.add_out_significance(connector) return sign
def __add_sign(sname, need_signif=True): if sname in signs: sign = signs[sname] else: sign = Sign(sname) signs[sname] = sign if need_signif: obj_signifs[sign] = sign.add_significance() return sign
def signify_actions(actions, constraints, signs, agent, obj_means, obj_signifs): for action in actions: act_sign = Sign(action.name) act_signif = act_sign.add_significance() def update_significance(predicate, signature, effect=False): pred_sign = signs[predicate.name] if len(pred_sign.significances) > 1: pred_cm = pred_resonate('significance', pred_sign, predicate, signs, signature) elif len(pred_sign.significances) == 0: pred_cm = pred_sign.add_significance() else: pred_cm = pred_sign.significances[1] connector = act_signif.add_feature(pred_cm, effect=effect) pred_sign.add_out_significance(connector) if len(predicate.signature) == 1: fact = predicate.signature[0] role_sign = signs[fact[1][0].name + fact[0]] conn = act_signif.add_feature(role_sign.significances[1], connector.in_order, effect=effect, zero_out=True) role_sign.add_out_significance(conn) elif not len(predicate.signature) == 0: if not predicate.signature[0][1][ 0].name == predicate.signature[1][1][0].name: for role_sign in pred_cm.get_signs(): connector_new = act_signif.add_feature( role_sign.significances[1], connector.in_order, effect=effect, zero_out=True) role_sign.add_out_significance(connector_new) for predicate in action.precondition: update_significance(predicate, action.signature, False) for predicate in action.effect.addlist: update_significance(predicate, action.signature, True) signs[action.name] = act_sign if constraints: if not action.agents: nonspecialized(constraints, act_signif, signs, agent, obj_means, obj_signifs) else: specialized(action, signs, obj_means, obj_signifs, act_signif, agent, constraints) else: simple(signs, obj_means, act_signif)
def _ground_actions(actions, obj_means, constraints, signs, agents, agent_type): events = [] # ground actions for action_name, smaller in actions.items(): if not action_name in signs: act_sign = Sign(action_name) signs[action_name] = act_sign act_signif = act_sign.add_significance() else: act_sign = signs[action_name] act_signif = act_sign.add_significance() for part, decription in smaller.items(): effect = True if part == "cause": effect = False for predicate, signature in decription.items(): if len(signature['cause']) > 1: pred = get_predicate(predicate, signature, signs) if pred: connector = act_signif.add_feature(pred, effect=effect) pred.sign.add_out_significance(connector) else: raise Exception( "predicate *{0}* has wrong definition in action *{1}*" .format(predicate, action_name)) elif len(signature['cause']) == 1: pred = signs[predicate].significances[1] connector = act_signif.add_feature(pred, effect=effect) pred.sign.add_out_significance(connector) role_sign = signs[signature["cause"][0]] conn = act_signif.add_feature(role_sign.significances[1], connector.in_order, effect=effect) role_sign.add_out_significance(conn) if not constraints: for ag in agents: act_mean = act_signif.copy('significance', 'meaning') ag_sign = signs[ag] act_mean.replace('meaning', signs[agent_type], obj_means[ag_sign]) connector = act_mean.add_feature(obj_means[ag_sign]) efconnector = act_mean.add_feature(obj_means[ag_sign], effect=True) events.append(act_mean.effect[abs(efconnector.in_order) - 1]) ag_sign.add_out_meaning(connector) else: events.extend(constr_replace(constraints, act_signif, agents)) return events
def add_sign(updated_fact, ufn, ufr): if isinstance(updated_fact[0], tuple): used_facts.add(updated_fact[0][1:]) else: used_facts.add(ufn) if ufr not in signs: signs[ufr] = Sign(ufr) if not ufr in roles: roles.append(ufr)
def _define_situation(name, predicates, signs, network='image'): situation = Sign(name) sit_cm = getattr(situation, 'add_' + network)() elements = {} def get_or_add(sign): if sign not in elements: cm = getattr(sign, 'add_' + network)() elements[sign] = cm return elements.get(sign) for predicate in predicates: pred_sign = signs[predicate.name] pred_cm = getattr(pred_sign, 'add_' + network)() connector = sit_cm.add_feature(pred_cm) getattr(pred_sign, 'add_out_' + network)(connector) if len(predicate.signature) == 1: obj_sign = signs[predicate.signature[0][0]] sig_cm = get_or_add(obj_sign) conn = sit_cm.add_feature(sig_cm, connector.in_order) getattr(obj_sign, 'add_out_' + network)(conn) elif len(predicate.signature) > 1: pre_signs = set() for fact in predicate.signature: role_signs = [ con.in_sign for con in getattr(signs[fact[0]], 'out_significances') if con.in_sign.name != 'object' ] for el in role_signs: if el.significances: if len(el.significances[1].cause) == 1 and len( el.significances[1].effect) == 0: pre_signs.add(el) if len(pre_signs) < len(predicate.signature): for fact in predicate.signature: fact_sign = signs[fact[0]] fact_cm = get_or_add(fact_sign) conn = pred_cm.add_feature(fact_cm) getattr(fact_sign, 'add_out_' + network)(conn) else: for fact in predicate.signature: fact_sign = signs[fact[0]] fact_image = get_or_add(fact_sign) conn = sit_cm.add_feature(fact_image, connector.in_order) getattr(fact_sign, 'add_out_' + network)(conn) conn = pred_cm.add_feature(fact_image) getattr(fact_sign, 'add_out_' + network)(conn) global_situation = signs['situation'] global_cm = getattr(global_situation, 'add_' + network)() connector = global_cm.add_feature(sit_cm) getattr(situation, 'add_out_' + network)(connector) return situation, elements
def add_obj_link(obj_name, word, link="hyper", obj_sign={}, signifs={}): if not word in obj_sign: obj_sign[word] = Sign(word) signifs[word] = obj_sign[word].add_significance() if link == "hyper" or link == "syno": connector = signifs[word].add_feature(signifs[obj_name], zero_out=True) obj_sign[obj_name].add_out_significance(connector) if link == "hypo" or link == "syno": connector = signifs[obj_name].add_feature(signifs[word], zero_out=True) obj_sign[word].add_out_significance(connector)
def save_plan(self, start, finish, actions, plan_name): # Creating plan action for further use if not plan_name: plan_name = 'plan_' + self.name if not start.sign.meanings: scm = start.copy('image', 'meaning') start.sign.add_meaning(scm) for con in start.sign.out_meanings.copy(): if con.in_sign.name == plan_name: start.sign.out_meanings.remove(con) if not finish.sign.meanings: fcm = finish.copy('image', 'meaning') finish.sign.add_meaning(fcm) for con in finish.sign.out_meanings.copy(): if con.in_sign.name == plan_name: finish.sign.out_meanings.remove(con) plan_sign = Sign(plan_name + self.name) plan_mean = plan_sign.add_meaning() connector = plan_mean.add_feature(start.sign.meanings[1]) start.sign.add_out_meaning(connector) conn = plan_mean.add_feature(finish.sign.meanings[1], effect=True) finish.sign.add_out_meaning(conn) self.signs[plan_sign.name] = plan_sign # Adding Sequence of actions to plan image plan_image = plan_sign.add_image() for act in actions: im = act.sign.add_image() connector = plan_image.add_feature(im) act.sign.add_out_image(connector) # Adding scenario vs partly concrete actions to the plan sign scenario = self.scenario_builder(start, finish, actions) plan_signif = plan_sign.add_significance() for act in scenario: connector = plan_signif.add_feature(act) act.sign.add_out_significance(connector) return [plan_sign, start.sign, finish.sign]
def update_single(facts): for fact in facts: role_name = fact[1][0].name + fact[0] fact_name = fact[1][0].name if role_name not in signs: role_sign = Sign(role_name) signs[role_name] = role_sign else: role_sign = signs[role_name] if fact_name not in signs: fact_sign = Sign(fact_name) signs[fact_name] = fact_sign else: fact_sign = signs[fact_name] role_signif = role_sign.add_significance() fact_signif = fact_sign.add_significance() connector = role_signif.add_feature(fact_signif, zero_out=True) fact_sign.add_out_significance(connector)
def create_subplan(subplan, agent, signs, plan_sit, plan_map, start=False): elem_acts_im = [] if agent == 'I': ag_sign = I_obj[0] whose = agent else: ag_sign = signs[agent] whose = 'They' act_st = subplan[0] if isinstance(act_st[-1], dict): descr1 = act_st[-1] else: descr1 = act_st[-1][0] # Remake situations coze they could be synthesized by other agent act_sit_start, act_map_start, size = create_situation( descr1, ag_sign, whose) if agent == 'I': I_sign = signs['I'] I_im = I_sign.add_image() act_sit_start.replace('image', ag_sign, I_im) plan_map.append(act_map_start.sign) act_fn = subplan[-1] if isinstance(act_fn[-1], dict): logging.debug('cant find goal sit for subplan') descr2 = act_fn[-1] else: descr2 = act_fn[-1][1] # Change goal sit size ag_x = descr1['objects'][ag_sign.name]['x'] ag_y = descr1['objects'][ag_sign.name]['y'] for el in subplan: if el[1] == 'Clarify': new_size = (size[2] - size[0]) // 6 size = [ ag_x - new_size, ag_y - new_size, ag_x + new_size, ag_y + new_size ] elif el[1] == 'Abstract': new_size = size[2] - size[0] size = [ size[0] - new_size, size[1] - new_size, size[2] + new_size, size[3] + new_size ] act_sit_finish, act_map_finish, _ = create_situation( descr2, ag_sign, whose, size) plan_map.append(act_map_finish.sign) if agent == 'I': I_sign = signs['I'] I_im = I_sign.add_image() act_sit_finish.replace('image', ag_sign, I_im) active_sit_start_mean = act_sit_start.copy('image', 'meaning') plan_sit.append(act_sit_start.sign) active_sit_finish_mean = act_sit_finish.copy('image', 'meaning') plan_sit.append(act_sit_finish.sign) global SUBPLAN_COUNTER SUBPLAN_COUNTER += 1 if agent != 'I': plan_sign = Sign(SUBPLAN_PREFIX + 'they_' + agent + '_' + str(SUBPLAN_COUNTER)) plan_mean = plan_sign.add_meaning() connector = plan_mean.add_feature(active_sit_start_mean) active_sit_start_mean.sign.add_out_meaning(connector) conn = plan_mean.add_feature(active_sit_finish_mean, effect=True) active_sit_finish_mean.sign.add_out_meaning(conn) signs[plan_sign.name] = plan_sign else: plan_sign = Sign(SUBPLAN_PREFIX + 'I_' + str(SUBPLAN_COUNTER)) plan_mean = plan_sign.add_meaning() connector = plan_mean.add_feature(active_sit_start_mean) active_sit_start_mean.sign.add_out_meaning(connector) conn = plan_mean.add_feature(active_sit_finish_mean, effect=True) active_sit_finish_mean.sign.add_out_meaning(conn) plan_image = plan_sign.add_image() for act in subplan: act_sign = self.signs[act[1]] im = act_sign.add_image() connector = plan_image.add_feature(im) act_sign.add_out_image(connector) elem_acts_im.append(im) signs[plan_sign.name] = plan_sign ## changing start and finish if start == True: self.start_situation = act_sit_start self.start_map = act_map_start self.goal_situation = act_sit_finish self.goal_map = act_map_finish return [ act_sit_start, plan_sign.name, plan_mean, act_st[3], (None, None), (act_map_start, None), (descr1, descr2) ], signs, plan_sit, plan_map, elem_acts_im
def signify_connection(signs): Send = Sign("Send") send_signif = Send.add_significance() Broadcast = Sign("Broadcast") brdct_signif = Broadcast.add_significance() connector = brdct_signif.add_feature(send_signif) Send.add_out_significance(connector) Approve = Sign("Approve") approve_signif = Approve.add_significance() connector = approve_signif.add_feature(send_signif) Send.add_out_significance(connector) signs[Send.name] = Send signs[Broadcast.name] = Broadcast signs[Approve.name] = Approve They_sign = signs["They"] They_signif = They_sign.add_significance() brdct_signif = Broadcast.add_significance() connector = They_signif.add_feature(brdct_signif) Broadcast.add_out_significance(connector) approve_signif = Approve.add_significance() They_signif = They_sign.add_significance() connector = They_signif.add_feature(approve_signif) Approve.add_out_significance(connector) brdct_signif = Broadcast.add_significance() executer = brdct_signif.add_feature(Broadcast.name.lower(), effect=True, actuator=True) Send.add_out_significance(executer) approve_signif = Approve.add_significance() executer = approve_signif.add_feature(Approve.name.lower(), effect=True, actuator=True) Send.add_out_significance(executer)
def ground(problem, plagent, exp_signs=None): domain = problem.domain actions = domain.actions.values() predicates = domain.predicates.values() constraints = problem.constraints # Objects objects = problem.objects objects.update(domain.constants) logging.debug('Objects:\n%s' % objects) # Remove old type_map if exp_signs: objects = _update_exp_signs(exp_signs, objects) # Create a map from types to objects type_map = _create_type_map(objects) logging.debug("Type to object map:\n%s" % type_map) # Create type subtype map subtype_map = _create_subtype(domain.types) obj_signifs = {} # add agents, because on significances they have a inner link to I and They signs obj_means = {} # Check logic in exp if exp_signs: signs = exp_signs I_sign = signs['I'] They_sign = signs['They'] obj_means[I_sign] = I_sign.meanings[1] obj_signifs[I_sign] = I_sign.significances[1] obj_means[They_sign] = They_sign.meanings[1] obj_signifs[They_sign] = They_sign.significances[1] signs['situation'] = exp_signs['situation'] else: signs = {} I_sign = Sign("I") obj_means[I_sign] = I_sign.add_meaning() obj_signifs[I_sign] = I_sign.add_significance() signs[I_sign.name] = I_sign They_sign = Sign("They") obj_means[They_sign] = They_sign.add_meaning() obj_signifs[They_sign] = They_sign.add_significance() signs[They_sign.name] = They_sign signs['situation'] = Sign('situation') for obj in objects: obj_sign = Sign(obj) obj_signifs[obj_sign] = obj_sign.add_significance() signs[obj] = obj_sign if obj_sign.name == plagent: connector = obj_signifs[obj_sign].add_feature(obj_signifs[I_sign], zero_out=True) I_sign.add_out_significance(connector) obj_means[obj_sign] = obj_sign.add_meaning() for tp, objects in type_map.items(): if exp_signs: tp_sign = signs[tp.name] else: tp_sign = Sign(tp.name) for obj in objects: obj_signif = obj_signifs[signs[obj]] tp_signif = tp_sign.add_significance() connector = tp_signif.add_feature(obj_signif, zero_out=True) signs[obj].add_out_significance(connector) if not exp_signs: signs[tp.name] = tp_sign others = set() for id in range(1, len(signs['agent'].significances) + 1): other_ag = signs['agent'].significances[id].get_signs() if signs[plagent] not in other_ag: others |= other_ag for subagent in others: if subagent.name != plagent: if not They_sign in subagent.significances[1].get_signs(): signif = obj_signifs[They_sign] if signif.is_empty(): They_signif = signif else: They_signif = They_sign.add_significance() connector = subagent.significances[1].add_feature( They_signif, zero_out=True) They_sign.add_out_significance(connector) obj_means[subagent] = subagent.add_meaning() if not exp_signs: updated_predicates = _update_predicates(predicates, actions) signify_predicates(predicates, updated_predicates, signs, subtype_map, domain.constants) signify_actions(actions, constraints, signs, plagent, obj_means, obj_signifs) signify_connection(signs) start_situation, pms = _define_situation('*start*', problem.initial_state, signs, 'image') goal_situation, pms = _define_situation('*finish*', problem.goal, signs, 'image') # if problem.name.startswith("blocks"): # list_signs = task_signs(problem) # _expand_situation_ma_blocks(goal_situation, signs, pms, list_signs) # For task return MaPlanningTask(problem.name, signs, start_situation, goal_situation)
def create_script_sign(list_files, name_table=None, key_word="sem_rel", script_name="Script"): """ This function creates Script and the required signs for it and for the actions, roles and their possible placeholders (objects). The adding of connectors in Script is implemented in function add_significance This function returns the Sign of Script (S), the signs of actions (dict 'actions_sign'), the role signs (dict 'role_sign'), the placeholders signs (dict 'obj_sign'), characteristics signs (dict 'char_sign') significances (dict 'signifs') """ if name_table is None: name_table = "DELETE.pickle" # Extract semantic relations and syntactic dependences for all texts in list_files # into table graph_script = get_srcipt(list_files, name_table) V_descr = graph_script.V_descr # The script sign S = Sign(script_name) # The keys of the following dictionaries are signs name. The value is sign actions_sign = {} role_sign = {} obj_sign = {} char_sign = {} signifs = {} signifs[script_name] = S.add_significance() order = None for v in graph_script.V: connector_script = add_signifs(V_descr[v], S=S, signifs=signifs, script_name=script_name, actions_sign=actions_sign, role_sign=role_sign, obj_sign=obj_sign, char_sign=char_sign, order=order) obj_sign_names = list(obj_sign.keys()) parser = Parser() hyperonyms_key = "Гиперонимы" hyponyms_key = "Гипонимы" synonyms_key = "Синонимы" for obj_name in obj_sign_names: response = parser.get_word_info(obj_name) hyperonyms = response[hyperonyms_key] if hyperonyms is None: hyperonyms = [] for word in hyperonyms: add_obj_link(obj_name, word, link="hyper", obj_sign=obj_sign, signifs=signifs) hyponyms = response[hyponyms_key] if hyponyms is None: hyponyms = [] for word in hyponyms: add_obj_link(obj_name, word, link="hypo", obj_sign=obj_sign, signifs=signifs) #synonyms = response[synonyms_key] #if synonyms is None: # synonyms = [] #for word in synonyms: # add_obj_link(obj_name, word, link = "syno", obj_sign = obj_sign, signifs = signifs) return S, actions_sign, role_sign, obj_sign, char_sign, signifs
def ground(problem, plagent, exp_signs=None): # ground I and They domain = problem.domain I_sign = Sign("I") obj_means[I_sign] = I_sign.add_meaning() obj_signifs[I_sign] = I_sign.add_significance() signs[I_sign.name] = I_sign They_sign = Sign("They") obj_means[They_sign] = They_sign.add_meaning() obj_signifs[They_sign] = They_sign.add_significance() signs[They_sign.name] = They_sign for type, stype in domain['types']: stype_sign = __add_sign(stype) stype_signif = stype_sign.add_significance() type_sign = __add_sign(type) connector = stype_signif.add_feature(obj_signifs[type_sign], zero_out=True) type_sign.add_out_significance(connector) for obj, type in problem.objects: obj_sign = __add_sign(obj) obj_means[obj_sign] = obj_sign.add_meaning() type_sign = signs[type] tp_signif = type_sign.add_significance() connector = tp_signif.add_feature(obj_signifs[obj_sign], zero_out=True) obj_sign.add_out_significance(connector) if obj_sign.name == plagent: connector = obj_signifs[obj_sign].add_feature(obj_signifs[I_sign], zero_out=True) I_sign.add_out_significance(connector) obj_means[obj_sign] = obj_sign.add_meaning() others = set() for id in range(1, len(signs['agent'].significances) + 1): other_ag = signs['agent'].significances[id].get_signs() if signs[plagent] not in other_ag: others |= other_ag for subagent in others: if subagent.name != plagent: if not They_sign in subagent.significances[1].get_signs(): signif = obj_signifs[They_sign] if signif.is_empty(): They_signif = signif else: They_signif = They_sign.add_significance() connector = subagent.significances[1].add_feature( They_signif, zero_out=True) They_sign.add_out_significance(connector) obj_means[subagent] = subagent.add_meaning() for predicate in domain['predicates']: _ground_predicate(predicate.name, predicate.signature) for action in domain['actions']: _ground_action(action.name, action.parameters, action.preconditions, action.effect, problem.constraints, plagent) for task in domain['tasks']: __add_sign(task.name, False) methods = sorted(domain['methods'], key=lambda method: len(method.subtasks)) for method in methods: __ground_method(method.parameters, method.subtasks, method.ordering, method.task, domain, 2) # Ground Init start = __add_sign('*start %s*' % str(problem.name), False) sit_im = start.add_image() for predicate in problem.init: pred_im = _ground_htn_predicate(predicate.name, predicate.signature, plagent) connector = sit_im.add_feature(pred_im) pred_im.sign.add_out_image(connector) sit_im.copy('image', 'meaning') # Ground htns to meanings goal = None subtasks = [] for htn in problem.htns: htn_name = 'htn_' + str(problem.htns.index(htn)) htn_sign = __add_sign(htn_name, False) htn_mean = htn_sign.add_meaning() for task in htn.ordering: subtask = htn.subtasks[task] cm = __ground_htn_subtask(subtask[0], subtask[1], domain) connector = htn_mean.add_feature(cm) cm.sign.add_out_meaning(connector) subtasks.append(htn_sign) from mapmulti.grounding.pddl_grounding import signify_connection signify_connection(signs) return Task(problem.name, signs, start, goal, subtasks)
def define_situation(sit_name, cell_map, conditions, agent_state, signs): signs[sit_name] = Sign(sit_name) sit_image = signs[sit_name].add_image() contain_sign = signs['contain'] cellx = signs['cell?x'] celly = signs['cell?y'] few_sign = signs['few'] location_signif = \ [matr for _, matr in signs['location'].significances.items() if signs['direction'] in matr.get_signs()][0] cell_distr = {'cell-0': 'above-left', 'cell-1': 'left', 'cell-2': 'below-left', 'cell-3': 'above', \ 'cell-5': 'below', 'cell-6': 'above-right', 'cell-7': 'right', 'cell-8': 'below-right'} mapper = { cell: value for cell, value in cell_map.items() if cell != 'cell-4' } agent = agent_state['name'] orientation = agent_state['direction'] actuator = agent_state['actuator'] for cell, objects in mapper.items(): noth_sign = signs['nothing'] flag = False if 0 in objects: flag = True cont_signif = [ signif for _, signif in contain_sign.significances.items() if celly in signif.get_signs() and noth_sign in signif.get_signs() ][0] else: cont_signif = [ signif for _, signif in contain_sign.significances.items() if celly in signif.get_signs() and signs['object'] in signif.get_signs() ][0] cont_am = [] connectors = [] if flag: noth_image = noth_sign.add_image() cont_image = cont_signif.copy('significance', 'image') cont_image.replace('image', noth_sign, noth_image) cell_image = signs[cell].add_image() cont_image.replace('image', celly, cell_image) cont_am.append(cont_image) else: for obj in objects: obj_image = signs[obj].add_image() cont_image = cont_signif.copy('significance', 'image') cont_image.replace('image', signs['object'], obj_image) few_image = few_sign.add_image() cell_image = signs[cell].add_image() cont_image.replace('image', signs['amount'], few_image) cont_image.replace('image', celly, cell_image) cont_am.append(cont_image) for image in cont_am: if not connectors: connector = sit_image.add_feature(image) contain_sign.add_out_image(connector) connectors.append(connector) else: connector = sit_image.add_feature(image, connectors[0].in_order) contain_sign.add_out_image(connector) dir_y = signs[cell_distr[cell]] diry_image = dir_y.add_image() closely_signif = [ signif for _, signif in signs['closely'].significances.items() if cellx in signif.get_signs() and celly in signif.get_signs() ][0] closely_image = closely_signif.copy('significance', 'image') cellx_image = signs['cell-4'].add_image() celly_image = signs[cell].add_image() closely_image.replace('image', cellx, cellx_image) closely_image.replace('image', celly, celly_image) location_image = location_signif.copy('significance', 'image') location_image.replace('image', signs['distance'], closely_image) location_image.replace('image', signs['direction'], diry_image) connector = sit_image.add_feature(location_image, connectors[0].in_order) location_image.sign.add_out_image(connector) empl_signif = [ signif for _, signif in signs['employment'].significances.items() if cellx in signif.get_signs() ][0] empl_image = empl_signif.copy('significance', 'image') cellx_image = signs['cell-4'].add_image() empl_image.replace('image', cellx, cellx_image) Ag_image = agent.add_image() empl_image.replace('image', signs['agent?ag'], Ag_image) conn = sit_image.add_feature(empl_image) empl_image.sign.add_out_image(conn) dir = signs['direction'] orientation_image = orientation.add_image() orient_signif = [ signif for _, signif in signs['orientation'].significances.items() if dir in signif.get_signs() ][0] orient_image = orient_signif.copy('significance', 'image') orient_image.replace('image', dir, orientation_image) Ag_image = agent.add_image() orient_image.replace('image', signs['agent?ag'], Ag_image) conn = sit_image.add_feature(orient_image) orient_image.sign.add_out_image(conn) if actuator: act_img = actuator[0][1].copy(actuator[1], 'image') connector = sit_image.add_feature(act_img) act_img.sign.add_out_image(connector) if actuator[0][0].name == 'handempty': Ag_image = agent.add_image() conn = sit_image.add_feature(Ag_image, connector.in_order) agent.add_out_image(conn) if isinstance(conditions, dict): # in the grounding for predicate, signature in conditions.items(): to_change = [] signat = [] pred_sm = None if len(signature['cause']) > 1: for el in signature['cause']: cms = [ cm.sign.name for cm in signs[el].spread_up_activity_slice( 'significance', 1, 2) ] to_change.append(cms) for signa in itertools.product(*to_change): if signa[0] == signa[1]: continue descr = {"cause": signa, "effect": []} pred_sm = get_predicate(predicate, descr, signs, fixplace=True) if pred_sm: signat = signa break pred_im = pred_sm.copy('significances', 'image') for role_sign_name in signat: obj_name = signature['cause'][signat.index(role_sign_name)] obj_image = signs[obj_name].add_image() pred_im.replace('image', signs[role_sign_name], obj_image) connector = sit_image.add_feature(pred_im) pred_im.sign.add_out_image(connector) else: pr_name = re.sub(r'[^\w\s{P}]+|[\d]+', r'', predicate).strip() pred_sm = signs[pr_name].significances[1] pred_im = pred_sm.copy('significances', 'image') obj_im = signs[signature['cause'][0]].add_image() connector = sit_image.add_feature(pred_im) pred_im.sign.add_out_image(connector) conn = sit_image.add_feature(obj_im, connector.in_order) obj_im.sign.add_out_image(conn) elif isinstance(conditions, list): # in copying from 1 sit to new one. Used in clarification, abstr and others for condition in conditions: event = condition.copy(sit_image, 'image', 'image', {}) sit_image.add_event(event) # for event in events: # copied = {} # sit_image.cause.append(event.copy(sit_image, 'meaning', 'image', copied)) global_situation = signs['situation'] global_cm = global_situation.add_image() connector = global_cm.add_feature(sit_image) sit_image.sign.add_out_image(connector) return sit_image
def signify_connection(signs): Send = Sign("Send") send_signif = Send.add_significance() Broadcast = Sign("Broadcast") brdct_signif = Broadcast.add_significance() connector = brdct_signif.add_feature(send_signif) Send.add_out_significance(connector) Approve = Sign("Approve") approve_signif = Approve.add_significance() connector = approve_signif.add_feature(send_signif) Send.add_out_significance(connector) signs[Send.name] = Send signs[Broadcast.name] = Broadcast signs[Approve.name] = Approve They_sign = signs["They"] agents = They_sign.spread_up_activity_obj("significance", 1) agents_type = [] for agent in agents: agents_type.append({ cm.sign for cm in agent.sign.spread_up_activity_obj("significance", 1) }) types = [] if agents_type: types = [ t for t in reduce(lambda x, y: x & y, agents_type) if t != signs["object"] ] if types and len(agents): type = types[0] else: type = signs["I"] They_signif = They_sign.add_significance() brdct_signif = Broadcast.add_significance() connector = They_signif.add_feature(brdct_signif) Broadcast.add_out_significance(connector) type_signif = type.add_significance() approve_signif = Approve.add_significance() connector = type_signif.add_feature(approve_signif) Approve.add_out_significance(connector) brdct_signif = Broadcast.add_significance() executer = brdct_signif.add_feature(Broadcast.name.lower(), effect=True, actuator=True) Send.add_out_significance(executer) approve_signif = Approve.add_significance() executer = approve_signif.add_feature(Approve.name.lower(), effect=True, actuator=True) Send.add_out_significance(executer)
def save_plan(self, start, finish, actions, plan_name, subplans=None): # Creating plan action for further use if not plan_name: plan_name = 'plan_' + self.name if not start.sign.meanings: scm = start.copy('image', 'meaning') start.sign.add_meaning(scm) if not finish.sign.meanings: fcm = finish.copy('image', 'meaning') finish.sign.add_meaning(fcm) plan_sign = Sign(plan_name) plan_mean = plan_sign.add_meaning() connector = plan_mean.add_feature(start.sign.meanings[1]) start.sign.add_out_meaning(connector) conn = plan_mean.add_feature(finish.sign.meanings[1], effect=True) finish.sign.add_out_meaning(conn) self.signs[plan_sign.name] = plan_sign # Adding Sequence of actions to plan image plan_image = plan_sign.add_image() iter = -1 if not subplans: for act in actions: im = act[2].sign.add_image() connector = plan_image.add_feature(im) act[2].sign.add_out_image( connector ) # add connector to plan_sign threw images to out_image else: # ots = {subplans.index(it): range(it[1], it[2]+1) for it in subplans} # for act in actions: # iter += 1 # flag = False # for index, value in ots.items(): # if iter == value[0]: # if subplans[index][0].images: # im = subplans[index][0].images[1] # else: # im = subplans[index][0].add_image() # connector = plan_image.add_feature(im) # subplans[index][0].add_out_image(connector) # flag = True # break # elif iter in value: # flag = True # break # if flag: # continue # else: # im = act[2].sign.add_image() # connector = plan_image.add_feature(im) # act[2].sign.add_out_image(connector) for sub in subplans: if sub[2].sign.images: connector = plan_image.add_feature(sub[2].sign.images[1]) else: they_im = sub[2].sign.add_image() connector = plan_image.add_feature(they_im) sub[2].sign.add_out_image( connector ) # add connector to plan_sign threw images to out_image # Adding scenario vs partly concrete actions to the plan sign scenario = self.scenario_builder(start, finish, actions) plan_signif = plan_sign.add_significance() for act in scenario: connector = plan_signif.add_feature(act) act.sign.add_out_significance(connector) return [plan_sign, start.sign, finish.sign]
def signify_actions(actions, signs, obj_means, agent_roles): for action in actions: act_sign = Sign(action.name) act_signif = act_sign.add_significance() def update_significance(predicate, signature, effect=False): pred_sign = signs[predicate.name] if len(pred_sign.significances) > 1: pred_cm = pred_resonate('significance', pred_sign, predicate, signs, signature) if not pred_cm: raise Exception( 'Cant find *{0}* matrice in *{1}* action'.format( predicate.name, action.name)) elif len(pred_sign.significances) == 0: pred_cm = pred_sign.add_significance() else: pred_cm = pred_sign.significances[1] connector = act_signif.add_feature(pred_cm, effect=effect) pred_sign.add_out_significance(connector) if len(predicate.signature) == 1: signa = predicate.signature[0] if not signa[0].startswith('?'): new_fact = '?' + signa[0] else: new_fact = signa[0] role_sign = signs[signa[1][0].name + new_fact] conn = act_signif.add_feature(role_sign.significances[1], connector.in_order, effect=effect, zero_out=True) role_sign.add_out_significance(conn) elif not len(predicate.signature) == 0: if not predicate.signature[0][1][ 0].name == predicate.signature[1][1][0].name: for role_sign in pred_cm.get_signs(): connector_new = act_signif.add_feature( role_sign.significances[1], connector.in_order, effect=effect, zero_out=True) role_sign.add_out_significance(connector_new) for predicate in action.precondition: update_significance(predicate, action.signature, False) for predicate in action.effect.addlist: update_significance(predicate, action.signature, True) signs[action.name] = act_sign act_meaning = act_signif.copy('significance', 'meaning') I_sign = signs['I'] connector = act_meaning.add_feature(obj_means[I_sign]) efconnector = act_meaning.add_feature(obj_means[I_sign], effect=True) I_sign.add_out_meaning(connector) for agent, roles in agent_roles.items(): I_obj_mean = agent.add_meaning() mean_signs = set() act_mean = act_meaning.spread_down_activity('meaning', 3) for pm_list in act_mean: mean_signs |= set([c.sign for c in pm_list]) role_signs = roles & mean_signs for rs in role_signs: act_meaning.replace('meaning', rs, I_obj_mean)
def ground(problem, plagent, exp_signs=None): domain = problem.domain # ground I and They I_sign = Sign("I") obj_means[I_sign] = I_sign.add_meaning() obj_signifs[I_sign] = I_sign.add_significance() signs[I_sign.name] = I_sign They_sign = Sign("They") obj_means[They_sign] = They_sign.add_meaning() obj_signifs[They_sign] = They_sign.add_significance() signs[They_sign.name] = They_sign situation = Sign('situation') signs['situation'] = situation for type, stype in domain['types']: stype_sign = __add_sign(stype) stype_signif = stype_sign.add_significance() type_sign = __add_sign(type) connector = stype_signif.add_feature(obj_signifs[type_sign], zero_out=True) type_sign.add_out_significance(connector) for obj, type in problem.objects: obj_sign = __add_sign(obj) obj_means[obj_sign] = obj_sign.add_meaning() type_sign = signs[type] tp_signif = type_sign.add_significance() connector = tp_signif.add_feature(obj_signifs[obj_sign], zero_out=True) obj_sign.add_out_significance(connector) if obj_sign.name == plagent: connector = obj_signifs[obj_sign].add_feature(obj_signifs[I_sign], zero_out=True) I_sign.add_out_significance(connector) obj_means[obj_sign] = obj_sign.add_meaning() for predicate in domain['predicates']: _ground_predicate(predicate.name, predicate.signature) for action in domain['actions']: _ground_action(action.name, action.parameters, action.preconditions, action.effect, plagent=plagent) for task in domain['tasks']: __add_sign(task.name, False) methods = sorted(domain['methods'], key=lambda method: len(method.subtasks)) for method in methods: __ground_method(method.parameters, method.subtasks, method.ordering, method.task, domain, 2) #Ground Init start = __add_sign('*start %s*' % str(problem.name), False) sit_im = start.add_image() for predicate in problem.init: pred_im = _ground_htn_predicate(predicate.name, predicate.signature, plagent) connector = sit_im.add_feature(pred_im) pred_im.sign.add_out_image(connector) sit_im.copy('image', 'meaning') global_cm = situation.add_image() connector = global_cm.add_feature(sit_im) getattr(start, 'add_out_image')(connector) #Ground htns to meanings goal = None subtasks = [] for htn in problem.htns: htn_name = 'htn_' + str(problem.htns.index(htn)) htn_sign = __add_sign(htn_name, False) htn_mean = htn_sign.add_meaning() for task in htn.ordering: subtask = htn.subtasks[task] cm = __ground_htn_subtask(subtask[0], subtask[1], problem) connector = htn_mean.add_feature(cm) cm.sign.add_out_meaning(connector) subtasks.append(htn_sign) return Task(problem.name, signs, start, goal, subtasks)
def ground(problem, agent, exp_signs=None): domain = problem.domain actions = domain.actions.values() predicates = domain.predicates.values() # Objects objects = problem.objects objects.update(domain.constants) logging.debug('Objects:\n%s' % objects) # Remove old type_map if exp_signs: objects = _update_exp_signs(exp_signs, objects) # Create a map from types to objects type_map = _create_type_map(objects) logging.debug("Type to object map:\n%s" % type_map) # Create type subtype map subtype_map = _create_subtype(domain.types) obj_signifs = {} obj_means = {} # Check logic in exp if exp_signs: signs = exp_signs I_sign = signs['I'] obj_means[I_sign] = I_sign.meanings[1] obj_signifs[I_sign] = I_sign.significances[1] else: signs = {} I_sign = Sign("I") obj_means[I_sign] = I_sign.add_meaning() obj_signifs[I_sign] = I_sign.add_significance() signs[I_sign.name] = I_sign signs['situation'] = Sign('situation') for obj in objects: obj_sign = Sign(obj) obj_signifs[obj] = obj_sign.add_significance() signs[obj] = obj_sign if obj_sign.name == agent: connector = obj_signifs[obj].add_feature(obj_signifs[I_sign], zero_out=True) I_sign.add_out_significance(connector) for tp, objects in type_map.items(): if exp_signs: tp_sign = signs[tp.name] else: tp_sign = Sign(tp.name) for obj in objects: obj_signif = obj_signifs[obj] tp_signif = tp_sign.add_significance() connector = tp_signif.add_feature(obj_signif, zero_out=True) signs[obj].add_out_significance(connector) if not exp_signs: signs[tp.name] = tp_sign if not exp_signs: updated_predicates = _update_predicates(predicates, actions) signify_predicates(predicates, updated_predicates, signs, subtype_map, domain.constants) agent_roles = {} pred_names = {pred.name for pred in predicates} if agent: agent_role_cms = signs[agent].spread_up_activity_obj( 'significance', 3) roles = { cm.sign for cm in agent_role_cms if cm.sign.name not in pred_names } agent_roles[signs[agent]] = roles signify_actions(actions, signs, obj_means, agent_roles) start_situation, pms = _define_situation('*start*', problem.initial_state, signs, 'image') goal_situation, pms = _define_situation('*finish*', problem.goal, signs, 'image') return Task(problem.name, signs, start_situation, goal_situation)
def signify_predicates(predicates, updated_predicates, signs, subtype_map, constants=None): for predicate in predicates: pred_sign = Sign(predicate.name) signs[predicate.name] = pred_sign def update_single(facts): for fact in facts: role_name = fact[1][0].name + fact[0] fact_name = fact[1][0].name if role_name not in signs: role_sign = Sign(role_name) signs[role_name] = role_sign else: role_sign = signs[role_name] if fact_name not in signs: fact_sign = Sign(fact_name) signs[fact_name] = fact_sign else: fact_sign = signs[fact_name] role_signif = role_sign.add_significance() fact_signif = fact_sign.add_significance() connector = role_signif.add_feature(fact_signif, zero_out=True) fact_sign.add_out_significance(connector) def update_significance(fact, predicate, subtype_map, updated_predicates, index, effect=False, constants=None): def add_sign(updated_fact, ufn, ufr): if isinstance(updated_fact[0], tuple): used_facts.add(updated_fact[0][1:]) else: used_facts.add(ufn) if ufr not in signs: signs[ufr] = Sign(ufr) if not ufr in roles: roles.append(ufr) role_name = fact[1][0].name + fact[0] fact_name = fact[1][0].name roles = [] roles.append(role_name) role_signifs = [] subroles = [] if role_name not in signs: signs[role_name] = Sign(role_name) if fact_name in subtype_map.keys(): subroles = subtype_map[fact_name] for role, signif in subtype_map.items(): if fact_name in signif: for srole in subroles: srole_name = role + "?" + srole signs[srole_name] = Sign(srole_name) if not srole_name in roles: roles.append(srole_name) sfact_name = fact_name + "?" + srole signs[sfact_name] = Sign(sfact_name) if not sfact_name in roles: roles.append(sfact_name) used_facts = set() for updated_fact in updated_predicates[pred_sign.name]: ufn = updated_fact[1][0].name if not updated_fact[0].startswith('?'): new_fact = '?' + updated_fact[0] else: new_fact = updated_fact[0] ufr = updated_fact[1][0].name + new_fact if updated_fact[0] in constants: ufr_sign = Sign(ufr) signs[ufr] = ufr_sign role_signif = ufr_sign.add_significance() obj_sign = signs[updated_fact[0]] conn = role_signif.add_feature(obj_sign.significances[1], zero_out=True) obj_sign.add_out_significance(conn) role_signifs.append(role_signif) else: predicate_names = [ signa[1][0].name for signa in predicate.signature ] if fact_name == ufn: add_sign(updated_fact, ufn, ufr) elif fact[0] == updated_fact[0]: add_sign(updated_fact, ufn, ufr) elif ufn in subtype_map[ fact_name] and not ufn in predicate_names: add_sign(updated_fact, ufn, ufr) for role_name in roles: role_sign = signs[role_name] obj_sign = signs[fact_name] spec_sign = None if obj_sign.name in role_sign.name: spec_sign = role_sign.name[len(obj_sign.name) + 1:] smaller_roles = [] if spec_sign and subroles: for srole in subroles: if spec_sign in srole: smaller_roles.append(srole) if not smaller_roles and spec_sign: smaller_roles = [ obj for obj in used_facts if spec_sign in obj and obj in signs ] if smaller_roles: for obj in smaller_roles: updated_obj_sign = signs[obj] if not obj_sign == updated_obj_sign: role_signif = role_sign.add_significance() connector = role_signif.add_feature( updated_obj_sign.significances[1], zero_out=True) updated_obj_sign.add_out_significance(connector) role_signifs.append(role_signif) else: role_signif = role_sign.add_significance() conn = role_signif.add_feature( obj_sign.significances[1], zero_out=True) obj_sign.add_out_significance(conn) role_signifs.append(role_signif) else: role_signif = role_sign.add_significance() conn = role_signif.add_feature(obj_sign.significances[1], zero_out=True) obj_sign.add_out_significance(conn) role_signifs.append(role_signif) # signa - variations if index < len(predicate.signature) - 1: signifs[index] = role_signifs else: signifs[index] = role_signifs if not constants: for elems in itertools.product(*signifs.values()): pred_signif = pred_sign.add_significance() for elem in elems: conn = pred_signif.add_feature(elem, zero_out=True) elem.sign.add_out_significance(conn) else: pred_signif = pred_sign.add_significance() for signa in predicate.signature: for element in signifs: if signa[1][0].name in element.sign.name: conn = pred_signif.add_feature(element, zero_out=True) element.sign.add_out_significance(conn) break # predicate with solo signa or without signa simular to role if len(predicate.signature) >= 2: signifs = {} for index in range(len(predicate.signature)): update_significance(predicate.signature[index], predicate, subtype_map, updated_predicates, index, constants=constants) else: update_single(updated_predicates[predicate.name]) pred_sign.add_significance()
def define_map(map_name, region_map, cell_location, near_loc, regions_struct, signs): signs[map_name] = Sign(map_name) map_image = signs[map_name].add_image() elements = {} contain_sign = signs['contain'] region_sign = signs['region'] few_sign = signs['few'] noth_sign = signs['nothing'] location_signif = \ [matr for _, matr in signs['location'].significances.items() if signs['direction'] in matr.get_signs()][0] contain_reg = [ region for region, cells in cell_location.items() if 'cell-4' in cells ][0] def get_or_add(sign): if sign not in elements: image = sign.add_image() elements[sign] = image return elements.get(sign) for region, objects in region_map.items(): region_x = signs[region] flag = False if 0 in objects: flag = True objects.remove(0) objects.add("nothing") cont_signif = [ signif for _, signif in contain_sign.significances.items() if signs['region'] in signif.get_signs() and noth_sign in signif.get_signs() ][0] else: cont_signif = [ signif for _, signif in contain_sign.significances.items() if signs['region'] in signif.get_signs() and signs['object'] in signif.get_signs() ][0] connectors = [] for object in objects: if object in signs: ob_sign = signs[object] else: ob_sign = Sign(object) signs[object] = ob_sign for s_name, sign in signs.items(): if s_name in object and s_name != object: obj_signif = ob_sign.add_significance() tp_signif = sign.add_significance() connector = tp_signif.add_feature(obj_signif, zero_out=True) ob_sign.add_out_significance(connector) break ob_image = get_or_add(ob_sign) pm = cont_signif.copy('significance', 'image') region_image = region_x.add_image() pm.replace('image', region_sign, region_image) pm.replace('image', signs['object'], ob_image) if not flag: few_image = few_sign.add_image() pm.replace('image', signs['amount'], few_image) if connectors: con = connectors[0] connector = map_image.add_feature(pm, con.in_order) else: connector = map_image.add_feature(pm) contain_sign.add_out_image(connector) if not connectors: connectors.append(connector) loc_sign = get_reg_location(cell_location, near_loc, region, signs) connector = connectors[0] am = None for id, signif in loc_sign.significances.items(): if resonated(signif, regions_struct, region, contain_reg, signs): am = signif.copy('significance', 'image') break if not am: print('Did not find applicable map') sys.exit(1) cell_image = signs["cell-4"].add_image() am.replace('image', signs["cell?x"], cell_image) inner_matrices = am.spread_down_activity('image', 3) for lmatrice in inner_matrices: if lmatrice[-1].sign.name == "region?z": reg_image = signs[region].add_image() am.replace('image', signs["region?z"], reg_image) break else: for lmatrice in inner_matrices: if lmatrice[-1].sign.name == "region?y": reg_image = signs[region].add_image() am.replace('image', signs["region?y"], reg_image) reg_image = signs[contain_reg].add_image() am.replace('image', signs["region?x"], reg_image) # direction matrice if contain_reg != region: dir_sign = signs[regions_struct[contain_reg][region][1]] else: dir_sign = signs["inside"] dir_matr = dir_sign.add_image() # location matrice location_am = location_signif.copy('significance', 'image') location_am.replace('image', signs['distance'], am) location_am.replace('image', signs['direction'], dir_matr) con = map_image.add_feature(location_am, connector.in_order) loc_sign.add_out_image(con) return map_image
def _add_signifs(name_act, full_name_obj, role_name, actions_sign={}, role_sign={}, obj_sign={}, signifs={}, char_sign={}, is_predicate=False): """ The function has to add events into cause of action 'name_act' The input of function: name_act (string) Name of action. Invinitive of corresponding verb full_name_obj (string) Name of object. role_name (string) The name of role S (Sign) the Sign of Script actions_sign (dict) the dictionary with values are signs of actions and keys are their names obj_sign (dict) the dictionary with values are signs of placeholders and keys are their names char_sign (dict) the dictionary with values are signs of characteristics and keys are their names role_sign (dict) the dictionary with values are roles of characteristics and keys are their names signifs (dict) the dictionary with values are causal matrices of significances and keys are their names """ if (not role_name in role_sign) and (not role_name is None): role_sign[role_name] = Sign(role_name) signifs[role_name] = role_sign[role_name].add_significance() elif role_name is None: # create connector for temporativ and locativ if not full_name_obj in role_sign: role_sign[full_name_obj] = Sign(full_name_obj) signifs[full_name_obj] = role_sign[full_name_obj].add_significance( ) new_predicate = True else: new_predicate = False connector = signifs[name_act].add_feature(signifs[full_name_obj], zero_out=True) role_sign[full_name_obj].add_out_significance(connector) if is_predicate and new_predicate: predicate_name = full_name_obj char_name, full_name_obj = parsing_predicate(predicate_name) if not full_name_obj in obj_sign: obj_sign[full_name_obj] = Sign(full_name_obj) signifs[full_name_obj] = obj_sign[ full_name_obj].add_significance() connector = signifs[predicate_name].add_feature( signifs[full_name_obj], zero_out=True) obj_sign[full_name_obj].add_out_significance(connector) if not char_name in char_sign: char_sign[char_name] = Sign(char_name) signifs[char_name] = char_sign[char_name].add_significance() connector = signifs[predicate_name].add_feature(signifs[char_name], zero_out=True) char_sign[char_name].add_out_significance(connector) return # action -> locativ connector = signifs[name_act].add_feature(signifs[role_name], zero_out=True) role_sign[role_name].add_out_significance(connector) # locativ -> placeholder if not full_name_obj in obj_sign: obj_sign[full_name_obj] = Sign(full_name_obj) signifs[full_name_obj] = obj_sign[full_name_obj].add_significance() signifs[role_name] = role_sign[role_name].add_significance() connector = signifs[role_name].add_feature(signifs[full_name_obj], zero_out=True) obj_sign[full_name_obj].add_out_significance(connector)
def _ground_predicates(predicates, signs): # ground predicates for predicate_name, signature in predicates.items(): variations = [pr for pr in signature if predicate_name in pr] if not predicate_name in signs: pred_sign = Sign(predicate_name) signs[predicate_name] = pred_sign else: pred_sign = signs[predicate_name] if 'cause' and 'effect' in signature: pred_signif = pred_sign.add_significance() if len(signature['cause']) > 1: for part, iner in signature.items(): matrices = get_attributes(iner, signs) for el in matrices: if part == "cause": connector = pred_signif.add_feature(el[1], effect=False, zero_out=True) else: connector = pred_signif.add_feature(el[1], effect=True, zero_out=True) el[0].add_out_significance(connector) elif variations: for part, iner in signature.items(): mixed = [] matrices = [] pred_signif = pred_sign.add_significance() for element in iner: effect = True if 'cause' in element: effect = False if not 'any' in iner[element]: matrices = get_attributes(iner[element], signs) for el in matrices: connector = pred_signif.add_feature(el[1], effect=effect, zero_out=True) el[0].add_out_significance(connector) else: for key, el in iner[element].items(): matrices.extend(get_attributes(el, signs)) mixed.append(matrices) matrices = [] if mixed: combinations = itertools.product(mixed[0], mixed[1]) history = [] for element in combinations: el_signs = element[0][0], element[1][0] if not element[0][0] == element[1][ 0] and el_signs not in history: history.append(el_signs) history.append((el_signs[1], el_signs[0])) pred_signif = pred_sign.add_significance() connector = pred_signif.add_feature(element[0][1], effect=False) element[0][0].add_out_significance(connector) connector = pred_signif.add_feature(element[1][1], effect=True) element[1][0].add_out_significance(connector)
def _add_signifs_effect_action(name_act, full_name_obj, add_name_act, actions_sign={}, role_sign={}, obj_sign={}, char_sign={}, signifs={}): """ The function has to add events into effect of action 'name_act' The input of function: name_act (string) Name of action. Invinitive of corresponding verb full_name_obj (string) Name of object. add_name_act (string) The form of action from text. It is used for constructing participle S (Sign) the Sign of Script actions_sign (dict) the dictionary with values are signs of actions and keys are their names obj_sign (dict) the dictionary with values are signs of placeholders and keys are their names char_sign (dict) the dictionary with values are signs of characteristics and keys are their names role_sign (dict) the dictionary with values are roles of characteristics and keys are their names signifs (dict) the dictionary with values are causal matrices of significances and keys are their names """ try: morph = pymorphy2.MorphAnalyzer() char_name = morph.parse(add_name_act)[0].inflect( {'PRTF', 'perf', 'pssv', 'past'}).word except Exception: char_name = name_act + "_PRTF_pssv_past_perf" pred_name = "{not}" + char_name + "(" + full_name_obj + ")" + "[amod]" if not pred_name in role_sign: role_sign[pred_name] = Sign(pred_name) pred_sign = role_sign[pred_name] signifs[pred_name] = pred_sign.add_significance() # action -> predicat connector = signifs[name_act].add_feature(signifs[pred_name], zero_out=True, effect=False) pred_sign.add_out_significance(connector) if not full_name_obj in obj_sign: obj_sign[full_name_obj] = Sign(full_name_obj) signifs[full_name_obj] = obj_sign[full_name_obj].add_significance() connector = signifs[pred_name].add_feature(signifs[full_name_obj], zero_out=True) obj_sign[full_name_obj].add_out_significance(connector) try: morph = pymorphy2.MorphAnalyzer() char_name = morph.parse(add_name_act)[0].inflect( {'PRTF', 'perf', 'pssv', 'past'}).word except Exception: char_name = name_act + "_PRTF_pssv_past_perf" if not char_name in char_sign: char_sign[char_name] = Sign(char_name) signifs[char_name] = char_sign[char_name].add_significance() connector = signifs[pred_name].add_feature(signifs[char_name], zero_out=True) char_sign[char_name].add_out_significance(connector) pred_name = char_name + "(" + full_name_obj + ")" + "[amod]" if not pred_name in role_sign: role_sign[pred_name] = Sign(pred_name) pred_sign = role_sign[pred_name] signifs[pred_name] = pred_sign.add_significance() # action -> predicat connector = signifs[name_act].add_feature(signifs[pred_name], zero_out=True, effect=True) pred_sign.add_out_significance(connector) if not full_name_obj in obj_sign: obj_sign[full_name_obj] = Sign(full_name_obj) signifs[full_name_obj] = obj_sign[full_name_obj].add_significance() connector = signifs[pred_name].add_feature(signifs[full_name_obj], zero_out=True) obj_sign[full_name_obj].add_out_significance(connector) try: morph = pymorphy2.MorphAnalyzer() char_name = morph.parse(add_name_act)[0].inflect( {'PRTF', 'perf', 'pssv', 'past'}).word except Exception: char_name = name_act + "_PRTF_pssv_past_perf" if not char_name in char_sign: char_sign[char_name] = Sign(char_name) signifs[char_name] = char_sign[char_name].add_significance() connector = signifs[pred_name].add_feature(signifs[char_name], zero_out=True) char_sign[char_name].add_out_significance(connector)
def spatial_ground(problem, plagent, agents, exp_signs=None, backward = False): global signs initial_state = problem.initial_state initial_state.update(problem.map) goal_state = problem.goal_state goal_state.update(problem.map) # Prepare states to plagent init_state = {key: value for key, value in deepcopy(initial_state).items() if key != plagent} init_state['I'] = initial_state[plagent] init_state['objects']['I'] = init_state['objects'].pop(plagent) go_state = {key: value for key, value in deepcopy(goal_state).items() if key != plagent} go_state['I'] = goal_state[plagent] go_state['objects']['I'] = go_state['objects'].pop(plagent) agents.remove(plagent) agents.append('I') obj_signifs = {} obj_means = {} # Create agents and communications agent_type = None types = problem.domain['types'] roles = problem.domain['roles'] if exp_signs: signs, types = ut._clear_model(exp_signs, signs, types) signs, roles = ut._clear_model(exp_signs, signs, roles) I_sign = exp_signs['I'] signs['I'] = I_sign They_sign = exp_signs['They'] signs['They'] = They_sign Clarify = exp_signs['Clarify'] signs['Clarify'] = Clarify Abstract = exp_signs['Abstract'] signs['Abstract'] = Abstract signs['situation'] = exp_signs['situation'] else: I_sign = Sign("I") They_sign = Sign("They") obj_means[I_sign] = I_sign.add_meaning() obj_signifs[I_sign] = I_sign.add_significance() signs[I_sign.name] = I_sign obj_means[They_sign] = They_sign.add_meaning() obj_signifs[They_sign] = They_sign.add_significance() signs[They_sign.name] = They_sign Clarify = Sign('Clarify') signs[Clarify.name] = Clarify Abstract = Sign('Abstract') signs[Abstract.name] = Abstract signs['situation'] = Sign('situation') # ground types for type_name, smaller in types.items(): if not type_name in signs and not exp_signs: type_sign = Sign(type_name) signs[type_name] = type_sign else: if exp_signs: type_sign = exp_signs[type_name] else: type_sign = signs[type_name] if smaller: for obj in smaller: if not obj in signs: obj_sign = Sign(obj) signs[obj] = obj_sign else: obj_sign = signs[obj] obj_signif = obj_sign.add_significance() obj_signifs[obj_sign] = obj_signif tp_signif = type_sign.add_significance() connector = tp_signif.add_feature(obj_signif, zero_out=True) obj_sign.add_out_significance(connector) # Assign I to agent if obj_sign.name == plagent: connector = obj_signif.add_feature(obj_signifs[I_sign], zero_out=True) I_sign.add_out_significance(connector) agent_type = type_name else: obj_signifs[type_sign] = type_sign.add_significance() # Assign other agents others = {signs[ag] for ag in agents if ag != 'I'} for subagent in others: if not They_sign in subagent.significances[1].get_signs(): signif = obj_signifs[They_sign] if signif.is_empty(): They_signif = signif else: They_signif = They_sign.add_significance() connector = subagent.significances[1].add_feature(They_signif, zero_out=True) They_sign.add_out_significance(connector) obj_means[subagent] = subagent.add_meaning() # Signify roles for role_name, smaller in roles.items(): role_sign = Sign(role_name) signs[role_name] = role_sign for object in smaller: obj_sign = signs[object] obj_signif = obj_sign.significances[1] role_signif = role_sign.add_significance() connector = role_signif.add_feature(obj_signif, zero_out=True) obj_sign.add_out_significance(connector) if object == agent_type: agent_type = role_name # Find and signify walls if exp_signs: if not 'wall' in signs: signs['wall'] = exp_signs['wall'] ws = signs['wall'] views = [] if ws.images: for num, im in ws.images.items(): if len(im.cause): for view in im.cause[0].coincidences: if view.view: views.append(view.view) if 'wall' in problem.map: for wall in problem.map['wall']: if wall not in views: cimage = ws.add_image() cimage.add_feature(wall, effect=False, view = True) else: logging.warning('There are no walls around! Check your task!!!') sys.exit(1) # Ground predicates and actions if not exp_signs: ut._ground_predicates(problem.domain['predicates'], signs) ut._ground_actions(problem.domain['actions'], obj_means, problem.constraints, signs, agents, agent_type) else: #TODO check if new action or predicate variation appeared in new task for pred in problem.domain['predicates'].copy(): if pred in exp_signs: signs[pred] = exp_signs[pred] problem.domain['predicates'].pop(pred) for act in problem.domain['actions'].copy(): if act in exp_signs: signs[act] = exp_signs[act] problem.domain['actions'].pop(act) ut._ground_predicates(problem.domain['predicates'], signs) ut._ground_actions(problem.domain['actions'], obj_means, problem.constraints, signs, agents, agent_type) #Copy all experience subplans and plans for sname, sign in exp_signs.items(): if sname not in signs: signs[sname] = sign # Define start situation maps = {} if backward: maps[0] = problem.goal_state else: maps[0] = problem.initial_state ms = maps[0].pop('map-size') walls = maps[0].pop('wall') static_map = {'map-size': ms, 'wall': walls} # Create maps and situations for planning agents regions_struct = ut.get_struct() additions = [] additions.extend([maps, regions_struct, static_map]) cells = {} agent_state = {} for agent in agents: region_map, cell_map_start, cell_location, near_loc, cell_coords, size, cl_lv_init = ut.signs_markup(init_state, static_map, agent) agent_state_start = ut.state_prediction(signs[agent], init_state, signs) start_situation = ut.define_situation('*start-sit*-'+agent, cell_map_start, problem.initial_state['conditions'], agent_state_start, signs) start_map = ut.define_map('*start-map*-'+agent, region_map, cell_location, near_loc, regions_struct, signs) ut.state_fixation(start_situation, cell_coords, signs, 'cell') # Define goal situation region_map, cell_map_goal, cell_location, near_loc, cell_coords, size, cl_lv_goal = ut.signs_markup(go_state, static_map, agent) agent_state_finish = ut.state_prediction(signs[agent], go_state, signs) goal_situation = ut.define_situation('*goal-sit*-'+agent, cell_map_goal, problem.goal_state['conditions'], agent_state_finish, signs) goal_map = ut.define_map('*goal-map*-'+agent, region_map, cell_location, near_loc, regions_struct, signs) ut.state_fixation(goal_situation, cell_coords, signs, 'cell') #fixation map map_size = ut.scale(ms) rmap = [0, 0, map_size[0], map_size[1]] region_location, _ = ut.locater('region-', rmap, initial_state['objects'], walls) ut.state_fixation(start_map, region_location, signs, 'region') ut.signify_connection(signs) if agent == 'I': additions[0][0][plagent]['cl_lv_init'] = cl_lv_init additions[0][0][plagent]['cl_lv_goal'] = cl_lv_goal else: additions[0][0][agent]['cl_lv_init'] = cl_lv_init additions[0][0][agent]['cl_lv_goal'] = cl_lv_goal if backward: cell_map_goal['cell-4'] = {plagent} cells[agent] = {0:cell_map_goal} else: cell_map_start['cell-4'] = {plagent} cells[agent] = {0: cell_map_start} agent_state[agent] = {'start-sit':start_situation.sign, 'goal-sit': goal_situation.sign, 'start-map':start_map.sign, 'goal-map': goal_map.sign} additions.insert(2, cells) return SpTask(problem.name, signs, agent_state, additions, problem.initial_state, {key:value for key, value in problem.goal_state.items() if key not in static_map}, static_map, plagent)
def add_signifs(v_descr, S=None, actions_sign={}, role_sign={}, obj_sign={}, char_sign={}, signifs={}, script_name="Script", locativ_name=None, temporativ_name=None, subj_name=None, obj_name='объект', order=None): possible_predicate_names = ['объект'] mark = False for name in possible_predicate_names: mark = mark or (name in v_descr) if not mark: return if 'Sentence' in v_descr: sentence = v_descr['Sentence'] else: return if 'субъект' in v_descr: obj = v_descr['субъект'] stop = True for i in obj: for j in i['субъект']: lemma_subj = j[0].lemma if lemma_subj.lower() == "я": stop = False if stop: return if 'verb' in v_descr: name_act = v_descr['verb'][0].lemma add_name_act = sentence[v_descr['verb'][0].index] if not name_act in actions_sign: actions_sign[name_act] = Sign(name_act) signifs[name_act] = actions_sign[name_act].add_significance() try: connector_script = signifs[script_name].add_feature( signifs[name_act], order=order, zero_out=False) #zero_out=True) except Exception: connector_script = signifs[script_name].add_feature( signifs[name_act], order=None, zero_out=False) #zero_out=True) actions_sign[name_act].add_out_significance(connector_script) else: return if 'локатив' in v_descr: full_name_obj = v_descr['локатив']['локатив'][0][0].lemma full_locativ = union(sentence, v_descr['локатив']['локатив'][0][1]) _add_signifs(name_act, full_locativ, locativ_name, actions_sign=actions_sign, role_sign=role_sign, obj_sign=obj_sign, char_sign=char_sign, signifs=signifs) predicate_name = full_locativ if not full_name_obj in obj_sign: obj_sign[full_name_obj] = Sign(full_name_obj) signifs[full_name_obj] = obj_sign[full_name_obj].add_significance() connector = signifs[predicate_name].add_feature(signifs[full_name_obj], zero_out=True) obj_sign[full_name_obj].add_out_significance(connector) if 'темпоратив' in v_descr: full_name_obj = v_descr['темпоратив'][1][0].lemma full_temporativ = union(sentence, v_descr['темпоратив'][1]) _add_signifs(name_act, full_temporativ, temporativ_name, actions_sign=actions_sign, role_sign=role_sign, obj_sign=obj_sign, char_sign=char_sign, signifs=signifs) predicate_name = full_temporativ if not full_name_obj in obj_sign: obj_sign[full_name_obj] = Sign(full_name_obj) signifs[full_name_obj] = obj_sign[full_name_obj].add_significance() connector = signifs[predicate_name].add_feature(signifs[full_name_obj], zero_out=True) obj_sign[full_name_obj].add_out_significance(connector) if 'объект' in v_descr: obj = v_descr['объект'] for i in obj: for j in i['объект']: lemma_obj = j[0].lemma full_obj = union(sentence, j[1]) #root = get_tree(full_obj)[0] #print("\n"+full_obj, get_tree(full_obj)) #print(root.value.lemma) #for child, type_ in root.kids: # print('-', child.value.lemma, type_) predicates = j[2] for predicate in predicates: _add_signifs(name_act, predicate, None, actions_sign=actions_sign, role_sign=role_sign, obj_sign=obj_sign, char_sign=char_sign, signifs=signifs, is_predicate=True) # _add_signifs(name_act, lemma_obj, obj_name, # actions_sign = actions_sign, # role_sign = role_sign, # obj_sign = obj_sign, # signifs = signifs) _add_signifs_effect_action(name_act, lemma_obj, add_name_act, actions_sign=actions_sign, role_sign=role_sign, obj_sign=obj_sign, char_sign=char_sign, signifs=signifs) """ if 'субъект' in v_descr: obj = v_descr['субъект'] for i in obj: for j in i['субъект']: lemma_subj = j[0].lemma full_subj = union(sentence, j[1]) _add_signifs(name_act, lemma_subj, subj_name, actions_sign = actions_sign, role_sign = role_sign, obj_sign = obj_sign, char_sign = char_sign, signifs = signifs) """ return connector_script