def _get_case_data_1() -> CaseData: topology_graph = stk.polymer.Linear( building_blocks=(stk.BuildingBlock('BrCCBr', [stk.BromoFactory()]), ), repeating_unit='A', num_repeating_units=2, ) return CaseData( fitness_normalizer=stk.DivideByMean(), population=( stk.MoleculeRecord( topology_graph=topology_graph, ).with_fitness_value(1), stk.MoleculeRecord( topology_graph=topology_graph, ).with_fitness_value(2), stk.MoleculeRecord( topology_graph=topology_graph, ).with_fitness_value(3), ), normalized=( stk.MoleculeRecord( topology_graph=topology_graph, ).with_fitness_value(0.5), stk.MoleculeRecord( topology_graph=topology_graph, ).with_fitness_value(1), stk.MoleculeRecord( topology_graph=topology_graph, ).with_fitness_value(1.5), ), )
def _get_case_data_2() -> CaseData: topology_graph = stk.polymer.Linear( building_blocks=(stk.BuildingBlock('BrCCBr', [stk.BromoFactory()]), ), repeating_unit='A', num_repeating_units=2, ) return CaseData( fitness_normalizer=stk.DivideByMean( filter=lambda population, record: record.get_fitness_value( ) is not None, ), population=( stk.MoleculeRecord( topology_graph=topology_graph, ).with_fitness_value( (1, 10, 100)), stk.MoleculeRecord( topology_graph=topology_graph, ).with_fitness_value( (2, 20, 200)), stk.MoleculeRecord( topology_graph=topology_graph, ).with_fitness_value( (3, 30, 300)), stk.MoleculeRecord(topology_graph), ), normalized=( stk.MoleculeRecord( topology_graph=topology_graph, ).with_fitness_value( (0.5, 0.5, 0.5)), stk.MoleculeRecord( topology_graph=topology_graph, ).with_fitness_value((1, 1, 1)), stk.MoleculeRecord( topology_graph=topology_graph, ).with_fitness_value( (1.5, 1.5, 1.5)), stk.MoleculeRecord(topology_graph), ), )
return f is not None elif isinstance(f, list): return None not in population.get_fitness_values()[mol] else: return False # Minimize synthetic accessibility and asymmetry. # Maximise pore volume and window size. fitness_normalizer = stk.TryCatch( stk.Sequence( save_fitness, stk.Power([1, 1, -1, -1], filter=valid_fitness), stk.DivideByMean(filter=valid_fitness), stk.Multiply([5, 1, 10, 10], filter=valid_fitness), stk.Sum(filter=valid_fitness), # Replace all fitness values that are lists or None with # a small value. stk.ReplaceFitness(replacement_fn=lambda population: 1e-8, filter=lambda p, m: isinstance( p.get_fitness_values()[m], (list, type(None)), )), ), stk.ReplaceFitness(replacement_fn=lambda population: 1e-8, )) # ##################################################################### # Exit condition. # #####################################################################
def main(): parser = argparse.ArgumentParser() parser.add_argument('--mongodb_uri', help='The MongoDB URI for the database to connect to.', default='mongodb://localhost:27017/') args = parser.parse_args() logging.basicConfig(level=logging.INFO) # Use a random seed to get reproducible results. random_seed = 4 generator = np.random.RandomState(random_seed) logger.info('Making building blocks.') # Load the building block databases. fluoros = tuple( get_building_blocks( path=pathlib.Path(__file__).parent / 'fluoros.txt', functional_group_factory=stk.FluoroFactory(), )) bromos = tuple( get_building_blocks( path=pathlib.Path(__file__).parent / 'bromos.txt', functional_group_factory=stk.BromoFactory(), )) initial_population = tuple(get_initial_population(fluoros, bromos)) # Write the initial population. for i, record in enumerate(initial_population): write(record.get_molecule(), f'initial_{i}.mol') client = pymongo.MongoClient(args.mongodb_uri) db = stk.ConstructedMoleculeMongoDb(client) fitness_db = stk.ValueMongoDb(client, 'fitness_values') # Plot selections. generation_selector = stk.Best( num_batches=25, duplicate_molecules=False, ) stk.SelectionPlotter('generation_selection', generation_selector) mutation_selector = stk.Roulette( num_batches=5, random_seed=generator.randint(0, 1000), ) stk.SelectionPlotter('mutation_selection', mutation_selector) crossover_selector = stk.Roulette( num_batches=3, batch_size=2, random_seed=generator.randint(0, 1000), ) stk.SelectionPlotter('crossover_selection', crossover_selector) fitness_calculator = stk.PropertyVector( property_functions=( get_num_rotatable_bonds, get_complexity, get_num_bad_rings, ), input_database=fitness_db, output_database=fitness_db, ) fitness_normalizer = stk.NormalizerSequence( fitness_normalizers=( # Prevent division by 0 error in DivideByMean, by ensuring # a value of each property to be at least 1. stk.Add((1, 1, 1)), stk.DivideByMean(), # Obviously, because all coefficients are equal, the # Multiply normalizer does not need to be here. However, # it's here to show that you can easily change the relative # importance of each component of the fitness value, by # changing the values of the coefficients. stk.Multiply((1, 1, 1)), stk.Sum(), stk.Power(-1), ), ) ea = stk.EvolutionaryAlgorithm( num_processes=1, initial_population=initial_population, fitness_calculator=fitness_calculator, mutator=stk.RandomMutator( mutators=( stk.RandomBuildingBlock( building_blocks=fluoros, is_replaceable=is_fluoro, random_seed=generator.randint(0, 1000), ), stk.SimilarBuildingBlock( building_blocks=fluoros, is_replaceable=is_fluoro, random_seed=generator.randint(0, 1000), ), stk.RandomBuildingBlock( building_blocks=bromos, is_replaceable=is_bromo, random_seed=generator.randint(0, 1000), ), stk.SimilarBuildingBlock( building_blocks=bromos, is_replaceable=is_bromo, random_seed=generator.randint(0, 1000), ), ), random_seed=generator.randint(0, 1000), ), crosser=stk.GeneticRecombination(get_gene=get_functional_group_type, ), generation_selector=generation_selector, mutation_selector=mutation_selector, crossover_selector=crossover_selector, fitness_normalizer=fitness_normalizer, ) logger.info('Starting EA.') generations = [] for generation in ea.get_generations(50): for record in generation.get_molecule_records(): db.put(record.get_molecule()) generations.append(generation) # Write the final population. for i, record in enumerate(generation.get_molecule_records()): write(record.get_molecule(), f'final_{i}.mol') logger.info('Making fitness plot.') # Normalize the fitness values across the entire EA before # plotting the fitness values. generations = tuple( normalize_generations( fitness_calculator=fitness_calculator, fitness_normalizer=fitness_normalizer, generations=generations, )) fitness_progress = stk.ProgressPlotter( generations=generations, get_property=lambda record: record.get_fitness_value(), y_label='Fitness Value', ) fitness_progress.write('fitness_progress.png') fitness_progress.get_plot_data().to_csv('fitness_progress.csv') logger.info('Making rotatable bonds plot.') rotatable_bonds_progress = stk.ProgressPlotter( generations=generations, get_property=lambda record: get_num_rotatable_bonds(record. get_molecule()), y_label='Number of Rotatable Bonds', ) rotatable_bonds_progress.write('rotatable_bonds_progress.png')