def __get_ispl_poss(action_tuple_list, model, fluent_tuple_list): #feature_list = Util.get #context_operator.get ispl_fluent_list = ['%s%s'%(f,'_'.join(para_list)) for f, para_list, sort in fluent_tuple_list] fluent_list = ['%s(%s)'%(f,','.join(para_list)) for f, para_list, sort in fluent_tuple_list] ispl_action_list = ['%s%s'%(a,'_'.join(para_list)) for a, para_list in action_tuple_list] action_list = ['%s(%s)'%(a,','.join(para_list)) for a, para_list in action_tuple_list] pred_fluent_list = ['%s(%s)'%(f,','.join(para_list)) for f, para_list, sort in fluent_tuple_list \ if f in context_operator.get_predicates()] action_poss_list = [ atomic_regress.poss_or_ssa(action) for action in action_list ] #print '\n '.join(action_poss_list) action_poss_list = [ Formula.transform_entailment(poss) for poss in action_poss_list ] action_poss_list = [ ____add_env(poss, fluent_list) for poss in action_poss_list ] action_poss_list = [ Formula.grounding(poss, model) for poss in action_poss_list ] action_poss_list = [ ____ispl_simplify(poss, 'state') for poss in action_poss_list] action_poss_list = [ ____to_ispl_preds(poss, pred_fluent_list) for poss in action_poss_list ] action_poss_list = [ ____to_ispl_vars(poss, fluent_list, ispl_fluent_list) for poss in action_poss_list] action_poss_list = [ ____to_ispl_logic(poss) for poss in action_poss_list] action_poss_list = [ "%s:{%s};"%(poss, ispl_action_list[e]) for e, poss in enumerate(action_poss_list) if poss !='false'] #return '\n '.join(action_poss_list) return action_poss_list
def test_formula_expressions_can_be_parsed(): formula = parser.expr( 'base_value * MULTIPLIER + STAMINA // 3 - SPEED // 5 + ENHANCERS' ).compile() value = eval(formula, {}, { 'base_value': 3, 'MULTIPLIER': 1, 'STAMINA': 3, 'SPEED': 10, 'ENHANCERS': 3 }) assert value == 5 # expr = NumExpr('base_value * MULTIPLIER + STAMINA / 3 - SPEED / 5 + ENHANCERS') variables = { 'base_value': 3, 'MULTIPLIER': 1, 'STAMINA': 3, 'SPEED': 10, 'ENHANCERS': 3, 'BANANAS': 8 } formula = Formula( 'base_value * MULTIPLIER + STAMINA // 3 - SPEED // 5 + ENHANCERS') assert formula.evaluate(variables) == 5
def __get_ispl_formula(formula, model, fluent_tuple_list): #print formula ispl_fluent_list = ['%s%s'%(f,'_'.join(para_list)) for f, para_list, sort in fluent_tuple_list] fluent_list = ['%s(%s)'%(f,','.join(para_list)) for f, para_list, sort in fluent_tuple_list] pred_fluent_list = ['%s(%s)'%(f,','.join(para_list)) for f, para_list, sort in fluent_tuple_list \ if f in context_operator.get_predicates()] formula = Formula.transform_entailment(formula) formula = ____add_env(formula, fluent_list) #print formula formula = Formula.grounding(formula, model) #print formula formula = ____ispl_simplify(formula, 'Environment.Action') #print formula formula = ____to_ispl_preds(formula, pred_fluent_list) #print formula #formula = ____add_env(formula, fluent_list) #print formula formula = Util.endecode_string(formula, fluent_list, ispl_fluent_list) #print formula formula = ____to_ispl_logic(formula) #print formula #print return formula
def is_stable_or_dead(protocol, valuation, disabled): # Dead? dead = True for t in protocol.transitions: p, q = tuple(t.pre) if (not t.silent() and (t.pre not in disabled) and (valuation[Var(p)] is not False) and (valuation[Var(q)] is not False)): dead = False break if dead: return True # Stable? V = protocol.states - valuation.absent_states() out = {protocol.output(q) for q in V} if len(out) > 1: return False else: x = out.pop() R = set() for t in protocol.transitions: for q in t.post: if protocol.output(q) != x: R.add(t.pre) formula = Formula(valuation, disabled) return formula.implies_all_absent_tautology_check(R)
def test_formula_set_params(self): f = Formula() f({'a': 2, 'b': 5}) self.assertEqual(f('a'), 2) self.assertEqual(f.get_param('b'), 5)
def stratify(factor, variable): """ Create a new variable, stratified by the levels of a Factor. Parameters ---------- variable : str or a simple sympy expression whose string representation are all lower or upper case letters, i.e. it can be interpreted as a name Returns ------- formula : Formula Formula whose mean has one parameter named _variable%d, for each level in factor.levels Examples -------- >>> f = Factor('a', ['x','y']) >>> sf = f.stratify('theta') >>> sf.mean _theta0*a_x + _theta1*a_y """ if not set(str(variable)).issubset(lowercase + uppercase + '0123456789'): raise ValueError('variable should be interpretable as a ' 'name and not have anything but digits ' 'and letters') variable = sympy.sympify(variable) f = Formula(factor.formula.terms, char=variable) f.name = factor.name return f
def __init__(self, residue_dict, derivative): self.residue_dict = residue_dict self.derivative = derivative formula = Formula(derivative.form()) for residue, count in residue_dict.iteritems(): formula.add(residue.form().multiply(count)) self.formula = formula
def stratify(self, variable): """ Create a new variable, stratified by the levels of a Factor. Parameters ---------- variable : str or a simple sympy expression whose string representation are all lower or upper case letters, i.e. it can be interpreted as a name Returns ------- formula : Formula Formula whose mean has one parameter named variable%d, for each level in self.levels Examples -------- >>> f = Factor('a', ['x','y']) >>> sf = f.stratify('theta') >>> sf.mean _theta0*a_x + _theta1*a_y """ if not set(str(variable)).issubset(lowercase + uppercase + '0123456789'): raise ValueError('variable should be interpretable as a ' 'name and not have anything but digits ' 'and numbers') variable = sympy.sympify(variable) f = Formula(self.formula.terms, char=variable) f.name = self.name return f
def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.controls_layout = list() self.result_flag = False self.text_layout = [[], ['AC', '+/-', '%', '/'], ['7', '8', '9', 'X'], ['4', '5', '6', '-'], ['1', '2', '3', '+'], ['0', None, ',', '=']] self.callbacks_layout = [ [], [ self._bttn_AC, self._bttn_unary_minus, self._bttn_percent, self._bttn_divide ], [self._bttn_7, self._bttn_8, self._bttn_9, self._bttn_multiply], [self._bttn_4, self._bttn_5, self._bttn_6, self._bttn_minus], [self._bttn_1, self._bttn_2, self._bttn_3, self._bttn_plus], [self._bttn_0, None, self._bttn_decimal, self._bttn_equals], ] self.display_stringvar = tk.StringVar() self.create_widgets() self.formula = Formula() print('init')
def is_very_fast(protocol, valuation, disabled): graph, vertices, edges = transformation_graph(protocol, valuation, disabled) components, _, is_bottom = label_components(graph, attractors=True) U = {q for q in vertices if not is_bottom[components[vertices[q]]]} formula = Formula(valuation, disabled) for t in protocol.transitions: p, q = tuple(t.pre) p_, q_ = tuple(t.post) if (p in vertices and q in vertices and p_ in vertices and q_ in vertices and len({p, q, p_, q_} & U) > 0): if ((components[vertices[p]] != components[vertices[p_]]) and (components[vertices[p]] != components[vertices[q_]]) and (components[vertices[q]] != components[vertices[p_]]) and (components[vertices[q]] != components[vertices[q_]])): continue elif formula.implies_all_absent_tautology_check({t.pre}): continue else: return False return True
def formulaVars(self, f: Formula) -> Set[str]: """ List variables in formula f. This depends on correct implementation of subf() and Variable.name. """ if isinstance(f, Variable): return set([f.name()]) return set.union(set(), *(self.formulaVars(sf) for sf in f.subf()))
def test_formula_fn_registry_args(self): f = Formula() @f(1) def a(b, c): return b + c self.assertEqual(f.get_fn_by_name('a')[f.__ARGS_KEY__][1], ['b', 'c'])
def test_formula_fn_registry_call(self): f = Formula() @f(1) def a(b): return b ** 2 self.assertEqual(f.get_fn_by_name('a')[f.__CALL_KEY__][1](2), 4)
def add_fixed_topics_formulas(self, topics, prob_thresh=0.5): # Adds fixed topics by matching on chemical formulas from formula import Formula print "Matching topics based on formulas" ti = [(topic, self.topic_index[topic]) for topic in self.topic_index] ti = sorted(ti, key=lambda x: x[1]) topic_reverse, _ = zip(*ti) self.beta_matrix = np.zeros((self.K, len(self.word_index)), np.float) self.n_fixed_topics = 0 frag_formulas = {} loss_formulas = {} for word in self.word_index: split_word = word.split('_') if len(split_word) == 3: formula = Formula(split_word[2]) if word.startswith('loss'): loss_formulas[str(formula)] = word else: frag_formulas[str(formula)] = word for topic in topics['beta']: matched_probability = 0.0 matches = {} for word, probability in topics['beta'][topic].items(): split_word = word.split('_') if len(split_word) == 3: # it has a formula formula_string = str(Formula(split_word[2])) matched_word = None if word.startswith( 'loss') and formula_string in loss_formulas: matched_word = loss_formulas[formula_string] elif word.startswith( 'fragment') and formula_string in frag_formulas: matched_word = frag_formulas[formula_string] if not matched_word == None: matches[word] = matched_word matched_probability += probability print "Topic: {}, {} probability matched ({})".format( topic, matched_probability, topics['topic_metadata'][topic].get('annotation', "")) if matched_probability > prob_thresh: # We have a match for word in matches: self.beta_matrix[self.n_fixed_topics, self.word_index[matches[word]]] = topics[ 'beta'][topic][word] # Normalise self.beta_matrix[self.n_fixed_topics, :] /= self.beta_matrix[ self.n_fixed_topics, :].sum() topic_here = topic_reverse[self.n_fixed_topics] print "Match accepted, storing as {}".format(topic_here) self.topic_metadata[topic_here]['type'] = 'fixed' for key, val in topics['topic_metadata'][topic].items(): self.topic_metadata[topic_here][key] = val self.n_fixed_topics += 1
def test_formula_param_add_when_fn_call_outside_formula(self): f = Formula() @f(1) def a(b, c): return b - c a(100, 98) self.assertEqual(f.get_params(), {'a': 2, 'b': 100, 'c': 98})
def parseToTree(symbol, node): if symbol not in operatorList or symbol == "~": if symbol == ")": while 1: node = node.parent if node.symbol != "~": break if node.symbol == None: if node.parent != None and node.parent.symbol != "~": node.parent.right = node.left else: node.parent.left = node.left return node else: return node elif node.symbol == None or node.symbol == "~": if symbol == "(": node.left = Formula(None, None, node) elif symbol == "~": node.left = Negation(None, symbol, node) else: node.left = Atom(None, symbol, node) return node.left else: if symbol == "(": node.right = Formula(None, None, node) elif symbol == "~": node.right = Negation(None, symbol, node) else: node.right = Atom(None, symbol, node) return node.right elif symbol in operatorList and symbol != "~": while 1: node = node.parent if node.symbol != "~": break if symbol == "^": node = Conjunction(node) elif symbol == "v": node = Disjunction(node) elif symbol == "=>": node = Implication(node) else: node = Biconditional(node) node.left.parent = node if node.parent: if not node.parent.symbol or node.parent.symbol == "~": node.parent.left = node else: node.parent.right = node return node return node
def get_prep_value(self, value): if value is None: return value if isinstance(value, tuple): formula, value = value value = Formula(formula, value) value = value.value elif self.formula: value = Formula(self.formula, value) value = value.value return value
def prog_28(fname): # TODO::::::::::::::::::::::::::: from formula import Formula import solver formulas = {} f = open(fname) ns = eval(f.readline().strip()) f.readline() for i in xrange(ns): formula = Formula() line = f.readline().strip() cnt = 0 while line: if cnt == 0: line = f.readline().strip() cnt +=1 continue e1,e2 = map(int, line.split()) formula.add_clause((e1,e2)) line = f.readline().strip() formulas[i] = formula f.close() # print random_formula(2,6) for i in xrange(ns): formula = formulas[i] # print formula flg = solver.satisfiable(formula) if flg: print 1, sg = max(solver.find_component(formula), key=len) for n in sorted(sg): print n, else: print 0, print
def test_simple_subtract(var1, var2, expected_result, precision): """Calculating the subtraction of two numbers.""" assert expected_result == Formula("var1 - var2", precision).get( {"var1": var1, "var2": var2} ) assert expected_result == Formula("var1 - var2", precision).get( {"var1": var1, "var2": var2, "addition": "12345"} ) assert expected_result == Formula(var1 + "-" + var2, precision).get() assert expected_result == Formula(var1 + "-" + var2, precision).get({}) assert expected_result == Formula(var1 + "-" + var2, precision).get( {u"asdf_фыва": "-1", u"й": "1e-100500"} )
def compute_J(protocol, valuation, disabled, F, mem, graph, vertices): key = (valuation, frozenset(disabled)) if key in mem: return mem[key] newM = set() M = set() sF = set(F) distance = shortest_distance(graph, directed=True) while not (len(newM) == len(sF)): newM = nextH(newM, sF.difference(newM), distance, vertices) M = newM stable = (len(M) == 0) while not stable: to_remove = set() for pair in M: # AB constraints = [] for t in protocol.transitions: if (t.post == pair): constraints.append(([], [], t.pre)) elif len(set(pair) & t.postset) == 1: p = tuple(set(pair) & t.postset)[0] # E q = pair.other(p) # F q_ = t.post.other(p) # G if (q_ != q): # G != F if p != q: # E != F constraints.append(([Var(q)], [Var(p)], t.pre)) elif p not in t.pre: # E = F and E not in AB constraints.append(([Var(p, True)], [], t.pre)) formula = Formula(valuation, disabled | M) if not formula.tautology_check(constraints): to_remove.add(pair) if len(to_remove) > 0: M -= to_remove else: stable = True if len(M) > 0: break mem[key] = M return M
def test_simple_sum(var1, var2, expected_result, precision): """Calculating the sum of two numbers.""" assert expected_result == Formula("var1 + var2", precision).get( {"var1": var1, "var2": var2} ) assert expected_result == Formula("var1 + var2", precision).get( {"var1": var1, "var2": var2, "addition": "1e5000000"} ) assert expected_result == Formula(var1 + "+" + var2, precision).get() assert expected_result == Formula(var1 + "+" + var2, precision).get({}) assert expected_result == Formula(var1 + "+" + var2, precision).get( {"qwer": "-1", u"й": "0"} )
def __get_ispl_update(fluent_tuple_list, p1_action_tuple_list, p2_action_tuple_list, model): universe, assignment, default_value = model ispl_fluent_list = ['%s%s'%(f,'_'.join(para_list)) for f, para_list, sort in fluent_tuple_list] fluent_list = ['%s(%s)'%(f,','.join(para_list)) for f, para_list, sort in fluent_tuple_list] predicates = context_operator.get_predicates() fun_fluent_list = [('%s(%s)'%(f,','.join(para_list)), sort) for f, para_list, sort in fluent_tuple_list if f not in predicates] pred_fluent_list = ['%s(%s)'%(f,','.join(para_list)) for f, para_list, sort in fluent_tuple_list if f in predicates and f!='turn'] #print fun_fluent_list #print pred_fluent_list fluent_value_list = sum([list(itertools.product([fluent],universe[sort])) \ for fluent, sort in fun_fluent_list] ,[]) fluent_value_list = ['%s=%s'%(fluent,value) for fluent, value in fluent_value_list] fluent_value_list.extend(pred_fluent_list) ispl_p1_action_list = ['Player1.Action = %s%s'%(a,'_'.join(para_list)) for a, para_list in p1_action_tuple_list] p1_action_list = ['%s(%s)'%(a,','.join(para_list)) for a, para_list in p1_action_tuple_list] ispl_p2_action_list = ['Player2.Action = %s%s'%(a,'_'.join(para_list)) for a, para_list in p2_action_tuple_list] p2_action_list = ['%s(%s)'%(a,','.join(para_list)) for a, para_list in p2_action_tuple_list] action_pair_list = [(a,b) for a, b in zip(p1_action_list+p2_action_list, ispl_p1_action_list+ispl_p2_action_list)] update_pair_list = [ (a,b,c) for a, (b,c) in itertools.product(fluent_value_list, action_pair_list)] update_pair_list = [ (fluent, atomic_regress.poss_or_ssa(action, fluent), ispl_action) \ for fluent, action, ispl_action in update_pair_list] # transform (=>) to (not or) update_pair_list = [ (a, Formula.transform_entailment(b), c) for a, b, c in update_pair_list] update_pair_list = [ (a, Formula.grounding(b,model), c) for a, b, c in update_pair_list] update_pair_list = [ (a, ____ispl_simplify(b,'Player1.Action'), c) for a, b, c in update_pair_list] #update_pair_list = [ (a, b, c) for a, b, c in update_pair_list if b is not None] pred_fluent_list = ['%s(%s)'%(f,','.join(para_list)) for f, para_list, sort in fluent_tuple_list if f in predicates] # add =true to each predicates update_pair_list = [ (fluent, ____to_ispl_preds(update, pred_fluent_list), ispl_action) for fluent, update, ispl_action in update_pair_list] fun_update_pair_list = [ (fluent, update, ispl_action) for fluent, update, ispl_action in update_pair_list if fluent not in pred_fluent_list and update !='false'] pred_update_pair_list = [ (fluent, update, ispl_action) for fluent, update, ispl_action in update_pair_list if fluent in pred_fluent_list] update_list = ['%s if (%s) and %s;'%(fluent, update, ispl_action) for fluent, update, ispl_action in fun_update_pair_list ] update_list += ['%s=true if (%s) and %s;'%(fluent, update, ispl_action) for fluent, update, ispl_action in pred_update_pair_list if update !='false' ] update_list += ['%s=false if !(%s) and %s;'%(fluent, update, ispl_action) for fluent, update, ispl_action in pred_update_pair_list if update !='false' ] update_list += ['%s=false if %s;'%(fluent, ispl_action) for fluent, update, ispl_action in pred_update_pair_list if update =='false' ] update_list += turn_list #update_list = [____add_env(formula, fluent_list) for formula in update_list] update_list = [ Util.endecode_string(formula, fluent_list, ispl_fluent_list) for formula in update_list] update_list = [ ____to_ispl_logic(formula) for formula in update_list] #return '\n '.join(update_list) return update_list
def test_formula_reset_params(self): f = Formula() calc = Calc(f) @f(1) def a(b): return b ** 2 f({'b': 5}) calc('a') f.reset_params() self.assertEqual(f.get_params(), {})
def main() -> None: try: logging.basicConfig(filename='logs/run%s.log' % re.sub('\W+', '_', str(datetime.now())), level=logging.DEBUG) except FileNotFoundError: logging.disable(2333) logging.info('original file is:') n, M = parse() fm = Formula(n, M) if fm.solve(): print('s SATISFIABLE') #logging.debug(str(fm.model)) else: print('s UNSATISFIABLE')
def next_rule(self): for state in self.states.values(): if not state.cloned: state.cloned = True if state.is_consistent(): next_formulas = state.get_next_formulas() if len(next_formulas) == 0: next_formulas = {Formula(TruthValue.TRUE.value)} found_pre_state = False for pre_state in self.pre_states.values(): if next_formulas == pre_state.formulas: pre_state.parents.add(state) state.children.add(pre_state) found_pre_state = True break if not found_pre_state: new_node = Node(tableau=self, parents=state, children=set(), node_type=NodeType.PRE_STATE, initial=False, formulas=next_formulas) state.children.add(new_node)
def contrasts(self): """ Return the canonical contrasts of the ANCOVA. The order is determined by the sorted order of numerical terms in the ANCOVA. Each numerical term yields several >>> x = Term('x'); f = Factor('f', [2,1,3]) ; h =Factor('h', range(2)) >>> a = ANCOVA((x,f), (x,(f,h))) >>> a.contrasts {'I(x):f': Formula([f_1*x, f_3*x, f_2*x]), 'I(1):1': Formula([1]), 'I(x):f:h': Formula([f_2*h_1*x, f_1*h_1*x, f_3*h_1*x])} """ if not hasattr(self, "_contrasts"): self._contrasts = {} self._contrast_reps = [] self._formulae = [] for expr in sorted(self.graded_dict.keys()): formulae = get_contributions(self.codings[expr], self.sorted_factors) for formula, srep in formulae: v = formula * Formula([expr]) sexpr = "I(%s)" % str(expr) if srep: crep = ':'.join([sexpr,srep]) else: crep = sexpr self._contrasts[crep] = v self._contrast_reps.append(crep) self._formulae.append(v) return self._contrasts
def from_json(comp_id: int, ref_id=None): """Reads competition from json result file takes com_id as argument""" from db.tables import TblResultFile as R with db_session() as db: if ref_id: file = db.query(R).get(ref_id).filename else: file = db.query(R.filename).filter(and_(R.comp_id == comp_id, R.task_id.is_(None), R.active == 1)).scalar() if file: comp = Comp(comp_id=comp_id) with open(path.join(RESULTDIR, file), 'r') as f: '''read task json file''' data = json.load(f) for k, v in data['info'].items(): # not using update to intercept changing in formats if hasattr(comp, k): setattr(comp, k, v) # comp.as_dict().update(data['info']) comp.stats = dict(**data['stats']) comp.rankings.update(data['rankings']) comp.tasks.extend(data['tasks']) comp.formula = Formula.from_dict(data['formula']) comp.data = dict(**data['file_stats']) results = [] for p in data['results']: '''get participants''' participant = Participant(comp_id=comp_id) participant.as_dict().update(p) results.append(participant) # should already be ordered, so probably not necessary comp.participants = sorted(results, key=lambda k: k.score, reverse=True) return comp
def read(img: Union[str, PicHandler], path: str='D:\\Project\\') -> ElemBlock: if isinstance(img, str): ph = PicHandler(img, path=path) else: ph = img blocks = Parser.parse(ph.blocksOfPixels(), sensivity=4, merge='math') Parser.swap_coordinates(blocks) elemBlocks = [FormulaRecognizer.recBlock(block) for block in blocks] try: f = Formula(elemBlocks) except: return ElemBlock('', Position(0, 0, 0, 0), ok=False) print(f.texCode) #ph._show() return f.getFormula()
def _getmaineffect(self, ref=-1): if not hasattr(self, "_main_effect"): terms = [FactorTerm(self.name, l) for l in self.levels] ref_term = terms[ref] terms.pop(ref) self._main_effect = Formula([term - ref_term for term in terms]) return self._main_effect
def test_getting_variables(): """Check that formula return correct varables.""" formula = Formula("a*b+c+D/qwe+s_s_s.*16+3^йцу4^f^t+a+xx+x+x+x") assert formula.variables() == { "a", "b", "c", "D", "qwe", "s_s_s.", u"йцу4", # support python2.7. It's not necessary in python3+ "f", "t", "xx", "x", }
def read(cls, fp, short_name=None, keep_task_path=False, from_CIVL=False): """ A XML reader to read FSDB files Unfortunately the fsdb format isn't published so much of this is simply an exercise in reverse engineering. Input: - fp: STR: filepath - from_CIVL: BOOL: look for pilot on CIVL database """ """read the fsdb file""" try: tree = ET.parse(fp) root = tree.getroot() except ET.Error: print("FSDB Read Error.") return None pilots = [] tasks = [] """Comp Info""" print("Getting Comp Info...") fs_comp = root.find('FsCompetition') comp = Comp.from_fsdb(fs_comp, short_name) """Formula""" comp.formula = Formula.from_fsdb(fs_comp) comp.formula.comp_class = comp.comp_class """Pilots""" print("Getting Pilots Info...") if from_CIVL: print('*** get from CIVL database') p = root.find('FsCompetition').find('FsParticipants') for pil in p.iter('FsParticipant'): pilot = Participant.from_fsdb(pil, from_CIVL=from_CIVL) # pp(pilot.as_dict()) pilots.append(pilot) comp.participants = pilots """Tasks""" print("Getting Tasks Info...") t = root.find('FsCompetition').find('FsTasks') for tas in t.iter('FsTask'): '''create task obj''' task = Task.from_fsdb(tas, comp.time_offset, keep_task_path) '''check if task was valid''' if task is not None: if not task.task_path: task.create_path() # task.time_offset = int(comp.time_offset) """Task Results""" node = tas.find('FsParticipants') if node is not None: task.pilots = [] print("Getting Results Info...") for res in node.iter('FsParticipant'): '''pilots results''' pilot = FlightResult.from_fsdb(res, task) task.pilots.append(pilot) tasks.append(task) return cls(comp, tasks, fp)
def assign_formula(self, features, for_adducts, with_tol_ppm=10.0): """ assign molecular formula to features using multiprocessing module :param for_adducts: string adducts list :param features: list or set ? of features :param with_tol_ppm: mz tolerance in order to perform the look up :return: dictionary with key: feature, value: list of metabolites """ m_count, not_found = 0, 0 for for_adduct in for_adducts: formula = Formula.from_str(for_adduct) logging.info("searching for adducts: {}".format(str(formula))) # pool = billiard.Pool(processes=billiard.cpu_count()) # args = [(self.HMDB_FILE, f, formula, with_tol_ppm) for f in features] # metabs = pool.map(search_metabolites_for, args, chunksize=20) # pool.close() #DEBUG CODE metabolites = [] for f in features: metabolites.append(search_metabolites_for((self.HMDB_FILE, f, formula, with_tol_ppm))) # create Annotation objects for f, metabs in izip(features, metabolites): if not metabs: not_found += 1 else: m_count += len(metabs) for_adducts_str = '[M{}{}]='.format('-' if f.polarity > 0 else '+', formula) f.annotations += [Annotation(m, for_adducts_str) for m in metabs] return m_count, not_found
def drop_first(self): ref = 0 if not hasattr(self, "_drop1"): terms = [FactorTerm(self.name, l) for l in self.levels] ref_term = terms[ref] terms.pop(ref) self._drop1 = Formula(terms) return self._drop1
def is_fast(protocol, valuation, disabled): graph, vertices, edges = transformation_graph(protocol, valuation, disabled) components, _, is_bottom = label_components(graph, attractors=True) U = {q for q in vertices if not is_bottom[components[vertices[q]]]} R = {q: set() for q in vertices} expV = set() for (p, q) in edges: if components[vertices[p]] != components[vertices[q]]: for t in edges[p, q]: expV.add(t.pre) if t.pre not in disabled: for r in (set(t.pre) & U): R[r].add(t.pre) for q in U: formula = Formula(valuation, disabled) formula.assert_some_pair_present(expV) formula.assert_some_states_present({q}) if not formula.implies_some_present_tautology_check(R[q]): return False return True
def formula(self): """ Create a formula. """ if not hasattr(self, "_formula"): self._formula = Formula( [FactorTerm(self.name, l) for l in self.levels], char=self._char) return self._formula
def main(): """Quick tests.""" from relationsymbol import RelationSymbol from vocabulary import Vocabulary ahead_rs = RelationSymbol('Ahead', 4) behind_rs = RelationSymbol('Behind', 4) pm_rs = RelationSymbol('PM', 1) vocabulary = Vocabulary( ['C1', 'C2'], [ahead_rs, behind_rs, pm_rs], ['V1', 'V2']) f1 = Formula(vocabulary, 'Ahead', 'C1', 'V1') f2 = Formula(vocabulary, 'Behind', 'C1') a = AssumptionBase(f1, f2) a2 = AssumptionBase(f2, f1) print a2
def sat_formula(model, formula): universe, assignment, default_value = model formula = __to_python_formula(formula) #print '1,---------',formula formula = Formula.transform_entailment(formula) #print '2,---------',formula ground_formula = Formula.grounding(formula, model) #print '3,--------',ground_formula logical_formula = __assignment(ground_formula, assignment) #print '4,--------model replace',logical_formula #print 'kkkk',context_operator.get_sort_symbols_dict() #logger.debug("Checking formula %s with model %s \n formula after grounding: %s \n after model_replace %s"%(formula,model,ground_formula,logical_formula)) scope = __get_const_value(context_operator.get_sort_symbols_dict(), context_operator.get_fluents(), assignment) flag = eval(logical_formula, scope) #logger.debug('sat?: \n%s'%flag) return flag
def _compute_actual_statistic(self, statname, properties): statistic = self.statistics[statname] current_value = statistic.value multiplicators = sum( self._compute_property_value(property) for property in properties if property['factor'] == 'multiplicative') additions = sum( self._compute_property_value(property) for property in properties if property['factor'] == 'additive') formulas = [ Formula(property['formula']) for property in properties if property['factor'] == 'custom' ] # Usually used for percentages that should not ever reach 100% additive_multiplicatively = [ self._compute_property_value(property) for property in properties if property['factor'] == 'additive-multiplicatively' ] if additive_multiplicatively: additive_multiplicatively_value = reduce( lambda x, y: x + x * y, sorted(additive_multiplicatively)) else: additive_multiplicatively_value = 0 if not formulas: current_value = statistic.value * max( 1, multiplicators) + additions + additive_multiplicatively_value else: formula_keywords = { 'MULTIPLICATORS', 'ADDITIONS', 'ADDITIVE_MULTIPLICATIVELY', 'base_value' } for formula in formulas: variables = set(formula.variables) - formula_keywords locals = dict((variable, self.get_keyword_count(variable)) for variable in variables) locals.update({ 'base_value': statistic.value, 'ADDITIONS': additions, 'MULTIPLICATORS': max(1, multiplicators), 'ADDITIVE_MULTIPLICATIVELY': additive_multiplicatively_value }) current_value = formula.evaluate(locals) return ActualStatistic( statname, statistic.value, round(current_value) if statistic.needs_rounding else current_value)
def getTreeList(RList): KBList = [] for R in RList: node = Formula(None) for symbol in R: node = parseToTree(symbol, node) node = findRoot(node) KBList.append(node) return KBList
def test_calc(self): f = Formula() calc = Calc(f) @f(1) def a(b, c): return b + c @f(2) def b(c): return c * 2 f({'c': 4}) calc('a') self.assertEqual(f('a'), 12) self.assertEqual(f.get_param('b'), 8)
def load(self): with open(self.std_file,'rU') as f: for i in range(9): f.readline() # remove heads for line in f: split_line = line.split(',') polarity = split_line[4] rts = split_line[9] # observed, not predicted if rts == '-': rt = 0.0 else: rt = float(rts) if polarity == '+' and rt > 0.0: name = split_line[2] formula = split_line[3] f = Formula(formula) new_mol = Mol(name,formula,f.compute_exact_mass(),rt*60.0) self.mols.append(new_mol) self.mols = sorted(self.mols,key = lambda x: x.mass)
def test_tokenize(self): data = [ ('A', ('A',)), ('A + B * C', ('A', '+', 'B', '*', 'C')), ('A+B*C', ('A', '+', 'B', '*', 'C')), ('(r*r)*3.14', ('(', 'r', '*', 'r', ')', '*', '3.14')), ('((A+1)-B)', ('(', '(', 'A', '+', '1', ')', '-', 'B', ')')), ] for string, result in data: self.assertEqual(Formula.tokenize(string), result)
def test_parse(self): data = [ (('A',), ('A',)), (('A', '+', 'B', '*', 'C'), ('A', 'B', 'C', '*', '+')), (('A', '/', 'B', '*', 'C'), ('A', 'B', '/', 'C', '*')), (('A', '*', 'B', '+', 'C'), ('A', 'B', '*', 'C', '+')), (('A', '*', '(', 'B', '+', 'C', ')'), ('A', 'B', 'C', '+', '*')), (('(', 'A', '-', 'B', ')', '+', 'C'), ('A', 'B', '-', 'C', '+')), (('10', '/', '(', '1.0', '-', '0.5', ')'), ('10', '1.0', '0.5', '-', '/')) ] for tokens, result in data: self.assertEqual(Formula.parse(tokens), result)
def test_safe_eval(self): data = [ ('A', {'A': 1}, 1), ('A + B * C', {'A': 1, 'B': 2, 'C': 3}, 7), ('A / B * C', {'A': 1, 'B': 2, 'C': 3}, 1.5), ('A * B + C', {'A': 1, 'B': 2, 'C': 3}, 5), ('A * (B + C)', {'A': 1, 'B': 2, 'C': 3}, 5), ('A * A * 3.141592', {'A': 2}, 12.566368), ('100 / ( 1.0 - 0.5 )', None, 200.0) ] for expr, namespace, result in data: formula = Formula(expr) self.assertEqual(formula.safe_eval(namespace), result) # Test for division by zero self.assertTrue(math.isnan(Formula('1 / 0').safe_eval())) # Invalid expressions with self.assertRaises(ValueError): Formula('A + 3').safe_eval(None) with self.assertRaises(ValueError): Formula('B A + 3').safe_eval({'A': 1, 'B': 2})
def isNextState(nextFormulas, nextAtom): """ Checks if an atom satisfies a list of formulas with next operator as main connective. :param nextFormulas: List of formulas with next operator as main connective. :type nextFormulas: List of :py:class:`~formula.Formula` :param nextAtom: Atom. :type nextAtom: List of :py:class:`~formula.Formula` :returns: ``True`` if the atom satisfies the termporal formulas or ``False`` otherwise. :rtype: Boolean :Example: >>> from modelCheckingGraph import * >>> atom = [Formula({'o': {'<>': {'^': {'': 'in=true', '~': {'o': 'x=2'}}}}}), ... Formula({'': 'in=true'}), Formula({'o': 'x=2'}), Formula({'': 'x=2'}), ... Formula({'<>': {'^': {'': 'in=true', '~': {'o': 'x=2'}}}}), ... Formula({'~': {'^': {'': 'in=true', '~': {'o': 'x=2'}}}})] >>> >>> formulas = [Formula({'o': 'x=2'})] >>> isNextState(formulas,atom) True .. note:: We say that an atom satisfies a list of formulas when for all the formulas :math:`\circ\phi` in the list we found a formula :math:`\phi` in the atom. .. seealso:: :py:class:`formula.Formula` """ for formula in nextFormulas: next = Formula(formula.getValues()) if not isInAtom(next.getFormula(), nextAtom): return False return True
def test(self, formula, string, cases): print("Testing %s" % (string)) parsed = Formula.parse(string) self.compare(parsed.toString(), string, "Formula.parse(XXX).toString() == XXX") # This expects subf() to work correctly, if it doesn't # we still will catch the difference in toplevel formulas # or evals below. self.compareFormulas(parsed, formula) for interpretation, result in cases: print(" interpretation %s:" % (repr(interpretation),)) self.compare(parsed.eval(interpretation), result, "eval")
class Derivative: derivatives = {} #will load from config/derivatives.yaml during __init__.py def __init__(self, code): self.code = code self.formula = Formula(Derivative.derivatives[code]['formula']) def form(self): return Formula(self.formula) def name(self): return Derivative.derivatives[self.code]['name'] def code(self): return self.code def __str__(self): return self.code def mass(self): return self.formula.mass()
parser.add_option("-t", "--ticks", type="float", dest="ticks", default=None, help="Number of ticks allowed per batch. 1 tick = 0.5 sec. Defaults to the recipe time.") if __name__ == '__main__': (options, args) = parser.parse_args() if options.list_recipes: for recipe in recipes: if all(map(lambda t: t in recipe.tags, options.tags)): line = [recipe.name] remaining_tags = set(recipe.tags) - set(options.tags) if remaining_tags and options.verbose: line.append("[%s]" % (",".join(remaining_tags),)) print " ".join(line) elif options.recipe_requested is not None: recipe = recipe_for_item(options.recipe_requested) if recipe: print recipe else: print "Could not find recipe with name %s" % (options.recipe_requested,) elif options.build_target is not None: ticks = options.ticks or recipe_for_item(options.build_target).ticks formula = Formula(options.build_target, amount=options.amount, ticks=ticks) formula.expand() print formula
def diagrammatic_to_sentential(context, F, named_states, attribute_interpretation, variable_assignment, *formulae): """ Verify that on the basis of the present diagram :math:`(\sigma;\\rho)` of the Context object :math:`(\\beta;(\sigma;\\rho))` in the ``context`` parameter and some set of Formula objects :math:`F_{1}, \ldots, F_{k}, k \ge 0` provided as optional positional arguments in the ``formulae`` parameter, that for each NamedState object :math:`(\sigma_{1}; \\rho_{1}), \ldots,(\sigma_{n}; \\rho_{n}), n > 0`, contained in the ``named_states`` parameter, a Formula object :math:`F` provided in the ``F`` parameter can be derived in every one of these :math:`n` cases. This is rule :math:`[C_{3}]`. This function works as follows: 1. If :math:`k > 0` (i.e., if at least one Formula object is provided as an optional positional argument to the ``formulae`` parameter), compute the basis :math:`\mathcal{B}(F_{1}, \\rho, \chi) ~ \cup ~ \cdots ~ \cup ~ \ \mathcal{B}(F_{k}, \\rho, \chi)` of :math:`F_{1}, \ldots, F_{k}` and determine if the NamedState objects :math:`(\sigma_{1}; \\rho_{1}), \ldots,(\sigma_{n}; \\rho_{n})` provided in the ``named_states`` parameter form an exhuastive set of possibilities on this basis. 2. Determine if the proviso :math:`(\sigma;\\rho) \\Vvdash_{\{F_{1}, \ldots, F_{k}\}} \ \{(\sigma_{1}; \\rho_{1}), \ldots,(\sigma_{n}; \\rho_{n})\}` (where :math:`k \ge 0`) holds. 3. Return the evaluation of :math:`(\\beta \cup \{F_{1}, \ldots, F_{k}\};(\sigma;\\rho)) \models F`. :param context: The Context object :math:`(\\beta;(\sigma;\\rho))` from \ which the present diagram :math:`(\sigma;\\rho)` comes from. :type context: Context :param F: The Formula object :math:`F` derivable in the :math:`n > 0` \ cases provided by the NamedState objects \ :math:`(\sigma_{1}; \\rho_{1}), \ldots,(\sigma_{n}; \\rho_{n})` in the \ ``named_state`` parameter. :type F: Formula :param named_states: The NamedState objects \ :math:`(\sigma_{1}; \\rho_{1}), \ldots,(\sigma_{n}; \\rho_{n}), n > 0` \ functioning as the set of :math:`n` exhaustive cases from which :math:`F` \ can be derived. :type named_states: ``list`` :param attribute_interpretation: The AttributeInterpretation object \ :math:`I` to use for the interpretation of truth values and the \ computation of the basis of :math:`F_{1}, \ldots, F_{k}`. :type attribute_interpretation: AttributeInterpretation :param variable_assignment: The VariableAssignment object :math:`\chi` to \ consider when computing the basis \ :math:`\mathcal{B}(F_{1}, \\rho, \chi) ~ \cup ~ \cdots ~ \cup ~ \ \mathcal{B}(F_{k}, \\rho, \chi)` of :math:`F_{1}, \ldots, F_{k}` or \ ``None`` if all terms of the :math:`F_{1}, \ldots, F_{k}` are in \ :math:`\\rho`. :type variable_assignment: VariableAssignment | ``None`` :param formulae: The :math:`{k \ge 0}` Formula objects \ :math:`F_{1}, \ldots, F_{k}` to use in the computation of the basis, \ computation of the proviso and the evaluation of \ :math:`{(\\beta \cup \{F_{1}, \ldots, F_{k}\};(\sigma;\\rho)) \models F}`. :type formulae: Formula :return: The result of the evaluation of \ :math:`(\\beta \cup \{F_{1}, \ldots, F_{k}\};(\sigma;\\rho)) \models F`. :rtype: ``bool`` :raises ValueError: If :math:`{k > 0}`, the NamedState objects \ :math:`{(\sigma_{1}; \\rho_{1}), \ldots,(\sigma_{n}; \\rho_{n}), n > 0}` \ are not exhaustive on the basis of the Formula objects \ :math:`F_{1}, \ldots, F_{k}` or the proviso \ :math:`{(\sigma;\\rho) \\Vvdash_{\{F_{1}, \ldots, F_{k}\}} \ \{(\sigma_{1}; \\rho_{1}), \ldots,(\sigma_{n}; \\rho_{n})\}}` (where \ :math:`k \ge 0`) does not hold. """ if formulae: constant_assignment = context._named_state._p basis = Formula.get_basis(constant_assignment, variable_assignment, attribute_interpretation, *formulae) if not context._named_state.is_exhaustive(basis, *named_states): raise ValueError("named states are not exahustive on basis of formulae.") assumption_base = AssumptionBase(*formulae) else: assumption_base = AssumptionBase(context._assumption_base._vocabulary) proviso = context._named_state.is_named_entailment(assumption_base, attribute_interpretation, *named_states) if not proviso: raise ValueError("[C3] proviso does not hold") formulae_union = context._assumption_base._formulae + list(formulae) if formulae_union: assumption_base_union = AssumptionBase(*formulae_union) else: assumption_base_union = AssumptionBase(context._assumption_base._vocabulary) # Determine if (β ∪ {F1,...,Fk}; (σ; ρ)) |= F; proviso holds at this point extended_context = Context(assumption_base_union, context._named_state) if extended_context.entails_formula(F, attribute_interpretation): return True else: return False
def __init__(self, code): self.residue = code formula = Formula(Residue.residues[code]['formula']) formula.add('C2H2NO') self.formula = formula
def __init__(self, code): self.code = code self.formula = Formula(Derivative.derivatives[code]['formula'])
def getClosure(formula, closure): """ Function that generates the closure of a temporal formula. :param formula: Temporal formula that we want to find the closure :param closure: Empty list to store the subformulas of the closure :type formula: Formula :type closure: List :Example: >>> from closure import * >>> phi = Formula({"<>": {"^":{"":"in=true","~":{"o":"x=2"}}}}) >>> closure = [] >>> getClosure(phi,closure) >>> for formula in closure: ... print formula.getFormula() ... {'<>': {'^': {'': 'in=true', '~': {'o': 'x=2'}}}} {'~': {'<>': {'^': {'': 'in=true', '~': {'o': 'x=2'}}}}} {'o': {'<>': {'^': {'': 'in=true', '~': {'o': 'x=2'}}}}} {'~': {'o': {'<>': {'^': {'': 'in=true', '~': {'o': 'x=2'}}}}}} {'o': {'~': {'<>': {'^': {'': 'in=true', '~': {'o': 'x=2'}}}}}} {'^': {'': 'in=true', '~': {'o': 'x=2'}}} {'~': {'^': {'': 'in=true', '~': {'o': 'x=2'}}}} {'': 'in=true'} {'~': 'in=true'} {'o': 'x=2'} {'~': {'o': 'x=2'}} {'o': {'~': 'x=2'}} {'': 'x=2'} {'~': 'x=2'} .. note:: This function is based on the conditions shown in the section 6.1 of the thesis document. """ if formula.isNegativeFormula(): formula = Formula(formula.getValues()) subformula = formula.getValues() if formula.isProposition(): # PROPOSITION rule closure.append(Formula({"": subformula})) # p closure.append(Formula({"~": subformula})) # ~p elif formula.getConnective() == "^" : # AND rule subformulas = formula.getSubFormulas() closure.append(Formula({"^": subformula})) # phi ^ psi closure.append(Formula({"~": {"^": subformula}})) # ~ (phi ^ psi) getClosure(subformulas[0],closure) getClosure(subformulas[1],closure) elif formula.getConnective() == "v" : # OR rule subformulas = formula.getSubFormulas() closure.append(Formula({"v": subformula})) # phi v psi closure.append(Formula({"~": {"v": subformula}})) # ~ (phi v psi) getClosure(subformulas[0],closure) getClosure(subformulas[1],closure) elif formula.getConnective() == "o" : # NEXT rule closure.append(Formula({"o": subformula})) # o phi closure.append(Formula({"~": {"o": subformula}})) # ~o phi closure.append(Formula({"o": {"~": subformula}})) # o~ phi getClosure(Formula(formula.getValues()),closure) elif formula.getConnective() == "<>": # FUTURE rule closure.append(Formula({"<>": subformula})) # <> phi closure.append(Formula({"~": {"<>": subformula}})) # ~<> phi closure.append(Formula({"o": {"<>": subformula}})) # o<> phi closure.append(Formula({"~": {"o": {"<>": subformula}}})) # ~o<> phi closure.append(Formula({"o": {"~": {"<>": subformula}}})) # o~<> phi getClosure(Formula(formula.getValues()),closure) elif formula.getConnective() == "[]": # GLOBALLY rule closure.append(Formula({"[]": subformula})) # [] phi closure.append(Formula({"~": {"[]": subformula}})) # ~[] phi closure.append(Formula({"o": {"[]": subformula}})) # o[] phi closure.append(Formula({"~": {"o": {"[]": subformula}}})) # ~o[] phi closure.append(Formula({"o": {"~": {"[]": subformula}}})) # o~[] phi getClosure(Formula(formula.getValues()),closure)
def parse_baseface(self, row, f_name): row["last_mix_total_10"] = "" row["last_10_text_style"] = "" row["last_6_text_style"] = "" row["last_4_text_style"] = "" row["last_4_status_text_style"] = "" #预测赛果之用 row["formula_total"] = Formula(Formula.TYPE_TOTAL) row["formula_last10"] = Formula(Formula.TYPE_LAST10) row["formula_last6"] = Formula(Formula.TYPE_LAST6) row["formula_last4"] = Formula(Formula.TYPE_LAST4) row["formula_last_mid"] = Formula(Formula.TYPE_LAST_MID) parser = soup(f_name) if not parser: return row["match_date"] = self.parse_match_date(parser) row["asian"] = self.parse_asian_odds(parser) ########################进球数比较引擎数据构造块####################### #球队主客混合平均进球数 avg_balls = self.parse_balls_io_total_10(parser) if len(avg_balls)==4: defence_main=get_zero_div(avg_balls[0],avg_balls[1]) defence_client=get_zero_div(avg_balls[2],avg_balls[3]) #本赛季 row["formula_total"].main_force = avg_balls[0] row["formula_total"].client_force = avg_balls[2] row["formula_total"].main_defence = defence_main row["formula_total"].client_defence = defence_client win = "%.1f,%.1f" % (avg_balls[0],defence_main) lost = "%.1f,%.1f" % (avg_balls[2],defence_client) row["last_mix_total_10"] = "(%s)/(%s)" % (win,lost) #分主客区段平均进球数 main_data = self.count_team_battle_balls_io("team_zhanji2_1",parser) client_data = self.count_team_battle_balls_io("team_zhanji2_0",parser) #视图数据 row["last_4_status_text_style"] = "(%s)/(%s)" % ("".join(main_data["status"]),"".join(client_data["status"])) row["last_10_text_style"] = "(%.1f,%.1f)/(%.1f,%.1f)" % (main_data["last_10"]["win"],main_data["last_10"]["percentage"],client_data["last_10"]["win"],client_data["last_10"]["percentage"]) row["last_6_text_style"] = "(%.1f,%.1f)/(%.1f,%.1f)" % (main_data["last_6"]["win"],main_data["last_6"]["percentage"],client_data["last_6"]["win"],client_data["last_6"]["percentage"]) row["last_4_text_style"] = "(%.1f,%.1f)/(%.1f,%.1f)" % (main_data["last_4"]["win"],main_data["last_4"]["percentage"],client_data["last_4"]["win"],client_data["last_4"]["percentage"]) #区段比较数据 for last_n in [10,6,4]: formula_key = "formula_last%i" % last_n data_key = "last_%i" % last_n row[formula_key].main_force = main_data[data_key]["win"] row[formula_key].main_defence = main_data[data_key]["percentage"] row[formula_key].client_force = client_data[data_key]["win"] row[formula_key].client_defence = client_data[data_key]["percentage"] pass #掐头去尾中间比较数据 row["formula_last_mid"].main_force = main_data["last_mid"]["win"] row["formula_last_mid"].main_defence = main_data["last_mid"]["percentage"] row["formula_last_mid"].client_force = client_data["last_mid"]["win"] row["formula_last_mid"].client_defence = client_data["last_mid"]["percentage"]