-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathutil.py
457 lines (389 loc) · 14.1 KB
/
util.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
# 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.
"""
Helper functions for the JobCore and GenericJob objects
"""
import os
import posixpath
import psutil
import tarfile
import stat
import shutil
from typing import Optional, Union
from pyiron_base.utils.instance import static_isinstance
from pyiron_base.utils.safetar import safe_extract
__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__ = "[email protected]"
__status__ = "production"
__date__ = "Nov 28, 2020"
def _copy_database_entry(new_job_core, job_copied_id):
"""
Copy database entry from previous job
Args:
new_job_core (GenericJob): Copy of the job object
job_copied_id (int): Job id of the copied job
"""
db_entry = new_job_core.project.db.get_item_by_id(job_copied_id)
if db_entry is not None:
db_entry["job"] = new_job_core.job_name
db_entry["subjob"] = new_job_core.project_hdf5.h5_path
db_entry["project"] = new_job_core.project_hdf5.project_path
db_entry["projectpath"] = new_job_core.project_hdf5.root_path
del db_entry["id"]
job_id = new_job_core.project.db.add_item_dict(db_entry)
new_job_core.reset_job_id(job_id=job_id)
def _copy_to_delete_existing(project_class, job_name, delete_job):
"""
Check if the job exists already in the project, if that is the case either
delete it or reload it depending on the setting of delete_job
Args:
project_class (Project): The project to copy the job to.
(Default is None, use the same project.)
job_name (str): The new name to assign the duplicate job. Required if the project is `None` or the same
project as the copied job. (Default is None, try to keep the same name.)
delete_job (bool): Delete job if it exists already
Returns:
GenericJob/ None
"""
job_table = project_class.job_table(recursive=False)
if len(job_table) > 0 and job_name in job_table.job.values:
if not delete_job:
return project_class.load(job_name)
else:
project_class.remove_job(job_name)
return None
def _get_project_for_copy(job, project, new_job_name):
"""
Internal helper function to generate a project and hdf5 project for copying
Args:
job (JobCore): Job object used for comparison
project (JobCore/ProjectHDFio/Project/None): The project to copy the job to.
(Default is None, use the same project.)
new_job_name (str): The new name to assign the duplicate job. Required if the
project is `None` or the same project as the copied job. (Default is None,
try to keep the same name.)
Returns:
Project, ProjectHDFio
"""
if static_isinstance(
obj=project.__class__, obj_type="pyiron_base.jobs.job.core.JobCore"
):
file_project = project.project
hdf5_project = project.project_hdf5.open(new_job_name)
elif isinstance(project, job.project.__class__):
file_project = project
hdf5_project = job.project_hdf5.__class__(
project=project, file_name=new_job_name, h5_path="/" + new_job_name
)
elif isinstance(project, job.project_hdf5.__class__):
file_project = project.project
hdf5_project = project.open(new_job_name)
elif project is None:
file_project = job.project
hdf5_project = job.project_hdf5.__class__(
project=file_project, file_name=new_job_name, h5_path="/" + new_job_name
)
else:
raise ValueError("Project should be JobCore/ProjectHDFio/Project/None")
return file_project, hdf5_project
_special_symbol_replacements = {
".": "d",
"-": "m",
"+": "p",
",": "c",
" ": "_",
}
def _get_safe_job_name(
name: Union[str, tuple],
ndigits: Optional[int] = 8,
special_symbols: Optional[dict] = None,
):
"""
Sanitize a job name, optionally appending numeric values.
Args:
name (str|tuple): The name to sanitize, or a tuple of the name and any number
of numeric values to append with '_' in between.
ndigits (int|None): How many digits to round any floating point values in a
`name` tuple to. (Default is 8; to not round at all use None.)
special_symbols (dict|None): Conversions of special symbols to apply. This will
be applied to the default conversion dict, which contains:
DEFAULT_CONV_DICT
Returns:
(str): The sanitized (and possibly rounded) name.
"""
d_special_symbols = _special_symbol_replacements.copy()
if special_symbols is not None:
d_special_symbols.update(special_symbols)
def round_(value, ndigits=ndigits):
if isinstance(value, float) and ndigits is not None:
return round(value, ndigits=ndigits)
return value
if not isinstance(name, str):
name_rounded = [round_(nn) for nn in name]
job_name = "_".join([str(nn) for nn in name_rounded])
else:
job_name = name
for k, v in d_special_symbols.items():
job_name = job_name.replace(k, v)
_is_valid_job_name(job_name=job_name)
return job_name
_get_safe_job_name.__doc__ = _get_safe_job_name.__doc__.replace(
"DEFAULT_CONV_DICT", f"{_special_symbol_replacements}"
)
def _rename_job(job, new_job_name):
""" """
new_job_name = _get_safe_job_name(new_job_name)
child_ids = job.child_ids
if child_ids:
for child_id in child_ids:
ham = job.project.load(child_id)
ham.move_to(job.project.open(new_job_name + "_hdf5"))
old_working_directory = job.working_directory
if len(job.project_hdf5.h5_path.split("/")) > 2:
new_location = job.project_hdf5.open("../" + new_job_name)
else:
new_location = job.project_hdf5.__class__(
job.project, new_job_name, h5_path="/" + new_job_name
)
if job.job_id:
job.project.db.item_update(
{"job": new_job_name, "subjob": new_location.h5_path}, job.job_id
)
old_job_name = job.name
job._name = new_job_name
job.project_hdf5.copy_to(destination=new_location, maintain_name=False)
job.project_hdf5.remove_file()
job.project_hdf5 = new_location
if os.path.exists(old_working_directory):
shutil.move(old_working_directory, job.working_directory)
os.rmdir("/".join(old_working_directory.split("/")[:-1]))
if os.path.exists(os.path.join(job.working_directory, old_job_name + ".tar.bz2")):
os.rename(
os.path.join(job.working_directory, old_job_name + ".tar.bz2"),
os.path.join(job.working_directory, job.job_name + ".tar.bz2"),
)
def _is_valid_job_name(job_name):
"""
internal function to validate the job_name - only available in Python 3.4 <
Args:
job_name (str): job name
"""
if not job_name.isidentifier():
raise ValueError(
f'Invalid name for a pyiron object, must be letters, digits (not as first character) and "_" only, not {job_name}'
)
if len(job_name) > 50:
raise ValueError(
"Invalid name for a PyIron object: must be less then or "
"equal to 50 characters"
)
def _copy_restart_files(job):
"""
Internal helper function to copy the files required for the restart job.
"""
if not (os.path.isdir(job.working_directory)):
raise ValueError(
"The working directory is not yet available to copy restart files"
)
for i, actual_name in enumerate(
[os.path.basename(f) for f in job.restart_file_list]
):
if actual_name in job.restart_file_dict.keys():
new_name = job.restart_file_dict[actual_name]
shutil.copy(
job.restart_file_list[i],
posixpath.join(job.working_directory, new_name),
)
else:
shutil.copy(job.restart_file_list[i], job.working_directory)
def _kill_child(job):
"""
Internal helper function to kill a child process.
Args:
job (JobCore): job object to decompress
"""
if (
static_isinstance(
obj=job.__class__, obj_type="pyiron_base.jobs.master.GenericMaster"
)
and not job.server.run_mode.queue
and (job.status.running or job.status.submitted)
):
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=["pid", "cwd"])
except psutil.NoSuchProcess:
pass
else:
if pinfo["cwd"] is not None and pinfo["cwd"].startswith(
job.working_directory
):
job_process = psutil.Process(pinfo["pid"])
job_process.kill()
def _job_compress(job, files_to_compress=None):
"""
Compress the output files of a job object.
Args:
job (JobCore): job object to compress
files_to_compress (list): list of files to compress
"""
if not _job_is_compressed(job):
if files_to_compress is None:
files_to_compress = list(job.list_files())
cwd = os.getcwd()
try:
os.chdir(job.working_directory)
with tarfile.open(
os.path.join(job.working_directory, job.job_name + ".tar.bz2"),
"w:bz2",
) as tar:
for name in files_to_compress:
if "tar" not in name and not stat.S_ISFIFO(os.stat(name).st_mode):
tar.add(name)
for name in files_to_compress:
if "tar" not in name:
fullname = os.path.join(job.working_directory, name)
if os.path.isfile(fullname):
os.remove(fullname)
elif os.path.isdir(fullname):
shutil.rmtree(fullname)
finally:
os.chdir(cwd)
else:
print("The files are already compressed!")
def _job_decompress(job):
"""
Decompress the output files of a compressed job object.
Args:
job (JobCore): job object to decompress
"""
try:
tar_file_name = os.path.join(job.working_directory, job.job_name + ".tar.bz2")
with tarfile.open(tar_file_name, "r:bz2") as tar:
safe_extract(tar, job.working_directory)
os.remove(tar_file_name)
except IOError:
pass
def _job_is_compressed(job):
"""
Check if the job is already compressed or not.
Args:
job (JobCore): job object to check
Returns:
bool: [True/False]
"""
compressed_name = job.job_name + ".tar.bz2"
for name in job.list_files():
if compressed_name in name:
return True
return False
def _job_archive(job):
"""
Compress HDF5 file of the job object to tar-archive
Args:
job (JobCore): job object to archive
"""
fpath = job.project_hdf5.file_path
jname = job.job_name
h5_dir_name = jname + "_hdf5"
h5_file_name = jname + ".h5"
cwd = os.getcwd()
try:
os.chdir(fpath)
with tarfile.open(
os.path.join(fpath, job.job_name + ".tar.bz2"), "w:bz2"
) as tar:
for name in [h5_dir_name, h5_file_name]:
tar.add(name)
for name in [h5_dir_name, h5_file_name]:
fullname = os.path.join(fpath, name)
if os.path.isfile(fullname):
os.remove(fullname)
elif os.path.isdir(fullname):
shutil.rmtree(fullname)
finally:
os.chdir(cwd)
def _job_unarchive(job):
"""
Decompress HDF5 file of the job object from tar-archive
Args:
job (JobCore): job object to unarchive
"""
fpath = job.project_hdf5.file_path
try:
tar_name = os.path.join(fpath, job.job_name + ".tar.bz2")
with tarfile.open(tar_name, "r:bz2") as tar:
safe_extract(tar, fpath)
os.remove(tar_name)
finally:
pass
def _job_is_archived(job):
"""
Check if the HDF5 file of the Job is compressed as tar-archive
Args:
job (JobCore): job object to check
Returns:
bool: [True/False]
"""
return os.path.isfile(
os.path.join(job.project_hdf5.file_path, job.job_name + ".tar.bz2")
)
def _job_delete_hdf(job):
"""
Delete HDF5 file of job object
Args:
job (JobCore): job object to delete
"""
if os.path.isfile(job.project_hdf5.file_name):
os.remove(job.project_hdf5.file_name)
def _job_delete_files(job):
"""
Delete files in the working directory of job object
Args:
job (JobCore): job object to delete
"""
working_directory = str(job.working_directory)
if job._import_directory is None and os.path.exists(working_directory):
shutil.rmtree(working_directory)
else:
job._import_directory = None
def _job_remove_folder(job):
"""
Delete the working directory of the job object
Args:
job (JobCore): job object to delete
"""
working_directory = os.path.abspath(os.path.join(str(job.working_directory), ".."))
if os.path.exists(working_directory) and len(os.listdir(working_directory)) == 0:
shutil.rmtree(working_directory)
def _job_store_before_copy(job):
"""
Store job in HDF5 file for copying
Args:
job (GenericJob): job object to copy
Returns:
bool: [True/False] if the HDF5 file of the job exists already
"""
if not job.project_hdf5.file_exists:
delete_file_after_copy = True
else:
delete_file_after_copy = False
job.to_hdf()
return delete_file_after_copy
def _job_reload_after_copy(job, delete_file_after_copy):
"""
Reload job from HDF5 file after copying
Args:
job (GenericJob): copied job object
delete_file_after_copy (bool): delete HDF5 file after reload
"""
job.from_hdf()
if delete_file_after_copy:
job.project_hdf5.remove_file()