def mutate(mol, mutation_rate): if random.random() > mutation_rate: return mol Chem.Kekulize(mol, clearAromaticFlags=True) p = [0.15, 0.14, 0.14, 0.14, 0.14, 0.14, 0.15] for i in range(10): rxn_smarts_list = 7 * [''] rxn_smarts_list[0] = insert_atom() rxn_smarts_list[1] = change_bond_order() rxn_smarts_list[2] = delete_cyclic_bond() rxn_smarts_list[3] = add_ring() rxn_smarts_list[4] = delete_atom() rxn_smarts_list[5] = change_atom(mol) rxn_smarts_list[6] = append_atom() rxn_smarts = np.random.choice(rxn_smarts_list, p=p) #print 'mutation',rxn_smarts rxn = AllChem.ReactionFromSmarts(rxn_smarts) new_mol_trial = rxn.RunReactants((mol, )) new_mols = [] for m in new_mol_trial: m = m[0] #print Chem.MolToSmiles(mol),mol_OK(mol) if co.mol_OK(m) and co.ring_OK(m): new_mols.append(m) if len(new_mols) > 0: return random.choice(new_mols) return None
def crossover(parent_a_mol,parent_b_mol): parent_a, parent_b = mol2string(parent_a_mol), mol2string(parent_b_mol) for _ in range(50): cut_point_a = cut_point(parent_a) cut_point_b = cut_point(parent_b) a1 = parent_a[0:cut_point_a] b2 = parent_b[cut_point_b:len(parent_b)] child_string = a1 + b2 child_mol = string2mol(child_string) #print(child_string,Chem.MolToSmiles(child_mol),child_mol,co.mol_OK(child_mol)) if co.mol_OK(child_mol): return child_mol return None
def mutate(mol,mutation_rate): if random.random() > mutation_rate: return mol Chem.Kekulize(mol,clearAromaticFlags=True) child = stco.mol2string(mol) symbols = get_symbols() for i in range(50): random_number = random.random() mutated_gene = random.randint(0, len(child) - 1) random_symbol_number = random.randint(0, len(symbols)-1) new_child = list(child) random_number = random.random() new_child[mutated_gene] = symbols[random_symbol_number] new_child_mol = stco.string2mol(new_child) #print(child_smiles,Chem.MolToSmiles(child_mol),child_mol,co.mol_OK(child_mol)) if co.mol_OK(new_child_mol): return new_child_mol return mol
def reproduce(mating_pool, population_size, mutation_rate): new_population = [] count = 0 while len(new_population) < population_size: parent_A = random.choice(mating_pool) parent_B = random.choice(mating_pool) #print Chem.MolToSmiles(parent_A),Chem.MolToSmiles(parent_B) new_child = co.crossover(parent_A, parent_B) #print new_child if new_child != None: new_child = mu.mutate(new_child, mutation_rate) #print "after mutation",new_child if new_child != None: mol = co.mol_OK(new_child) if mol != True: count += 1 else: new_population.append(new_child) else: count += 1 else: count += 1 return new_population, count