/
serial.py
521 lines (413 loc) · 17.3 KB
/
serial.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
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
from __future__ import print_function
from collections import OrderedDict
import inspect
import time
import numpy as np
from pyiron.base.master.generic import GenericMaster, get_function_from_string
from pyiron.base.generic.parameters import GenericParameters
"""
The serial master class is a metajob consisting of a dynamic list of jobs which are executed in serial mode.
"""
__author__ = "Jan Janssen"
__copyright__ = (
"Copyright 2020, Max-Planck-Institut für Eisenforschung GmbH - "
"Computational Materials Design (CM) Department"
)
__version__ = "1.0"
__maintainer__ = "Jan Janssen"
__email__ = "janssen@mpie.de"
__status__ = "production"
__date__ = "Sep 1, 2017"
class SerialMasterBase(GenericMaster):
"""
The serial master class is a metajob consisting of a dynamic list of jobs which are executed in serial mode. The job
is derived from the GenericMaster.
Args:
project (ProjectHDFio): ProjectHDFio instance which points to the HDF5 file the job is stored in
job_name (str): name of the job, which has to be unique within the project
Attributes:
.. attribute:: job_name
name of the job, which has to be unique within the project
.. attribute:: status
execution status of the job, can be one of the following [initialized, appended, created, submitted,
running, aborted, collect, suspended, refresh,
busy, finished]
.. attribute:: job_id
unique id to identify the job in the pyiron database
.. attribute:: parent_id
job id of the predecessor job - the job which was executed before the current one in the current job series
.. attribute:: master_id
job id of the master job - a meta job which groups a series of jobs, which are executed either in parallel
or in serial.
.. attribute:: child_ids
list of child job ids - only meta jobs have child jobs - jobs which list the meta job as their master
.. attribute:: project
Project instance the jobs is located in
.. attribute:: project_hdf5
ProjectHDFio instance which points to the HDF5 file the job is stored in
.. attribute:: job_info_str
short string to describe the job by it is job_name and job ID - mainly used for logging
.. attribute:: working_directory
working directory of the job is executed in - outside the HDF5 file
.. attribute:: path
path to the job as a combination of absolute file system path and path within the HDF5 file.
.. attribute:: version
Version of the hamiltonian, which is also the version of the executable unless a custom executable is used.
.. attribute:: executable
Executable used to run the job - usually the path to an external executable.
.. attribute:: library_activated
For job types which offer a Python library pyiron can use the python library instead of an external
executable.
.. attribute:: server
Server object to handle the execution environment for the job.
.. attribute:: queue_id
the ID returned from the queuing system - it is most likely not the same as the job ID.
.. attribute:: logger
logger object to monitor the external execution and internal pyiron warnings.
.. attribute:: restart_file_list
list of files which are used to restart the calculation from these files.
.. attribute:: job_type
Job type object with all the available job types: ['ExampleJob', 'SerialMaster', 'ParallelMaster',
'ScriptJob', 'ListMaster']
.. attribute:: child_names
Dictionary matching the child ID to the child job name.
.. attribute:: start_job
The first job of the series.
.. attribute:: input
The input of the start job - the first job of the series.
"""
def __init__(self, project, job_name):
self._input = GenericParameters("parameters") # e.g. convergence goal
super(SerialMasterBase, self).__init__(project, job_name=job_name)
self.__name__ = "SerialMaster"
self.__version__ = "0.3"
self._output = GenericOutput()
self._max_iterations = 100
self._start_job = None
self._run_fast = False
self._logger.debug("run_fast: {}".format(self._run_fast))
self._convergence_goal = None
self._convergence_goal_qwargs = {}
self._convergence_goal_str = None
@property
def start_job(self):
"""
Get the first job of the series.
Returns:
GenericJob: start job
"""
if self._start_job:
return self._start_job
elif len(self) > 0:
self._start_job = self[-1]
return self._start_job
else:
return None
@start_job.setter
def start_job(self, job):
"""
Set the first job of the series - that is the same like appending the job.
Args:
job (GenericJob): start job
"""
self.append(job)
@property
def ref_job(self):
return self.start_job
@ref_job.setter
def ref_job(self, job):
self.append(job)
@property
def input(self):
"""
Get the input of the start job - the first job of the series.
Returns:
GenericParameters: input of the start job
"""
if self.start_job:
return self._start_job.input
else:
return None
@input.setter
def input(self, value):
"""
Set the input of the start job - the first job of the series.
Args:
value (GenericParameters): input of the start job
"""
if self.start_job:
self._start_job.input = value
else:
raise ValueError(
"Input can only be set after a start job has been assinged."
)
def set_input_to_read_only(self):
"""
This function enforces read-only mode for the input classes, but it has to be implement in the individual
classes.
"""
self._input.read_only = True
def get_initial_child_name(self):
"""
Get name of the initial child.
Returns:
str: name of the initial child
"""
return self.project.db.get_item_by_id(self.child_ids[0])["job"]
def create_next(self, job_name=None):
"""
Create the next job in the series by duplicating the previous job.
Args:
job_name (str): name of the new job - optional - default='job_<index>'
Returns:
GenericJob: next job
"""
if len(self) == 0:
raise ValueError("No job available in job list, please append a job first.")
if len(self._job_name_lst) > len(self.child_ids):
return self.pop(-1)
ham_old = self.project.load(self.child_ids[-1], convert_to_object=True)
if ham_old.status.aborted:
ham_old.status.created = True
return ham_old
elif not ham_old.status.finished:
return None
if job_name is None:
job_name = "_".join(
ham_old.job_name.split("_")[:-1] + [str(len(self.child_ids))]
)
new_job = ham_old.restart(job_name=job_name)
new_job.server.cores = self.server.cores
return new_job
def collect_output(self):
"""
Collect the output files of the individual jobs and set the output of the last job to be the output of the
SerialMaster - so the SerialMaster contains the same output as its last child.
"""
ham_lst = [self.project_hdf5.inspect(child_id) for child_id in self.child_ids]
if (
"output" in ham_lst[0].list_groups()
and "generic" in ham_lst[0]["output"].list_groups()
):
nodes = ham_lst[0]["output/generic"].list_nodes()
with self.project_hdf5.open("output/generic") as hh:
for node in nodes:
hh[node] = np.concatenate(
[ham["output/generic/{}".format(node)] for ham in ham_lst],
axis=0,
)
def collect_logfiles(self):
"""
The collect logfiles function is required by the GenericJob class, therefore we use an empty template here.
"""
pass
def copy(self):
"""
Copy the GenericJob object which links to the job and its HDF5 file
Returns:
GenericJob: New GenericJob object pointing to the same job
"""
new_job = super(SerialMasterBase, self).copy()
new_job.start_job = self.start_job
return new_job
def from_hdf(self, hdf=None, group_name=None):
"""
Restore the SerialMaster from an HDF5 file
Args:
hdf (ProjectHDFio): HDF5 group object - optional
group_name (str): HDF5 subgroup name - optional
"""
super(SerialMasterBase, self).from_hdf(hdf=hdf, group_name=group_name)
with self.project_hdf5.open("input") as hdf5_input:
self._input.from_hdf(hdf5_input)
convergence_goal_str = hdf5_input["convergence_goal"]
if convergence_goal_str == "None":
self._convergence_goal = None
else:
self._convergence_goal_str = convergence_goal_str
self._convergence_goal = get_function_from_string(convergence_goal_str)
self._convergence_goal_qwargs = hdf5_input["convergence_goal_qwargs"]
def get_from_childs(self, path):
"""
Extract the output from all child jobs and appending it to a list
Args:
path (str): path inside the HDF5 files of the individual jobs like 'output/generic/volume'
Returns:
list: list of output from the child jobs
"""
var_lst = []
for child_id in self.child_ids:
ham = self.project.load(child_id, convert_to_object=False)
var = ham.__getitem__(path)
var_lst.append(var)
return np.array(var_lst)
def iter_jobs(self, convert_to_object=True):
"""
Iterate over the jobs within the SerialMaster
Args:
convert_to_object (bool): load the full GenericJob object (default) or just the HDF5 / JobCore object
Returns:
yield: Yield of GenericJob or JobCore
"""
for job_id in self.child_ids:
yield self.project.load(job_id, convert_to_object=convert_to_object)
def run_if_interactive(self):
pass
def _get_job_template(self):
self._logger.info("run serial master {}".format(self.job_info_str))
job = self.pop(-1)
job._master_id = self.job_id
if self.server.new_hdf:
job._hdf5 = self.project_hdf5.create_hdf(
path=self.project.open(self.job_name + "_hdf5").path,
job_name=job.job_name,
)
else:
job._hdf5 = self.project_hdf5.open(job.job_name)
self._logger.info("SerialMaster: run job {}".format(job.job_name))
return job
@staticmethod
def _run_child_job(job):
job.run()
def _run_if_master_queue(self, job):
job.run()
if job.python_execution_process:
job.python_execution_process.communicate()
self.run_if_refresh()
def _run_if_master_non_modal_child_non_modal(self, job):
job.run()
if self.master_id:
del self
def _run_if_master_modal_child_modal(self, job):
job.run()
self.run_if_refresh()
def _run_if_master_modal_child_non_modal(self, job):
job.run()
while not job.status.finished and not job.status.aborted:
job.refresh_job_status()
time.sleep(5)
self.run_if_refresh()
def run_static(self, **qwargs):
self.status.running = True
if len(self) > len(self.child_ids):
job = self._get_job_template()
self.status.suspended = True
if self.server.run_mode.queue:
self._run_if_master_queue(job)
elif self.server.run_mode.non_modal and job.server.run_mode.non_modal:
self._run_if_master_non_modal_child_non_modal(job)
elif self.server.run_mode.modal and job.server.run_mode.modal:
self._run_if_master_modal_child_modal(job)
elif self.server.run_mode.modal and job.server.run_mode.non_modal:
self._run_if_master_modal_child_non_modal(job)
else:
raise TypeError()
else:
self.status.collect = True
self.run()
def set_goal(self, convergence_goal, **qwargs):
"""
Set a convergence goal for the SerialMaster - this is necessary to stop the series.
Args:
convergence_goal (Function): the convergence goal can be any Python function, but if external packages are
used like numpy they have to be imported within the function.
**qwargs: arguments of the convergence goal function.
"""
self._convergence_goal = convergence_goal
self._convergence_goal_qwargs = qwargs
self._convergence_goal_str = inspect.getsource(convergence_goal)
if self.project_hdf5.file_exists:
self.to_hdf()
def show(self):
"""
list all jobs in the SerialMaster
Returns:
list: list of jobs ['job', <index>, <GenericJob>]
"""
return [["job", str(i), str(job)] for i, job in enumerate(self)]
def to_hdf(self, hdf=None, group_name=None):
"""
Store the SerialMaster in an HDF5 file
Args:
hdf (ProjectHDFio): HDF5 group object - optional
group_name (str): HDF5 subgroup name - optional
"""
super(SerialMasterBase, self).to_hdf(hdf=hdf, group_name=group_name)
with self.project_hdf5.open("input") as hdf5_input:
self._input.to_hdf(hdf5_input)
if self._convergence_goal is not None:
try:
hdf5_input["convergence_goal"] = inspect.getsource(
self._convergence_goal
)
except IOError:
hdf5_input["convergence_goal"] = self._convergence_goal_str
hdf5_input["convergence_goal_qwargs"] = self._convergence_goal_qwargs
else:
hdf5_input["convergence_goal"] = "None"
def write_input(self):
"""
Write the input files - for the SerialMaster this only contains convergence goal.
"""
self._input.write_file(file_name="input.inp", cwd=self.working_directory)
def __len__(self):
"""
Length of the SerialMaster equal the number of childs appended.
Returns:
int: length of the SerialMaster
"""
return len(self.child_ids + self._job_name_lst)
def __getitem__(self, item):
"""
Get/ read data from the GenericMaster
Args:
item (str, slice): path to the data or key of the data object
Returns:
dict, list, float, int: data or data object
"""
child_id_lst = self.child_ids
child_name_lst = [
self.project.db.get_item_by_id(child_id)["job"]
for child_id in self.child_ids
]
if isinstance(item, int):
total_lst = child_name_lst + self._job_name_lst
item = total_lst[item]
return self._get_item_when_str(
item=item, child_id_lst=child_id_lst, child_name_lst=child_name_lst
)
def run_if_refresh(self):
"""
Internal helper function the run if refresh function is called when the job status is 'refresh'. If the job was
suspended previously, the job is going to be started again, to be continued.
"""
conv_goal_exists = bool(self._convergence_goal)
self._logger.info("Does the convergence goal exit: {}".format(conv_goal_exists))
if not conv_goal_exists:
self.status.collect = True
self.run()
else:
subjobs_statuses = set(
[
self.project.db.get_item_by_id(child_id)["status"]
for child_id in self.child_ids
]
)
if len(subjobs_statuses) == 0 or subjobs_statuses == {"finished"}:
ham = self._convergence_goal(self, **self._convergence_goal_qwargs)
if ham is not True:
self.append(ham)
self.to_hdf()
self.run_static()
else:
self.status.collect = True
self.run()
class GenericOutput(OrderedDict):
"""
Generic Output just a place holder to store the output of the last child directly in the SerialMaster.
"""
def __init__(self):
super(GenericOutput, self).__init__()