-
Notifications
You must be signed in to change notification settings - Fork 0
/
job.py
1690 lines (1588 loc) · 62.7 KB
/
job.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import hashlib
import io
import itertools as it
import os
import re
import shutil
import time
import numpy as np
import paramiko
from AaronTools import addlogger, getlogger
from AaronTools.atoms import Atom
from AaronTools.comp_output import CompOutput
from AaronTools.config import Config
from AaronTools.const import AARONLIB, UNIT
from AaronTools.fileIO import Frequency
from AaronTools.geometry import Geometry
from AaronTools.theory import GAUSSIAN_ROUTE
from fireworks import (
Firework,
FWAction,
FWorker,
LaunchPad,
ScriptTask,
Workflow,
)
from fireworks.core.launchpad import LazyFirework
from fireworks.user_objects.queue_adapters.common_adapter import (
CommonAdapter as QueueAdapter,
)
from fireworks.utilities.fw_utilities import explicit_serialize
from jinja2 import Environment, FileSystemLoader
TEMPLATES = [
os.path.join(AARONLIB, "templates"),
os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates"),
]
ENVIRONMENT = Environment(loader=FileSystemLoader(TEMPLATES))
LAUNCHPAD = LaunchPad.auto_load()
MAX_ATTEMPTS = 10 # number of attempts, regardless of error
MAX_SUBMIT = (
3 # number of submission attempts (errors with queue submission itself)
)
def find_qadapter_template(qadapter_template):
for path in TEMPLATES:
rv = os.path.join(path, qadapter_template)
if os.access(rv, os.R_OK):
return rv
log = getlogger()
log.exception("Could not find %s in %s", qadapter_template, str(TEMPLATES))
def find_exec_template(exec_template):
for path in TEMPLATES:
rv = os.path.join(path, exec_template)
if os.access(rv, os.R_OK):
return rv
log = getlogger()
log.exception("Could not find %s in %s", exec_template, str(TEMPLATES))
def conf_rmsd_tol(geom):
"""
Automatically determine a reasonable rmsd tolerance for the input
geometry based on its size and number of atoms
"""
com = geom.COM()
tolerance = 0
max_d = None
for atom in geom.atoms:
d = np.linalg.norm(atom.coords - com)
tolerance += d ** 2
if max_d is None or d > max_d:
max_d = d
tolerance /= len(geom.atoms)
return tolerance ** (1 / 2) / max_d
def get_steps(config):
step_dict = {}
for option, val in config["Job"].items():
key = option.split()
if len(key) == 1 and key[0] == "type":
step_dict[0] = val
continue
step = key[0]
key = "".join(key[1:])
if "type" != key:
continue
if "changes" in val and not "".join(config._changes.keys()):
continue
if int(step) == float(step):
step_dict[int(step)] = val
else:
step_dict[float(step)] = val
step_list = sorted(step_dict.keys())
return step_list
@addlogger
@explicit_serialize
class Job:
"""
Attributes:
:structure: Geometry - the structure (updated during run)
:config: Config - the configuration object
:step: Union[float, int] - the current step
:step_list: List[Union[float, int]] - all steps to perform
:fw_id: int - the FW id for the current step
:parent_fw_id: int - FW id for direct parent of fw_id
:root_fw_id: int - FW id for root FW of this job's workflow
:quiet: bool - supress extraneous printing if true
Class constants:
:SKIP_SPEC: List[Tuple[str]] - (Config section name, Config option regex) pairs
used to exclude spec items when querying the launchpad database
:SKIP_CONNECT: bool - when True, paramkio.Connection objects will NOT be created on
initialization of new Job objects (default is False)
"""
# spec items to skip when building query dict
SKIP_SPEC = [
("Geometry", "^(?!constrain(ts)?).*$"),
("Results", "^.*$"),
("Plot", "^.*$"),
("HPC", "^.*$"),
("Job", "^(?!(type|\d+ type|exec_type)).*$"),
("Substitution", "^.*$"), # already included in config._changes
("Mapping", "^.*$"), # already included in config._changes
# these can change without needing new FW
(
"^.*$",
"^(.*_dir|local_only|log_level|.*_citations)$",
),
("^.*$", "project"), # this is included in metadata
("^.*$", "include"), # this has been parsed into the main body
"_changed_list",
]
SKIP_CONNECT = False
LOG = None
LOGLEVEL = "INFO"
def __init__(
self,
structure,
config,
quiet=True,
make_root=True,
testing=False,
):
"""
:structure Union[Geometry, Firework, str]: the starting geometry structure
:config Config: the configuration object to associate with this job
:quiet bool: print extra info when loading config if False
:make_changes bool: do structure modification as specified in config
:make_root bool: set to False to prevent addition of root FW (it will still check to see if it's there)
:testing bool: prevents adding new FW to launchpad upon initialization of the
job object; this should only be set to True for testing purposes
"""
self.quiet = quiet
self.config = None
self.step_list = []
self.structure = None
self.structure_hash = None
self.step = None
self.conformer = 0
self.fw_id = None
self.parent_fw_id = None
self.root_fw_id = None
self.RUN_CONNECTION = None
self.XFER_CONNECTION = None
# loading in config-defined stuff
if isinstance(config, Config):
self.config = config
else:
self.config = Config(config, quiet=quiet)
self.set_connections(self.config)
# load structure from fw spec
if isinstance(structure, (Firework, LazyFirework)):
self.load_fw(structure)
# or from passed geometry
elif isinstance(structure, Geometry):
self.structure = structure
else:
self.structure = Geometry(structure)
if self.config.get("Job", "include", fallback="").lower() == "detect":
if self.structure.name.lower().startswith("int"):
self.config.set("Job", "include", "Minimum")
elif self.structure.name.lower().startswith("ts"):
self.config.set("Job", "include", "TS")
else:
raise RuntimeError(
"Could not detect workflow type for {}. [Job] include=detect is only valid for template files starting with 'int' or 'ts' (case insensitive)".format(
self.structure.name
)
)
self.config._parse_includes("Job")
self.step_list = self.get_steps()
if self.step is None:
try:
self.step = self.step_list[0]
except IndexError:
self.step = 0
# find fw id for root and current step's job
self.jobname = os.path.join(
".".join(self.config._changes.keys()), self.structure.name
)
if not self.structure_hash:
structure_hash = hashlib.sha256()
tmp = ""
for a in sorted(
self.structure.atoms, key=lambda x: np.linalg.norm(x.coords)
):
tmp += str(np.round(a.coords, 3).tolist())
structure_hash.update(tmp.encode())
self.structure_hash = structure_hash.hexdigest()
if not testing:
self.set_root(make_root=make_root)
# remote connection commands
def set_connections(self, config, skip_connect=None):
"""
Sets RUN_CONNECTION and XFER_CONNECTION using config options to initialize
paramiko connection objects
:config: the configuration object with user/host info
:skip_connect: overrides self.SKIP_CONNECT
"""
if skip_connect or (skip_connect is None and self.SKIP_CONNECT):
return
run_user = config.get("HPC", "user", fallback=False)
run_host = config.get("HPC", "host", fallback=False)
xfer_user = config.get("HPC", "transfer_user", fallback=run_user)
xfer_host = config.get("HPC", "transfer_host", fallback=run_host)
if run_host:
self.RUN_CONNECTION = paramiko.client.SSHClient()
self.RUN_CONNECTION.load_system_host_keys()
self.RUN_CONNECTION.connect(run_host, username=run_user)
if xfer_host:
self.XFER_CONNECTION = paramiko.client.SSHClient()
self.XFER_CONNECTION.load_system_host_keys()
self.XFER_CONNECTION.connect(xfer_host, username=xfer_user)
def remote_mkdir(self, dirname):
"""
Make a directory on the remote machine.
Will create parent directories as needed.
:dirname: the path name of the directory to create
"""
if not dirname:
return
with self.XFER_CONNECTION.open_sftp() as sftp:
try:
sftp.mkdir(dirname)
except FileNotFoundError:
self.remote_mkdir(os.path.dirname(dirname))
sftp.mkdir(dirname)
except OSError:
self.LOG.error(
"Couldn't mkdir %s on remote host. This can often be resolved by "
"simply restarting AaronJr. If you still have problems, try "
"creating the directory manually.",
dirname,
)
exit(1)
def remote_put(self, source, target):
"""
Copies `source` to the remote `target` location
Returns: True if put command exited successfully, False if self.XFER_CONNECTION
not associated with a connection object.
:source: path to local file or file-like object
:target: path to desired remote file location, can be a directory if `source`
is a path to a file
"""
if self.XFER_CONNECTION is None:
return False
def _put(source, target, put_method):
try:
put_method(source, target)
except FileNotFoundError:
self.remote_mkdir(os.path.dirname(target))
put_method(source, target)
with self.XFER_CONNECTION.open_sftp() as sftp:
try:
_put(source, target, sftp.put)
except TypeError:
_put(source, target, sftp.putfo)
return True
def remote_get(self, source, target):
"""
Copy file from remote `source` to local `target`.
Will only copy the remote file if one of the following conditions are met:
1. The local file does not exist
2. The remote file was modified more recently than the target file
:source: path to remote file
:target: path to local file
"""
if self.XFER_CONNECTION is None:
return False
try:
with self.XFER_CONNECTION.open_sftp() as sftp:
remote_mtime = sftp.stat(source).st_mtime
except FileNotFoundError:
return False
try:
local_mtime = os.stat(target).st_mtime
except FileNotFoundError:
local_mtime = None
if local_mtime is not None and int(local_mtime) > int(remote_mtime):
return False
try:
with self.XFER_CONNECTION.open_sftp() as sftp:
sftp.get(source, target)
except FileNotFoundError:
os.mkdir(os.path.dirname(target))
with self.XFER_CONNECTION.open_sftp() as sftp:
sftp.get(source, target)
return True
def remote_run(self, cmd):
if self.RUN_CONNECTION is None:
return None, None
_, stdout, stderr = self.RUN_CONNECTION.exec_command(cmd)
stdout = stdout.read().decode()
stderr = stderr.read().decode()
# self.LOG.debug("%s %s", stdout, stderr)
return stdout, stderr
# utilities
def _make_changes(self):
self.structure = self.config.make_changes(self.structure)
def _root_fw(self, workflow=None, make_root=True):
"""
Makes the root fw, if we need one, and marks as completed.
The root fw is for organizational purposes for multi-step jobs, nothing is run.
"""
# if we can find a FW for the original structure, use that FW's root
# instead of making a new one (changes are children of original)
self.set_fw()
if self.fw_id:
self.set_root()
return self.root_fw_id
# build spec for new root fw
spec = self.get_spec(step="all")
for key in self.config.SPEC_ATTRS:
if key in ["infile", "metadata"]:
continue
del spec[key]
name = self.get_workflow_name()
fw = self.find_fw(spec=spec)
if fw is None and make_root:
fw = Firework([], spec=spec, name=name)
LAUNCHPAD.add_wf(
Workflow([fw], name=name, metadata=self.config.metadata)
)
if fw.state == "READY":
fw, launch_id = LAUNCHPAD.checkout_fw(
FWorker(), "", fw_id=fw.fw_id
)
LAUNCHPAD.complete_launch(launch_id, action=FWAction())
return fw.fw_id
def _get_exec_task(self, step=None, conformer=None, structure=None):
config = self.config_for_step(step=step, conformer=conformer)
if structure is None:
structure = self.structure
exec_type = config["Job"]["exec_type"]
exec_template = ENVIRONMENT.get_template(exec_type + ".template")
options = dict(
list(config["HPC"].items()) + list(config["Job"].items())
)
filename = os.path.join(
config["HPC"]["work_dir"],
self.get_basename(step=step, conformer=conformer),
)
options["work_dir"], options["job_name"] = os.path.split(filename)
# build hash for scratch subdirectory using search spec and filename
h = hashlib.sha1(
str(self.query_spec(step=step, conformer=conformer)).encode()
)
h.update(filename.encode())
options["scratch_dir"] = os.path.join(
config["HPC"].get("scratch_dir", fallback="scratch"),
h.hexdigest(),
)
if exec_type in ["xtb", "crest"]:
theory = config.get_theory(structure)
cmdline = theory.get_xtb_cmdline(config)
if "--optts" in cmdline:
options["optts"] = "true"
del cmdline["--optts"]
options["cmdline"] = ""
for key, val in cmdline.items():
if val is not None:
options["cmdline"] += "{} {} ".format(key, val)
else:
options["cmdline"] += "{} ".format(key)
options["cmdline"] = options["cmdline"].rstrip()
script = exec_template.render(**options)
return ScriptTask.from_str(script)
def _make_qadapter(self, fw_id):
config = self.config_for_step()
qadapter_template = self._find_qadapter_template()
# transfer template, if needed
if config["HPC"].get("host"):
AARONLIB_REMOTE, _ = self.remote_run("echo -n $AARONLIB")
remote_template = os.path.join(
AARONLIB_REMOTE,
"templates",
"{}_qadapter.template".format(config["HPC"]["queue_type"]),
)
self.remote_put(qadapter_template, remote_template)
qadapter_template = remote_template
if "rocket_launch" not in config["HPC"]:
config["HPC"][
"rocket_launch"
] = 'rlaunch -l "$AARONLIB/my_launchpad.yaml" singleshot'
# create qadapter
qadapter = QueueAdapter(
q_type=config["HPC"]["queue_type"],
q_name=config["HPC"]["queue"],
template_file=qadapter_template,
**dict(list(config["Job"].items()) + list(config["HPC"].items())),
)
# save qadapter; transfer if remote
rel_dir = os.path.dirname(self.jobname)
if config["HPC"].get("host"):
filename = os.path.join(
config["HPC"].get("remote_dir"),
rel_dir,
"qadapter_{}.yaml".format(fw_id),
)
content = qadapter.to_format(f_format="yaml")
self.remote_run("mkdir -p {}".format(os.path.dirname(filename)))
self.remote_run("touch {}".format(filename))
self.remote_put(io.StringIO(content), filename)
else:
filename = os.path.join(
config["HPC"].get("top_dir"),
rel_dir,
"qadapter_{}.yaml".format(fw_id),
)
qadapter.to_file(filename)
return filename
def _find_qadapter_template(self, step=None):
if step is None:
step = self.step
config = self.config_for_step(step=step)
qadapter_template = "{}_qadapter.template".format(
config["HPC"]["queue_type"]
)
return find_qadapter_template(qadapter_template)
def _structure_dict(self, structure=None, original_comment=True):
if structure is None:
structure = self.structure
if isinstance(structure, Geometry):
atoms = [str(a) for a in structure]
comment = structure.comment
elif isinstance(structure, tuple):
comment, atoms = structure
else:
self.LOG.debug("%s %s", type(structure), structure)
if original_comment:
return {"comment": self.structure.comment, "atoms": atoms}
else:
return {"comment": comment, "atoms": atoms}
def _last_launch(self, fw):
try:
return fw.launches[-1]
except IndexError:
return fw.archived_launches[-1]
def _get_stored_data(self, output):
skip_attrs = ["opts", "other"]
data = {}
for key, val in output.to_dict().items():
if key in skip_attrs:
continue
if key not in ["error", "error_msg", "finished"]:
try:
if len(val) == 0:
continue
except TypeError:
pass
if val is None:
continue
if key == "conformers" and val is not None:
tmp = {}
for i, v in enumerate(val):
tmp[str(i)] = self._structure_dict(
v, original_comment=False
)
data[str(key)] = tmp
continue
if key == "geometry" and val is not None:
data[str(key)] = self._structure_dict(
val, original_comment=False
)
continue
if key == "frequency":
# this dict can easily be recreated by calling sort_frequencies
# and the float keys mess up bson storage (can only have str keys)
del val["by_frequency"]
data[str(key)] = val
return data
def get_steps(self):
self.step_list = get_steps(self.config)
return self.step_list
def config_for_step(self, step=None, conformer=None):
if step is None:
step = self.step
config = self.config.copy()
if conformer is not None:
config.conformer = conformer
return config.for_step(step)
def get_spec(self, step=None, conformer=None, structure=None, skip=None):
if step is None:
step = self.step
if conformer is None:
conformer = self.conformer
if skip is None:
skip = []
skip += [("DEFAULT", ".*")]
if step == "all":
config = self.config
else:
config = self.config_for_step(step=step)
spec = {
"starting_structure": self.structure_hash,
"structure": self._structure_dict(structure=structure),
"step_list": self.step_list,
}
if step != "all":
spec["step"] = (
int(step) if int(step) == float(step) else float(step)
)
spec["conformer"] = conformer
spec = config.as_dict(spec, skip=skip)
return spec
def query_spec(self, step=None, conformer=None, spec=None):
"""
Builds a suitable pymongo-style query for searching for the job
Returns: dict()
"""
if step is None:
step = self.step
if conformer is None:
conformer = self.conformer
if spec is None:
spec = self.get_spec(
step=step,
conformer=conformer,
skip=self.SKIP_SPEC,
)
query_spec = {}
# changing resource requested shouldn't be a separate job
qadapter_template = self._find_qadapter_template(step=step)
with open(qadapter_template) as f:
qadapter_template = f.read()
res = re.findall("\$\${(.*?)}", qadapter_template)
exclude_pattern = re.compile(".*?/({})".format("|".join(res)))
for key, val in spec.items():
# these values are variable during the course of the job
if key in ["structure", "step_list", "_args", "_kwargs", "infile"]:
continue
if exclude_pattern.fullmatch(key):
continue
if key.endswith(
("basis", "method", "solvent", "solvent_model", "ecp")
):
query_spec["spec." + key] = {
"$regex": "^{}$".format(re.escape(val)),
"$options": "i",
}
else:
query_spec["spec." + key] = val
return query_spec
def find_fw(self, step=None, conformer=None, spec=None):
"""
Searches the launchpad for a particular FW
Returns the FW, if unique FW found, or None
"""
query_spec = self.query_spec(step=step, conformer=conformer, spec=spec)
# archived FWs are soft-deleted, so we don't want those
query_spec["state"] = {"$not": {"$eq": "ARCHIVED"}}
fw_id = LAUNCHPAD.get_fw_ids(query=query_spec)
fws = []
for fw in fw_id:
fw = LAUNCHPAD.get_fw_by_id(fw)
fws += [fw]
if fws and len(fws) == 1:
return fws.pop()
elif fws:
raise RuntimeError(
"fw spec returns multiple fireworks (ids: {})".format(
[fw.fw_id for fw in fws]
)
)
return None
def set_fw(self, step=None, conformer=None, spec=None, fw_id=None):
if (
(fw_id is None or int(fw_id) == int(self.fw_id))
and (step is None or float(step) == float(self.step))
and (conformer is None or int(conformer) == int(self.conformer))
):
fw_id = self.fw_id
if fw_id is None:
fw = self.find_fw(step=step, conformer=conformer, spec=spec)
else:
fw = LAUNCHPAD.get_fw_by_id(fw_id)
if fw:
self.load_fw(fw)
return fw
def load_fw(self, fw):
self.fw_id = fw.fw_id
self.config._args = fw.spec["_args"]
self.config._kwargs = fw.spec["_kwargs"]
if "step" in fw.spec:
self.step = fw.spec["step"]
if "conformer" in fw.spec:
self.conformer = fw.spec["conformer"]
if "structure" in fw.spec:
comment = fw.spec["structure"]["comment"]
atoms = []
for a in fw.spec["structure"]["atoms"]:
name, element, x, y, z = a.split()
atoms += [
Atom(
element=element,
coords=[x, y, z],
name=name,
)
]
self.structure = Geometry(atoms, refresh_ranks=False)
self.structure.comment = comment
self.structure.parse_comment()
self.structure_hash = fw.spec["starting_structure"]
if not hasattr(self, "structure"):
self.structure = Geometry()
idx = fw.name.rfind("." + str(self.step))
if idx > -1:
self.jobname = fw.name[:idx]
else:
self.jobname = fw.name
idx = self.jobname.find(
os.path.join(".".join(self.config._changes.keys()), "")
)
if idx > -1:
self.structure.name = self.jobname[idx:]
else:
self.structure.name = self.jobname
self.set_root()
def set_root(self, make_root=True):
"""
Sets self.root_fw_id to the root FW for the workflow containing `fw_id`,
creating it if not found in when make_root=True
:fw_id: defaults to self.fw_id
:make_root: set to False to prevent root FW creation
"""
if self.fw_id is None:
self.set_fw()
if self.fw_id is None:
self.root_fw_id = self._root_fw(make_root=make_root)
if self.parent_fw_id is None:
self.parent_fw_id = self.root_fw_id
return
links = LAUNCHPAD.get_wf_by_fw_id_lzyfw(self.fw_id).links
self.parent_fw_id = []
for key, val in links.items():
if self.fw_id in val:
self.parent_fw_id += [key]
children = set(it.chain.from_iterable(links.values()))
for key in links:
if key not in children:
self.root_fw_id = key
break
def get_workflow_name(self):
wf_name = os.path.join(
self.config.get("DEFAULT", "project", fallback=""),
self.config["DEFAULT"]["name"],
)
if self.config.get("Reaction", "reaction", fallback=""):
wf_name = os.path.join(
wf_name, self.config["Reaction"]["reaction"]
)
if self.config.get("Reaction", "template", fallback=""):
wf_name = os.path.join(
wf_name, self.config["Reaction"]["template"]
)
wf_name = "{}/{}".format(wf_name, self.jobname)
return wf_name
# file management
def get_basename(self, step=None, conformer=None):
if step is None:
step = self.step
if conformer is None:
conformer = self.conformer
name = self.jobname
if conformer:
name = "{}_{}".format(name, conformer)
if step:
name = "{}.{}".format(name, step)
return name
def get_input_name(self, skip_ext=False):
config = self.config_for_step()
exec_type = config["Job"]["exec_type"]
name = self.get_basename()
if exec_type == "gaussian":
if skip_ext:
return name
name += ".com"
elif exec_type == "crest":
name = os.path.join(name, "ref")
if skip_ext:
return name
name += ".xyz"
elif exec_type == "xtb":
if skip_ext:
return name
name += ".xyz"
else:
raise NotImplementedError(
"File type not added to AaronJr yet...", exec_type
)
return name
def get_output_name(self):
config = self.config_for_step()
name = self.get_basename()
exec_type = config["Job"]["exec_type"]
if exec_type == "gaussian":
name += ".log"
elif exec_type == "crest":
name = os.path.join(name, "out.crest")
elif exec_type == "xtb":
if "ts" in config["Job"]["type"]:
name = (name + ".xtb", name + ".freq")
else:
name += ".xtb"
else:
raise Exception
return name
def write(self, override_style=None, send=True):
config = self.config_for_step()
theory = config.get_theory(self.structure)
name = os.path.join(
config["Job"]["top_dir"], self.get_input_name(skip_ext=True)
)
exec_type = config["Job"]["exec_type"]
xcontrol = None
ref_name = None
auxfiles = []
if exec_type == "gaussian":
style = "com"
elif exec_type == "crest":
style = "xyz"
xcontrol = os.path.join(self.get_basename(), "xcontrol")
elif exec_type == "xtb":
style = "xyz"
xcontrol = os.path.join("{}.xcontrol".format(self.get_basename()))
ref_name = os.path.join("{}.xyz".format(self.get_basename()))
else:
raise Exception
if override_style is not None:
style = override_style
self.structure.write(
name=name, style=style, theory=theory, **config._kwargs
)
if xcontrol is not None:
auxfiles.append(
(
os.path.join(config["Job"]["top_dir"], xcontrol),
os.path.join(config["HPC"]["remote_dir"], xcontrol),
)
)
with open(auxfiles[-1][0], "w") as f:
f.write(theory.get_xcontrol(config, ref=ref_name))
if "transfer_host" in config["HPC"] and send:
if auxfiles:
self.transfer_input(aux_files=auxfiles)
else:
self.transfer_input()
return config
def transfer_input(self, aux_files=None):
config = self.config_for_step()
name = self.get_input_name()
source = os.path.join(config["Job"].get("top_dir"), name)
target = os.path.join(config["HPC"].get("remote_dir"), name)
args = [(source, target)]
if aux_files is not None:
args.extend(aux_files)
for source, target in args:
# self.LOG.debug("{} -> {}".format(source, target))
if not self.quiet:
print(
"Sending {} to {}...".format(
os.path.basename(target), config["HPC"].get("host")
)
)
self.remote_put(source, target)
def transfer_output(self, state=None, update=False):
config = self.config_for_step()
name = self.get_output_name()
if isinstance(name, tuple):
name, freq_name = name
else:
freq_name = None
source = os.path.join(config["HPC"]["remote_dir"], name)
target = os.path.join(config["Job"]["top_dir"], name)
new = self.remote_get(source, target)
if not self.quiet and new:
self.LOG.info(
"Downloaded {} from {}".format(name, config["HPC"]["host"])
)
exec_type = config["Job"]["exec_type"]
if exec_type == "crest" and (update or state == "COMPLETED"):
# this doesn't get written until the very end
try:
new = self.remote_get(
os.path.join(
os.path.dirname(source), "crest_conformers.xyz"
),
os.path.join(
os.path.dirname(target), "crest_conformers.xyz"
),
)
if not self.quiet and new:
self.LOG.info(
"Downloaded {} from {}".format(
"crest_conformers.xyz", config["HPC"]["host"]
)
)
except FileNotFoundError:
if update:
pass
if exec_type == "xtb" and freq_name is not None:
new = self.remote_get(
os.path.join(config["HPC"]["remote_dir"], freq_name),
os.path.join(config["Job"]["top_dir"], freq_name),
)
if not self.quiet and new:
self.LOG.info(
"Downloaded {} from {}".format(
".".join(freq_name),
config["HPC"]["host"],
)
)
return new
def archive_output(self, error_type):
config = self.config_for_step()
name = self.get_output_name()
if isinstance(name, tuple):
name, _ = name
local_name = os.path.join(config["Job"]["top_dir"], name)
fw = LAUNCHPAD.get_fw_by_id(self.fw_id)
try:
launch_id = fw.launches[-1].launch_id
except IndexError:
launch_id = fw.archived_launches[-1].launch_id
old_name, ext = os.path.splitext(name)
new_name = os.path.join(
config["Job"]["top_dir"],
"archived",
"{}_{}.{}.{}{}".format(
old_name, error_type, fw.fw_id, launch_id, ext
),
)
os.makedirs(os.path.dirname(new_name), exist_ok=True)
if os.path.isfile(local_name):
shutil.move(local_name, new_name)
def get_output(self, load_geom=False):
fw = LAUNCHPAD.get_fw_by_id(self.fw_id)
if fw.state != "COMPLETED":
return None
output = CompOutput()
for key, val in fw.launches[-1].action.stored_data.items():
if key == "geometry" and load_geom:
atoms = []
for v in val["atoms"]:
name, element, x, y, z = v.split()
atoms.append(
Atom(name=name, element=element, coords=[x, y, z])
)
val = Geometry(atoms)
if key == "frequency" and val:
val = Frequency(
[Frequency.Data(**item) for item in val["data"]]
)
setattr(output, key, val)
return output
# workflow management
def add_fw(
self, parent_fw_id=None, step=None, conformer=None, structure=None
):
"""
Adds FW to the appropriate workflow (creating if necessary) and updates self.fw_id accordingly
Returns: the created FW
:parent_fw_id: for linking within workflow (default to self.parent_fw_id)
:step: the step number
:conformer: the conformer number
:structure: the structure to use
"""
# make firework
fw = Firework(
[
self._get_exec_task(
step=step, conformer=conformer, structure=structure
)
],
spec=self.get_spec(
step=step, conformer=conformer, structure=structure
),
name=self.get_basename(step=step, conformer=conformer),
)
if not self.quiet:
print(
" Adding Firework for {} to workflow".format(
self.get_basename(step=step, conformer=conformer)
)
)
if parent_fw_id is None:
parent_fw_id = self.parent_fw_id
if isinstance(parent_fw_id, list):
LAUNCHPAD.append_wf(
Workflow([fw]), parent_fw_id, pull_spec_mods=False
)
elif parent_fw_id:
LAUNCHPAD.append_wf(
Workflow([fw]), [parent_fw_id], pull_spec_mods=False
)
else:
wf_name = self.get_workflow_name()
LAUNCHPAD.add_wf(
Workflow(
[fw],
name=wf_name,
metadata=self.config.metadata,
)
)
return fw
def add_workflow(
self, parent_fw_id=None, step_list=None, conformer=0, structure=None
):
"""
:parent_fw_id: assign the new workflow as children of this fw_id, default is
either the previous step's fw_id (if applicable) or the root_fw_id
:step_list: list(float) corresponding to the step numbers, defaults to the
return value of self.get_steps
:conformer: the conformer number to associate with the workflow
:structure: use this Geometry as starting structure