/
atomistic.py
675 lines (519 loc) · 23 KB
/
atomistic.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
# 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 ase.io import write as ase_write
import copy
import numpy as np
import warnings
from pyiron.atomistics.structure.atoms import Atoms
from pyiron.base.generic.parameters import GenericParameters
from pyiron.base.job.generic import GenericJob as GenericJobCore
from pyiron.base.master.generic import GenericMaster
try:
from pyiron.base.project import ProjectGUI
except (ImportError, TypeError, AttributeError):
pass
__author__ = "Jan Janssen"
__copyright__ = "Copyright 2019, 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 AtomisticGenericJob(GenericJobCore):
"""
Atomistic Generic Job class extends the Generic Job class with all the functionality to run jobs containing
atomistic structures. From this class all specific atomistic Hamiltonians are derived. Therefore it should contain
the properties/routines common to all atomistic jobs. The functions in this module should be as generic as possible.
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']
"""
def __init__(self, project, job_name):
super(AtomisticGenericJob, self).__init__(project, job_name)
self.__name__ = "AtomisticGenericJob"
self.__version__ = "0.1"
self._structure = None
self._generic_input = GenericInput()
self.output = GenericOutput(job=self)
self.map_functions = MapFunctions()
@property
def structure(self):
"""
Returns:
"""
return self._structure
@structure.setter
def structure(self, basis):
"""
Args:
basis:
Returns:
"""
self._generic_input['structure'] = 'atoms'
self._structure = basis
def copy_to(self, project=None, new_job_name=None, input_only=False, new_database_entry=True):
"""
Args:
destination:
new_job_name:
input_only:
new_database_entry:
Returns:
"""
new_generic_job = super(AtomisticGenericJob, self).copy_to(project=project,
new_job_name=new_job_name,
input_only=input_only,
new_database_entry=new_database_entry)
if not new_generic_job._structure:
new_generic_job._structure = copy.copy(self._structure)
return new_generic_job
def calc_minimize(self, e_tol=1e-8, f_tol=1e-8, max_iter=1000, pressure=None, n_print=1):
"""
Args:
e_tol:
f_tol:
max_iter:
pressure:
n_print:
Returns:
"""
self._generic_input['calc_mode'] = 'minimize'
self._generic_input['max_iter'] = max_iter
self._generic_input['pressure'] = pressure
self._generic_input.remove_keys(['temperature', 'n_ionic_steps', 'n_print', 'velocity'])
def calc_static(self):
"""
Returns:
"""
self._generic_input['calc_mode'] = 'static'
self._generic_input.remove_keys(['max_iter', 'pressure', 'temperature', 'n_ionic_steps', 'n_print', 'velocity'])
def calc_md(self, temperature=None, pressure=None, n_ionic_steps=1000, time_step=None, n_print=100,
temperature_damping_timescale=100., pressure_damping_timescale=None, seed=None, tloop=None,
initial_temperature=True, langevin=False):
self._generic_input['calc_mode'] = 'md'
self._generic_input['temperature'] = temperature
self._generic_input['n_ionic_steps'] = n_ionic_steps
self._generic_input['n_print'] = n_print
self._generic_input.remove_keys(['max_iter', 'pressure'])
def from_hdf(self, hdf=None, group_name=None):
"""
Recreates instance from the hdf5 file
Args:
hdf (str): Path to the hdf5 file
group_name (str): Name of the group which contains the object
"""
super(AtomisticGenericJob, self).from_hdf(hdf=hdf, group_name=group_name)
with self._hdf5.open("input") as hdf5_input:
try:
self._generic_input.from_hdf(hdf5_input)
except ValueError:
pass
def to_hdf(self, hdf=None, group_name=None):
"""
Store the GenericJob in an HDF5 file
Args:
hdf (ProjectHDFio): HDF5 group object - optional
group_name (str): HDF5 subgroup name - optional
"""
super(AtomisticGenericJob, self).to_hdf(hdf=hdf, group_name=group_name)
with self._hdf5.open("input") as hdf5_input:
self._generic_input.to_hdf(hdf5_input)
def store_structure(self):
"""
Returns:
"""
if self.structure is not None:
structure_container = self.create_job(job_type=self.project.job_type.StructureContainer,
job_name=self.job_name + '_structure')
structure_container.structure = self.structure
self.parent_id = structure_container.job_id
else:
ValueError('There is no structure attached to the current Job.')
def animate_structure(self, spacefill=True, show_cell=True, stride=1, center_of_mass=False, particle_size=0.5):
"""
Animates the job if a trajectory is present
Args:
spacefill (bool):
show_cell (bool):
stride (int): show animation every stride [::stride]
use value >1 to make animation faster
default=1
center_of_mass (bool):
Returns:
animation: nglview IPython widget
"""
if not self.status.finished:
raise ValueError("This job can't be animated until it is finished")
try:
import nglview
except ImportError:
raise ImportError("The animate() function requires the package nglview to be installed")
animation = nglview.show_asetraj(self.trajectory(stride=stride, center_of_mass=center_of_mass))
if spacefill:
animation.add_spacefill(radius_type='vdw', scale=0.5, radius=particle_size)
animation.remove_ball_and_stick()
else:
animation.add_ball_and_stick()
if show_cell:
if self.structure.cell is not None:
animation.add_unitcell()
return animation
def view_structure(self, snapshot=-1, spacefill=True, show_cell=True):
"""
Args:
snapshot (int): Snapshot of the trajectory one wants
spacefill (bool):
show_cell (bool):
Returns:
view: nglview IPython widget
"""
import nglview
atoms = self.get_structure(snapshot)
picture = nglview.show_ase(atoms)
if spacefill:
picture.add_spacefill(radius_type='vdw', scale=0.5)
picture.remove_ball_and_stick()
else:
picture.add_ball_and_stick()
if show_cell:
if atoms.cell is not None:
picture.add_unitcell()
return picture
def validate_ready_to_run(self):
"""
Returns:
"""
if not self.structure and self._generic_input['structure'] == 'atoms':
raise ValueError('This job does not contain a valid structure: {}'.format(self.job_name))
def db_entry(self):
"""
Generate the initial database entry
Returns:
(dict): db_dict
"""
db_dict = super(AtomisticGenericJob, self).db_entry()
if self.structure:
parent_structure = self.structure.get_parent_basis()
db_dict["ChemicalFormula"] = parent_structure.get_chemical_formula()
return db_dict
def restart(self, snapshot=-1, job_name=None, job_type=None):
"""
Restart a new job created from an existing calculation.
Args:
project (pyiron.project.Project instance): Project instance at which the new job should be created
snapshot (int): Snapshot of the calculations which would be the initial structure of the new job
job_name (str): Job name
job_type (str): Job type
Returns:
new_ham: New job
"""
new_ham = super(AtomisticGenericJob, self).restart(snapshot=snapshot, job_name=job_name, job_type=job_type)
if isinstance(new_ham, GenericMaster) and not isinstance(self, GenericMaster):
new_child = self.restart(snapshot=snapshot, job_name=None, job_type=None)
new_ham.append(new_child)
if self.status.finished:
new_ham.structure = self.get_structure(iteration_step=snapshot)
new_ham._generic_input['structure'] = 'atoms'
else:
new_ham._generic_input['structure'] = 'continue_final'
return new_ham
# Required functions
def continue_with_restart_files(self, job_type=None, job_name=None):
"""
Args:
job_type:
job_name:
Returns:
"""
if job_name is None:
job_name = "{}_continue".format(self.job_name)
new_ham = self.restart(job_type=job_type, job_name=job_name)
if self.status.initialized:
self._job_id = self.save()
new_ham.parent_id = self.job_id
new_ham._generic_input['structure'] = 'continue_final'
return new_ham
def continue_with_final_structure(self, job_type=None, job_name=None):
"""
Args:
job_type:
job_name:
Returns:
"""
if job_name is None:
job_name = "{}_continue".format(self.job_name)
if job_type is None:
job_type = self.__name__
new_ham = self.create_job(job_type, job_name)
if self.status.initialized:
self._job_id = self.save()
new_ham.parent_id = self.job_id
if self.status.finished:
new_ham.structure = self.get_structure(iteration_step=-1)
new_ham._generic_input['structure'] = 'atoms'
else:
new_ham._generic_input['structure'] = 'continue_final'
return new_ham
def trajectory(self, stride=1, center_of_mass=False, atom_indices=None, snapshot_indices=None):
"""
Args:
stride (int): The trajectories are generated with every 'stride' steps
center_of_mass (list/numpy.ndarray): The center of mass
atom_indices (list/numpy.ndarray): The atom indices for which the trajectory should be generated
snapshot_indices (list/numpy.ndarray): The snapshots for which the trajectory should be generated
Returns:
pyiron.atomistics.job.atomistic.Trajectory: Trajectory instance
"""
if snapshot_indices is None:
positions = self['output/generic/positions']
cells = self['output/generic/cells']
else:
positions = self['output/generic/positions'][snapshot_indices]
cells = self['output/generic/cells'][snapshot_indices]
if atom_indices is None:
return Trajectory(positions[::stride], self.structure.get_parent_basis(),
center_of_mass=center_of_mass, cells=cells[::stride])
else:
return Trajectory(positions[::stride, atom_indices, :],
self.structure.get_parent_basis()[atom_indices], center_of_mass=center_of_mass,
cells=cells[::stride])
def write_traj(self, filename, file_format=None, parallel=True, append=False, stride=1, center_of_mass=False,
atom_indices=None, snapshot_indices=None, **kwargs):
"""
Writes the trajectory in a given file file_format based on the `ase.io.write`_ function.
Args:
filename (str): Filename of the output
file_format (str): The specific file_format of the output
parallel (bool):
append (bool):
stride (int): Writes trajectory every `stride` steps
center_of_mass (bool): True if the positions are centered on the COM
atom_indices (list/numpy.ndarray): The atom indices for which the trajectory should be generated
snapshot_indices (list/numpy.ndarray): The snapshots for which the trajectory should be generated
**kwargs: Additional ase arguments
.. _ase.io.write: https://wiki.fysik.dtu.dk/ase/_modules/ase/io/formats.html#write
"""
traj = self.trajectory(stride=stride, center_of_mass=center_of_mass, atom_indices=atom_indices,
snapshot_indices=snapshot_indices)
# Using thr ASE output writer
ase_write(filename=filename, images=traj, format=file_format, parallel=parallel, append=append, **kwargs)
# Compatibility functions
def get_final_structure(self):
"""
Returns:
"""
warnings.warn("get_final_structure() is deprecated - please use get_structure() instead.", DeprecationWarning)
return self.get_structure(iteration_step=-1)
def set_kpoints(self, mesh=None, scheme='MP', center_shift=None, symmetry_reduction=True, manual_kpoints=None,
weights=None, reciprocal=True):
"""
Args:
mesh:
scheme:
center_shift:
symmetry_reduction:
manual_kpoints:
weights:
reciprocal:
Returns:
"""
raise NotImplementedError("The set_kpoints function is not implemented for this code.")
def set_encut(self, encut):
"""
Args:
encut:
Returns:
"""
raise NotImplementedError("The set_encut function is not implemented for this code.")
def get_encut(self):
raise NotImplementedError("The set_encut function is not implemented for this code.")
def get_structure(self, iteration_step=-1):
"""
Gets the structure from a given iteration step of the simulation (MD/ionic relaxation). For static calculations
there is only one ionic iteration step
Args:
iteration_step (int): Step for which the structure is requested
Returns:
pyiron.atomistics.structure.atoms.Atoms: The required structure
"""
if not (self.structure is not None):
raise AssertionError()
snapshot = self.structure.copy()
snapshot.cell = self.get("output/generic/cells")[iteration_step]
snapshot.positions = self.get("output/generic/positions")[iteration_step]
indices = self.get("output/generic/indices")
if indices is not None:
snapshot.indices = indices[iteration_step]
return snapshot
def map(self, function, parameter_lst):
master = self.create_job(job_type=self.project.job_type.MapMaster, job_name='map_' + self.job_name)
master.modify_function = function
master.parameter_list = parameter_lst
return master
def gui(self):
"""
Returns:
"""
ProjectGUI(self)
def _structure_to_hdf(self):
if self.structure is not None and self._generic_input['structure'] == 'atoms':
with self.project_hdf5.open("input") as hdf5_input:
self.structure.to_hdf(hdf5_input)
def _structure_from_hdf(self):
if 'structure' in self.project_hdf5['input'].list_groups() and self._generic_input['structure'] == 'atoms':
with self.project_hdf5.open("input") as hdf5_input:
self.structure = Atoms().from_hdf(hdf5_input)
def _write_chemical_formular_to_database(self):
if self.structure:
parent_structure = self.structure.get_parent_basis()
self.project.db.item_update({"ChemicalFormula": parent_structure.get_chemical_formula()}, self._job_id)
def _before_successor_calc(self, ham):
if ham._generic_input['structure'] == 'continue_final':
ham.structure = self.get_structure(iteration_step=-1)
ham.to_hdf()
def set_encut(job, parameter):
job.set_encut(parameter)
return job
def set_kpoints(job, parameter):
job.set_kpoints(parameter)
return job
def set_structure(job, parameter):
job.structure = parameter
return job
class MapFunctions(object):
def __init__(self):
self.set_structure = set_structure
self.set_encut = set_encut
self.set_kpoints = set_kpoints
class Trajectory(object):
"""
A trajectory instance compatible with the ase.io class
Args:
positions (numpy.ndarray): The array of the trajectory in cartesian coordinates
structure (pyiron.atomistics.structure.atoms.Atoms): The initial structure instance from which the species info
is derived
center_of_mass (bool): False (default) if the specified positions are w.r.t. the origin
cells (numpy.ndarray): Optional argument of the cell shape at every time step (Nx3x3 array) when the volume
varies
"""
def __init__(self, positions, structure, center_of_mass=False, cells=None):
if center_of_mass:
pos = np.copy(positions)
pos[:, :, 0] = (pos[:, :, 0].T - np.mean(pos[:, :, 0], axis=1)).T
pos[:, :, 1] = (pos[:, :, 1].T - np.mean(pos[:, :, 1], axis=1)).T
pos[:, :, 2] = (pos[:, :, 2].T - np.mean(pos[:, :, 2], axis=1)).T
self._positions = pos
else:
self._positions = positions
self._structure = structure
self._cells = cells
def __getitem__(self, item):
new_structure = self._structure.copy()
if self._cells is not None:
new_structure.cell = self._cells[item]
new_structure.positions = self._positions[item]
# This step is necessary for using ase.io.write for trajectories
new_structure.arrays['positions'] = new_structure.positions
# new_structure.arrays['cells'] = new_structure.cell
return new_structure
def __len__(self):
return len(self._positions)
class GenericInput(GenericParameters):
def __init__(self, input_file_name=None, table_name="generic"):
super(GenericInput, self).__init__(input_file_name=input_file_name, table_name=table_name, comment_char="#",
separator_char="=")
def load_default(self):
"""
Loads the default file content
"""
file_content = '''\
calc_mode=static # static, minimize, md
structure=atoms # atoms, continue_final
'''
self.load_string(file_content)
class GenericOutput(object):
def __init__(self, job):
self._job = job
@property
def cells(self):
return self._job['output/generic/cells']
@property
def energy_pot(self):
return self._job['output/generic/energy_pot']
@property
def energy_tot(self):
return self._job['output/generic/energy_tot']
@property
def forces(self):
return self._job['output/generic/forces']
@property
def positions(self):
return self._job['output/generic/positions']
@property
def pressures(self):
return self._job['output/generic/pressures']
@property
def steps(self):
return self._job['output/generic/steps']
@property
def temperature(self):
return self._job['output/generic/temperature']
@property
def computation_time(self):
return self._job['output/generic/computation_time']
@property
def unwrapped_positions(self):
return self._job['output/generic/unwrapped_positions']
@property
def volume(self):
return self._job['output/generic/volume']
def __dir__(self):
hdf5_path = self._job['output/generic']
if hdf5_path is not None:
return hdf5_path.list_nodes()
else:
return []