-
Notifications
You must be signed in to change notification settings - Fork 51
/
utils.py
677 lines (498 loc) · 19.2 KB
/
utils.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
import os
import platform
import shutil
import warnings
from time import time
from typing import Any, Optional, Sequence, List, Callable
from functools import wraps
from subprocess import Popen, PIPE, STDOUT
from tempfile import mkdtemp
import loky
import loky.backend.resource_tracker
import multiprocessing as mp
import autode.config
from autode.config import Config
from autode.log import logger
from autode.values import Allocation
from autode.exceptions import (
AutodeException,
NoAtomsInMolecule,
NoCalculationOutput,
NoConformers,
NoMolecularGraph,
MethodUnavailable,
CouldNotGetProperty,
)
try:
loky.backend.context.set_start_method("loky")
except RuntimeError:
logger.warning("Loky context has already been set")
# Loky uses a resource tracker server process that is always
# active, otherwise the parallelisation fails. It needs to
# be started by a dummy call that initiates loky in the current
# working dir, otherwise on Windows there will be permission errors
current_context = loky.backend.context.get_context()
if isinstance(current_context, loky.backend.context.LokyContext) or isinstance(
current_context, loky.backend.context.LokyInitMainContext
):
loky.backend.resource_tracker.ensure_running()
current_context = None
def copy_current_config(parent_config: "autode.config._ConfigClass") -> None:
"""
Copies an instance of Config into current process. Required to set the
process pool workers' Config to the same state as the parent, when
not forking the interpreter. To be only run on initializing workers
Args:
parent_config: Parent config instance that will be copied into
present process
"""
# if forking the interpreter, no need to copy vars
if platform.system() != "Windows":
if isinstance(
loky.backend.context.get_context(), mp.context.ForkContext
):
return None
for attrib in dir(parent_config):
# no need to copy class methods
if attrib.startswith("__"):
pass
elif attrib in [
"_ORCA",
"_G09",
"_G16",
"_NWChem",
"_XTB",
"_MOPAC",
"_QChem",
]:
pass
# if attribute is basic type
elif isinstance(
getattr(parent_config, attrib),
(
int,
float,
str,
bool,
list,
tuple,
dict,
type(None),
autode.values.Value,
),
):
autode.Config.__setattr__(attrib, getattr(parent_config, attrib))
elif attrib in [
"ORCA",
"G09",
"G16",
"NWChem",
"XTB",
"MOPAC",
"QChem",
]:
method_attrib_local = getattr(autode.Config, attrib)
for sub_attrib in dir(method_attrib_local):
if not sub_attrib.startswith("__"):
method_attrib_local.__setattr__(
sub_attrib,
getattr(getattr(parent_config, attrib), sub_attrib),
)
else:
raise AttributeError(
f"Unknown attribute in parent Config: {attrib}"
)
def get_total_memory() -> int:
"""Returns total amount of physical memory available in bytes"""
if platform.system() == "Windows":
from ctypes import Structure, c_int32, c_uint64, sizeof, byref, windll
# Use Win32 API : https://stackoverflow.com/questions/31546309/
class MemoryStatusEx(Structure):
_fields_ = [
("length", c_int32),
("memoryLoad", c_int32),
("totalPhys", c_uint64),
("availPhys", c_uint64),
("totalPageFile", c_uint64),
("availPageFile", c_uint64),
("totalVirtual", c_uint64),
("availVirtual", c_uint64),
("availExtendedVirtual", c_uint64),
]
def __init__(self):
self.length = sizeof(self)
win_mem = MemoryStatusEx()
if windll.kernel32.GlobalMemoryStatusEx(byref(win_mem)):
return int(win_mem.totalPhys)
else:
raise RuntimeError
else:
return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")
def check_sufficient_memory(func: Callable):
"""Decorator to check that enough memory is available for a calculation"""
@wraps(func)
def wrapped_function(*args, **kwargs):
physical_mem = None
required_mem = int(Config.n_cores) * Config.max_core
try:
physical_mem = Allocation(get_total_memory(), units="bytes")
except (ValueError, OSError, RuntimeError):
logger.warning("Cannot check physical memory")
if physical_mem is not None and physical_mem < required_mem:
raise RuntimeError(
"Cannot run function - insufficient memory. Had"
f' {physical_mem.to("GB")} GB but required '
f'{required_mem.to("GB")} GB'
)
return func(*args, **kwargs)
return wrapped_function
@check_sufficient_memory
def run_external(
params: List[str], output_filename: str, stderr_to_log: bool = True
):
"""
Standard method to run a EST calculation with subprocess writing the
output to the calculation output filename
---------------------------------------------------------------------------
Arguments:
params: e.g. [/path/to/method, input-filename]
output_filename: Filename to output stdout to
stderr_to_log: Should the stderr be added to the logged warnings?
"""
with open(output_filename, "w") as output_file:
# /path/to/method input_filename > output_filename
process = Popen(params, stdout=output_file, stderr=PIPE)
with process.stderr:
for line in iter(process.stderr.readline, b""):
if stderr_to_log:
logger.warning("STDERR: %r", line.decode())
process.wait()
return None
@check_sufficient_memory
def run_external_monitored(
params: Sequence[str],
output_filename: str,
break_word: str = "MPI_ABORT",
break_words: Optional[List[str]] = None,
):
"""
Run an external process monitoring the standard output and error for a
word that will terminate the process
---------------------------------------------------------------------------
Arguments:
params (list(str)):
output_filename (str):
break_word (str): String that if found will terminate the process
break_words (list(str) | None): List of break_word-s
"""
# Defining a set will override a single break word
break_words = [break_word] if break_words is None else break_words
def output_reader(process, out_file):
for line in process.stdout:
if any(word in line.decode("utf-8") for word in break_words):
raise ChildProcessError
print(line.decode("utf-8"), end="", file=out_file)
return None
with open(output_filename, "w") as output_file:
proc = Popen(params, stdout=PIPE, stderr=STDOUT)
try:
output_reader(proc, output_file)
except ChildProcessError:
logger.warning("External terminated")
proc.terminate()
return None
return None
def work_in(dir_ext: str):
"""Execute a function in a different directory"""
def func_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
here = os.getcwd()
dir_path = os.path.join(here, dir_ext)
if not os.path.isdir(dir_path):
logger.info(f"Creating directory to store files: {dir_path:}")
os.mkdir(dir_path)
os.chdir(dir_path)
try:
result = func(*args, **kwargs)
finally:
os.chdir(here)
if len(os.listdir(dir_path)) == 0:
logger.warning(
f"Worked in {dir_path} but made no files "
f"- deleting"
)
os.rmdir(dir_path)
return result
return wrapped_function
return func_decorator
def work_in_tmp_dir(
filenames_to_copy: Optional[Sequence[str]] = None,
kept_file_exts: Optional[Sequence[str]] = None,
use_ll_tmp: bool = False,
):
"""Execute a function in a temporary directory.
-----------------------------------------------------------------------
Arguments:
filenames_to_copy: Filenames to copy to the temp dir
kept_file_exts: Filename extensions to copy back from the temp dir
use_ll_tmp (bool): If true then use autode.config.Config.ll_tmp_dir
"""
from autode.config import Config
if filenames_to_copy is None:
filenames_to_copy = []
if kept_file_exts is None:
kept_file_exts = []
def func_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
here = os.getcwd()
base_dir = Config.ll_tmp_dir if use_ll_tmp else None
if base_dir is not None:
assert os.path.exists(base_dir)
tmpdir_path = mkdtemp(dir=base_dir)
logger.info(f"Creating tmpdir to work in: {tmpdir_path}")
if len(filenames_to_copy) > 0:
logger.info(f"Copying {filenames_to_copy}")
for filename in filenames_to_copy:
if filename.endswith("_mol.in"):
# MOPAC needs the file to be called this
shutil.move(filename, os.path.join(tmpdir_path, "mol.in"))
else:
shutil.copy(filename, tmpdir_path)
# Move directories and execute
os.chdir(tmpdir_path)
try:
logger.info("Function ...running")
result = func(*args, **kwargs)
logger.info(" ...done")
for filename in os.listdir(tmpdir_path):
if any([filename.endswith(ext) for ext in kept_file_exts]):
logger.info(f"Copying back {filename}")
shutil.copy(filename, here)
finally:
os.chdir(here)
logger.info("Removing temporary directory")
shutil.rmtree(tmpdir_path)
return result
return wrapped_function
return func_decorator
def log_time(prefix: str = "Executed in: ", units: str = "ms"):
"""A function requiring a number of atoms to run"""
if units.lower() == "s" or units.lower() == "seconds":
s_to_units = 1.0
elif units.lower() == "ms" or units.lower() == "milliseconds":
s_to_units = 1000.0
else:
raise ValueError(f"Unsupported time unit: {units}")
def func_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
start_time = time()
result = func(*args, **kwargs)
logger.info(
f"{prefix} "
f"{(time() - start_time) * s_to_units:.2f} {units}"
)
return result
return wrapped_function
return func_decorator
def requires_atoms(func: Callable):
"""A function requiring a number of atoms to run"""
@wraps(func)
def wrapped_function(*args, **kwargs):
# Species must be the first argument
assert hasattr(args[0], "n_atoms")
if args[0].n_atoms == 0:
raise NoAtomsInMolecule
return func(*args, **kwargs)
return wrapped_function
def requires_graph(func: Callable):
"""A function requiring a number of atoms to run"""
@wraps(func)
def wrapped_function(*args, **kwargs):
# Species must be the first argument
assert hasattr(args[0], "graph")
if args[0].graph is None:
raise NoMolecularGraph
return func(*args, **kwargs)
return wrapped_function
def requires_conformers(func: Callable):
"""A function requiring the species to have a list of conformers"""
@wraps(func)
def wrapped_function(*args, **kwargs):
# Species must be the first argument
assert hasattr(args[0], "n_conformers")
if args[0].n_conformers == 0:
raise NoConformers
return func(*args, **kwargs)
return wrapped_function
def requires_hl_level_methods(func: Callable):
"""A function requiring both high and low-level methods to be available"""
@wraps(func)
def wrapped_function(*args, **kwargs):
from autode.methods import get_lmethod, get_hmethod
suffix = "neither was available."
try:
_ = get_lmethod()
# Have a low-level method, so the high-level must not be available
suffix = "the high-level was not available."
_ = get_hmethod()
except MethodUnavailable:
raise MethodUnavailable(
f"Function *{func.__name__}* requires both"
f" a high and low-level method but "
f"{suffix}"
)
return func(*args, **kwargs)
return wrapped_function
def requires_output(func: Callable):
"""A function requiring an output file and output file lines"""
@wraps(func)
def wrapped_function(*args, **kwargs):
# Calculation must be the first argument
assert hasattr(args[0], "output")
if args[0].output.file_lines is None:
raise NoCalculationOutput
return func(*args, **kwargs)
return wrapped_function
def requires_output_to_exist(func):
"""Calculation method requiring the output filename to be set"""
@wraps(func)
def wrapped_function(*args, **kwargs):
calc = args[0]
if not calc.output.exists:
raise CouldNotGetProperty(
f"Could not get property from "
f"{calc.name}. Has .run() been called?"
)
return func(*args, **kwargs)
return wrapped_function
def no_exceptions(func) -> Optional[Any]:
"""Calculation method requiring the output filename to be set"""
@wraps(func)
def wrapped_function(*args, **kwargs):
try:
return func(*args, **kwargs)
except (ValueError, IndexError, TypeError, AutodeException):
return None
return wrapped_function
def timeout(seconds: float, return_value: Optional[Any] = None) -> Any:
"""
Function decorator that times-out after a number of seconds
---------------------------------------------------------------------------
Arguments:
seconds:
return_value: Value returned if the function times out
Returns:
(Any): Result of the function | return_value
"""
def handler(queue, func, args, kwargs):
queue.put(func(*args, **kwargs))
def decorator(func):
def wrapper(*args, **kwargs):
current_context = loky.backend.context.get_context()
if isinstance(current_context, mp.context.SpawnContext):
logger.warning("Timeout does not work in spawn context")
return func(*args, **kwargs)
q = current_context.Queue()
p = current_context.Process(
target=handler, args=(q, func, args, kwargs)
)
p.start()
# TODO what errors can be thrown by this?
# Only error possible seems to be some kind of OS
# error in spawning new process. Should it be handled
# at all? If multiprocessing cannot make new processes
# then something is seriously wrong and there is no need
# to continue
# TODO should I have some leeway in the timeout to
# account for the time required to create a new process?
# TODO should I pass parent's config into worker processes?
# The only function that is wrapped with timeout is the graph
# isomorphism check, but that does not use Config, so it can
# be avoided
# TODO should there be a mechanism to check if the function
# creates more subprocesses? Because then those also need
# to be terminated. The previous autode code does not check
# for this. If only graph isomorphism is done, then we know
# there is no extra subprocess, so this is fine
p.join(timeout=seconds)
if p.is_alive():
p.terminate()
p.join()
return return_value
else:
return q.get()
return wrapper
return decorator
def hashable(_method_name: str, _object: Any):
"""Multiprocessing requires hashable top-level functions to be executed,
so convert a method into a top-level function"""
return getattr(_object, _method_name)
def run_in_tmp_environment(**kwargs):
"""
Apply a set of environment variables, execute a function and reset them
"""
class EnvVar:
def __init__(self, name, val):
self.name = str(name)
self.val = os.getenv(str(name), None)
self.new_val = str(val)
env_vars = [EnvVar(k, v) for k, v in kwargs.items()]
def func_decorator(func):
@wraps(func)
def wrapped_function(*args, **_kwargs):
for env_var in env_vars:
logger.info(f"Setting the {env_var.name} to {env_var.new_val}")
os.environ[env_var.name] = env_var.new_val
result = func(*args, **_kwargs)
for env_var in env_vars:
if env_var.val is None:
# Remove from the environment
os.environ.pop(env_var.name)
else:
# otherwise set it back to the old value
os.environ[env_var.name] = env_var.val
return result
return wrapped_function
return func_decorator
def deprecated(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
warnings.warn(
"This function is deprecated and will be removed "
"in autodE v1.4.0",
DeprecationWarning,
stacklevel=2,
)
return func(*args, **kwargs)
return wrapped_function
class StringDict:
r"""
Immutable dictionary stored as a single string. For example::
'a = b c = d'
"""
_value_type = str
def __init__(self, string: str, delim: str = " = "):
self._string = string
self._delim = delim
def __getitem__(self, item: str) -> Any:
split_string = self._string.split(f"{item}{self._delim}")
try:
return self._value_type(split_string[1].split()[0])
except (ValueError, IndexError) as e:
raise IndexError(
f"Failed to extract {item} from {self._string} "
f"using delimiter *{self._delim}*"
) from e
def get(self, item: str, default: Any) -> Any:
"""Get an item or return a default"""
try:
return self[item]
except IndexError:
return default
def __str__(self):
return self._string
class NumericStringDict(StringDict):
_value_type = float