def grid_search(f, grid_points): grid = cartesian_product(grid_points) min_args, min_value = grid[0], f(*grid[0]) for i in range(1, len(grid)): if f(*grid[i]) < min_value: min_args, min_value = grid[i], f(*grid[i]) return min_args
def grid_search(objective_function, grid_lines): intersection_points = cartesian_product(grid_lines) min_value = objective_function(intersection_points[0][0], intersection_points[0][1]) min_point = [intersection_points[0][0], intersection_points[0][1]] for point in intersection_points: temp_value = objective_function(point[0], point[1]) if temp_value < min_value: min_value = temp_value min_point = point return min_point
def example(self): """ Returns an example of cartesian product of magmas EXAMPLES:: sage: C = Magmas().CartesianProducts().example(); C The cartesian product of (Rational Field, Integer Ring, Integer Ring) sage: C.category() Category of Cartesian products of monoids sage: TestSuite(C).run() """ from cartesian_product import cartesian_product from sage.rings.integer_ring import ZZ from sage.rings.rational_field import QQ return cartesian_product([QQ, ZZ, ZZ])
def evaluate_pathways_recursively(enzyme_lists): histogram = Bag() all_combinations = cartesian_product([enzyme_lists[s] for s in enzyme_lists.keys()]) best_combination = None best_score = None counter = 0 for combination in all_combinations: score = evaluate_pathway(combination) if (best_combination == None or score < best_score): (best_combination, best_score) = (combination, score) histogram[score] += 1 counter += 1 #print "%.2f%%\r" % (100.0 * counter / len(all_combinations)), return (histogram, best_combination)
def evaluate_pathways_recursively(enzyme_lists): histogram = Bag() all_combinations = cartesian_product( [enzyme_lists[s] for s in enzyme_lists.keys()]) best_combination = None best_score = None counter = 0 for combination in all_combinations: score = evaluate_pathway(combination) if (best_combination == None or score < best_score): (best_combination, best_score) = (combination, score) histogram[score] += 1 counter += 1 #print "%.2f%%\r" % (100.0 * counter / len(all_combinations)), return (histogram, best_combination)
def example(self): """ Return an example of cartesian product of magmas. EXAMPLES:: sage: C = Magmas().CartesianProducts().example(); C The cartesian product of (Rational Field, Integer Ring, Integer Ring) sage: C.category() Join of Category of rings ... sage: sorted(C.category().axioms()) ['AdditiveAssociative', 'AdditiveCommutative', 'AdditiveInverse', 'AdditiveUnital', 'Associative', 'Distributive', 'Unital'] sage: TestSuite(C).run() """ from cartesian_product import cartesian_product from sage.rings.integer_ring import ZZ from sage.rings.rational_field import QQ return cartesian_product([QQ, ZZ, ZZ])
def pattern_matching(self, G, reaction_id): """ this function finds every embodiment of G_subs in G (every mapping from G to G_subs) and applies the reaction to G (by replacing the subgraph in G with G_prod) """ def verify_reaction_bonds(G, G_subs, map_prefix, m1, n1): """ verifies that one can map node 'm' in G_subs, to node 'n' in G, given a map_prefix. This method actually check all the new bonds that m->n will add, and verifies they are consistent in G_subs. """ if (n1 >= G.get_num_nodes()): # m1 is an imported atom (like H2O or PO3), don't check its bonds return True for m2 in range(len(map_prefix)): n2 = map_prefix[m2] if (n2 >= G.get_num_nodes()): continue # m2 is an imported atom (like H2O or PO3), don't check its bonds if (G_subs.get_bond(m1, m2) != G.get_bond(n1, n2)): return False return True def combine_atom_mappings_recursive(G, G_subs, atom_mappings, possible_mappings, map_prefix=[]): """ atom_mappings[n] is a list of possible indices in G for mapping the node 'n' in G_subs possible_mappings is a parameter that will be filled with the possible mappings, which are mappings that have the right atom types, attributes and bond orders """ N = G.get_num_nodes() M = G_subs.get_num_nodes() m = len(map_prefix) if (m == M): possible_mappings.append(map_prefix) return for n in atom_mappings[m]: # n is a candidate for map[m] if (verify_reaction_bonds(G, G_subs, map_prefix, m, n)): combine_atom_mappings_recursive(G, G_subs, atom_mappings, possible_mappings, map_prefix + [n]) return def combine_atom_mappings(G, G_subs, atom_mappings): possible_mappings = [] combine_atom_mappings_recursive(G, G_subs, atom_mappings, possible_mappings) return possible_mappings G_subs = self.reaction_templates[reaction_id]['G_SUBS'] import_atoms = self.reaction_templates[reaction_id]['IMPORT'] N = G.get_num_nodes() M = G_subs.get_num_nodes() # find for each atom in G_template, which atoms in G match it atom_mappings = [] imported_atom_index = N for m in range(M): if (m in import_atoms): # if this atom is imported, assign it to a new index (larger than N) atom_mapping_m = [imported_atom_index] imported_atom_index += 1 else: atom_mapping_m = [] for n in range(N): if (G_subs.nodes[m] in [G.nodes[n], atom_wildcard] and \ G_subs.hydrogens[m] <= G.hydrogens[n] and \ G_subs.chirality[m] in [G.chirality[n], 3, 0]): atom_mapping_m.append(n) atom_mappings.append(atom_mapping_m) # now check each unique mapping, and see if the bonds are matching too product_hash_set = set() product_list = [] possible_mappings = combine_atom_mappings(G, G_subs, atom_mappings) #print >> sys.stderr, "# of possible mappings: %d" % len(possible_mappings) for mapping in possible_mappings: G_new = G.clone() self.apply_reaction(G_new, reaction_id, mapping) h_new = G_new.hash() ## print "%s : %s, %s" % (reaction_id, str(mapping), h_new), # skip this product if has already been reached using another mapping if (h_new in product_hash_set): ## print "DUPLICATE" continue product_hash_set.add(h_new) # update the product attributes (hydrogen atoms, ionic charges) # fail if these attributes cannot be resolved try: G_new.update_attributes() except ChemException: ## print "UNRESOLVED ATTRIBUTES" continue if (self.use_antimotifs): # fail if the product contains an anti-motif antimotif_list = G_new.find_antimotifs() if (antimotif_list != []): for motif in antimotif_list: self.antimotif_counter[motif] = self.antimotif_counter.get(motif, 0) + 1 ## print "FOUND ANTI-MOTIF: " + str(antimotif_list) continue # fail if any of the atoms has a positive charge, # which means that it has more bonds than its valence. if (max(G_new.charges) > 0): ## print "POSITIVE CHARGE" continue ## print "GREAT SUCCESS!!!" if (self.ignore_chirality): product_list.append((G_new, reaction_id, mapping)) else: # assign both chiralities to any undefined chiral point # in the new graph. This means there will be 2^n new graphs # if there are 'n' undefined chiral points. N = G_new.get_num_nodes(); undef_chiral_indices = [] for n in range(N): if (G_new.chirality[n] == 3): undef_chiral_indices.append(n) if (undef_chiral_indices == []): product_list.append((G_new, reaction_id, mapping)) else: #print "*** Chiral wildcard!!! ***" #print G_new #print G_new.chirality #print undef_chiral_indices for chiral_list in cartesian_product([[1,2]]*len(undef_chiral_indices)): G_chir = G_new.clone() for i in range(len(undef_chiral_indices)): G_chir.chirality[undef_chiral_indices[i]] = chiral_list[i] #print G_chir product_list.append((G_chir, reaction_id, mapping)) return product_list
def pattern_matching(self, G, reaction_id): """ this function finds every embodiment of G_subs in G (every mapping from G to G_subs) and applies the reaction to G (by replacing the subgraph in G with G_prod) """ def verify_reaction_bonds(G, G_subs, map_prefix, m1, n1): """ verifies that one can map node 'm' in G_subs, to node 'n' in G, given a map_prefix. This method actually check all the new bonds that m->n will add, and verifies they are consistent in G_subs. """ if n1 >= G.get_num_nodes(): # m1 is an imported atom (like H2O or PO3), don't check its bonds return True for m2 in range(len(map_prefix)): n2 = map_prefix[m2] if n2 >= G.get_num_nodes(): continue # m2 is an imported atom (like H2O or PO3), don't check its bonds if G_subs.get_bond(m1, m2) != G.get_bond(n1, n2): return False return True def combine_atom_mappings_recursive(G, G_subs, atom_mappings, possible_mappings, map_prefix=[]): """ atom_mappings[n] is a list of possible indices in G for mapping the node 'n' in G_subs possible_mappings is a parameter that will be filled with the possible mappings, which are mappings that have the right atom types, attributes and bond orders """ N = G.get_num_nodes() M = G_subs.get_num_nodes() m = len(map_prefix) if m == M: possible_mappings.append(map_prefix) return for n in atom_mappings[m]: # n is a candidate for map[m] if verify_reaction_bonds(G, G_subs, map_prefix, m, n): combine_atom_mappings_recursive(G, G_subs, atom_mappings, possible_mappings, map_prefix + [n]) return def combine_atom_mappings(G, G_subs, atom_mappings): possible_mappings = [] combine_atom_mappings_recursive(G, G_subs, atom_mappings, possible_mappings) return possible_mappings G_subs = self.reaction_templates[reaction_id]["G_SUBS"] import_atoms = self.reaction_templates[reaction_id]["IMPORT"] N = G.get_num_nodes() M = G_subs.get_num_nodes() # find for each atom in G_template, which atoms in G match it atom_mappings = [] imported_atom_index = N for m in range(M): if m in import_atoms: # if this atom is imported, assign it to a new index (larger than N) atom_mapping_m = [imported_atom_index] imported_atom_index += 1 else: atom_mapping_m = [] for n in range(N): if ( G_subs.nodes[m] in [G.nodes[n], atom_wildcard] and G_subs.hydrogens[m] <= G.hydrogens[n] and G_subs.chirality[m] in [G.chirality[n], 3, 0] ): atom_mapping_m.append(n) atom_mappings.append(atom_mapping_m) # now check each unique mapping, and see if the bonds are matching too product_hash_set = set() product_list = [] possible_mappings = combine_atom_mappings(G, G_subs, atom_mappings) # print >> sys.stderr, "# of possible mappings: %d" % len(possible_mappings) for mapping in possible_mappings: G_new = G.clone() self.apply_reaction(G_new, reaction_id, mapping) h_new = G_new.hash() ## print "%s : %s, %s" % (reaction_id, str(mapping), h_new), # skip this product if has already been reached using another mapping if h_new in product_hash_set: ## print "DUPLICATE" continue product_hash_set.add(h_new) # update the product attributes (hydrogen atoms, ionic charges) # fail if these attributes cannot be resolved try: G_new.update_attributes() except ChemException: ## print "UNRESOLVED ATTRIBUTES" continue if self.use_antimotifs: # fail if the product contains an anti-motif antimotif_list = G_new.find_antimotifs() if antimotif_list != []: for motif in antimotif_list: self.antimotif_counter[motif] = self.antimotif_counter.get(motif, 0) + 1 ## print "FOUND ANTI-MOTIF: " + str(antimotif_list) continue # fail if any of the atoms has a positive charge, # which means that it has more bonds than its valence. if max(G_new.charges) > 0: ## print "POSITIVE CHARGE" continue ## print "GREAT SUCCESS!!!" if self.ignore_chirality: product_list.append((G_new, reaction_id, mapping)) else: # assign both chiralities to any undefined chiral point # in the new graph. This means there will be 2^n new graphs # if there are 'n' undefined chiral points. N = G_new.get_num_nodes() undef_chiral_indices = [] for n in range(N): if G_new.chirality[n] == 3: undef_chiral_indices.append(n) if undef_chiral_indices == []: product_list.append((G_new, reaction_id, mapping)) else: # print "*** Chiral wildcard!!! ***" # print G_new # print G_new.chirality # print undef_chiral_indices for chiral_list in cartesian_product([[1, 2]] * len(undef_chiral_indices)): G_chir = G_new.clone() for i in range(len(undef_chiral_indices)): G_chir.chirality[undef_chiral_indices[i]] = chiral_list[i] # print G_chir product_list.append((G_chir, reaction_id, mapping)) return product_list