Skip to content

Commit ca37531

Browse files
committed
Changes to quantum_espresso_workflow.py
- Add `scale_structure` task - Prepend return dict keys of `generate_structures` with `s_` - Add function to serialize return atoms dict to pure python data types - Rename `name` -> `element` for `get_bulk_structure`, as `name` clashes with WG
1 parent ae7a1de commit ca37531

File tree

1 file changed

+51
-5
lines changed

1 file changed

+51
-5
lines changed

quantum_espresso_workflow.py

Lines changed: 51 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import subprocess
3+
import numpy as np
34

45
from ase.atoms import Atoms
56
from ase.build import bulk
@@ -57,7 +58,15 @@ def generate_structures(structure, strain_lst):
5758
structure_strain.cell * strain ** (1 / 3), scale_atoms=True
5859
)
5960
structure_lst.append(structure_strain)
60-
return {str(i): s.todict() for i, s in enumerate(structure_lst)}
61+
return {f"s_{i}": atoms_to_json_dict(atoms=s) for i, s in enumerate(structure_lst)}
62+
63+
64+
def scale_structure(structure, strain):
65+
structure_strain = Atoms(**structure)
66+
structure_strain.set_cell(
67+
structure_strain.cell * strain ** (1 / 3), scale_atoms=True
68+
)
69+
return structure_strain
6170

6271

6372
def plot_energy_volume_curve(volume_lst, energy_lst):
@@ -67,9 +76,46 @@ def plot_energy_volume_curve(volume_lst, energy_lst):
6776
plt.savefig("evcurve.png")
6877

6978

70-
def get_bulk_structure(name, a, cubic):
71-
return bulk(
72-
name=name,
79+
def get_bulk_structure(element, a, cubic):
80+
ase_atoms = bulk(
81+
name=element,
7382
a=a,
7483
cubic=cubic,
75-
).todict()
84+
)
85+
return atoms_to_json_dict(atoms=ase_atoms)
86+
87+
88+
def atoms_to_json_dict(atoms):
89+
"""
90+
Convert an ASE Atoms object to a fully JSON-serializable dictionary
91+
that uses only Python base data types.
92+
93+
Parameters:
94+
-----------
95+
atoms : ase.Atoms
96+
The Atoms object to convert
97+
98+
Returns:
99+
--------
100+
dict
101+
A dictionary representation using only Python base types
102+
"""
103+
# Get the dictionary representation from ASE
104+
atoms_dict = atoms.todict()
105+
106+
# Create a new dictionary with JSON-serializable values
107+
json_dict = {}
108+
109+
# Convert numpy arrays to lists
110+
for key, value in atoms_dict.items():
111+
if isinstance(value, np.ndarray):
112+
# Convert numpy boolean values to Python booleans
113+
if value.dtype == np.bool_ or value.dtype == bool:
114+
json_dict[key] = value.tolist()
115+
# Convert numpy arrays of numbers to Python lists
116+
else:
117+
json_dict[key] = value.tolist()
118+
else:
119+
json_dict[key] = value
120+
121+
return json_dict

0 commit comments

Comments
 (0)