-
Notifications
You must be signed in to change notification settings - Fork 1
/
simulator.py
556 lines (460 loc) · 18.1 KB
/
simulator.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
"""Simulator class for managing simulations of showers and array of telescopes."""
import logging
import re
from collections import defaultdict
from pathlib import Path
import numpy as np
import simtools.utils.general as gen
from simtools.corsika.corsika_config import CorsikaConfig
from simtools.io_operations import io_handler
from simtools.job_execution.job_manager import JobManager
from simtools.model.array_model import ArrayModel
from simtools.runners.corsika_runner import CorsikaRunner
from simtools.runners.corsika_simtel_runner import CorsikaSimtelRunner
from simtools.simtel.simulator_array import SimulatorArray
__all__ = [
"Simulator",
"InvalidRunsToSimulateError",
]
class InvalidRunsToSimulateError(Exception):
"""Exception for invalid runs to simulate."""
class Simulator:
"""
Simulator is managing the simulation of showers and of the array of telescopes.
It interfaces with simulation software packages (e.g., CORSIKA or sim_telarray).
The configuration is set as a dict corresponding to the command line configuration groups
(especially simulation_software, simulation_model, simulation_parameters).
Parameters
----------
args_dict : dict
Configuration dictionary
(includes simulation_software, simulation_model, simulation_parameters groups).
label: str
Instance label.
extra_commands: str or list of str
Extra commands to be added to the run script before the run command.
mongo_db_config: dict
MongoDB configuration.
"""
def __init__(
self,
args_dict,
label=None,
extra_commands=None,
mongo_db_config=None,
):
"""Initialize Simulator class."""
self._logger = logging.getLogger(__name__)
self.args_dict = args_dict
self.simulation_software = self.args_dict["simulation_software"]
self._logger.debug(f"Init Simulator {self.simulation_software}")
self.label = label
self.io_handler = io_handler.IOHandler()
self.runs = self._initialize_run_list()
self._results = defaultdict(list)
self._test = self.args_dict.get("test", False)
self._submit_engine = self.args_dict.get("submit_engine", "local")
self._submit_options = self.args_dict.get("submit_options", None)
self._extra_commands = extra_commands
self.array_model = self._initialize_array_model(mongo_db_config)
self._simulation_runner = self._initialize_simulation_runner(mongo_db_config)
@property
def simulation_software(self):
"""The attribute simulation_software."""
return self._simulation_software
@simulation_software.setter
def simulation_software(self, simulation_software):
"""
Set and test simulation_software type.
Parameters
----------
simulation_software: choices: [simtel, corsika, corsika_simtel]
implemented are sim_telarray and CORSIKA or corsika_simtel
(running CORSIKA and piping it directly to sim_telarray)
Raises
------
gen.InvalidConfigDataError
"""
if simulation_software not in ["simtel", "corsika", "corsika_simtel"]:
self._logger.error(f"Invalid simulation software: {simulation_software}")
raise gen.InvalidConfigDataError
self._simulation_software = simulation_software.lower()
def _initialize_array_model(self, mongo_db_config):
"""
Initialize array simulation model.
Parameters
----------
mongo_db_config: dict
Database configuration.
Returns
-------
ArrayModel
ArrayModel object.
"""
return ArrayModel(
label=self.label,
site=self.args_dict.get("site"),
layout_name=self.args_dict.get("array_layout_name"),
mongo_db_config=mongo_db_config,
model_version=self.args_dict.get("model_version", None),
)
def _initialize_run_list(self):
"""
Initialize run list using the configuration values 'run_number_start' and 'number_of_runs'.
Returns
-------
list
List of run numbers.
Raises
------
KeyError
If 'run_number_start' or 'number_of_runs' are not found in the configuration.
"""
try:
return self._validate_run_list_and_range(
run_list=None,
run_range=[
self.args_dict["run_number_start"],
self.args_dict["run_number_start"] + self.args_dict["number_of_runs"],
],
)
except KeyError as exc:
self._logger.error(
"Error in initializing run list (missing 'run_number_start' or 'number_of_runs')"
)
raise exc
def _validate_run_list_and_range(self, run_list, run_range):
"""
Prepare list of run numbers from a list or from a range.
If both arguments are given, they will be merged into a single list.
Attributes
----------
run_list: list
list of runs (integers)
run_range:list
min and max of range of runs to be simulated (two list entries)
Returns
-------
list
list of unique run numbers (integers)
"""
if run_list is None and run_range is None:
self._logger.debug("Nothing to validate - run_list and run_range not given.")
return None
validated_runs = []
if run_list is not None:
if not isinstance(run_list, list):
run_list = [run_list]
if not all(isinstance(r, int) for r in run_list):
msg = "run_list must contain only integers."
self._logger.error(msg)
raise InvalidRunsToSimulateError
validated_runs = list(run_list)
if run_range is not None:
if not all(isinstance(r, int) for r in run_range) or len(run_range) != 2:
msg = "run_range must contain two integers only."
self._logger.error(msg)
raise InvalidRunsToSimulateError
run_range = np.arange(run_range[0], run_range[1])
self._logger.debug(f"run_range: {run_range}")
validated_runs.extend(list(run_range))
validated_runs_unique = sorted(set(validated_runs))
self._logger.info(f"run_list: {validated_runs_unique}")
return list(validated_runs_unique)
def _initialize_simulation_runner(self, db_config):
"""
Initialize corsika configuration and simulation runners.
Parameters
----------
db_config: dict
Database configuration.
Returns
-------
CorsikaRunner or SimulatorArray or CorsikaSimtelRunner
Simulation runner object.
"""
corsika_config = CorsikaConfig(
array_model=self.array_model,
label=self.label,
args_dict=self.args_dict,
db_config=db_config,
)
runner_class = {
"corsika": CorsikaRunner,
"simtel": SimulatorArray,
"corsika_simtel": CorsikaSimtelRunner,
}.get(self.simulation_software)
return runner_class(
label=self.label,
corsika_config=corsika_config,
simtel_path=self.args_dict.get("simtel_path"),
keep_seeds=False,
use_multipipe=runner_class is CorsikaSimtelRunner,
)
def _fill_results_without_run(self, input_file_list):
"""
Fill results dict without calling submit (e.g., for testing).
Parameters
----------
input_file_list: str or list of str
Single file or list of files of shower simulations.
"""
input_file_list = self._enforce_list_type(input_file_list)
for file in input_file_list:
run = self._guess_run_from_file(file)
self._fill_results(file, run)
if run not in self.runs:
self.runs.append(run)
def simulate(self, input_file_list=None):
"""
Submit a run script as a job.
Parameters
----------
input_file_list: str or list of str
Single file or list of files of shower simulations.
"""
self._logger.info(f"Submission command: {self._submit_engine}")
runs_and_files_to_submit = self._get_runs_and_files_to_submit(
input_file_list=input_file_list
)
self._logger.info(
f"Starting submission for {len(runs_and_files_to_submit)} "
f"run{'s' if len(runs_and_files_to_submit) > 1 else ''}"
)
for run_number, input_file in runs_and_files_to_submit.items():
run_script = self._simulation_runner.prepare_run_script(
run_number=run_number, input_file=input_file, extra_commands=self._extra_commands
)
job_manager = JobManager(
submit_engine=self._submit_engine,
submit_options=self._submit_options,
test=self._test,
)
job_manager.submit(
run_script=run_script,
run_out_file=self._simulation_runner.get_file_name(
file_type="sub_log", run_number=run_number
),
log_file=self._simulation_runner.get_file_name(
file_type=("log"), run_number=run_number
),
)
self._fill_results(input_file, run_number)
def _get_runs_and_files_to_submit(self, input_file_list=None):
"""
Return a dictionary with run numbers and simulation files.
The latter are expected to be given for the simtel simulator.
Parameters
----------
input_file_list: str or list of str
Single file or list of files of shower simulations.
Returns
-------
runs_and_files: dict
dictionary with run number as key and (if available) simulation
file name as value
Raises
------
ValueError
If no runs are to be submitted.
"""
_runs_and_files = {}
self._logger.debug(f"Getting runs and files to submit ({input_file_list})")
if self.simulation_software == "simtel":
input_file_list = self._enforce_list_type(input_file_list)
_runs_and_files = {self._guess_run_from_file(file): file for file in input_file_list}
elif self.simulation_software in ["corsika", "corsika_simtel"]:
_runs_and_files = {run: None for run in self._get_runs_to_simulate()}
if len(_runs_and_files) == 0:
raise ValueError("No runs to submit.")
return _runs_and_files
@staticmethod
def _enforce_list_type(input_file_list):
"""
Enforce the input list to be a list.
Parameters
----------
input_file_list: str or list of str
Single file or list of files of shower simulations.
Returns
-------
list
List of input files.
"""
if not input_file_list:
return []
return input_file_list if isinstance(input_file_list, list) else [input_file_list]
def _guess_run_from_file(self, file):
"""
Extract the run number from the given file name.
Input file names can follow any pattern with the
string 'run' followed by the run number.
Parameters
----------
file: Path
Simulation file name
Returns
-------
int
The extracted run number. If extraction fails, returns 1 and logs a warning.
"""
file_name = str(Path(file).name)
try:
run_str = re.search(r"run\d*", file_name).group()
return int(run_str[3:])
except (ValueError, AttributeError):
self._logger.warning(f"Run number could not be guessed from {file_name} using run = 1")
return 1
def _fill_results(self, file, run_number):
"""
Fill the results dict with input, output, hist, and log files.
Parameters
----------
file: str
input file name
run_number: int
run number
"""
self._results["output"].append(
str(self._simulation_runner.get_file_name(file_type="output", run_number=run_number))
)
self._results["sub_out"].append(
str(
self._simulation_runner.get_file_name(
file_type="sub_log", run_number=run_number, mode="out"
)
)
)
if self.simulation_software in ["simtel", "corsika_simtel"]:
self._results["log"].append(
str(
self._simulation_runner.get_file_name(
simulation_software="simtel", file_type="log", run_number=run_number
)
)
)
self._results["input"].append(str(file))
self._results["hist"].append(
str(
self._simulation_runner.get_file_name(
simulation_software="simtel", file_type="histogram", run_number=run_number
)
)
)
else:
self._results["corsika_autoinputs_log"].append(
str(
self._simulation_runner.get_file_name(
simulation_software="corsika", file_type="log", run_number=run_number
)
)
)
self._results["input"].append(None)
self._results["hist"].append(None)
self._results["log"].append(None)
def get_file_list(self, file_type="output"):
"""
Get list of files generated by simulations.
Options are "input", "output", "hist", "log".
Not all file types are available for all simulation types.
Returns an empty list for an unknown file type.
Parameters
----------
file_type : str
File type to be listed.
Returns
-------
list
List with the full path of all output files.
"""
self._logger.info(f"Getting list of {file_type} files")
return self._results[file_type]
def print_list_of_files(self, file_type="output"):
"""
Print list of output files generated by simulations.
Options are "input", "output", "hist", "log".
Parameters
----------
file_type : str
File type to be listed.
"""
self._logger.info(f"Printing list of {file_type} files")
for file in self._results[file_type]:
print(file)
def _make_resources_report(self, input_file_list):
"""
Prepare a simple report on computing wall clock time used in the simulations.
Parameters
----------
input_file_list: str or list of str
Single file or list of files of shower simulations.
Returns
-------
dict
Dictionary with reports on computing resources
"""
if len(self._results["sub_out"]) == 0:
if input_file_list is None:
return {"Wall time/run [sec]": np.nan}
self._fill_results_without_run(input_file_list)
runtime = []
_resources = {}
for run in self.runs:
_resources = self._simulation_runner.get_resources(run_number=run)
if _resources.get("runtime"):
runtime.append(_resources["runtime"])
mean_runtime = np.mean(runtime)
resource_summary = {}
resource_summary["Wall time/run [sec]"] = mean_runtime
if "n_events" in _resources and _resources["n_events"] > 0:
resource_summary["#events/run"] = _resources["n_events"]
resource_summary["Wall time/1000 events [sec]"] = (
mean_runtime * 1000 / _resources["n_events"]
)
return resource_summary
def resources(self, input_file_list=None):
"""
Print a simple report on computing resources used.
Includes run time per run only at this point.
Parameters
----------
input_file_list: str or list of str
Single file or list of files of shower simulations.
"""
resources = self._make_resources_report(input_file_list)
print("-----------------------------")
print(f"Computing Resources Report - {self.simulation_software} Simulations")
for key, value in resources.items():
print(f"{key} = {value:.2f}")
print("-----------------------------")
def _get_runs_to_simulate(self, run_list=None, run_range=None):
"""
Process run_list and run_range and return the validated list of runs.
Attributes
----------
run_list: list
list of runs (integers)
run_range:list
min and max of range of runs to be simulated (two list entries)
Returns
-------
list
list of unique run numbers (integers)
"""
if run_list is None and run_range is None:
return [] if self.runs is None else self.runs
return self._validate_run_list_and_range(run_list, run_range)
def save_file_lists(self):
"""Save files lists for output and log files."""
for file_type in ["output", "log", "hist"]:
file_name = self.io_handler.get_output_directory(label=self.label).joinpath(
f"{file_type}_files.txt"
)
file_list = self.get_file_list(file_type=file_type)
if all(element is not None for element in file_list) and len(file_list) > 0:
self._logger.info(f"Saving list of {file_type} files to {file_name}")
with open(file_name, "w", encoding="utf-8") as f:
for line in self.get_file_list(file_type=file_type):
f.write(f"{line}\n")
else:
self._logger.debug(f"No files to save for {file_type} files.")