def make_monomer(length):
        """make an alkyl chain with two phenyl end caps
        
        >>> length = 7
        >>> ap_monomer = AlkylPhenylPolymer.make_monomer(length)
        >>> ap_monomer.get_num_atoms() == 6 * 2 + length
        True
        
        >>> display(Draw.MolToImage(mol_with_atom_index(ap_monomer.to_rdkit_mol()),
        ...                        size=(700, 300)))
        """
        alkane = init_building_block(smiles='F' + 'C' * length + 'F',
                                     functional_groups=[stk.FluoroFactory()])
        benzene = init_building_block(smiles='FC1=CC=CC=C1',
                                      functional_groups=[stk.FluoroFactory()])

        alkyl_phenyl = stk.ConstructedMolecule(
            topology_graph=stk.polymer.Linear(
                building_blocks=(alkane, benzene),
                repeating_unit='BAB',
                num_repeating_units=1,
                optimizer=stk.MCHammer(),
            ))

        return stk.BuildingBlock.init_from_molecule(alkyl_phenyl)
예제 #2
0
             hydrogen=stk.H(5),
             atom=stk.C(1),
             bonders=(stk.S(0), ),
             deleters=(stk.H(5), ),
         ),
         stk.Thiol(
             sulfur=stk.S(4),
             hydrogen=stk.H(12),
             atom=stk.C(3),
             bonders=(stk.S(4), ),
             deleters=(stk.H(12), ),
         ),
     ),
 ),
 lambda: CaseData(
     factory=stk.FluoroFactory(),
     molecule=stk.BuildingBlock('FCC(F)CCF'),
     functional_groups=(
         stk.Fluoro(
             fluorine=stk.F(0),
             atom=stk.C(1),
             bonders=(stk.C(1), ),
             deleters=(stk.F(0), ),
         ),
         stk.Fluoro(
             fluorine=stk.F(3),
             atom=stk.C(2),
             bonders=(stk.C(2), ),
             deleters=(stk.F(3), ),
         ),
         stk.Fluoro(
예제 #3
0
     55,
     56,
     57,
     58,
     59,
     31,
     62,
     63,
 ),
 stk.BuildingBlock(
     smiles=('Br[C+]1[C+]2[N+][C+2]C2(Br)[C+](I)[C+'
             '](I)[C+](Br)[C+]1Br'),
     functional_groups=[
         stk.BromoFactory(),
         stk.IodoFactory(),
         stk.FluoroFactory(),
     ],
 ): (0, 1, 18, 50, 51),
 stk.BuildingBlock(
     smiles=('Br[C+]1[C+]2[S][C+2]C2(Br)[C+](I)[C+]'
             '(I)[C+](Br)[C+]1Br'),
     functional_groups=[
         stk.BromoFactory(),
         stk.IodoFactory(),
         stk.FluoroFactory(),
     ],
 ): (2, 16, 34, 49),
 stk.BuildingBlock(
     smiles=('Br[C+]1[C+]2[S][O]C2(Br)[C+](I)[C+](I'
             ')[C+](Br)[C+]1Br'),
     functional_groups=[
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')
예제 #5
0
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)
    ea = stk.EvolutionaryAlgorithm(
        initial_population=initial_population,
        fitness_calculator=stk.FitnessFunction(get_fitness_value),
        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=stk.Best(
            num_batches=25,
            duplicate_molecules=False,
        ),
        mutation_selector=stk.Roulette(
            num_batches=5,
            random_seed=generator.randint(0, 1000),
        ),
        crossover_selector=stk.Roulette(
            num_batches=3,
            batch_size=2,
            random_seed=generator.randint(0, 1000),
        ),
    )

    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.')

    fitness_progress = stk.ProgressPlotter(
        generations=generations,
        get_property=lambda record: record.get_fitness_value(),
        y_label='Fitness Value',
    )
    fitness_progress.write('fitness_progress.png')

    logger.info('Making rotatable bonds plot.')

    rotatable_bonds_progress = stk.ProgressPlotter(
        generations=generations,
        get_property=get_num_rotatable_bonds,
        y_label='Number of Rotatable Bonds',
    )
    rotatable_bonds_progress.write('rotatable_bonds_progress.png')