-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenetic_algorithm_driver.py
315 lines (278 loc) · 9.3 KB
/
genetic_algorithm_driver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
"""Driver script for running a GA algorithm.
Written by Magnus Strandgaard 2023
Example:
How to run:
$ python genetic_algorithm_driver.py --args
"""
import argparse
import logging
import os
import pathlib
import sys
import time
from pathlib import Path, PosixPath
from typing import NoReturn
from catalystGA.utils import MoleculeOptions
from classes.GeneticAlgorithm import GeneticAlgorithm
from classes.schrock_paralell import Schrock
from utils.utils import get_git_revision_short_hash
# Initialize logger
_logger: logging.Logger = logging.getLogger(__name__)
def get_arguments(arg_list=None) -> argparse.Namespace:
"""
Args:
arg_list: Automatically obtained from the commandline if provided.
Otherwise default arguments are used
Returns:
parser.parse_args(arg_list)(Namespace): Dictionary like class that contain the driver arguments.
"""
parser = argparse.ArgumentParser(
description="Run GA algorithm", fromfile_prefix_chars="+"
)
### Population
parser.add_argument(
"--population_size",
type=int,
default=5,
help="Sets the size of population pool.",
)
parser.add_argument(
"--n_confs",
type=int,
default=2,
help="How many conformers to generate",
)
parser.add_argument(
"--num_rotatable_bonds",
type=int,
default=20,
help="Setting the limit for num rotatable bonds for each FULL catalyt",
)
parser.add_argument(
"--max_size",
type=int,
default=100,
help="Sets the max number of heavy atoms in the FULL catalyst",
)
parser.add_argument(
"--min_size",
type=int,
default=2,
help="Sets the min number of heavy atoms in the FULL catalyst",
)
### Ligand distribution
parser.add_argument(
"--DativeLigands",
type=int,
default=0,
help="How many Dative ligands to use",
)
parser.add_argument(
"--CovalentLigands",
type=int,
required=True,
help="""How many X-ligands to use""",
)
parser.add_argument(
"--BidentateLigands",
type=int,
default=0,
help="How many Bidentate ligands to use",
)
### Computational
parser.add_argument(
"--molecules_per_chunk",
type=int,
default=1,
help="How many molecules to put in each chunk",
)
parser.add_argument(
"--cpus_per_chunk",
type=int,
default=1,
help="Number of cores for each chunk of molecules",
)
parser.add_argument(
"--mem_per_cpu",
type=str,
default="500MB",
help="Mem per cpu allocated for submitit job",
)
parser.add_argument(
"--partition",
choices=[
"kemi1",
"xeon16",
"xeon24",
"xeon40",
],
required=True,
help="""Choose partition to run on""",
)
### Diverse GA args
parser.add_argument("--debug", action="store_true")
parser.add_argument(
"--find_connection_point",
action="store_true",
help="Pre-screeen ligand candidate for connection points.",
)
parser.add_argument(
"--load_from_pickle",
default=False,
type=pathlib.Path,
help="Load starting population from pickle",
)
parser.add_argument(
"--minimize_score",
action="store_false",
help="Minimize the score in the scoring function.",
)
parser.add_argument(
"--generations",
type=int,
default=1,
help="How many times is the population optimized",
)
parser.add_argument(
"--n_tries",
type=int,
default=1,
help="How many overall runs of the GA",
)
parser.add_argument(
"--scoring_function",
choices=["calculate_score_logP", "calculate_score"],
required=True,
help="Choose one of the specified scoring functions to be run.",
)
parser.add_argument(
"--sa_screening",
dest="sa_screening",
default=False,
action="store_true",
)
parser.add_argument(
"--filename",
type=str,
default="./data/ZINC_250k.smi",
help="",
)
parser.add_argument(
"--output_dir",
type=PosixPath,
default="debug/",
help="Directory to put output files",
)
parser.add_argument(
"--scratch",
type=Path,
default="SCRATCH",
help="Directory to put scratch files",
)
parser.add_argument(
"--cleanup", action="store_true", help="Clean xtb files after calulation"
),
### XTB related options
parser.add_argument(
"--method",
type=str,
default="2",
help="gfn method to use",
)
parser.add_argument(
"--timeout_min",
type=int,
default=12,
help="Minutes before timeout for each slurm job.(Each chunk of molecules)",
)
parser.add_argument(
"--rms_prune",
type=float,
default=0.25,
help="Embedding pruning",
)
parser.add_argument(
"--energy_cutoff",
type=float,
default=0.0319,
help="Cutoff for conformer energies",
)
parser.add_argument(
"--opt",
type=str,
default="tight",
help="Opt convergence criteria for XTB",
)
return parser.parse_args(arg_list)
def main() -> NoReturn:
"""Main function that starts the GA."""
args = get_arguments()
# Get arguments as dict and add scoring function to dict.
args_dict = vars(args)
# Root output dir
root = args.output_dir
# Set Options for Molecule
mol_options = MoleculeOptions(
individual_type=Schrock,
max_size=args.max_size,
min_size=args.min_size,
num_rotatable_bonds=args.num_rotatable_bonds,
)
# Run the GA
for i in range(args.n_tries):
# Start the time
t0 = time.time()
# Create output_dir
args_dict["output_dir"] = root / f"gen_{i}_{time.strftime('%Y-%m-%d_%H-%M')}"
Path(args_dict["output_dir"]).mkdir(parents=True, exist_ok=True)
# Setup logger
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)-5.5s] %(message)s",
handlers=[
logging.FileHandler(
os.path.join(args_dict["output_dir"], "printlog.txt"), mode="w"
),
logging.StreamHandler(), # For debugging. Can be removed on remote
],
)
# Log current git commit hash
logging.info("Current git hash: %s", get_git_revision_short_hash())
# Log the argparse set values
logging.info("Input args: %r", args)
# Set how many cpus per mol
args_dict["cpus_per_mol"] = (
args_dict["cpus_per_chunk"] // args_dict["molecules_per_chunk"]
)
# Initialize GA
ga = GeneticAlgorithm(args=args_dict, mol_options=mol_options)
# Run the GA
ga.run()
# Final output handling and logging
t1 = time.time()
logging.info(f"# Total duration: {(t1 - t0) / 60.0:.2f} minutes")
logging.info(
""" GA RUN IS DONE
/$$$$$$$ /$$ /$$ /$$$$$$$ /$$
| $$__ $$|__/ | $$ | $$__ $$ | $$
| $$ \ $$ /$$ /$$$$$$$ /$$$$$$$| $$$$$$$ | $$ \ $$ /$$$$$$ /$$$$$$$ /$$$$$$$| $$$$$$$
| $$$$$$$ | $$ /$$_____/ /$$_____/| $$__ $$ | $$$$$$$ |____ $$ /$$_____/ /$$_____/| $$__ $$
| $$__ $$| $$| $$$$$$ | $$ | $$ \ $$ | $$__ $$ /$$$$$$$| $$$$$$ | $$ | $$ \ $$
| $$ \ $$| $$ \____ $$| $$ | $$ | $$ | $$ \ $$ /$$__ $$ \____ $$| $$ | $$ | $$
| $$$$$$$/| $$ /$$$$$$$/| $$$$$$$| $$ | $$ /$$ | $$$$$$$/| $$$$$$$ /$$$$$$$/| $$$$$$$| $$ | $$
|_______/ |__/|_______/ \_______/|__/ |__/| $/ |_______/ \_______/|_______/ \_______/|__/ |__/
|_/
/$$ /$$ /$$ /$$$$$$$ /$$
| $$ | $$ | $$ | $$__ $$ | $$
| $$ | $$ /$$$$$$ | $$$$$$$ /$$$$$$ /$$$$$$ | $$ \ $$ /$$$$$$ /$$$$$$$ /$$$$$$$| $$$$$$$
| $$$$$$$$ |____ $$| $$__ $$ /$$__ $$ /$$__ $$ | $$$$$$$ /$$__ $$ /$$_____/ /$$_____/| $$__ $$
| $$__ $$ /$$$$$$$| $$ \ $$| $$$$$$$$| $$ \__/ | $$__ $$| $$ \ $$| $$$$$$ | $$ | $$ \ $$
| $$ | $$ /$$__ $$| $$ | $$| $$_____/| $$ | $$ \ $$| $$ | $$ \____ $$| $$ | $$ | $$
| $$ | $$| $$$$$$$| $$$$$$$/| $$$$$$$| $$ | $$$$$$$/| $$$$$$/ /$$$$$$$/| $$$$$$$| $$ | $$
|__/ |__/ \_______/|_______/ \_______/|__/ |_______/ \______/ |_______/ \_______/|__/ |__/
"""
)
# Ensure the program exists when running on the frontend.
sys.exit(0)
if __name__ == "__main__":
main()