forked from open-lasso-python/lasso-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiffcrash_run.py
1359 lines (1105 loc) · 45.5 KB
/
diffcrash_run.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 argparse
import glob
import logging
import os
import platform
import re
import shutil
import subprocess
import sys
import time
import typing
from concurrent import futures
from typing import List, Union
import psutil
from ..logging import str_error, str_info, str_running, str_success, str_warn
# pylint: disable = too-many-lines
DC_STAGE_SETUP = "SETUP"
DC_STAGE_IMPORT = "IMPORT"
DC_STAGE_MATH = "MATH"
DC_STAGE_EXPORT = "EXPORT"
DC_STAGE_MATRIX = "MATRIX"
DC_STAGE_EIGEN = "EIGEN"
DC_STAGE_MERGE = "MERGE"
DC_STAGES = [
DC_STAGE_SETUP,
DC_STAGE_IMPORT,
DC_STAGE_MATH,
DC_STAGE_EXPORT,
DC_STAGE_MATRIX,
DC_STAGE_EIGEN,
DC_STAGE_MERGE,
]
def get_application_header():
"""Prints the header of the command line tool"""
return """
==== D I F F C R A S H ====
an open-lasso-python utility script
"""
def str2bool(value) -> bool:
"""Converts some value from the cmd line to a boolean
Parameters
----------
value: `str` or `bool`
Returns
-------
bool_value: `bool`
value as boolean
"""
if isinstance(value, bool):
return value
if value.lower() in ("yes", "true", "t", "y", "1"):
return True
if value.lower() in ("no", "false", "f", "n", "0"):
return False
raise argparse.ArgumentTypeError("Boolean value expected.")
def parse_diffcrash_args():
"""Parse the arguments from the command line
Returns
-------
args : `argparse.Namespace`
parsed arguments
"""
# print title
print(get_application_header())
parser = argparse.ArgumentParser(
description="Python utility script for Diffcrash written by OPEN-LASSO."
)
parser.add_argument(
"--reference-run", type=str, required=True, help="filepath of the reference run."
)
parser.add_argument(
"--exclude-runs", type=str, nargs="*", default=[], help="Runs to exclude from the analysis."
)
parser.add_argument(
"--crash-code",
type=str,
required=True,
help="Which crash code is used ('dyna', 'pam' or 'radioss').",
)
parser.add_argument(
"--start-stage",
type=str,
nargs="?",
default=DC_STAGES[0],
help=f"At which specific stage to start the analysis ({', '.join(DC_STAGES)}).",
)
parser.add_argument(
"--end-stage",
type=str,
nargs="?",
default=DC_STAGES[-1],
help=f"At which specific stage to stop the analysis ({', '.join(DC_STAGES)}).",
)
parser.add_argument(
"--diffcrash-home",
type=str,
default=os.environ["DIFFCRASHHOME"] if "DIFFCRASHHOME" in os.environ else "",
nargs="?",
required=False,
help=(
"Home directory where Diffcrash is installed."
" Uses environment variable 'DIFFCRASHHOME' if unspecified."
),
)
parser.add_argument(
"--use-id-mapping",
type=str2bool,
nargs="?",
const=True,
default=False,
help="Whether to use id-based mapping (default is nearest neighbour).",
)
parser.add_argument(
"--project-dir",
type=str,
nargs="?",
default="project",
help="Project dir to use for femzip.",
)
parser.add_argument(
"--config-file", type=str, nargs="?", default="", help="Path to the config file."
)
parser.add_argument(
"--parameter-file", type=str, nargs="?", default="", help="Path to the parameter file."
)
parser.add_argument(
"--n-processes",
type=int,
nargs="?",
default=max(1, psutil.cpu_count() - 1),
help="Number of processes to use (default: max-1).",
)
parser.add_argument(
"simulation_runs",
type=str,
nargs="*",
help="Simulation runs or patterns used to search for simulation runs.",
)
if len(sys.argv) < 2:
parser.print_help()
sys.exit(0)
return parser.parse_args(sys.argv[1:])
def run_subprocess(args):
"""Run a subprocess with the specified arguments
Parameters:
-----------
args : `list` of `str`
Returns
-------
rc : `int`
process return code
Notes
-----
Suppresses stderr.
"""
return subprocess.Popen(args, stderr=subprocess.DEVNULL).wait()
class DiffcrashRun:
"""Class for handling the settings of a diffcrash run"""
# pylint: disable = too-many-instance-attributes
# pylint: disable = too-many-arguments
def __init__(
self,
project_dir: str,
crash_code: str,
reference_run: str,
simulation_runs: typing.Sequence[str],
exclude_runs: typing.Sequence[str],
diffcrash_home: str = "",
use_id_mapping: bool = False,
config_file: str = None,
parameter_file: str = None,
n_processes: int = 1,
logfile_dir: str = None,
):
"""Object handling a diffcrash run
Parameters
----------
project_dir : `str`
directory to put all buffer files etc., in
crash_code : `str`
crash code to use.
reference_run : `str`
filepath to the reference run
simulation_runs: `list` of `str`
patterns used to search for simulation runs
diffcrash_home : `str`
home directory of diffcrash installation. Uses environment
variable DIFFCRASHHOME if not set.
use_id_mapping : `bool`
whether to use id mapping instead of nearest neighbor mapping
config_file : `str`
filepath to a config file
parameter_file : `str`
filepath to the parameter file
n_processes : `int`
number of processes to spawn for worker pool
logfile_dir : `str`
directory to put logfiles in
"""
# settings
self._msg_option = "{:16s}: {}"
self._log_formatter = logging.Formatter("%(levelname)s:%(asctime)s %(message)s")
# logdir
if logfile_dir is not None:
self.logfile_dir = logfile_dir
else:
self.logfile_dir = os.path.join(project_dir, "Log")
self.logfile_filepath = os.path.join(self.logfile_dir, "DiffcrashRun.log")
# logger
self.logger = self._setup_logger()
# make some space in the log
self.logger.info(get_application_header())
# diffcrash home
self.diffcrash_home = self._parse_diffcrash_home(diffcrash_home)
self.diffcrash_home = os.path.join(self.diffcrash_home, "bin")
self.diffcrash_lib = os.path.join(os.path.dirname(self.diffcrash_home), "lib")
if platform.system() == "Linux":
os.environ["PATH"] = (
os.environ["PATH"] + ":" + self.diffcrash_home + ":" + self.diffcrash_lib
)
if platform.system() == "Windows":
os.environ["PATH"] = (
os.environ["PATH"] + ";" + self.diffcrash_home + ";" + self.diffcrash_lib
)
# project dir
self.project_dir = self._parse_project_dir(project_dir)
# crashcode
self.crash_code = self._parse_crash_code(crash_code)
# reference run
self.reference_run = self._parse_reference_run(reference_run)
# mapping
self.use_id_mapping = self._parse_use_id_mapping(use_id_mapping)
# exlude runs
self.exclude_runs = exclude_runs
# simulation runs
self.simulation_runs = self._parse_simulation_runs(
simulation_runs, self.reference_run, self.exclude_runs
)
# config file
self.config_file = self._parse_config_file(config_file)
# parameter file
self.parameter_file = self._parse_parameter_file(parameter_file)
# n processes
self.n_processes = self._parse_n_processes(n_processes)
def _setup_logger(self) -> logging.Logger:
# better safe than sorry
os.makedirs(self.logfile_dir, exist_ok=True)
# create console log channel
# streamHandler = logging.StreamHandler(sys.stdout)
# streamHandler.setLevel(logging.INFO)
# streamHandler.setFormatter(self._log_formatter)
# create file log channel
file_handler = logging.FileHandler(self.logfile_filepath)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(self._log_formatter)
# create logger
logger = logging.getLogger("DiffcrashRun")
logger.setLevel(logging.INFO)
# logger.addHandler(streamHandler)
logger.addHandler(file_handler)
return logger
def _parse_diffcrash_home(self, diffcrash_home) -> str:
diffcrash_home_ok = len(diffcrash_home) != 0
msg = self._msg_option.format("diffcrash-home", diffcrash_home)
print(str_info(msg))
self.logger.info(msg)
if not diffcrash_home_ok:
err_msg = (
"Specify the path to the Diffcrash installation either "
+ "with the environment variable 'DIFFCRASHHOME' or the option --diffcrash-home."
)
self.logger.error(err_msg)
raise RuntimeError(str_error(err_msg))
return diffcrash_home
def _parse_crash_code(self, crash_code) -> str:
# these guys are allowed
valid_crash_codes = ["dyna", "radioss", "pam"]
# do the thing
crash_code_ok = crash_code in valid_crash_codes
print(str_info(self._msg_option.format("crash-code", crash_code)))
self.logger.info(self._msg_option.format("crash-code", crash_code))
if not crash_code_ok:
err_msg = (
f"Invalid crash code '{crash_code}'. "
f"Please use one of: {str(valid_crash_codes)}"
)
self.logger.error(err_msg)
raise RuntimeError(str_error(err_msg))
return crash_code
def _parse_reference_run(self, reference_run) -> str:
reference_run_ok = os.path.isfile(reference_run)
msg = self._msg_option.format("reference-run", reference_run)
print(str_info(msg))
self.logger.info(msg)
if not reference_run_ok:
err_msg = f"Filepath '{reference_run}' is not a file."
self.logger.error(err_msg)
raise RuntimeError(str_error(err_msg))
return reference_run
def _parse_use_id_mapping(self, use_id_mapping) -> bool:
msg = self._msg_option.format("use-id-mapping", use_id_mapping)
print(str_info(msg))
self.logger.info(msg)
return use_id_mapping
def _parse_project_dir(self, project_dir):
project_dir = os.path.abspath(project_dir)
msg = self._msg_option.format("project-dir", project_dir)
print(str_info(msg))
self.logger.info(msg)
return project_dir
def _parse_simulation_runs(
self,
simulation_run_patterns: typing.Sequence[str],
reference_run: str,
exclude_runs: typing.Sequence[str],
):
# search all denoted runs
simulation_runs = []
for pattern in simulation_run_patterns:
simulation_runs += glob.glob(pattern)
simulation_runs = [filepath for filepath in simulation_runs if os.path.isfile(filepath)]
# search all excluded runs
runs_to_exclude = []
for pattern in exclude_runs:
runs_to_exclude += glob.glob(pattern)
runs_to_exclude = [filepath for filepath in runs_to_exclude if os.path.isfile(filepath)]
n_runs_before_filtering = len(simulation_runs)
simulation_runs = [
filepath for filepath in simulation_runs if filepath not in runs_to_exclude
]
n_runs_after_filtering = len(simulation_runs)
# remove the reference run
if reference_run in simulation_runs:
simulation_runs.remove(reference_run)
# sort it because we can!
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
return [atoi(c) for c in re.split(r"(\d+)", text)]
simulation_runs = sorted(simulation_runs, key=natural_keys)
# check
simulation_runs_ok = len(simulation_runs) != 0
msg = self._msg_option.format("# simul.-files", len(simulation_runs))
print(str_info(msg))
self.logger.info(msg)
msg = self._msg_option.format(
"# excluded files", (n_runs_before_filtering - n_runs_after_filtering)
)
print(str_info(msg))
self.logger.info(msg)
if not simulation_runs_ok:
err_msg = (
"No simulation files could be found with the specified patterns. "
"Check the argument 'simulation_runs'."
)
self.logger.error(err_msg)
raise RuntimeError(str_error(err_msg))
return simulation_runs
def _parse_config_file(self, config_file) -> Union[str, None]:
_msg_config_file = ""
if len(config_file) > 0 and not os.path.isfile(config_file):
config_file = None
_msg_config_file = f"Can not find config file '{config_file}'"
# missing config file
else:
config_file = None
_msg_config_file = (
"Config file missing. "
"Consider specifying the path with the option '--config-file'."
)
msg = self._msg_option.format("config-file", config_file)
print(str_info(msg))
self.logger.info(msg)
if _msg_config_file:
print(str_warn(_msg_config_file))
self.logger.warning(_msg_config_file)
return config_file
def _parse_parameter_file(self, parameter_file) -> Union[None, str]:
_msg_parameter_file = ""
if len(parameter_file) > 0 and not os.path.isfile(parameter_file):
parameter_file = None
_msg_parameter_file = f"Can not find parameter file '{parameter_file}'"
# missing parameter file
else:
parameter_file = None
_msg_parameter_file = (
"Parameter file missing. Consider specifying the "
"path with the option '--parameter-file'."
)
msg = self._msg_option.format("parameter-file", parameter_file)
print(str_info(msg))
self.logger.info(msg)
if _msg_parameter_file:
print(str_warn(_msg_parameter_file))
self.logger.warning(_msg_parameter_file)
return parameter_file
def _parse_n_processes(self, n_processes) -> int:
print(str_info(self._msg_option.format("n-processes", n_processes)))
if n_processes <= 0:
err_msg = f"n-processes is '{n_processes}' but must be at least 1."
self.logger.error(err_msg)
raise ValueError(str_error(err_msg))
return n_processes
def create_project_dirs(self):
"""Creates all project relevant directores
Notes
-----
Created dirs:
- logfile_dir
- project_dir
"""
os.makedirs(self.project_dir, exist_ok=True)
os.makedirs(self.logfile_dir, exist_ok=True)
def run_setup(self, pool: futures.ThreadPoolExecutor):
"""Run diffcrash setup
Parameters
----------
pool : `concurrent.futures.ThreadPoolExecutor`
multiprocessing pool
"""
# SETUP
msg = "Running Setup ... "
print(str_running(msg) + "\r", end="", flush="")
self.logger.info(msg)
args = []
if self.config_file is None and self.parameter_file is None:
args = [
os.path.join(self.diffcrash_home, "DFC_Setup_" + self.crash_code + "_fem"),
self.reference_run,
self.project_dir,
]
elif self.config_file is not None and self.parameter_file is None:
args = [
os.path.join(self.diffcrash_home, "DFC_Setup_" + self.crash_code + "_fem"),
self.reference_run,
self.project_dir,
"-C",
self.config_file,
]
elif self.config_file is None and self.parameter_file is not None:
if ".fz" in self.reference_run:
args = [
os.path.join(self.diffcrash_home, "DFC_Setup_" + self.crash_code + "_fem"),
self.reference_run,
self.project_dir,
"-P",
self.parameter_file,
]
else:
args = [
os.path.join(self.diffcrash_home, "DFC_Setup_" + self.crash_code),
self.reference_run,
self.project_dir,
"-P",
self.parameter_file,
]
elif self.config_file is not None and self.parameter_file is not None:
if ".fz" in self.reference_run:
args = [
os.path.join(self.diffcrash_home, "DFC_Setup_" + self.crash_code + "_fem"),
self.reference_run,
self.project_dir,
"-C",
self.config_file,
"-P",
self.parameter_file,
]
else:
args = [
os.path.join(self.diffcrash_home, "DFC_Setup_" + self.crash_code),
self.reference_run,
self.project_dir,
"-C",
self.config_file,
"-P",
self.parameter_file,
]
start_time = time.time()
# submit task
return_code_future = pool.submit(run_subprocess, args)
return_code = return_code_future.result()
# check return code
if return_code != 0:
err_msg = f"Running Setup ... done in {time.time() - start_time:.2f}s"
print(str_error(err_msg))
self.logger.error(err_msg)
err_msg = "Process somehow failed."
self.logger.error(err_msg)
raise RuntimeError(str_error(err_msg))
# check log
messages = self.check_if_logfiles_show_success("DFC_Setup.log")
if messages:
err_msg = f"Running Setup ... done in {time.time() - start_time:.2f}s"
print(str_error(err_msg))
self.logger.error(err_msg)
# print failed logs
for msg in messages:
print(str_error(msg))
self.logger.error(msg)
err_msg = "Setup failed."
self.logger.error(err_msg)
raise RuntimeError(str_error(err_msg))
# print success
err_msg = f"Running Setup ... done in {time.time() - start_time:.2f}s"
print(str_success(msg))
self.logger.info(msg)
def run_import(self, pool: futures.ThreadPoolExecutor):
"""Run diffcrash import of runs
Parameters
----------
pool : `concurrent.futures.ThreadPoolExecutor`
multiprocessing pool
"""
# pylint: disable = too-many-locals, too-many-branches, too-many-statements
# list of arguments to run in the command line
import_arguments = []
# id 1 is the reference run
# id 2 and higher are the imported runs
counter_offset = 2
# assemble arguments for running the import
# entry 0 is the reference run, thus we start at 1
# pylint: disable = consider-using-enumerate
for i_filepath in range(len(self.simulation_runs)):
# parameter file missing
if self.parameter_file is None:
if self.use_id_mapping:
args = [
os.path.join(self.diffcrash_home, "DFC_Import_" + self.crash_code + "_fem"),
"-id",
self.simulation_runs[i_filepath],
self.project_dir,
str(i_filepath + counter_offset),
]
else:
args = [
os.path.join(self.diffcrash_home, "DFC_Import_" + self.crash_code + "_fem"),
self.simulation_runs[i_filepath],
self.project_dir,
str(i_filepath + counter_offset),
]
# indeed there is a parameter file
else:
if self.use_id_mapping:
args = [
os.path.join(self.diffcrash_home, "DFC_Import_" + self.crash_code),
"-ID",
self.simulation_runs[i_filepath],
self.project_dir,
str(i_filepath + counter_offset),
]
else:
args = [
os.path.join(self.diffcrash_home, "DFC_Import_" + self.crash_code),
self.simulation_runs[i_filepath],
self.project_dir,
str(i_filepath + counter_offset),
]
# append args to list
import_arguments.append(args)
# do the thing
msg = "Running Imports ...\r"
print(str_running(msg), end="", flush=True)
self.logger.info(msg)
start_time = time.time()
return_code_futures = [pool.submit(run_subprocess, args) for args in import_arguments]
# wait for imports to finish (with a progressbar)
n_imports_finished = sum(
return_code_future.done() for return_code_future in return_code_futures
)
while n_imports_finished != len(return_code_futures):
# check again
n_new_imports_finished = sum(
return_code_future.done() for return_code_future in return_code_futures
)
# print
percentage = n_new_imports_finished / len(return_code_futures) * 100
if n_imports_finished != n_new_imports_finished:
# pylint: disable = consider-using-f-string
msg = "Running Imports ... [{0}/{1}] - {2:3.2f}%\r".format(
n_new_imports_finished, len(return_code_futures), percentage
)
print(str_running(msg), end="", flush=True)
self.logger.info(msg)
n_imports_finished = n_new_imports_finished
# wait a little bit
time.sleep(0.25)
return_codes = [return_code_future.result() for return_code_future in return_code_futures]
# print failure
if any(return_code != 0 for return_code in return_codes):
n_failed_runs = 0
for i_run, return_code in enumerate(return_codes):
if return_code != 0:
_err_msg = str_error(
f"Run {i_run} failed to import with error code '{return_code}'."
)
print(str_error(_err_msg))
self.logger.error(_err_msg)
n_failed_runs += 1
err_msg = f"Running Imports ... done in {time.time() - start_time:.2f}s "
print(str_error(err_msg))
self.logger.error(err_msg)
err_msg = f"Import of {n_failed_runs} runs failed."
self.logger.error(err_msg)
raise RuntimeError(str_error(err_msg))
# check log files
messages = self.check_if_logfiles_show_success("DFC_Import_*.log")
if messages:
# print failure
msg = f"Running Imports ... done in {time.time() - start_time:.2f}s "
print(str_error(msg))
self.logger.info(msg)
# print failed logs
for msg in messages:
self.logger.error(msg)
print(str_error(msg))
err_msg = (
f"At least one import failed. Please check the log files in '{self.logfile_dir}'."
)
self.logger.error(err_msg)
raise RuntimeError(str_error(err_msg))
# print success
print(str_success(f"Running Imports ... done in {time.time() - start_time:.2f}s "))
def run_math(self, pool: futures.ThreadPoolExecutor):
"""Run diffcrash math
Parameters
----------
pool : `concurrent.futures.ThreadPoolExecutor`
multiprocessing pool
"""
msg = "Running Math ... \r"
print(str_running(msg), end="", flush=True)
self.logger.info(msg)
start_time = time.time()
return_code_future = pool.submit(
run_subprocess,
[os.path.join(self.diffcrash_home, "DFC_Math_" + self.crash_code), self.project_dir],
)
return_code = return_code_future.result()
# check return code
if return_code != 0:
msg = f"Running Math ... done in {time.time() - start_time:.2f}s "
print(str_error(msg))
self.logger.error(msg)
err_msg = f"Caught a nonzero return code '{return_code}'"
self.logger.error(err_msg)
raise RuntimeError(str_error(err_msg))
# check logs
messages = self.check_if_logfiles_show_success("DFC_MATH*.log")
if messages:
# print failure
msg = f"Running Math ... done in {time.time() - start_time:.2f}s "
print(str_error(msg))
self.logger.error(msg)
# print failed logs
for msg in messages:
print(str_error(msg))
self.logger.error(msg)
err_msg = (
"Logfile does indicate a failure. "
f"Please check the log files in '{self.logfile_dir}'."
)
self.logger.error(err_msg)
raise RuntimeError(str_error(err_msg))
# print success
msg = f"Running Math ... done in {time.time() - start_time:.2f}s "
print(str_success(msg))
self.logger.info(msg)
def run_export(self, pool: futures.ThreadPoolExecutor):
"""Run diffcrash export
Parameters
----------
pool : `concurrent.futures.ThreadPoolExecutor`
multiprocessing pool
"""
msg = "Running Export ... "
print(str_running(msg) + "\r", end="", flush=True)
self.logger.info(msg)
if self.config_file is None:
export_item_list = []
# check for pdmx
pdmx_filepath_list = glob.glob(os.path.join(self.project_dir, "*_pdmx"))
if pdmx_filepath_list:
export_item_list.append(os.path.basename(pdmx_filepath_list[0]))
# check for pdij
pdij_filepath_list = glob.glob(os.path.join(self.project_dir, "*_pdij"))
if pdij_filepath_list:
export_item_list.append(os.path.basename(pdij_filepath_list[0]))
else:
export_item_list = self.read_config_file(self.config_file)
# remove previous existing exports
for export_item in export_item_list:
export_item_filepath = os.path.join(self.project_dir, export_item + ".d3plot.fz")
if os.path.isfile(export_item_filepath):
os.remove(export_item_filepath)
# do the thing
start_time = time.time()
return_code_futures = [
pool.submit(
run_subprocess,
[
os.path.join(self.diffcrash_home, "DFC_Export_" + self.crash_code),
self.project_dir,
export_item,
],
)
for export_item in export_item_list
]
return_codes = [result_future.result() for result_future in return_code_futures]
# check return code
if any(rc != 0 for rc in return_codes):
msg = f"Running Export ... done in {time.time() - start_time:.2f}s "
print(str_error(msg))
self.logger.error(msg)
for i_export, export_return_code in enumerate(return_codes):
if export_return_code != 0:
msg = (
f"Return code of export '{export_item_list[i_export]}' "
f"was nonzero: '{export_return_code}'"
)
self.logger.error(msg)
print(str_error(msg))
msg = "At least one export process failed."
self.logger.error(msg)
raise RuntimeError(str_error(msg))
# check logs
messages = self.check_if_logfiles_show_success("DFC_Export_*")
if messages:
# print failure
msg = f"Running Export ... done in {time.time() - start_time:.2f}s "
print(str_error(msg))
self.logger.error(msg)
# print logs
for msg in messages:
print(str_error(msg))
self.logger.error(msg)
msg = (
"At least one export failed. "
f"Please check the log files in '{self.logfile_dir}'."
)
self.logger.error(msg)
raise RuntimeError(str_error(msg))
# print success
msg = f"Running Export ... done in {time.time() - start_time:.2f}s "
print(str_success(msg))
self.logger.info(msg)
def run_matrix(self, pool: futures.ThreadPoolExecutor):
"""Run diffcrash matrix
Parameters
----------
pool : `concurrent.futures.ThreadPoolExecutor`
multiprocessing pool
"""
msg = "Running Matrix ... "
print(str_running(msg) + "\r", end="", flush=True)
self.logger.info(msg)
start_time = time.time()
# create the input file for the process
matrix_inputfile = self._create_matrix_input_file(self.project_dir)
# run the thing
return_code_future = pool.submit(
run_subprocess,
[
os.path.join(self.diffcrash_home, "DFC_Matrix_" + self.crash_code),
self.project_dir,
matrix_inputfile,
],
)
# please hold the line ...
return_code = return_code_future.result()
# check return code
if return_code != 0:
# print failure
msg = f"Running Matrix ... done in {time.time() - start_time:.2f}s "
print(str_error(msg))
self.logger.error(msg)
msg = "The DFC_Matrix process failed somehow."
self.logger.error(msg)
raise RuntimeError(str_error(msg))
# check log file
messages = self.check_if_logfiles_show_success("DFC_Matrix_*")
if messages:
# print failure
msg = f"Running Matrix ... done in {time.time() - start_time:.2f}s "
print(str_error(msg))
self.logger.info(msg)
# print why
for msg in messages:
print(str_error(msg))
self.logger.error(msg)
msg = f"DFC_Matrix failed. Please check the log files in '{self.logfile_dir}'."
self.logger.error(msg)
raise RuntimeError(str_error(msg))
# print success
msg = f"Running Matrix ... done in {time.time() - start_time:.2f}s "
print(str_success(msg))
self.logger.info(msg)
def run_eigen(self, pool: futures.ThreadPoolExecutor):
"""Run diffcrash eigen
Parameters
----------
pool : `concurrent.futures.ThreadPoolExecutor`
multiprocessing pool
"""
msg = "Running Eigen ... "
print(str_running(msg) + "\r", end="", flush=True)
self.logger.info(msg)
# create input file for process
eigen_inputfile = self._create_eigen_input_file(self.project_dir)