Python API Reference¶
The public API of amorphouspy is defined by what is importable directly from the top-level package:
The rest of the package is considered internal implementation and can be subject to breaking changes even in minor releases.
amorphouspy
¶
amorphouspy - workflows for atomistic modeling of oxide glasses.
Classes¶
DsfConfig
¶
Bases: InteractionConfig
Damped Shifted Force electrostatics.
Emitted as coul/dsf <alpha> <long_range_cutoff>.
Source code in amorphouspy/src/amorphouspy/lammps/potentials/_config.py
EwaldConfig
¶
Bases: InteractionConfig
Ewald summation electrostatics.
Emits coul/long <long_range_cutoff> plus a kspace_style ewald line.
Source code in amorphouspy/src/amorphouspy/lammps/potentials/_config.py
InteractionConfig
¶
PppmConfig
¶
Bases: InteractionConfig
PPPM (Particle-Particle Particle-Mesh) electrostatics.
Emits coul/long <long_range_cutoff> plus a kspace_style pppm line.
Source code in amorphouspy/src/amorphouspy/lammps/potentials/_config.py
WolfConfig
¶
Bases: InteractionConfig
Wolf summation electrostatics.
Emitted as coul/wolf <alpha> <long_range_cutoff>.
Source code in amorphouspy/src/amorphouspy/lammps/potentials/_config.py
Functions:¶
analyze_structure(atoms: Atoms | list[Atoms], *, frame_averaging: bool = False, compute_rings: bool = True, n_jobs: int = 1, r_max: float = 10.0, n_bins: int = 500) -> tuple[StructureData, StructureData]
¶
Perform a comprehensive structural analysis of an atomic configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atoms
|
Atoms | list[Atoms]
|
Atomic configuration to analyze, or a list of frames when frame_averaging=True. |
required |
frame_averaging
|
bool
|
If True, average results over all frames in atoms (list[Atoms]). Returns a tuple (mean_data, sem_data) where both are StructureData instances. Ring statistics are computed on the first frame only; all other properties are averaged over all frames. |
False
|
compute_rings
|
bool
|
Whether to run the ring statistics analysis. |
True
|
n_jobs
|
int
|
Number of worker processes for frame averaging. Used only when
|
1
|
r_max
|
float
|
Maximum radius in Å for RDF calculation (default 10.0). |
10.0
|
n_bins
|
int
|
Number of bins for RDF calculation (default 500). |
500
|
Returns:
| Name | Type | Description |
|---|---|---|
StructureData |
StructureData
|
Object containing structured analysis results. |
StructureData
|
When frame_averaging=True, returns tuple[StructureData, StructureData] — (mean, sem). |
Example
structure_data = analyze_structure(my_atoms) print(structure_data.density)
Source code in amorphouspy/src/amorphouspy/properties/structural/all.py
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 | |
average_over_frames(func: Callable[..., tuple], frames: list[Atoms], **kwargs: object) -> tuple[tuple, tuple]
¶
Call a per-frame analysis function on each frame, return mean and SEM for every output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., tuple]
|
Analysis function taking a single Atoms frame as first argument and returning a tuple. |
required |
frames
|
list[Atoms]
|
List of Atoms frames to average over. |
required |
**kwargs
|
object
|
Keyword arguments forwarded to func. |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[tuple, tuple]
|
(means, sems) — both tuples have the same length as func's return tuple. |
Example
means, sems = average_over_frames(compute_rdf, frames, r_max=8.0, n_bins=500) r, rdf_mean, cn_mean = means _, rdf_sem, cn_sem = sems
Source code in amorphouspy/src/amorphouspy/properties/structural/averaging.py
charges_from_potential(potential: pd.DataFrame, structure: Atoms) -> np.ndarray
¶
Return the charge that a potential assigns to every atom of a structure.
The potentials of :func:generate_potential set one fixed charge per atom type with lines
set type N charge q in their Config, and LAMMPS numbers the types in the order of Species. This
reads those lines back, so the charges are the ones the simulation uses, including a charge that depends on
the composition such as the oxygen charge of SHIK.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
potential
|
DataFrame
|
The potential DataFrame with the columns |
required |
structure
|
Atoms
|
The structure whose atoms are to be charged. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The charges in units of the elementary charge, shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the potential is empty, has no |
Example
potential = generate_potential(struct_dict, potential_type="pmmcs") charges = charges_from_potential(potential, structure)
Source code in amorphouspy/src/amorphouspy/lammps/potentials/potential.py
check_neutral_oxide(oxide: str) -> None
¶
Check if an oxide formula is charge neutral based on standard oxidation states.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
oxide
|
str
|
The chemical formula of the oxide (e.g., "Al2O3"). |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the oxide is invalid, oxidation states cannot be determined, or the net charge is not zero. |
Source code in amorphouspy/src/amorphouspy/fabrication/composition.py
classify_oxygens(structure: Atoms, cutoff: CutoffSpec, former_types: list[int], o_type: int) -> dict[int, str]
¶
Classify each oxygen atom as bridging (BO), non-bridging (NBO), free, or triclustered.
Convenience wrapper around :func:compute_qn_and_classify that returns
only the oxygen classification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
The atomic structure as ASE object. |
required |
cutoff
|
CutoffSpec
|
Cutoff radius for former-O neighbor search (Å), either a
scalar or a per-pair dict |
required |
former_types
|
list[int]
|
Atom types (atomic numbers) considered as formers. |
required |
o_type
|
int
|
Atom type (atomic number) considered as oxygen. |
required |
Returns:
| Type | Description |
|---|---|
dict[int, str]
|
A mapping from real atom ID to oxygen class string: |
dict[int, str]
|
|
dict[int, str]
|
|
Example
o_classes = classify_oxygens(atoms, cutoff=2.0, former_types=[14], o_type=8)
Source code in amorphouspy/src/amorphouspy/properties/structural/qn.py
classify_vibrational_groups(structure: Atoms, cutoff: CutoffSpec | None = None, former_types: list[int] | None = None, o_type: int = 8) -> dict[str, dict[str, np.ndarray]]
¶
Label every atom by element, oxygen class and network-former Q^n for partial VDOS.
Oxygen classes and Q^n come from :func:compute_qn_and_classify and :func:compute_qn_per_atom. Missing
cutoff and former_types are derived as in :func:analyze_structure: formers are the glass formers and
intermediates present, and each former-O cutoff is the first minimum of its RDF (r_max=10.0,
n_bins=500), with the same fallbacks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
The atomic structure as ASE object. Atom IDs are read from the |
required |
cutoff
|
CutoffSpec | None
|
Former-O cutoff in Å, either a scalar or a per-pair dict |
None
|
former_types
|
list[int] | None
|
Atomic numbers of the network formers. Derived from the composition if |
None
|
o_type
|
int
|
Atomic number of oxygen. |
8
|
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, ndarray]]
|
A dict with three groupings, each mapping a label to a sorted int64 array of 0-based positions:
|
dict[str, dict[str, ndarray]]
|
Labels without atoms are omitted. Without oxygen, |
dict[str, dict[str, ndarray]]
|
no formers, |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the |
Example
>>> from ase import Atoms
>>> d = 1.6
>>> positions = [[10, 10, 10], [10 + 2 * d, 10, 10], [10 + d, 10, 10],
... [10 - d, 10, 10], [10, 10 + d, 10], [10, 10, 10 + d],
... [10 + 3 * d, 10, 10], [10 + 2 * d, 10 + d, 10], [10 + 2 * d, 10, 10 + d]]
>>> dimer = Atoms("Si2O7", positions=positions, cell=[30, 30, 30], pbc=True)
>>> groups = classify_vibrational_groups(dimer, cutoff=2.0, former_types=[14])
>>> groups["element"]["Si"].tolist(), groups["oxygen"]["O_BO"].tolist(), groups["qn"]["Si_Q1"].tolist()
([0, 1], [2], [0, 1])
Source code in amorphouspy/src/amorphouspy/properties/vibrational/classification.py
compute_angles(structure: Atoms | list[Atoms], center_type: int, neighbor_type: int, cutoff: float, bins: int = 180) -> tuple[np.ndarray, np.ndarray]
¶
Compute bond angle distribution between triplets of neighbor_type-center-neighbor_type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms | list[Atoms]
|
Atomic structure. Pass a list to use the first frame. |
required |
center_type
|
int
|
Atom type at the angle center. |
required |
neighbor_type
|
int
|
Atom type forming the angle with center. |
required |
cutoff
|
float
|
Neighbor search cutoff. |
required |
bins
|
int
|
Number of histogram bins. Defaults to 180. |
180
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
A 2-tuple containing: bin_centers: Bin centers (degrees). angle_hist: Normalized angle histogram. |
Example
bins, hist = compute_angles(structure, center_type=1, neighbor_type=2, cutoff=3.0)
Source code in amorphouspy/src/amorphouspy/properties/structural/bond_angles.py
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 | |
compute_cavities(structure: Atoms, resolution: int = 128, cutoff_radii: dict[str, float] | float | str | None = None, probe_radius: float = 0.0) -> dict[str, np.ndarray]
¶
Compute cavity distribution and shape properties for a glass structure.
Domain-based cavity detection following pyMolDyn (Meyer et al. 2017). The simulation box is discretised into a 3D voxel grid; voxels whose centre lies within the atomic radius of any atom are marked as occupied. Connected regions of empty voxels -- detected with full 26-connectivity and periodic-boundary-condition awareness -- constitute cavities (domains).
Unlike pyMolDyn and sovapy, atoms are not snapped to the nearest voxel and radii are not rounded to whole voxels: every voxel is tested against the true atom position and radius, with the same rule for orthogonal and triclinic cells. The empty-voxel volume is therefore an unbiased estimate of the free volume at any resolution, and values differ from pyMolDyn and sovapy at the same resolution.
The grid spans exactly one periodic cell. Cavities that cross a cell face are joined to their continuation on the opposite face (including edges and corners) with a union-find merge that tracks periodic images, so every cavity is found regardless of where the cell boundary cuts it.
A cavity that connects to its own periodic image wraps around the cell and
is infinite under PBC (percolating). It is kept, with its volume and
surface area per cell, flagged in 'percolating', and its shape
descriptors set to NaN. Every empty voxel belongs to exactly one cavity, so
volumes.sum() is the total unoccupied volume of the cell.
The boundary of the empty space consists of the parts of the atom spheres not covered by other atoms. Surface areas are the areas of these exposed patches, sampled with 20 Shrake-Rupley points per A^2 (each atom's point set randomly rotated with a fixed seed), and each point is assigned to the cavity of the nearest empty voxel within 3 voxels along each axis. The resolution decides which cavity a patch belongs to and affects the total only through the dropped area: points with no empty voxel that close border crevices the grid does not resolve, and their area is dropped (0.07 % of the total for a 10,020-atom sodium silicate glass at resolution 128; 0.002 % at resolution 64, where the 3-voxel search reaches farther).
The total free volume converges quickly with resolution, but cavity counts, percolation and the split of volume and area between cavities converge more slowly: channels and necks narrower than about one voxel are not resolved. Check them at two resolutions.
Only domains are computed. pyMolDyn additionally offers center-based and surface-based cavities, which extend each domain into the atom spheres (to points nearer to a domain centre or domain surface point than to the nearest atom); those are not implemented here.
With probe_radius > 0 (e.g. 1.20 A, the Van der Waals radius of a
neutral H atom), every atom radius is increased by the probe radius, so
the cavities are the regions where the probe centre fits: each one holds
at least one probe, and a percolating one lets the probe cross the cell.
'volumes' and 'surface_areas' then describe the space of the probe
centre (accessible volume and surface). The accessible volume converges
with resolution, but in dense glasses most sites are pockets smaller than
a voxel, so the number of sites keeps growing with resolution (180, 236
and 301 at resolutions 128, 256 and 384 for H in a sodium silicate glass
with ionic radii); the space the probe body can fill is not computed.
The result depends strongly on the atom radii: with Van der Waals radii
almost no site in a dense silicate glass fits an H atom.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
ASE Atoms object with atomic coordinates and cell. |
required |
resolution
|
int
|
Number of voxels along the longest box dimension (default 128). Higher values resolve narrower channels and crevices between cavities and finer cavity shapes, at the cost of memory and runtime. |
128
|
cutoff_radii
|
dict[str, float] | float | str | None
|
Atomic radius specification. Four forms are accepted:
|
None
|
probe_radius
|
float
|
Radius in A of a probe sphere (default 0, no probe). |
0.0
|
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dictionary of 1D arrays, one entry per detected cavity, with keys:
- |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Examples:
>>> from ase.io import read
>>> structure = read('glass.xyz')
>>> cavities = compute_cavities(structure, resolution=128)
>>> free_volume_fraction = cavities['volumes'].sum() / structure.get_volume()
Source code in amorphouspy/src/amorphouspy/properties/structural/cavities.py
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 | |
compute_coordination(structure: Atoms | list[Atoms], target_type: int, cutoff: float, neighbor_types: list[int] | None = None) -> dict[int, float]
¶
Compute coordination number distribution for atoms of a target type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms | list[Atoms]
|
The atomic structure as ASE object. Pass a list to use the first frame. |
required |
target_type
|
int
|
Atom type (atomic number) for which to compute coordination. |
required |
cutoff
|
float
|
Cutoff radius in Å. |
required |
neighbor_types
|
list[int] | None
|
Valid neighbor atomic numbers. None means all types. |
None
|
Returns:
| Type | Description |
|---|---|
dict[int, float]
|
Mapping from coordination number to atom count. |
Example
structure = read('glass.xyz') dist = compute_coordination(structure, target_type=14, cutoff=2.0)
Source code in amorphouspy/src/amorphouspy/properties/structural/rdf.py
compute_debye_level(structure: Atoms, bulk_modulus_gpa: float, shear_modulus_gpa: float, *, normalization: VdosNormalization = 'unit') -> dict[str, float]
¶
Compute the Debye level of the reduced VDOS from elastic moduli and the density of a structure.
The isotropic elastic continuum with bulk modulus \(B\), shear modulus \(G\) and mass density \(\rho\) has the longitudinal and transverse sound velocities
in m/s for \(B\), \(G\) in GPa and \(\rho\) in g/cm\(^3\) (1 GPa / (1 g/cm\(^3\)) = \(10^6\) m\(^2\)/s\(^2\)). With the number density \(n\), the Debye frequency and temperature are
and the Debye VDOS \(g_D(\nu) = 3 \nu^2 / \nu_D^3\) (\(\nu \le \nu_D\), normalised to 1) gives the Debye level
\(g_D(\nu) / \nu^2 = 3 / \nu_D^3\) in THz\(^{-3}\), the low-frequency limit of the reduced VDOS of an isotropic solid.
For "3N" the level is \(3N\) times larger, matching a VDOS that integrates to \(3N\).
The moduli are taken as given: no fit of the VDOS is made, so without moduli there is no Debye level. Use moduli of
the same model and state as the VDOS, e.g. elastic_simulation(...)["moduli"]["B"] and ["G"], which are in
GPa. Only the masses (structure.get_masses(), in amu) and the cell volume enter \(\rho\) and \(n\); the positions
are not used.
The lowest frequency the periodic box supports is \(\nu_\mathrm{min} = v_T / L_\mathrm{max}\), the transverse acoustic mode whose wavelength is the largest perpendicular cell height \(L_\mathrm{max}\) (the edge \(L\) of a cubic box). The box has no acoustic modes below it, so the reduced VDOS there does not represent the bulk glass. Taking \(L_\mathrm{max}\) as the longest wavelength is exact for orthogonal boxes and assumes a cell that is not strongly skewed otherwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
Periodic structure as an ASE object, with a 3-D cell of positive volume. |
required |
bulk_modulus_gpa
|
float
|
Bulk modulus \(B\) in GPa. |
required |
shear_modulus_gpa
|
float
|
Shear modulus \(G\) in GPa. |
required |
normalization
|
VdosNormalization
|
|
'unit'
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
A dict of floats:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a modulus is not positive and finite, |
Example
>>> from ase import Atoms
>>> silica = Atoms("Si1000O2000", cell=[35.661] * 3, pbc=True) # 2.2 g/cm^3
>>> debye = compute_debye_level(silica, bulk_modulus_gpa=36.7, shear_modulus_gpa=31.2)
>>> round(debye["density_g_cm3"], 3), round(debye["transverse_velocity_m_s"])
(2.2, 3766)
>>> round(debye["debye_frequency_thz"], 2), round(debye["debye_temperature_k"])
(10.4, 499)
>>> round(debye["lowest_box_frequency_thz"], 3)
1.056
Source code in amorphouspy/src/amorphouspy/properties/vibrational/debye.py
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 | |
compute_dielectric_from_velocities(velocities: NDArray, masses: NDArray, charges: ArrayLike, dt_fs: float, volume_a3: float, *, groups: dict[str, dict[str, NDArray]] | None = None, eps_inf: float = 1.0, window: VdosWindow = 'hann', n_lag_frames: int | None = None, remove_com: bool = True) -> dict[str, Any]
¶
Compute the isotropic dielectric function from the charge-current fluctuations of an MD trajectory.
The charges \(Z_i\) moving with the velocities \(v_i\) carry the current \(J(t) = \sum_i Z_i\, v_i(t)\), the time derivative of the dipole moment of the cell (which, unlike the dipole itself, is well defined in a periodic box). Linear response gives the conductivity of the cell of volume \(V\) from the equilibrium fluctuations of \(J\),
with the same sign convention as :func:compute_dielectric_function (\(\operatorname{Im} \varepsilon \ge 0\) for
absorption). The transform is one-sided, so the real and imaginary parts obey the Kramers-Kronig relations.
The temperature is taken from the trajectory itself, \(k_B T = \langle \sum_i m_i |v_i|^2 \rangle / n_\mathrm{dof}\)
with \(n_\mathrm{dof} = 3N - 3\) when the centre-of-mass velocity is removed and \(3N\) otherwise, so the unit of
the velocities cancels and no temperature is passed. For a harmonic solid at equipartition the result is that of
:func:compute_dielectric_function with the strengths of :func:compute_ir_oscillator_strengths: each mode
contributes \(f_m\) to \(\langle J \cdot J \rangle / 3 k_B T\), and because the response of a harmonic oscillator is
the same in classical and quantum mechanics, no quantum correction applies. Anharmonicity enters through the
dynamics, as the temperature-dependent position and width of the peaks.
The correlation function is the unbiased estimate over all time origins for the lags
\(0 \ldots n_\mathrm{lag} - 1\). It is multiplied by the decaying half of window (1 at zero lag), which
smooths the spectrum over about \(1 / (n_\mathrm{lag}\, \Delta t)\), and transformed on the grid
np.fft.rfftfreq(2 * n_lag_frames, dt_fs * 1e-3): the cosine part with the trapezoid rule over the frames,
the sine part over the band-limited interpolation on a 16 times finer time grid, without which
\(\operatorname{Re} \varepsilon\) below a mode at \(\nu_0\) would be too large by about
\((2\pi\nu_0 \Delta t)^2 / 12\). The integral of \(\operatorname{Re} \sigma\) is fixed by the zero-lag value alone
(the f-sum rule), whatever the window. A window with negative side lobes, and above all None, can make
\(\operatorname{Im} \varepsilon\) slightly negative next to a sharp peak.
At \(\nu = 0\) the dielectric function is NaN: there \(\sigma\) is the DC ionic conductivity, which is finite when modifier ions diffuse during the run, and \(\varepsilon\) diverges.
With groups the current of every group \(G\) gives, for each pair of labels of one grouping, the part of
\(\varepsilon - \varepsilon_\infty\) that comes from \(\langle J_G(0) \cdot J_{G'}(t) \rangle\) and
\(\langle J_{G'}(0) \cdot J_G(t) \rangle\). The cross terms can be negative. Over the unordered pairs of a
grouping that holds every atom once they sum to \(\varepsilon - \varepsilon_\infty\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
velocities
|
NDArray
|
Velocities, shape \((n_\mathrm{frames}, N, 3)\), in any unit, sampled every |
required |
masses
|
NDArray
|
Atomic masses, shape \((N,)\), in the order of the atoms. |
required |
charges
|
ArrayLike
|
Atomic charges in units of the elementary charge: shape \((N,)\) for scalar charges or \((N, 3, 3)\) for charge tensors \(Z_{i,\alpha\beta}\). |
required |
dt_fs
|
float
|
Time between frames in fs. |
required |
volume_a3
|
float
|
The volume of the cell in Å\(^3\). |
required |
groups
|
dict[str, dict[str, NDArray]] | None
|
Atom groups as |
None
|
eps_inf
|
float
|
The high-frequency dielectric constant \(\varepsilon_\infty\); see
:func: |
1.0
|
window
|
VdosWindow
|
The window whose decaying half multiplies the correlation function: |
'hann'
|
n_lag_frames
|
int | None
|
The number of lags kept. Defaults to |
None
|
remove_com
|
bool
|
Whether to subtract the centre-of-mass velocity of every frame. |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary with:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the trajectory, masses or |
Warns:
| Type | Description |
|---|---|
UserWarning
|
If the charges do not sum to zero over the atoms. |
Example
Source code in amorphouspy/src/amorphouspy/properties/vibrational/infrared.py
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 | |
compute_dielectric_function(frequencies_thz: ArrayLike, strengths: ArrayLike, volume_a3: float, *, frequency_grid_thz: ArrayLike | None = None, eps_inf: float = 1.0, damping_thz: float = 0.5) -> dict[str, Any]
¶
Compute the isotropic dielectric function of damped harmonic modes from their oscillator strengths.
Every mode of frequency \(\nu_m\) and oscillator strength \(f_m\) (:func:compute_ir_oscillator_strengths) responds
to a field as a damped oscillator, and the modes of a cell of volume \(V\) add up to
with the time dependence \(e^{-i 2\pi\nu t}\), so that absorption is \(\operatorname{Im} \varepsilon \ge 0\). The
prefactor is \(44224.5\ \mathrm{THz^2\,Å^3\,amu}/e^2\). The peaks of \(\operatorname{Im} \varepsilon\) are the
transverse optical modes; those of the loss function of :func:compute_optical_response the longitudinal ones.
\(\varepsilon_\infty\) is the electronic contribution, which a model of rigid ions does not have: 1 leaves it out, and the square of the optical refractive index (about 2.1 for silica) adds the measured one. The damping \(\gamma\) is the full width at half maximum of the peaks of \(\operatorname{Im} \varepsilon\); in a harmonic calculation it is a numerical broadening that joins the discrete modes of a finite cell into a spectrum, not a physical linewidth.
Modes with \(\nu_m \le 0\) (imaginary modes, reported as negative frequencies) are left out and counted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frequencies_thz
|
ArrayLike
|
The mode frequencies in THz, shape \((M,)\), e.g. |
required |
strengths
|
ArrayLike
|
The oscillator strengths in \(e^2/\mathrm{amu}\), shape \((M,)\), e.g. |
required |
volume_a3
|
float
|
The volume of the cell in Å\(^3\). |
required |
frequency_grid_thz
|
ArrayLike | None
|
The frequencies in THz at which to evaluate, 1-D and strictly increasing. Defaults to a grid from 0 to the highest mode plus \(5\gamma\) in steps of \(\gamma / 5\). |
None
|
eps_inf
|
float
|
The high-frequency dielectric constant \(\varepsilon_\infty\). |
1.0
|
damping_thz
|
float
|
The damping \(\gamma\) in THz. |
0.5
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary with:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
>>> infrared = compute_ir_oscillator_strengths( # doctest: +SKIP
... modes["eigenvectors"], minimised.get_masses(), charges
... )
>>> dielectric = compute_dielectric_function( # doctest: +SKIP
... modes["frequencies_thz"], infrared["strengths"], minimised.cell.volume, eps_inf=2.1
... )
>>> dielectric["epsilon"].imag # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/infrared.py
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 | |
compute_guttmann_rings(structure: Atoms | list[Atoms], bond_lengths: dict[tuple[str, str], float], max_size: int = 24, n_cpus: int = 1) -> tuple[dict[int, float], float]
¶
Compute the Guttman ring size distribution and mean ring size.
The ring associated with each T-O bond is the shortest cycle containing it. The search runs on the bipartite T-O atom network, so oxygen triclusters cannot masquerade as small rings and edge-sharing polyhedra are detected. Under periodic boundary conditions only cycles that close in real space are counted; see the module docstring for the full criterion.
Ring size is the number of network-former atoms (T atoms) in the ring, following Guttman's original convention. The smallest reportable ring is 2, two formers bridged by two distinct oxygens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms | list[Atoms]
|
ASE Atoms object containing atomic coordinates and types. Pass a list to use the first frame. |
required |
bond_lengths
|
dict[tuple[str, str], float]
|
Maximum bond lengths for each element pair, e.g.
|
required |
max_size
|
int
|
Maximum ring size (number of T atoms) to search for. |
24
|
n_cpus
|
int
|
Number of worker processes for parallel ring search. Only
very large networks (>100 000 T-O bonds, roughly a 10⁵-atom cell)
benefit; below that the search runs sequentially whatever is asked
for, because starting worker processes costs more than it saves.
|
1
|
Returns:
| Name | Type | Description |
|---|---|---|
histogram |
dict[int, float]
|
Mapping from ring size to ring count. |
mean_ring_size |
float
|
Mean ring size weighted by count. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> from ase.io import read
>>> structure = read('glass.xyz')
>>> histogram, mean_size = compute_guttmann_rings(
... structure,
... bond_lengths={('Si', 'O'): 1.8},
... max_size=12,
... )
>>> # Parallel on 4 cores
>>> histogram, mean_size = compute_guttmann_rings(
... structure,
... bond_lengths={('Si', 'O'): 1.8},
... n_cpus=4,
... )
Source code in amorphouspy/src/amorphouspy/properties/structural/rings.py
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 | |
compute_harmonic_vdos(frequencies_thz: ArrayLike, eigenvectors: NDArray[np.float64] | None = None, *, groups: dict[str, dict[str, NDArray]] | None = None, frequency_grid_thz: ArrayLike | None = None, broadening_thz: float = 0.2, normalization: HarmonicNormalization = 'unit') -> dict[str, Any]
¶
Compute the harmonic VDOS and its group partials from the modes of :func:diagonalize_dynamical_matrix.
The input is the \(M = 3N - 3\) kept modes: frequencies \(\nu_k\) in THz (negative for imaginary modes) and the mass-weighted eigenvectors \(e_k\), orthonormal columns with row \(3i + \alpha\) for atom \(i\) and direction \(\alpha\). The weight of atom \(i\) in mode \(k\) and of a group \(G\) are
and the VDOS and its partials are sums of unit-area Gaussians of standard deviation \(\sigma\) (broadening_thz),
Partials within a grouping that covers every atom once (e.g. "element") sum to the total, and the classes of
a grouping that covers a subset sum to that subset's partial (e.g. the "oxygen" classes to "O").
Normalisation:
"unit"(default): \(c = 1/M\), so the total integrates to 1 over all modes."3N": \(c = 3N/M\), so the total integrates to \(3N\), as with the VACF route, although the three translations were dropped: each kept mode carries \(3N/M\) instead of 1.
What is not counted:
- Imaginary modes (\(\nu_k < 0\), any negative value, unlike the
imaginary_threshold_thzof :func:diagonalize_dynamical_matrix) are excluded from all sums and counted in"n_imaginary_excluded". They stay in \(M\), so the integral falls short of 1 (or \(3N\)) by their share,"imaginary_weight"\(= n/M\). - Gaussian weight below or above the grid is not renormalised either: the default grid starts at 0, so modes within
a few \(\sigma\) of 0 lose part of their weight.
"grid_integral"is the trapezoid integral of the total on the grid. A grid spacing up to \(\sigma/2\) integrates a Gaussian to better than \(10^{-10}\).
Completeness: summed over all \(3N\) modes, \(\sum_k w_{kG} = 3 N_G\). The translations are the mass-weighted rigid shifts \(\sqrt{m_i / m_\mathrm{tot}}\), so over the kept modes it is \(3 N_G - 3 m_G / m_\mathrm{tot}\), with \(N_G\) the atom count and \(m_G\) the mass of the group.
Relation to the VACF route: in mode \(k\), atom \(i\) carries the share \(a_{ik}\) of the mode's kinetic energy, since
its mass-weighted velocity is proportional to \(e_{3i+\alpha,k}\). A partial of
:func:compute_partial_vdos is the group's share of the mass-weighted velocity power, so with every mode at the
same mean kinetic energy (classical equipartition in a harmonic solid) the two routes use the same partial
definition, and the same normalisations.
The eigenvectors are not checked for orthonormality, which would cost a full \((M, M)\) matrix product; columns that are not orthonormal break \(\sum_i a_{ik} = 1\) and the sums above.
Memory: the eigenvectors are read in blocks of columns of _CHUNK_BYTES (64 MB), each reduced at once to the
groups, and the Gaussians are evaluated in blocks of modes of the same size. Neither a squared copy of the
eigenvectors nor an \((N, M)\) weight array is built.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frequencies_thz
|
ArrayLike
|
The \(M = 3N - 3\) mode frequencies in THz, negative for imaginary modes, e.g.
|
required |
eigenvectors
|
NDArray[float64] | None
|
The \((3N, M)\) float64 eigenvectors with orthonormal columns in the order of
|
None
|
groups
|
dict[str, dict[str, NDArray]] | None
|
|
None
|
frequency_grid_thz
|
ArrayLike | None
|
The frequencies in THz at which the VDOS is evaluated: 1-D, finite, strictly increasing,
at least 2 points. |
None
|
broadening_thz
|
float
|
The standard deviation \(\sigma\) of the Gaussians in THz (not the FWHM, which is \(2.355\sigma\)). |
0.2
|
normalization
|
HarmonicNormalization
|
|
'unit'
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary with:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Warns:
| Type | Description |
|---|---|
UserWarning
|
If the largest spacing of |
Example
>>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin") # doctest: +SKIP
>>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"]) # doctest: +SKIP
>>> modes = diagonalize_dynamical_matrix( # doctest: +SKIP
... matrix, masses=minimised.get_masses(), overwrite_matrix=True
... )
>>> groups = classify_vibrational_groups(minimised) # doctest: +SKIP
>>> vdos = compute_harmonic_vdos( # doctest: +SKIP
... modes["frequencies_thz"], modes["eigenvectors"], groups=groups, broadening_thz=0.1
... )
>>> vdos["vdos"]["oxygen"]["O_NBO"], vdos["grid_integral"], vdos["n_imaginary_excluded"] # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/harmonic.py
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 | |
compute_ir_oscillator_strengths(eigenvectors: NDArray[np.float64], masses: ArrayLike, charges: ArrayLike, *, groups: dict[str, dict[str, NDArray]] | None = None) -> dict[str, Any]
¶
Compute the infrared oscillator strength of every mode from its eigenvector and the atomic charges.
A mode \(m\) with mass-weighted eigenvector \(e_{3i+\beta,m}\) displaces atom \(i\) by \(e_{3i+\beta,m} / \sqrt{m_i}\) per unit normal coordinate. With the charge tensor \(Z_{i,\alpha\beta}\) of atom \(i\) (the dipole along \(\alpha\) created by a unit displacement along \(\beta\)), the dipole per unit normal coordinate, called the mode effective charge, is
and the isotropic oscillator strength, the orientational average of \(\tilde Z_{m,\alpha} \tilde Z_{m,\beta}\), is
Scalar charges \(q_i\) stand for \(Z_{i,\alpha\beta} = q_i \delta_{\alpha\beta}\): the rigid-ion model, in which the fixed charges of the potential move with the atoms and nothing polarises. Its peak positions are those of the potential, but its intensities are qualitative; Born effective charge tensors from an electronic-structure calculation can be passed instead.
For a full orthonormal set of \(3N\) modes the strengths obey the sum rule \(\sum_m \tilde Z_{m,\alpha} \tilde Z_{m,\beta} = \sum_i (Z_i Z_i^T)_{\alpha\beta} / m_i\); the three rigid translations hold \((\sum_i Z_i)(\sum_i Z_i)^T / \sum_i m_i\) of it, which is zero for a neutral cell.
With groups the sum over atoms is restricted to each group \(G\), giving \(\tilde Z^G_m\), and every pair of labels
of one grouping gets the strength
whose cross terms (\(G \neq G'\)) can be negative. Over the unordered pairs of a grouping that holds every atom once,
such as "element" of :func:classify_vibrational_groups, they sum to \(f_m\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eigenvectors
|
NDArray[float64]
|
The \((3N, K)\) float64 eigenvectors of the mass-weighted dynamical matrix, one orthonormal mode
per column with row \(3i + \alpha\) for atom \(i\) and direction \(\alpha\), e.g. |
required |
masses
|
ArrayLike
|
Atomic masses in amu, shape \((N,)\), in the order of the rows, e.g. |
required |
charges
|
ArrayLike
|
Atomic charges in units of the elementary charge, in the order of the rows: shape \((N,)\) for scalar charges or \((N, 3, 3)\) for charge tensors \(Z_{i,\alpha\beta}\). |
required |
groups
|
dict[str, dict[str, NDArray]] | None
|
Atom groups as |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary with:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Warns:
| Type | Description |
|---|---|
UserWarning
|
If the charges do not sum to zero over the atoms. |
Example
Source code in amorphouspy/src/amorphouspy/properties/vibrational/infrared.py
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 | |
compute_msd(frames: list[Atoms], *, timestep: float = 1.0, output_frequency: int = 1, max_lag: int | None = None, remove_com_drift: bool = True, per_species: bool = True, method: str = 'fft') -> dict[str, Any]
¶
Compute the mean-squared displacement from a trajectory.
With method="fft" (default) the multi-time-origin Fast Correlation Algorithm is used, which
requires uniformly-spaced frames and gives the best statistics. With method="single_origin"
the MSD is <|r(t) - r(0)|^2> referenced to the first frame; this is noisier but works on a
non-uniformly sampled trajectory (e.g. a log-then-linear dump), using each frame's actual time
from atoms.info["step"] when present. If every frame carries an "unwrapped_positions" array
(LAMMPS image-flag unwrapping) it is used directly; otherwise the trajectory is unwrapped on the
fly from wrapped positions and per-frame cells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frames
|
list[Atoms]
|
Trajectory as a list of :class: |
required |
timestep
|
float
|
MD integration timestep in femtoseconds. |
1.0
|
output_frequency
|
int
|
MD steps between successive frames (used for the time axis when frames carry
no |
1
|
max_lag
|
int | None
|
Largest lag (in frames) to report. Defaults to |
None
|
remove_com_drift
|
bool
|
Subtract the per-frame mass-weighted centre-of-mass displacement. |
True
|
per_species
|
bool
|
Also report MSD resolved per chemical element. |
True
|
method
|
str
|
|
'fft'
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with |
dict[str, Any]
|
per_species is set, also |
Example
Source code in amorphouspy/src/amorphouspy/properties/diffusion.py
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 | |
compute_network_connectivity(qn_dist: dict[int, int | float]) -> float
¶
Compute average network connectivity based on Qn distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
qn_dist
|
dict[int, int | float]
|
Qn distribution histogram. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Average network connectivity. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If qn_dist is empty or sum of counts is zero. |
Example
qn_dist = {0: 10, 1: 50, 2: 100, 3: 200, 4: 50} connectivity = compute_network_connectivity(qn_dist)
Source code in amorphouspy/src/amorphouspy/properties/structural/qn.py
compute_optical_response(frequencies_thz: ArrayLike, epsilon: ArrayLike) -> dict[str, Any]
¶
Compute the optical constants, absorption coefficient, reflectivity and loss function from \(\varepsilon(\nu)\).
The complex refractive index is \(n + i k = \sqrt{\varepsilon}\) (the root with \(n \ge 0\)). It gives the absorption coefficient of the intensity, \(I(x) = I_0 e^{-\alpha x}\), the reflectivity of a thick sample at normal incidence in vacuum, and the energy loss function, whose peaks mark the longitudinal optical modes:
with the wavenumber \(\tilde\nu = \nu / c\) in cm\(^{-1}\). NaN in epsilon (the zero-frequency bin of
:func:compute_dielectric_from_velocities) gives NaN at the same points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frequencies_thz
|
ArrayLike
|
The frequencies in THz, 1-D, finite and non-negative. |
required |
epsilon
|
ArrayLike
|
The complex dielectric function at these frequencies, e.g. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary with one array per frequency:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
Source code in amorphouspy/src/amorphouspy/properties/vibrational/infrared.py
compute_partial_vacf(velocities: NDArray, masses: NDArray, dt_fs: float, groups: dict[str, dict[str, NDArray]], *, max_lag_frames: int | None = None, normalization: VacfNormalization = 'unit', remove_com: bool = True) -> tuple[NDArray[np.float64], dict[str, dict[str, NDArray[np.float64]]]]
¶
Compute partial VACFs for many atom groups with one transform per atom.
Each partial is exactly what :func:compute_vacf_from_velocities returns with indices set to the group
(same centre-of-mass treatment, lags, normalisation and units), but every atom is transformed once, however many
groups it belongs to. groups has the layout returned by :func:classify_vibrational_groups. Within one
grouping that covers every atom once (e.g. "element"), the partials add up to the total VACF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
velocities
|
NDArray
|
Velocities of shape |
required |
masses
|
NDArray
|
Atomic masses of shape |
required |
dt_fs
|
float
|
Time between consecutive frames in fs (the dump interval, not the MD timestep). |
required |
groups
|
dict[str, dict[str, NDArray]]
|
|
required |
max_lag_frames
|
int | None
|
Largest lag in frames, as in :func: |
None
|
normalization
|
VacfNormalization
|
|
'unit'
|
remove_com
|
bool
|
Subtract the centre-of-mass velocity of the whole system from every frame. |
True
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
A tuple |
dict[str, dict[str, NDArray[float64]]]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
As :func: |
Example
>>> rng = np.random.default_rng(0)
>>> velocities = rng.normal(size=(100, 3, 3))
>>> masses = np.array([28.085, 15.999, 15.999])
>>> groups = {"element": {"Si": np.array([0]), "O": np.array([1, 2])}}
>>> lag_ps, partial = compute_partial_vacf(velocities, masses, 5.0, groups)
>>> _, total = compute_vacf_from_velocities(velocities, masses, 5.0)
>>> bool(np.allclose(partial["element"]["Si"] + partial["element"]["O"], total))
True
Source code in amorphouspy/src/amorphouspy/properties/vibrational/vacf.py
compute_partial_vdos(velocities: NDArray, masses: NDArray, dt_fs: float, groups: dict[str, dict[str, NDArray]], *, normalization: VdosNormalization = 'unit', remove_com: bool = True, window: VdosWindow = None) -> tuple[NDArray[np.float64], dict[str, dict[str, NDArray[np.float64]]]]
¶
Compute partial VDOS for many atom groups with one transform per atom.
Each partial is exactly what :func:compute_vdos_from_velocities returns with indices set to the group
(same centre-of-mass treatment, window, normalisation and units), but every atom is transformed once, however many
groups it belongs to. groups has the layout returned by :func:classify_vibrational_groups: classify once, then
reuse the indices for any number of trajectories or blocks. Within one grouping that covers every atom once (e.g.
"element"), the partials add up to the total VDOS computed with the same window and normalisation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
velocities
|
NDArray
|
Velocities of shape |
required |
masses
|
NDArray
|
Atomic masses of shape |
required |
dt_fs
|
float
|
Time between consecutive frames in fs (the dump interval, not the MD timestep). |
required |
groups
|
dict[str, dict[str, NDArray]]
|
|
required |
normalization
|
VdosNormalization
|
|
'unit'
|
remove_com
|
bool
|
Subtract the centre-of-mass velocity of the whole system from every frame. |
True
|
window
|
VdosWindow
|
|
None
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
A tuple |
dict[str, dict[str, NDArray[float64]]]
|
same keys as |
Raises:
| Type | Description |
|---|---|
ValueError
|
As :func: |
Example
>>> rng = np.random.default_rng(0)
>>> velocities = rng.normal(size=(100, 3, 3))
>>> masses = np.array([28.085, 15.999, 15.999])
>>> groups = {"element": {"Si": np.array([0]), "O": np.array([1, 2])}}
>>> frequencies_thz, partial = compute_partial_vdos(velocities, masses, 5.0, groups)
>>> _, total = compute_vdos_from_velocities(velocities, masses, 5.0)
>>> bool(np.allclose(partial["element"]["Si"] + partial["element"]["O"], total))
True
Source code in amorphouspy/src/amorphouspy/properties/vibrational/vdos.py
compute_participation_ratio(eigenvectors: NDArray[np.float64], masses: ArrayLike) -> NDArray[np.float64]
¶
Compute the participation ratio of every mode from the displacements of its mass-weighted eigenvector.
The eigenvectors \(e_{3i+\alpha,k}\) of the mass-weighted dynamical matrix (atom \(i\), direction \(\alpha\), mode \(k\)) give the atomic displacements \(u_{3i+\alpha,k} \propto e_{3i+\alpha,k} / \sqrt{m_i}\). With the squared displacement of atom \(i\), the participation ratio is (Taraskin and Elliott, Phys. Rev. B 56, 8605 (1997), Eq. 16, a definition they attribute to Bell and Dean)
The ratio form makes \(P_k\) independent of the scale and sign of each column, so the displacements need no
normalisation. \(P_k = 1\) when every atom moves by the same amount (a rigid translation, whatever the masses),
\(1/N\) for a mode on one atom and \(n/N\) for a mode shared equally by \(n\) atoms. The per-atom weight is summed over
the three directions before squaring, so \(P_k\) does not depend on the orientation of the axes. Unlike the
kinetic-energy share \(m_i b_{ik}\) used by :func:compute_harmonic_vdos, \(b_{ik}\) counts atoms by amplitude; the
two coincide for a single element.
An extended mode has \(P\) of order 1 at any size, but a mode on a fixed number of atoms has \(P \propto 1/N\), and in a small box the two can be hard to tell apart: a claim that a mode is localised needs the same band compared across box sizes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eigenvectors
|
NDArray[float64]
|
The \((3N, K)\) float64 eigenvectors of the mass-weighted dynamical matrix, one mode per column
with row \(3i + \alpha\) for atom \(i\) and direction \(\alpha\), e.g. |
required |
masses
|
ArrayLike
|
Atomic masses, shape \((N,)\), in the order of the rows, e.g. |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
The \((K,)\) float64 participation ratios, in the order of the columns, between \(1/N\) and 1. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
>>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin") # doctest: +SKIP
>>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"]) # doctest: +SKIP
>>> modes = diagonalize_dynamical_matrix( # doctest: +SKIP
... matrix, masses=minimised.get_masses(), overwrite_matrix=True
... )
>>> ratios = compute_participation_ratio(modes["eigenvectors"], minimised.get_masses()) # doctest: +SKIP
>>> bands = np.digitize(modes["frequencies_thz"], [8.0, 20.0, 28.0]) # doctest: +SKIP
>>> np.bincount(bands, weights=ratios) / np.bincount(bands) # mean P per band # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/harmonic.py
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 | |
compute_projected_rdf(frames: Atoms | list[Atoms], deformation_axis: Literal['x', 'y', 'z'] | None = None, shear_plane: Literal['xy', 'xz', 'yz'] | None = None, r_max: float = 10.0, n_bins: int = 500, type_pairs: list[tuple[int, int]] | None = None) -> tuple[np.ndarray, dict[tuple[int, int], np.ndarray] | None, dict[tuple[int, int], np.ndarray] | None]
¶
Compute the uniaxial and shear projected radial distribution functions.
Expands the pair correlation function onto the l=2 spherical harmonic components that carry the deformation signal:
- uniaxial_rdf: the Y20-based component along
deformation_axis. Vanishes for isotropic structures; grows with uniaxial strain. - shear_rdf: the Y21 or Y22 component for
shear_plane. Vanishes for isotropic structures; grows with shear.
At least one of deformation_axis or shear_plane must be provided.
Omit the one you do not need, its slot in the return tuple will be None.
For multiple frames the per-frame normalised values are averaged, so NPT trajectories with varying cell geometries are handled correctly.
Performance: Numba-JIT kernels accumulate all five needed Y*_lm components in a single i<j pass. On first call Numba compiles the kernels (~5 s); subsequent calls use cached bytecode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frames
|
Atoms | list[Atoms]
|
Single ASE Atoms object or list of frames for trajectory averaging. |
required |
deformation_axis
|
Literal['x', 'y', 'z'] | None
|
Axis along which uniaxial deformation was applied
('x', 'y', or 'z'). Determines which linear combination of Y20
and Re Y22 is returned as the uniaxial signal. |
None
|
shear_plane
|
Literal['xy', 'xz', 'yz'] | None
|
Plane in which shear deformation was applied
('xy', 'xz', or 'yz'). Determines which Y21/Y22 component is
returned as the shear signal. |
None
|
r_max
|
float
|
Maximum distance in Angstrom (default 10.0). Automatically clamped to floor(min_perpendicular_height / 2) with a warning if exceeded. |
10.0
|
n_bins
|
int
|
Number of radial bins (default 500). |
500
|
type_pairs
|
list[tuple[int, int]] | None
|
List of (atomic_number_a, atomic_number_b) pairs to compute. None computes all unique unordered combinations present in the first frame. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
r |
ndarray
|
Radial bin centres in Angstrom, shape (n_bins,). |
uniaxial_rdf |
dict[tuple[int, int], ndarray] | None
|
Dict keyed by (type1, type2) -> real array of shape (n_bins,),
or |
shear_rdf |
dict[tuple[int, int], ndarray] | None
|
Dict keyed by (type1, type2) -> real array of shape (n_bins,),
or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If both |
ValueError
|
If r_max after clamping would be <= 0. |
Example
from ase.build import bulk atoms = bulk("Si", "diamond", a=5.43) * (4, 4, 4)
Uniaxial only -- no shear plane needed¶
r, uniaxial, _ = compute_projected_rdf( ... atoms, deformation_axis="z", r_max=6.0 ... ) signal_SiSi = uniaxial[(14, 14)] # near zero for undeformed bulk
Source code in amorphouspy/src/amorphouspy/properties/structural/projected_rdf.py
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 | |
compute_qn(structure: Atoms | list[Atoms], cutoff: CutoffSpec, former_types: list[int], o_type: int) -> tuple[dict[int, float], dict[int, dict[int, float]]]
¶
Calculate Qn distribution.
The Q^n distribution characterizes connectivity of tetrahedral network-forming units based on bridging oxygens (BOs) count.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms | list[Atoms]
|
The atomic structure as ASE object. Pass a list to use the first frame. |
required |
cutoff
|
CutoffSpec
|
Cutoff radius for former-O neighbor search, either a scalar
or a per-pair dict |
required |
former_types
|
list[int]
|
Atom types considered as formers. |
required |
o_type
|
int
|
Atom type considered as oxygen. |
required |
Returns:
| Type | Description |
|---|---|
tuple[dict[int, float], dict[int, dict[int, float]]]
|
A 2-tuple containing: total_qn: Total Qn distribution. partial_qn: Partial Qn by former type. |
Example
structure = read('glass.xyz') total_qn, partial_qn = compute_qn(structure, cutoff=2.0, former_types=[14], o_type=8)
Source code in amorphouspy/src/amorphouspy/properties/structural/qn.py
compute_qn_and_classify(structure: Atoms | list[Atoms], cutoff: CutoffSpec, former_types: list[int], o_type: int) -> tuple[dict[int, float], dict[int, dict[int, float]], dict[int, str]]
¶
Calculate Qn distribution and classify each oxygen as BO/NBO/free/tri.
Performs a single neighbour search pass to compute both the Q^n distribution and the per-oxygen classification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms | list[Atoms]
|
The atomic structure as ASE object. Pass a list to use the first frame. |
required |
cutoff
|
CutoffSpec
|
Cutoff radius for former-O neighbor search (Å), either a
scalar or a per-pair dict |
required |
former_types
|
list[int]
|
Atom types (atomic numbers) considered as formers. |
required |
o_type
|
int
|
Atom type (atomic number) considered as oxygen. |
required |
Returns:
| Type | Description |
|---|---|
tuple[dict[int, float], dict[int, dict[int, float]], dict[int, str]]
|
A 3-tuple containing: total_qn: Total Qn distribution. partial_qn: Partial Qn by former type. oxygen_classes: Mapping from real atom ID to oxygen class string. |
Example
total_qn, partial_qn, o_classes = compute_qn_and_classify( ... structure, cutoff=2.0, former_types=[14], o_type=8 ... )
Source code in amorphouspy/src/amorphouspy/properties/structural/qn.py
compute_qn_per_atom(structure: Atoms, cutoff: CutoffSpec, former_types: list[int], o_type: int) -> dict[int, int]
¶
Return the Qn (number of bridging oxygens) of every network-former atom.
Uses the same neighbour search pass as :func:compute_qn_and_classify, so
the histogram of the returned values reproduces its Q^n distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
The atomic structure as ASE object. |
required |
cutoff
|
CutoffSpec
|
Cutoff radius for former-O neighbor search (Å), either a
scalar or a per-pair dict |
required |
former_types
|
list[int]
|
Atom types (atomic numbers) considered as formers. |
required |
o_type
|
int
|
Atom type (atomic number) considered as oxygen. |
required |
Returns:
| Type | Description |
|---|---|
dict[int, int]
|
A mapping from real atom ID (the |
dict[int, int]
|
1-based indices) to the number of bridging oxygens ( |
dict[int, int]
|
|
dict[int, int]
|
formers without oxygen neighbours as |
dict[int, int]
|
so counts above 6 are returned as-is. |
Example
qn_per_atom = compute_qn_per_atom(atoms, cutoff=2.0, former_types=[14], o_type=8)
Source code in amorphouspy/src/amorphouspy/properties/structural/qn.py
compute_rdf(structure: Atoms | list[Atoms], r_max: float = 10.0, n_bins: int = 500, type_pairs: list[tuple[int, int]] | None = None) -> tuple[np.ndarray, dict[tuple[int, int], np.ndarray], dict[tuple[int, int], np.ndarray]]
¶
Compute radial distribution functions (RDFs) and cumulative coordination numbers.
Calculates the pair-wise radial distribution function g(r) for specified atom-type pairs under periodic boundary conditions (orthogonal and triclinic), along with the cumulative coordination number n(r).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms | list[Atoms]
|
ASE Atoms object. Pass a list to use the first frame. |
required |
r_max
|
float
|
Maximum distance in Å (default 10.0). |
10.0
|
n_bins
|
int
|
Number of radial bins (default 500). |
500
|
type_pairs
|
list[tuple[int, int]] | None
|
List of (atomic_number_1, atomic_number_2) pairs. None -> all unique unordered combinations of present types plus all same-type pairs. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, dict[tuple[int, int], ndarray], dict[tuple[int, int], ndarray]]
|
A 3-tuple containing: r: Radial bin centres in Å, shape (n_bins,). rdfs: Normalised g(r) for each type pair. cn_cumulative: Cumulative coordination numbers. |
Notes
- If r_max exceeds half the smallest perpendicular cell height, it is automatically reduced to the largest integer value that does not exceed that limit, and a warning message is printed.
- If the adjusted r_max would be zero or negative (cell too small), a ValueError is raised instead.
- This function operates on array indices internally (not atom IDs) because it only needs type information and distances, not ID lookup.
- Periodic boundaries are handled via the minimum-image convention in fractional space, so both orthogonal and triclinic cells are correct.
Example
structure = read('glass.xyz') r, rdfs, cn = compute_rdf(structure, r_max=10.0, n_bins=500) g_SiO = rdfs[(8, 14)] cn_SiO = cn[(8, 14)] # O around Si cn_OSi = cn[(14, 8)] # Si around O
Source code in amorphouspy/src/amorphouspy/properties/structural/rdf.py
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 | |
compute_reduced_vdos(frequencies_thz: NDArray, vdos: NDArray, *, peak_range_thz: tuple[float, float] = (0.5, 5.0), debye: dict[str, float] | None = None) -> dict[str, Any]
¶
Compute the reduced VDOS \(g(\nu) / \nu^2\), the boson-peak position and its height over the Debye level.
The boson peak is the raw maximum of \(g(\nu) / \nu^2\) within peak_range_thz, with no smoothing or fit, so pass
a block-averaged VDOS (e.g. a Hann-windowed mean over blocks); the maximum of a single noisy spectrum is mostly
noise. The default range of 0.5 to 5 THz is a generic choice for oxide glasses (silica peaks near 1 THz); set it
for the system at hand. A maximum on the first or last bin of the range ("peak_at_range_edge") means no peak
was found inside it, e.g. a reduced VDOS that rises steeply towards zero frequency.
With debye (the output of :func:compute_debye_level), the peak height is also divided by the Debye level, and
every frequency below the lowest one the box supports is marked unreliable. The level is only compared, never
fitted: without debye none of these keys is returned. The VDOS and debye must use the same normalisation
("unit" or "3N").
Any VDOS works, including a partial VDOS, but the Debye comparison is meaningful for the total VDOS only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frequencies_thz
|
NDArray
|
Frequencies in THz, 1-D, non-negative and strictly increasing, e.g. from
:func: |
required |
vdos
|
NDArray
|
VDOS on |
required |
peak_range_thz
|
tuple[float, float]
|
|
(0.5, 5.0)
|
debye
|
dict[str, float] | None
|
The dict returned by :func: |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dict with:
|
dict[str, Any]
|
With |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
>>> from ase import Atoms
>>> silica = Atoms("Si1000O2000", cell=[35.661] * 3, pbc=True) # 2.2 g/cm^3
>>> debye = compute_debye_level(silica, bulk_modulus_gpa=36.7, shear_modulus_gpa=31.2)
>>> frequencies_thz = np.linspace(0.0, 10.0, 201)
>>> excess = 1 + np.exp(-0.5 * ((frequencies_thz - 1.2) / 0.4) ** 2)
>>> vdos = debye["debye_level_thz-3"] * frequencies_thz**2 * excess # Debye VDOS with an excess at 1.2 THz
>>> result = compute_reduced_vdos(frequencies_thz, vdos, debye=debye)
>>> round(result["boson_peak_thz"], 3), result["peak_at_range_edge"], round(result["boson_peak_over_debye"], 3)
(1.2, False, 2.0)
>>> bool(np.isnan(result["reduced_vdos"][0])), result["reduced_vdos"].shape
(True, (201,))
>>> round(float(frequencies_thz[result["reliable"]][0]), 3), result["peak_below_box_limit"]
(1.1, False)
Source code in amorphouspy/src/amorphouspy/properties/vibrational/debye.py
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 | |
compute_structure_factor(structure: Atoms | list[Atoms], q_min: float = 0.5, q_max: float = 20.0, n_q: int = 500, r_max: float = 10.0, n_bins: int = 2000, radiation: str = 'neutron', *, lorch_damping: bool = True, type_pairs: list[tuple[int, int]] | None = None) -> tuple[np.ndarray, np.ndarray, dict[tuple[int, int], np.ndarray]]
¶
Compute the 1D isotropic structure factor S(q) and Faber-Ziman partials.
Uses the Faber-Ziman formalism to compute partial structure factors S_ab(q) from partial radial distribution functions g_ab(r) via the sine transform, then combines them into the total S(q) weighted by coherent neutron scattering lengths or q-dependent X-ray form factors.
Neutron diffraction (Faber-Ziman total structure factor):
S(q) = 1 + sum_{a<=b} (2 - d_ab) * c_a * c_b * b_a * b_b * [S_ab(q) - 1] / <b>^2
where c_a is the atomic concentration, b_a the coherent scattering length (from NIST), and = sum_a c_a * b_a.
X-ray diffraction: b_a is replaced by the q-dependent International Tables form factor f_a(q) (four-Gaussian fit via pymatgen), making the weights q-dependent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms | list[Atoms]
|
ASE Atoms object with periodic boundary conditions. Pass a list to use the first frame. |
required |
q_min
|
float
|
Minimum momentum transfer in Angstroms^-1 (default 0.5). |
0.5
|
q_max
|
float
|
Maximum momentum transfer in Angstroms^-1 (default 20.0). |
20.0
|
n_q
|
int
|
Number of q-grid points (default 500). |
500
|
r_max
|
float
|
Real-space cutoff in Angstroms for the underlying RDF (default 10.0). |
10.0
|
n_bins
|
int
|
Number of radial bins for the RDF (default 2000). |
2000
|
radiation
|
str
|
Scattering probe: |
'neutron'
|
lorch_damping
|
bool
|
Apply the Lorch modification function M(r) = sinc(r/r_max) to suppress termination ripples from the finite r_max cutoff (default True). |
True
|
type_pairs
|
list[tuple[int, int]] | None
|
List of (Z_a, Z_b) pairs for which to compute partials.
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
q |
ndarray
|
Momentum transfer grid in Angstroms^-1, shape (n_q,). |
sq_total |
ndarray
|
Total structure factor S(q), shape (n_q,). |
sq_partials |
dict[tuple[int, int], ndarray]
|
Faber-Ziman partial structure factors S_ab(q), keyed by the canonical pair (min(Z_a, Z_b), max(Z_a, Z_b)), each with shape (n_q,). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
KeyError
|
If a scattering length or form factor is not available for an element present in the structure. |
Example
from ase.io import read structure = read("sodium_silicate.extxyz") q, sq, sq_partials = compute_structure_factor(structure, q_max=20.0) sq_SiO = sq_partials[(8, 14)] # partial S_SiO(q)
Source code in amorphouspy/src/amorphouspy/properties/structural/structure_factor.py
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 | |
compute_vacf_from_velocities(velocities: NDArray, masses: NDArray, dt_fs: float, *, indices: NDArray | None = None, max_lag_frames: int | None = None, normalization: VacfNormalization = 'unit', remove_com: bool = True) -> tuple[NDArray[np.float64], NDArray[np.float64]]
¶
Compute the mass-weighted velocity autocorrelation function (VACF) from an MD velocity trajectory.
The VACF is
where \(\langle \cdot \rangle\) is the average over all time origins with the unbiased estimator: lag \(k\) averages the \(N - k\) available products,
for \(k = 0, \dots,\) max_lag_frames, with \(N\) frames. Fewer origins enter at larger lags, so the statistical
noise grows with the lag; the default max_lag_frames = N // 2 keeps at least \(N/2\) origins at every lag.
The sums over origins are computed with FFTs (scipy.fft). Every velocity component of every atom is
zero-padded to \(2N\) frames before the forward transform, so the correlation is linear, not circular (no
wrap-around from the end of the trajectory to its start). The squared transforms are weighted by the masses and
summed over the atoms, and the sum is transformed back once, which is exact because the inverse transform is
linear. No window is applied: the VACF always uses the unwindowed velocities.
With remove_com=True (default), the instantaneous mass-weighted centre-of-mass velocity of the whole system,
\(\mathbf{v}_\mathrm{COM}(t) = \sum_i m_i \mathbf{v}_i(t) / \sum_i m_i\), is subtracted from every atom in every
frame first, also when indices selects a subset, exactly as in :func:compute_vdos_from_velocities. With
remove_com=False the velocities are used as given; a constant centre-of-mass velocity \(\mathbf{V}\) then adds
\(\sum_i m_i |\mathbf{V}|^2\) to the unnormalised total VACF at every lag.
Normalisation:
"unit"(default): divided by the total VACF at zero lag, the time average of \(\sum_i m_i |\mathbf{v}_i - \mathbf{v}_\mathrm{COM}|^2\) (of \(\sum_i m_i |\mathbf{v}_i|^2\) withremove_com=False), so the total \(C(0) = 1\) to rounding. Dimensionless."none": the numerator \(\sum_i m_i \langle \mathbf{v}_i(0) \cdot \mathbf{v}_i(t_k) \rangle\) in amu (velocity unit)\(^2\). Its value at zero lag is the time average of \(\sum_i m_i |\mathbf{v}_i - \mathbf{v}_\mathrm{COM}|^2\) (twice the mean internal kinetic energy).
A partial VACF (indices given) sums the numerator over the selected atoms only and, with "unit", is divided
by the same denominator as the total, so partials over disjoint selections add up to the total VACF, and a
partial's \(C(0)\) is the selection's share of the centred kinetic sum. The denominator comes from the
statistics read over all atoms, so a partial only transforms the selected atoms. Use
:func:compute_partial_vacf for many groups.
Relation to the VDOS: by the Wiener-Khinchin theorem the VDOS is the Fourier transform of the unnormalised VACF.
For a finite trajectory, the "none" spectral density of :func:compute_vdos_from_velocities (no window, same
remove_com) on its grid \(\nu_j = j / (N \Delta t)\) is exactly
with \(C\) the "none" VACF up to max_lag_frames = N - 1 and \(\Delta t\) in ps: the transform over all lags
with a triangular weight. The library computes the VDOS directly from the velocity spectrum, not from this
function; transforming a VACF truncated at a shorter lag gives a lower-resolution spectrum.
Memory: as in :func:compute_vdos_from_velocities, the trajectory is read twice in chunks of atoms, once for the
centre-of-mass velocity, the normalisation and the finiteness check, and once for the transforms, with chunks
sized for the padded length \(2N\). float32 input is transformed in single precision (no float64 copy); the
correlation is accumulated in float64. The input is never modified, and it may be a read-only np.memmap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
velocities
|
NDArray
|
Velocities of shape |
required |
masses
|
NDArray
|
Atomic masses of shape |
required |
dt_fs
|
float
|
Time between consecutive frames in fs (the dump interval, not the MD timestep). |
required |
indices
|
NDArray | None
|
0-based positions of the atoms in a partial VACF, e.g. one entry of
:func: |
None
|
max_lag_frames
|
int | None
|
Largest lag in frames, from 1 to |
None
|
normalization
|
VacfNormalization
|
|
'unit'
|
remove_com
|
bool
|
Subtract the centre-of-mass velocity of the whole system from every frame. |
True
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
A tuple |
NDArray[float64]
|
|
tuple[NDArray[float64], NDArray[float64]]
|
(velocity unit)\(^2\) for |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
>>> from amorphouspy import get_atomic_mass
>>> dt_fs, n_frames = 5.0, 2000
>>> t_ps = np.arange(n_frames) * dt_fs * 1e-3
>>> velocities = np.zeros((n_frames, 2, 3))
>>> velocities[:, 0, 0] = np.cos(2 * np.pi * 10.0 * t_ps)
>>> velocities[:, 1, 0] = -velocities[:, 0, 0]
>>> masses = np.full(2, get_atomic_mass("Si"))
>>> lag_ps, vacf = compute_vacf_from_velocities(velocities, masses, dt_fs)
>>> lag_ps.shape, round(float(lag_ps[10]), 6)
((1001,), 0.05)
>>> round(float(vacf[0]), 6), round(float(vacf[10]), 6) # half a 10 THz period after 0.05 ps
(1.0, -1.0)
>>> _, partial = compute_vacf_from_velocities(velocities, masses, dt_fs, indices=np.array([0]))
>>> round(float(partial[0]), 6)
0.5
Source code in amorphouspy/src/amorphouspy/properties/vibrational/vacf.py
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 | |
compute_vdos_from_velocities(velocities: NDArray, masses: NDArray, dt_fs: float, *, indices: NDArray | None = None, normalization: VdosNormalization = 'unit', remove_com: bool = True, window: VdosWindow = None) -> tuple[NDArray[np.float64], NDArray[np.float64]]
¶
Compute the vibrational density of states from an MD velocity trajectory.
The VDOS is the mass-weighted velocity power spectrum
the unnormalised forward DFT along time (the np.fft.rfft convention; computed with scipy.fft.rfft), on the
one-sided grid
\(\nu_k = k / (N \Delta t)\), \(k = 0, \dots, \lfloor N/2 \rfloor\), in THz. The frequency resolution is
\(1 / (N \Delta t)\) and the highest frequency is the Nyquist frequency \(1 / (2 \Delta t)\). No zero padding or
per-atom mean subtraction is applied, and no window unless window is set.
With a window, the (centre-of-mass-free) velocities are multiplied by \(w_t\), \(t = 0, \dots, N-1\), before the
transform. All windows are periodic (scipy.signal.get_window(window, N)):
"hann": \(w_t = \tfrac{1}{2}\left(1 - \cos(2\pi t / N)\right)\)."hamming": \(w_t = 0.54 - 0.46 \cos(2\pi t / N)\). Lower first sidelobe than Hann, but the edges are not zero (0.08), so leakage far from a peak decays more slowly."blackmanharris": the 4-term Blackman-Harris window \(w_t = \sum_{j=0}^{3} (-1)^j a_j \cos(2\pi j t / N)\), \(a = (0.35875, 0.48829, 0.14128, 0.01168)\), with sidelobes below \(-92\) dB.("gaussian", std): \(w_t = \exp\left(-\tfrac{1}{2}\left((t - N/2) / \sigma\right)^2\right)\) with \(\sigma\) =stdin frames, so its width relative to the block depends on \(N\). It is truncated at the edges (edge value \(e^{-8} \approx 3 \times 10^{-4}\) for \(\sigma = N/8\)). A narrow window (\(\sigma \ll N/8\)) widens every peak and can spread power further than no window at all.
A window suppresses spectral leakage from the finite trajectory length at the cost of resolution. The effective
resolution is \(\mathrm{ENBW} / (N \Delta t)\) with the equivalent noise bandwidth
\(\mathrm{ENBW} = N \sum_t w_t^2 / (\sum_t w_t)^2\) bins: 1.5 (Hann), 1.36 (Hamming), 2.0 (Blackman-Harris) and
about \(N / (2 \sqrt{\pi} \sigma)\) (Gaussian, \(\sigma \ll N\)). For 10 ps blocks that is 0.15, 0.14 and 0.20 THz,
and 0.23 THz for a Gaussian with \(\sigma = N/8\). With window=None (default) the full \(1 / (N \Delta t)\)
resolution is kept, and a peak between grid points leaks into distant bins.
With remove_com=True (default), the instantaneous mass-weighted centre-of-mass velocity of the whole system,
\(\mathbf{v}_\mathrm{COM}(t) = \sum_i m_i \mathbf{v}_i(t) / \sum_i m_i\), is subtracted from every atom in every
frame before the transform, also when indices selects a subset. With remove_com=False the velocities are
transformed as given, and any centre-of-mass drift appears at and near zero frequency.
Normalisation (all integrals are trapezoidal over the returned grid):
"unit"(default): the total VDOS integrates to 1 (units 1/THz)."3N": the total VDOS integrates to3 * n_atoms(the number of degrees of freedom, including the 3 removed with the centre of mass)."none": the power spectral density \(S(\nu_k) = (2 \Delta t / N) \sum_i m_i \sum_\alpha |V_{i\alpha}|^2\) in amu (velocity unit)\(^2\) ps. For an even number of frames its integral equals the time average of \(\sum_i m_i |\mathbf{v}_i|^2\) (twice the mean kinetic energy) exactly, by Parseval's theorem; for an odd number it is lower by half the last bin. With a window, \(V_{i\alpha}\) is the transform of the windowed velocities and the prefactor is \(2 \Delta t / \sum_t w_t^2\) instead of \(2 \Delta t / N\); the integral is then the \(w^2\)-weighted time average \(\sum_t w_t^2 \sum_i m_i |\mathbf{v}_i(t)|^2 / \sum_t w_t^2\) (exact for an even number of frames).
With a window, "unit" and "3N" are applied to the windowed total VDOS, which still integrates to exactly 1
and 3 * n_atoms.
A partial VDOS (indices given) is the same spectrum summed over the selected atoms only and is scaled by the
total VDOS's normalisation, so partials over disjoint selections add up to the total. Its integral is the
selection's share of the total kinetic energy, which is close to its share of atoms by equipartition: about
3 * len(indices) for "3N". The integral of the total spectrum comes from Parseval's theorem in the time
domain, so a partial only transforms the selected atoms. Use :func:compute_partial_vdos for many groups.
Memory: the trajectory is read twice in chunks of atoms (about 64 MB each), once for the centre-of-mass velocity,
the normalisation and the finiteness check, and once for the transforms. Besides the input, peak memory is about
two chunks. float32 input is transformed in single precision (no float64 copy); the spectrum is accumulated in
float64. The input is never modified, and it may be a read-only np.memmap (e.g. np.load(path,
mmap_mode="r")), in which case only the chunks being processed are read from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
velocities
|
NDArray
|
Velocities of shape |
required |
masses
|
NDArray
|
Atomic masses of shape |
required |
dt_fs
|
float
|
Time between consecutive frames in fs (the dump interval, not the MD timestep). |
required |
indices
|
NDArray | None
|
0-based positions of the atoms in a partial VDOS, e.g. one entry of
:func: |
None
|
normalization
|
VdosNormalization
|
|
'unit'
|
remove_com
|
bool
|
Subtract the centre-of-mass velocity of the whole system from every frame. |
True
|
window
|
VdosWindow
|
|
None
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
A tuple |
NDArray[float64]
|
from |
tuple[NDArray[float64], NDArray[float64]]
|
spectral density ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
>>> from amorphouspy import get_atomic_mass
>>> dt_fs, n_frames = 5.0, 2000
>>> t_ps = np.arange(n_frames) * dt_fs * 1e-3
>>> velocities = np.zeros((n_frames, 2, 3))
>>> velocities[:, 0, 0] = np.cos(2 * np.pi * 10.0 * t_ps)
>>> velocities[:, 1, 0] = -velocities[:, 0, 0]
>>> masses = np.full(2, get_atomic_mass("Si"))
>>> frequencies_thz, vdos = compute_vdos_from_velocities(velocities, masses, dt_fs)
>>> float(frequencies_thz[np.argmax(vdos)])
10.0
>>> round(float(np.trapezoid(vdos, frequencies_thz)), 6)
1.0
>>> _, partial = compute_vdos_from_velocities(
... velocities, masses, dt_fs, indices=np.array([0]), normalization="3N"
... )
>>> round(float(np.trapezoid(partial, frequencies_thz)), 6)
3.0
>>> _, vdos_hann = compute_vdos_from_velocities(velocities, masses, dt_fs, window="hann")
>>> float(frequencies_thz[np.argmax(vdos_hann)]), round(float(np.trapezoid(vdos_hann, frequencies_thz)), 6)
(10.0, 1.0)
Source code in amorphouspy/src/amorphouspy/properties/vibrational/vdos.py
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 | |
compute_vibrational_thermodynamics(frequencies_thz: NDArray, vdos: NDArray, temperatures_k: ArrayLike, *, lowest_frequency_thz: float | None = None) -> dict[str, Any]
¶
Compute the harmonic heat capacity, entropy and energies from a VDOS, with a lower temperature bound.
Each mode of frequency \(\nu\) is a quantum harmonic oscillator. With \(x = h \nu / (k_B T)\) it contributes
and a quantity per atom is \(Q(T) = 3 \int g(\nu)\, q(\nu, T)\, d\nu\) (three modes per atom), integrated with the
trapezoid rule on the given grid, as the VDOS functions of this module normalise. The VDOS must therefore be
normalised to 1 (normalization="unit" in :func:compute_vdos_from_velocities); this is not enforced, and
"vdos_integral" lets the caller check it. A partial VDOS from :func:compute_partial_vdos with "unit" gives
that group's additive contribution per atom of the whole system, so the partials sum to the total. At \(T = 0\) the
exact limits are returned: \(C_V = S = 0\) and \(U = F = E_\mathrm{ZP}\). Large \(x\) is evaluated in forms that cannot
overflow (with np.expm1 and np.log1p(-np.exp(-x))).
\(S\) and \(F\) diverge as \(\nu \to 0\), so only \(\nu > 0\) is integrated: the integrand is set to zero at every grid
point with \(\nu \le 0\) (the zero-frequency bin of the VACF route, and imaginary harmonic modes stored as negative
frequencies) and the trapezoid rule runs over the full grid. Nothing is dropped silently: "vdos_integral" is the
integral of \(g\) over the full grid, and "excluded_weight" is that integral minus the integral of \(g\) with the
points at \(\nu \le 0\) set to zero, i.e. the share of modes left out. At high \(T\), \(C_V\) tends to
\(3 \, (\mathrm{vdos\_integral} - \mathrm{excluded\_weight})\) k\(_B\) per atom.
At low temperature the values depend on the low-frequency VDOS, which a finite box or a short trajectory does not
resolve. Below \(T_\mathrm{min} = h \nu_\mathrm{low} / k_B\) (1 THz corresponds to 48 K) the values are flagged as
unreliable, not removed. Usual choices of \(\nu_\mathrm{low}\) (lowest_frequency_thz) are
debye["lowest_box_frequency_thz"] from :func:compute_debye_level (the lowest acoustic mode of the box), the
frequency resolution \(1 / (N \Delta t)\) of the VACF route, or the lowest non-zero mode of the harmonic route. With
None the first positive grid frequency is used, which is only the resolution of the grid, not the box limit, so
the bound is then too optimistic for a small box. \(T = 0\) is always flagged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frequencies_thz
|
NDArray
|
Frequencies in THz, 1-D and strictly increasing. Zero and negative values are allowed and excluded from the integrals. |
required |
vdos
|
NDArray
|
VDOS on |
required |
temperatures_k
|
ArrayLike
|
Temperatures in K, a scalar, a list or a 1-D array of finite values \(\ge 0\). |
required |
lowest_frequency_thz
|
float | None
|
\(\nu_\mathrm{low}\) in THz for the temperature bound, positive and finite, or |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dict with:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
>>> frequencies_thz = np.linspace(0.0, 10.0, 1001)
>>> vdos = 3 * frequencies_thz**2 / 10.0**3 # Debye VDOS with nu_D = 10 THz (theta_D = 480 K)
>>> thermo = compute_vibrational_thermodynamics(
... frequencies_thz, vdos, [0.0, 300.0, 3000.0], lowest_frequency_thz=1.0
... )
>>> thermo["heat_capacity_kb_per_atom"].round(3)
array([0. , 2.649, 2.996])
>>> round(thermo["temperature_bound_k"], 1), thermo["reliable"].tolist()
(48.0, [False, True, True])
>>> round(thermo["zero_point_energy_mev_per_atom"], 2) # 9/8 h nu_D
46.53
Source code in amorphouspy/src/amorphouspy/properties/vibrational/thermodynamics.py
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 | |
convert_frequency(values: float | NDArray, from_unit: FrequencyUnit, to_unit: FrequencyUnit) -> float | NDArray[np.float64]
¶
Convert frequencies between THz, cm^-1, meV and rad/ps.
The conversion goes through THz. Negative values (the convention for imaginary harmonic modes) keep their sign.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
float | NDArray
|
Frequency or array of frequencies in |
required |
from_unit
|
FrequencyUnit
|
Unit of |
required |
to_unit
|
FrequencyUnit
|
Target unit, one of the same four. |
required |
Returns:
| Type | Description |
|---|---|
float | NDArray[float64]
|
A float for scalar input, otherwise a new float64 array of the same shape as |
float | NDArray[float64]
|
modified; |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
round(convert_frequency(1.0, "THz", "cm-1"), 5) 33.35641 convert_frequency(np.array([-1.0, 2.0]), "THz", "rad/ps").round(4) array([-6.2832, 12.5664])
Source code in amorphouspy/src/amorphouspy/properties/vibrational/units.py
count_distribution(coord_numbers: dict[int, int]) -> dict[int, int]
¶
Convert coordination numbers to a histogram distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coord_numbers
|
dict[int, int]
|
Mapping from atom ID to coordination number. |
required |
Returns:
| Type | Description |
|---|---|
dict[int, int]
|
Coordination number frequency histogram. |
Example
dist = count_distribution({1: 4, 2: 4, 3: 3})
Source code in amorphouspy/src/amorphouspy/atoms/shared.py
create_random_atoms(composition: dict[str, float], n_molecules: int | None = None, target_atoms: int | None = None, mode: str = 'molar', stoichiometry: dict[str, dict[str, int]] | None = None, box_length: float = 50.0, min_distance: float = 1.6, seed: int = 42, max_attempts_per_atom: int = 100000) -> tuple[list[dict[str, str | list[float]]], dict[str, int]]
¶
Generate random atom positions for a glass system in a periodic cubic box.
Supports specifying system size either by total number of molecules (n_molecules)
or total number of atoms (target_atoms).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
composition
|
dict[str, float]
|
A dictionary mapping oxide formulas to their fractions, e.g. {"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}. |
required |
n_molecules
|
int | None
|
The desired total number of molecules. Mutually exclusive with |
None
|
target_atoms
|
int | None
|
The desired target number of atoms. Mutually exclusive with |
None
|
mode
|
str
|
The composition interpretation mode ("molar" or "weight"). Defaults to "molar". |
'molar'
|
stoichiometry
|
dict[str, dict[str, int]] | None
|
Optional pre-calculated stoichiometry dictionary. |
None
|
box_length
|
float
|
The length of the cubic simulation box in Angstroms. Defaults to 50.0. |
50.0
|
min_distance
|
float
|
The minimum allowed distance between any two atoms in Angstroms. Defaults to 1.6. |
1.6
|
seed
|
int
|
Random seed for reproducibility. Defaults to 42. |
42
|
max_attempts_per_atom
|
int
|
Maximum attempts to place a single atom before failing. Defaults to 100000. |
100000
|
Returns:
| Type | Description |
|---|---|
tuple[list[dict[str, str | list[float]]], dict[str, int]]
|
A tuple containing: - A list of atom dictionaries, each with "element" and "position". - A dictionary of total counts per element. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If composition sum is invalid or target mode is ambiguous. |
RuntimeError
|
If atom placement fails due to overcrowding (max attempts reached). |
Example
atoms_list, atom_counts = create_random_atoms( ... composition={"SiO2": 0.8, "Na2O": 0.2}, ... target_atoms=500, ... box_length=20.0 ... )
Source code in amorphouspy/src/amorphouspy/fabrication/geometry.py
cte_from_fluctuations_simulation(structure: Atoms, potential: pd.DataFrame, temperature: float = 300, npt_pressure: float = 0.0001, timestep: float = 1.0, equilibration_steps: int = 100000, production_steps: int = 200000, min_production_runs: int = 5, max_production_runs: int = 25, CTE_uncertainty_criterion: float = 1e-06, n_dump: int | None = None, n_print_thermo: int = 10, server_kwargs: dict[str, Any] | None = None, *, aniso: bool = False, seed: int | None = 12345, tmp_working_directory: str | Path | None = None) -> dict[str, Any]
¶
Perform a LAMMPS-based cte simulation protocol based on fluctuations.
This workflow equilibrates a structure at a target temperature and performs a production MD run to collect the instantaneous total energy, pressure and volume, needed to compute the CTE via H-V fluctuation analysis or V-T data, depending if only one temperature or multiple temperatures should be probed.
The number of steps used here is only for testing purposes. It is assumed in this workflow that the given in structure is pre-equilibrated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
Input structure (assumed pre-equilibrated). |
required |
potential
|
DataFrame
|
LAMMPS potential file. |
required |
temperature
|
float
|
Simulation temperature in Kelvin (default 300 K). |
300
|
npt_pressure
|
float
|
Target pressure in GPa (use pyiron units here!) for NPT simulations (default: 10-4 GPa = 10^5 Pa = 1 bar). |
0.0001
|
timestep
|
float
|
MD integration timestep in femtoseconds (default 1.0 fs). |
1.0
|
equilibration_steps
|
int
|
Number of MD steps for the equilibration run (default 100,000). |
100000
|
production_steps
|
int
|
Number of MD steps for the production runs (default 200,000). |
200000
|
min_production_runs
|
int
|
Minimum number of production runs to perform before checking for convergence (default 2). |
5
|
max_production_runs
|
int
|
Maximum number of production runs to perform before checking for convergence (default 10). |
25
|
CTE_uncertainty_criterion
|
float
|
Convergence criterion for the uncertainty of the linear CTE (default 1e-6/K). |
1e-06
|
n_dump
|
int | None
|
Interval of structure dumping in MD steps. If set to |
None
|
n_print_thermo
|
int
|
Interval of printing thermodynamic output in MD steps (default 10). |
10
|
server_kwargs
|
dict[str, Any] | None
|
Additional server configuration arguments for pyiron. |
None
|
aniso
|
bool
|
If false, an isotropic NPT calculation is performed and the simulation box is scaled uniformly. If True, anisotropic NPT calculation is performed and the simulation box can change shape and size independently along each axis (default False). |
False
|
seed
|
int | None
|
Random seed for velocity initialization (default 12345). If None, a random seed is used. |
12345
|
tmp_working_directory
|
str | Path | None
|
Temporary directory for job execution. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Nested dictionary containing the "summary" and "data" keys. In the "summary" section the CTE |
dict[str, Any]
|
values and their uncertainties are returned together with info whether CTE_uncertainty_criterion was |
dict[str, Any]
|
reached within the max_production_runs. |
dict[str, Any]
|
The "data" holds the collected data from all individual production runs. "run_index" is to |
dict[str, Any]
|
clearly identify which production run the data belongs to. "steps" contains the number of steps |
dict[str, Any]
|
for each run. Thermodynamic and structural data are averaged over each production run and these |
dict[str, Any]
|
averages are listed under the respective key. Example: |
dict[str, Any]
|
{ 'summary' : {"CTE_V_mean" : ..., "CTE_x_mean" : ..., "CTE_y_mean" : ..., "CTE_z_mean" : ..., "CTE_V_uncertainty" : ..., "CTE_x_uncertainty" : ..., "CTE_y_uncertainty" : ..., "CTE_z_uncertainty" : ..., "is_converged" : "True" or "False", "convergence_criterion" : float }, |
dict[str, Any]
|
'data': {"run_index" : [1, 2, 3, ...], "steps" : [...], "T" : [...], "E_tot" : [...], "ptot" : [...], "pxx" : [...], "pyy" : [...], "pzz" : [...], "V" : [...], "Lx" : [...], "Ly" : [...], "Lz" : [...], "CTE_V" : [...], "CTE_x" : [...], "CTE_y" : [...], "CTE_z" : [...], } |
dict[str, Any]
|
} |
Notes
- The structure is first pre-equilibrated with a short, hard-coded 10 ps NVT run. Only then follows the user-defined NPT equilibration and production runs.
- The simulation is only marked as converged if the uncertainty criterion is reached for all four CTE values (CTE_V, CTE_x, CTE_y, CTE_z) at the same time. The CTE_uncertainty_criterion is applied to as-is to the linear CTEs. How this is treated for the CTE_V, see next point.
- How to chose the uncertainty criterion for the volumetric CTE? Should it be the same as the defined CTE_uncertainty_criterion applied to the linear CTEs? Consider this: The volumetric CTE is approximately the sum of the linear CTEs along x, y, and z. If three variables x, y and z were uncorrelated and have known uncertainties sigma_x, sigma_y, and sigma_z, the uncertainty of the sum of them would be: sigma_V = sqrt( sigma_x2 + sigma_y2 + sigma_z*2 ). If we assume that the uncertainty criterion is reached at roughly the same time for all three variables, the uncertainty of the volumetric CTE can be approximated as sqrt(3)CTE_uncertainty_criterion. However, x, y and z are typically not uncorrelated. If calculated from the actual simulation data, the uncertainty of CTE_V is found to be approximately the same as the individual uncertainties of the linear CTEs. To be not too strict here, we keep the sqrt(3)*CTE_uncertainty_criterion for CTE_V.
Example
result = cte_from_fluctuations_simulation( ... structure=my_atoms, ... potential=my_potential, ... temperature=300, ... equilibration_steps=500_000, ... production_steps=200_000, ... min_production_runs=10, ... max_production_runs=50, ... CTE_uncertainty_criterion=1e-6, ... )
Source code in amorphouspy/src/amorphouspy/properties/cte.py
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 | |
cte_from_npt_fluctuations(temperature: float | list | np.ndarray, enthalpy: list | np.ndarray, volume: list | np.ndarray, N_points: int = 1000, *, use_running_mean: bool = False) -> float
¶
Compute the CTE from enthalpy-volume cross-correlations.
Data needs to be obtained from a constant pressure, constant temperature NPT simulation. Formula used can be found in See Tildesley, Computer Simulation of Liquids, Eq. 2.94.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
temperature
|
float | list | ndarray
|
Target temperature (defining the ensemble) in K. Can be specified as a single value (int/float). If provided as list or array-like, the mean will be used as target temperature. |
required |
enthalpy
|
list | ndarray
|
"Instantaneous enthalpy" in eV, list or np.ndarray. Not that the instantaneous enthalpy is given by H = U + pV, where U is the instantaneous internal energy (i.e., kinetic + potential of every timestep), p the pressure defining the ensemble and V the average volume. Note that this is not the same quantity as the enthalpy obtained from LAMMPS directly via the 'enthalpy' output from thermo_modify. The latter uses the instantaneous pressure at the given timestep instead of the average (or ensemble-defining) pressure. |
required |
volume
|
list | ndarray
|
Instantaneous volume in Ang^3, list or np.ndarray. Here, one can also feed individual cell lengths for anisotropic CTE calculations. |
required |
N_points
|
int
|
Window size for running mean calculation if running_mean is True. Defaults to 1000. |
1000
|
use_running_mean
|
bool
|
Conventionally, fluctuations are calculated as difference from the mean of the whole trajectory. If use_running_mean is True, running mean values are used to determine fluctuations. This can be useful for non-stationary data where drift in volume and energy is still observed. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
float
|
The calculated CTE value in 1/K. |
Example
cte = cte_from_npt_fluctuations( ... temperature=300.0, ... enthalpy=enthalpy_array, ... volume=volume_array ... )
Notes
- If temperature is provided as int/float, it will be used as-is for the target temperature to compute the CTE.
- If temperature is provided as list/array-like, the mean of the temperature data will be used as target temperature for the CTE calculation. See below how this is slightly changed if running mean is used.
- If running_mean is set to True used, a part of the volume and enthalpy data at the beginning and end of the arrays cannot be used because it is required to calculate the running mean values. To ensure that the data for the calculation of the fluctuations is consistent with the mean volume and target temperature (in case this was provided as list/array-like), also this data will be trimmed correspondingly.
Source code in amorphouspy/src/amorphouspy/properties/cte_analysis.py
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 | |
cte_from_volume_temperature_data(temperature: list | np.ndarray, volume: list | np.ndarray, reference_volume: float | None = None) -> tuple[float, float]
¶
Compute the CTE from slope of a linear fit to volume-temperature data.
This can be done from by performing various constant pressure, constant temperature NPT simulation at different temperatures. Afterwards, collect the averaged volume and fit linearly to the temperature. Divide slope by the volume belonging to the lowest temperature to obtain the CTE. If specified, the volume-temperature plot is shown and the fitted line is overlaid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
temperature
|
list | ndarray
|
Temperature in K. |
required |
volume
|
list | ndarray
|
Volume in Angstrom^3 or other structural quantity of interest. E.g., for anisotropic CTE calculations, one can also use individual cell lengths in Angstroms here. |
required |
reference_volume
|
optional
|
Reference of the volume (or structural quantity of interest) the CTE will be calculated from. If not otherwise specified, the volume corresponding to the lowest temperature is used as reference. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
The calculated CTE value in 1/K and the R^2 value of the linear fit. |
Note
- This function is currently not in use in the workflows. But it might be used for cross-checking.
- If volume-temperature data is used, the CTE needs to be divided by 3 to obtain the linear CTE.
Example
cte = cte_from_volume_temperature_data( ... temperature=[300, 400, 500], ... volume=[100.0, 100.1, 100.2] ... )
Source code in amorphouspy/src/amorphouspy/properties/cte_analysis.py
diagonalize_dynamical_matrix(matrix: NDArray[np.float64], *, masses: ArrayLike | None = None, overwrite_matrix: bool = False, eigenvectors: bool = True, driver: EigenDriver = 'evr', imaginary_threshold_thz: float = 0.01) -> dict[str, Any]
¶
Symmetrise and diagonalise a mass-weighted dynamical matrix and drop the three translational modes.
The input is the dynamical matrix of :func:read_dynamical_matrix,
in eV/Ų/amu, \((3N, 3N)\), row and column \(3i + \alpha\) for atom \(i\) and direction \(\alpha\). An eigenvalue
\(\lambda\) gives the frequency \(\nu = \sqrt{\lambda} / (2\pi)\), which is
\(\nu = 15.633\ \mathrm{THz} \times \sqrt{\lambda / (\mathrm{eV/Å^2/amu})}\) (the factor is
\(\sqrt{e / (10^{-20}\, m_\mathrm{u})} / (2\pi) / 10^{12}\) from scipy.constants). An imaginary mode,
\(\lambda < 0\), is reported as a negative frequency \(\nu = -\sqrt{|\lambda|} / (2\pi)\).
Steps:
- Asymmetry of the raw matrix, \(\max|D - D^\mathsf{T}| / \max|D|\), and the atom pair \((i, j)\), \(i \le j\), of the
worst entry. A finite-difference matrix is symmetric only to the difference error. A pair that crosses a cutoff
where the force jumps during a displacement \(h\) (an energy-shifted pair style such as the PMMCS
pedoneterm at 5.5 Å) gets a spurious term of about jump / (2h) in one entry but not in its transpose, so a large asymmetry points at such corrupted entries, and the atom pair tells where. It is measured before symmetrising, in blocks of rows, together with the check for NaN and inf. - Symmetrisation to \((D + D^\mathsf{T}) / 2\) in place, in the same blocks. With
overwrite_matrix=Falsethis works on one copy of the input; with True on the input itself. - Diagonalisation with
scipy.linalg.eigh(..., overwrite_a=True, driver=driver). This deliberately replaces thenumpy.linalg.eighof the original plan: numpy always copies the matrix and uses the divide-and-conquer driver, which with eigenvectors needs four matrices besides the input, against one for"evr"(see Memory). - The three translational modes are dropped: the three eigenvalues of smallest \(|\lambda|\), which are three
consecutive ones of the ascending spectrum. With
masses, each dropped mode's squared projection on the span of the mass-weighted rigid translations \(t_\alpha = \sqrt{m_i}\, e_\alpha / \sqrt{\sum_i m_i}\) is reported; it is 1 for a pure translation. A value below 0.9 warns: a soft mode is mixed in, or the translations are not the smallest \(|\lambda|\) (a sum-rule violation that lifts them, or an isolated cluster, whose rotations are zero modes too). - Kept frequencies below
-imaginary_threshold_thzcount as imaginary and warn, with the asymmetry atoms.
Memory (benchmark: a 3000-atom spring network, n = 9000, OpenBLAS 0.3.34 on 12 Apple M-series cores; peak
allocations, confirmed by the peak process RSS; scaled as \(n^2\) to \(N\) = 6000 and 10,000 atoms, where one matrix
is 2.6 GB and 7.2 GB). Totals include the input matrix; overwrite_matrix=False adds one copy:
- eigenvalues only, any driver: 1 matrix, 2.6 / 7.2 GB (2 matrices, 5.2 / 14.4 GB without overwrite).
"evr"with eigenvectors: 2 matrices (the eigenvectors are a new array), 5.2 / 14.4 GB (7.8 / 21.6 GB)."evx"with eigenvectors: the same as"evr"."evd"with eigenvectors: 3 matrices (the eigenvectors overwrite the input, plus two of workspace), 7.8 / 21.6 GB (10.4 / 28.8 GB)."ev"with eigenvectors: 1 matrix (the eigenvectors overwrite the input), 2.6 / 7.2 GB (5.2 / 14.4 GB).- For comparison,
numpy.linalg.eigh: 5 matrices, 13 / 36 GB.
The asymmetry and symmetrisation passes add up to about 0.2 GB of row blocks (_CHUNK_BYTES each), independent
of \(N\), and LAPACK \(O(n)\) workspace.
Time at n = 9000, with eigenvectors (scaled as \(n^3\), by 8 and 37, to 6000 and 10,000 atoms): "evr" 33 s
(4.4 min, 20 min), "evd" 27 s (3.6 min, 16 min; 66 s in a first, disturbed run), "evx" 316 s (42 min,
3.2 h), "ev" 339 s (45 min, 3.5 h). Eigenvalues only: about 10 s with every driver (1.3 min, 6 min).
"evr" is the default: within about 20 % of the fastest, "evd", at one matrix less, and memory is the limit
at 10,000 atoms.
With overwrite_matrix=True the input's contents are undefined afterwards (LAPACK overwrites it); with
"ev" or "evd" the returned eigenvectors share its memory. Only a writable C- or F-contiguous array can
be used without a copy, which is checked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
NDArray[float64]
|
The \((3N, 3N)\) mass-weighted dynamical matrix in eV/Ų/amu, float64 (no cast is made, since a cast would copy it). Not symmetrised. |
required |
masses
|
ArrayLike | None
|
Atomic masses in amu, shape \((N,)\), in the order of the matrix rows. Only used for the
translational overlap, so it needs |
None
|
overwrite_matrix
|
bool
|
Symmetrise and diagonalise |
False
|
eigenvectors
|
bool
|
Also return the eigenvectors of the kept modes. |
True
|
driver
|
EigenDriver
|
The LAPACK driver of |
'evr'
|
imaginary_threshold_thz
|
float
|
Kept frequencies below minus this value, in THz, count as imaginary. |
0.01
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary with:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Warns:
| Type | Description |
|---|---|
UserWarning
|
If a dropped mode overlaps the rigid translations by less than 0.9, or if any kept frequency is imaginary. |
Example
>>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin") # doctest: +SKIP
>>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"]) # doctest: +SKIP
>>> modes = diagonalize_dynamical_matrix( # doctest: +SKIP
... matrix, masses=minimised.get_masses(), overwrite_matrix=True
... )
>>> modes["asymmetry"], modes["n_imaginary"], modes["translational_overlap"] # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/dynamical_matrix.py
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 | |
diffusion_simulation(structure: Atoms, potential: pd.DataFrame, temperature_sim: float = 3000.0, timestep: float = 1.0, production_steps: int = 1000000, n_print_thermo: int = 100, server_kwargs: dict[str, Any] | None = None, *, equilibration_steps: int = 100000, thermostat: Thermostat, seed: int = 12345, tmp_working_directory: str | Path | None = None, max_lag: int | None = None, remove_com_drift: bool = True, crossover_ps: float = 100.0, points_per_decade: int = 9, linear_interval_ps: float = 10.0, save_trajectory: str | Path | None = None) -> dict[str, Any]
¶
Run an MD production trajectory and compute self-diffusion from the MSD.
Equilibrates the structure (Langevin then NVT) and runs an NVT production stage that dumps on a
log-then-linear schedule to keep the trajectory small: decade-log below crossover_ps (with
the default points_per_decade=9 the dumped steps are 1, 2, ..., 9, 10, 20, ..., 90, 100, ...)
and uniform every linear_interval_ps above it. The MSD is computed single-origin (the non-uniform
grid cannot use a multi-time-origin FFT estimator).
Equilibration and production are run at constant volume, so the simulation keeps the density of the input structure. Pass a structure pre-equilibrated at the desired density/pressure to control it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
Input structure (a melt or pre-equilibrated glass); its cell sets the run density. |
required |
potential
|
DataFrame
|
LAMMPS potential as a pandas DataFrame. |
required |
temperature_sim
|
float
|
Production temperature in Kelvin. |
3000.0
|
timestep
|
float
|
MD timestep in femtoseconds. |
1.0
|
production_steps
|
int
|
Number of MD steps in the production stage. |
1000000
|
n_print_thermo
|
int
|
Thermo/log output interval in MD steps. |
100
|
server_kwargs
|
dict[str, Any] | None
|
Additional arguments for the LAMMPS server (e.g. |
None
|
equilibration_steps
|
int
|
Length of the constant-volume equilibration stage in MD steps (use a small value for quick demos, the default for production-quality runs). |
100000
|
thermostat
|
Thermostat
|
Thermostat of the equilibration and production runs, |
required |
seed
|
int
|
Random seed for velocity initialization. |
12345
|
tmp_working_directory
|
str | Path | None
|
Directory for temporary simulation files. |
None
|
max_lag
|
int | None
|
Largest lag (frames) reported in the MSD. |
None
|
remove_com_drift
|
bool
|
Subtract the centre-of-mass drift before computing the MSD. |
True
|
crossover_ps
|
float
|
Log/linear crossover time in ps. |
100.0
|
points_per_decade
|
int
|
Decade-log dump points per decade below the crossover (9 → 1..9, 10..90, ...). |
9
|
linear_interval_ps
|
float
|
Uniform dump interval in ps above the crossover. |
10.0
|
save_trajectory
|
str | Path | None
|
If given, write the trajectory to this path (gzipped extXYZ when it ends in
|
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with |
dict[str, Any]
|
|
dict[str, Any]
|
(:func: |
Example
Source code in amorphouspy/src/amorphouspy/properties/diffusion.py
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 | |
elastic_simulation(structure: Atoms, potential: pd.DataFrame, temperature_sim: float = 300.0, npt_pressure: float | None = None, timestep: float = 1.0, equilibration_steps: int = 1000000, production_steps: int = 10000, n_dump: int | None = None, n_print_thermo: int | None = 1, strain: float = 0.001, server_kwargs: dict[str, Any] | None = None, *, ensemble: Ensemble, seed: int = 12345, tmp_working_directory: str | Path | None = None) -> dict[str, Any]
¶
Perform a LAMMPS-based elastic constant simulation via the stress-strain method.
This workflow calculates the elastic stiffness tensor (Cij) using finite differences. It equilibrates the structure, applies small normal and shear strains, and measures the resulting stress response to determine the elastic constants.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
Input structure (assumed pre-equilibrated). |
required |
potential
|
DataFrame
|
LAMMPS potential file. |
required |
temperature_sim
|
float
|
Simulation temperature in Kelvin (default 300.0 K). |
300.0
|
npt_pressure
|
float | None
|
Target pressure in GPa. Required for the |
None
|
timestep
|
float
|
MD integration timestep in femtoseconds (default 1.0 fs). |
1.0
|
equilibration_steps
|
int
|
Number of steps for the initial equilibration phase (default 1,000,000). |
1000000
|
production_steps
|
int
|
Number of MD steps for the production run (default 10,000). |
10000
|
n_dump
|
int | None
|
Dump output frequency (default None, i.e., dump only at final step). |
None
|
n_print_thermo
|
int | None
|
Thermodynamic output frequency (default 1). |
1
|
strain
|
float
|
Magnitude of the strain applied for finite differences (default 1e-3). |
0.001
|
server_kwargs
|
dict[str, Any] | None
|
Additional server configuration arguments. |
None
|
ensemble
|
Ensemble
|
Ensemble of the equilibration and production runs, one of |
required |
seed
|
int
|
Random seed for velocity initialization (default 12345). |
12345
|
tmp_working_directory
|
str | Path | None
|
Temporary directory for job execution. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing the results. Key "result" contains the "Cij" 6x6 matrix. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
- The structure is first equilibrated (NPT/NVT).
- Positive and negative strains are applied to cancel lower-order errors (central difference).
- Calculated Cij values assume Voigt notation.
- For production simulations, system size, cooling rate, equilibration time, and strain magnitude should be tested to ensure the robustness of the results.
Example
result = elastic_simulation( ... structure=my_atoms, ... potential=my_potential, ... temperature_sim=300.0, ... ensemble="nvt", ... strain=0.001 ... )
Source code in amorphouspy/src/amorphouspy/properties/elastic.py
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 | |
extract_composition(composition: dict[str, float], tolerance: float = COMPOSITION_TOLERANCE) -> dict[str, float]
¶
Validate and normalize a composition dictionary.
Handles both fractional (0.0-1.0) and percentage (0-100) inputs. Always returns fractions summing to 1.0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
composition
|
dict[str, float]
|
A dictionary mapping oxide formulas to their fractions, e.g. {"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}. |
required |
tolerance
|
float
|
Maximum allowed fractional deviation from 1.0. Defaults to
|
COMPOSITION_TOLERANCE
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
A dictionary mapping oxide formulas to their molar fractions. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the composition is empty, contains invalid elements, non-neutral oxides, or sums to an invalid total. |
Source code in amorphouspy/src/amorphouspy/fabrication/composition.py
extract_equilibration_frames(final_structure: Atoms, simulation_history: list[dict[str, Any]] | None = None) -> list[Atoms]
¶
Reconstruct Atoms snapshots from the final equilibration stage.
Falls back to a single-element list with final_structure when no simulation history is available or the history contains no position data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
final_structure
|
Atoms
|
The quenched structure from the melt-quench pipeline. |
required |
simulation_history
|
list[dict[str, Any]] | None
|
Full stage-by-stage MD history (optional). |
None
|
Returns:
| Type | Description |
|---|---|
list[Atoms]
|
List of ASE Atoms frames suitable for averaging. |
Source code in amorphouspy/src/amorphouspy/fabrication/meltquench.py
find_rdf_minimum(r: np.ndarray, rdf_data: np.ndarray, sigma: float = 2.0, window_length: int = 21, polyorder: int = 3) -> float | None
¶
Identify the first minimum in a radial distribution function (RDF) curve.
The function applies Gaussian and Savitzky-Golay smoothing to reduce noise, detects the first peak, and searches for the first subsequent minimum using gradient sign changes. If no valid minimum is found, it falls back to detecting where the RDF drops below 1.0 after the peak.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r
|
ndarray
|
Array of radial distances (Å), assumed to be uniformly spaced. |
required |
rdf_data
|
ndarray
|
RDF values corresponding to |
required |
sigma
|
float
|
Standard deviation for Gaussian smoothing. |
2.0
|
window_length
|
int
|
Window length for Savitzky-Golay filter. Must be odd. |
21
|
polyorder
|
int
|
Polynomial order for Savitzky-Golay filter. |
3
|
Returns:
| Type | Description |
|---|---|
float | None
|
The radial distance of the first minimum (Å) if found, otherwise |
Example
r = np.linspace(0, 10, 100) rdf = np.sin(r) + 1.0 # Dummy data min_r = find_rdf_minimum(r, rdf)
Source code in amorphouspy/src/amorphouspy/properties/structural/all.py
fit_arrhenius(temperatures: NDArray[np.float64] | list[float], diffusivities: NDArray[np.float64] | list[float]) -> tuple[tuple[float, float], NDArray[np.float64]]
¶
Fit an Arrhenius law D(T) = D0 * exp(-Ea / (kB T)) to diffusion data.
Performs a linear fit of ln D versus 1/T.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
temperatures
|
NDArray[float64] | list[float]
|
Temperatures in Kelvin (length >= 2). |
required |
diffusivities
|
NDArray[float64] | list[float]
|
Diffusion coefficients at each temperature (any consistent unit; |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
Tuple |
NDArray[float64]
|
|
Example
import numpy as np kb = 8.617333262e-5 temps = np.array([2000.0, 2500.0, 3000.0, 3500.0]) d0_true, ea_true = 1e-3, 1.2 d_vals = d0_true * np.exp(-ea_true / (kb * temps)) (d0, ea), _ = fit_arrhenius(temps, d_vals) bool(np.isclose(ea, ea_true, atol=1e-6)) True
Source code in amorphouspy/src/amorphouspy/properties/diffusion.py
fit_vft(T_data: ArrayLike, log10_eta_data: ArrayLike, initial_guess: tuple[float, float, float] = (-3, 1000, 200)) -> tuple[tuple[float, float, float], NDArray[np.float64]]
¶
Fits viscosity data to the Vogel-Fulcher-Tammann (VFT) model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
T_data
|
ArrayLike
|
Temperatures in Kelvin. |
required |
log10_eta_data
|
ArrayLike
|
log10(viscosity) values. |
required |
initial_guess
|
tuple[float, float, float]
|
Initial guess for (log10_eta0, B, T0). |
(-3, 1000, 200)
|
Returns:
| Type | Description |
|---|---|
tuple[tuple[float, float, float], NDArray[float64]]
|
A tuple containing the best-fit parameters and the covariance matrix. |
Example
params, cov = fit_vft(temps, log_visc_data) log10_eta0, B, T0 = params
Source code in amorphouspy/src/amorphouspy/properties/viscosity.py
formula_mass_g_per_mol(formula: str) -> float
¶
Calculate the molar mass of a compound using ASE atomic masses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formula
|
str
|
A string representing the chemical formula (e.g., "SiO2"). |
required |
Returns:
| Type | Description |
|---|---|
float
|
The molar mass of the compound in grams per mole. |
Source code in amorphouspy/src/amorphouspy/fabrication/composition.py
frames_from_melt_quench_result(result: dict, initial_structure: Atoms, *, stage: int = -1, stride: int = 1) -> list[Atoms]
¶
Extract trajectory frames from a melt_quench_simulation result dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
dict
|
The dict returned by :func: |
required |
initial_structure
|
Atoms
|
The |
required |
stage
|
int
|
Index into |
-1
|
stride
|
int
|
Take every stride-th frame. Defaults to |
1
|
Returns:
| Type | Description |
|---|---|
list[Atoms]
|
A list of :class: |
list[Atoms]
|
per-frame thermo data stored in |
list[Atoms]
|
(forces, velocities, unwrapped positions) in |
Example
result = melt_quench_simulation(atoms, potential, thermostat="nose_hoover") frames = frames_from_melt_quench_result(result, atoms) (r, rdfs_mean, cumcn_mean, rdfs_sem, cumcn_sem), _ = average_over_frames( ... compute_rdf, frames, r_max=8.0 ... )
Source code in amorphouspy/src/amorphouspy/lammps/io.py
generate_bond_length_dict(atoms: Atoms, specific_cutoffs: dict[tuple[str, str], float] | None = None, default_cutoff: float = 0.0) -> dict[tuple[str, str], float]
¶
Generate all symmetric element pairs and assign bond length cutoffs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atoms
|
Atoms
|
ASE Atoms object whose species determine the pair set. |
required |
specific_cutoffs
|
dict[tuple[str, str], float] | None
|
Optional cutoff overrides for specific element
pairs. Both orderings |
None
|
default_cutoff
|
float
|
Fallback bond length for pairs not in
|
0.0
|
Returns:
| Type | Description |
|---|---|
dict[tuple[str, str], float]
|
Dictionary mapping every symmetric element pair to its cutoff. |
Examples:
>>> from ase.io import read
>>> structure = read('glass.xyz')
>>> bond_lengths = generate_bond_length_dict(
... structure,
... specific_cutoffs={('Si', 'O'): 1.8},
... default_cutoff=2.0,
... )
Source code in amorphouspy/src/amorphouspy/properties/structural/rings.py
generate_potential(atoms_dict: dict, potential_type: str = 'pmmcs', *, electrostatics: InteractionConfig | None = None, use_three_body: bool = False, model_path: str | Path | None = None) -> pd.DataFrame
¶
Generate LAMMPS potential configuration for glass simulations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atoms_dict
|
dict
|
Structure dict from |
required |
potential_type
|
str
|
One of |
'pmmcs'
|
electrostatics
|
InteractionConfig | None
|
Coulomb solver settings. Defaults to DSF with each potential's built-in cutoffs and damping parameter. |
None
|
use_three_body
|
bool
|
For du_teter potential, include Stillinger-Weber three-body terms for O-P-O / P-O-P interactions (requires P in composition). No effect for other potentials. |
False
|
model_path
|
str | Path | None
|
For the grace potential, an explicit path to an already-exported
native GRACE-FS YAML file; None uses the default cache location. Only valid
when |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns Name, Filename, Model, Species, Config. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If use_three_body is True for a non-du_teter potential, or if model_path is given for a non-grace potential. |
Example
potential = generate_potential(struct_dict, potential_type="shik") potential = generate_potential(struct_dict, potential_type="bmp-harmonic") potential = generate_potential(struct_dict, potential_type="bmp-screened-harmonic") potential = generate_potential(struct_dict, potential_type="du_teter", use_three_body=True) potential = generate_potential(struct_dict, potential_type="yang2026") potential = generate_potential(struct_dict, potential_type="grace") potential = generate_potential(struct_dict, potential_type="grace", model_path="/data/models/FS_model.yaml")
Source code in amorphouspy/src/amorphouspy/lammps/potentials/potential.py
generate_structure(composition: dict[str, float], n_atoms: int = 6000, potential_type: str = 'pmmcs', density: float | None = None, structure_seed: int = 42, *, electrostatics_config: InteractionConfig | None = None, use_three_body: bool = False, model_path: str | Path | None = None) -> dict[str, Any]
¶
Generate an initial random structure and matching LAMMPS potential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
composition
|
dict[str, float]
|
Oxide composition as |
required |
n_atoms
|
int
|
Target number of atoms. |
6000
|
potential_type
|
str
|
Name of the interatomic potential to generate. |
'pmmcs'
|
density
|
float | None
|
Target density in g/cm³; |
None
|
structure_seed
|
int
|
Random seed for atom placement. |
42
|
electrostatics_config
|
InteractionConfig | None
|
Electrostatics configuration (e.g. |
None
|
use_three_body
|
bool
|
For du_teter potential, include Stillinger-Weber three-body terms for O-P-O / P-O-P interactions (requires P in composition). |
False
|
model_path
|
str | Path | None
|
For the grace potential, an explicit path to an already-exported
native GRACE-FS YAML file. Only valid when |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with |
Source code in amorphouspy/src/amorphouspy/pipelines/meltquench.py
get_ase_structure(atoms_dict: dict, replicate: tuple[int, int, int] = (1, 1, 1)) -> Atoms
¶
Generate a LAMMPS data file format string and read into an ASE Atoms object.
Based on the specifications in the provided atoms_dict, this function generates a LAMMPS data file format string, which is then read into an ASE Atoms object. The ASE Atoms object is then returned. atoms_dict is expected to specify a cubic box. Triclinic boxes are not supported.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atoms_dict
|
dict
|
Dictionary that must contain the atom counts and box dimensions under the keys "atoms" and "box". |
required |
replicate
|
tuple[int, int, int]
|
Replication factors for the box in x, y, and z directions. Default is (1, 1, 1), meaning no replication. |
(1, 1, 1)
|
Returns:
| Type | Description |
|---|---|
Atoms
|
ASE Atoms object of the specified structure. |
Example
struct_dict = get_structure_dict({"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}, target_atoms=1000) atoms = get_ase_structure(struct_dict)
Source code in amorphouspy/src/amorphouspy/fabrication/geometry.py
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 | |
get_atomic_mass(element: str | int) -> float
¶
Get the atomic mass of an element.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
element
|
str | int
|
Chemical symbol or atomic number. Multi-valence BMP labels like "Fe3" or "Ce4" are resolved to their base symbol ("Fe", "Ce"). |
required |
Returns:
| Type | Description |
|---|---|
float
|
Atomic mass in g/mol. |
Example
mass = get_atomic_mass("Si") print(mass) 28.085
Source code in amorphouspy/src/amorphouspy/atoms/mass.py
get_composition(composition: dict[str, float], mode: str = 'molar') -> dict[str, float]
¶
Convert a composition dictionary into normalized molar fractions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
composition
|
dict[str, float]
|
A dictionary mapping oxide formulas to their fractions, e.g. {"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}. |
required |
mode
|
str
|
The interpretation mode, either 'molar' or 'weight'. Defaults to "molar". |
'molar'
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
A dictionary mapping oxide formulas to their molar fractions. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in amorphouspy/src/amorphouspy/fabrication/composition.py
get_diffusion(msd_result: dict[str, Any], *, fit_start_frac: float = 0.2, fit_end_frac: float = 0.8, dimensionality: int = 3) -> dict[str, Any]
¶
Estimate self-diffusion coefficients from an MSD via the Einstein relation.
Fits MSD = 2 * d * D * t over the diffusive window and reports D in cm^2/s and m^2/s. A
warning is emitted if the log-log MSD slope in the window deviates from 1 (sub-diffusive).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msd_result
|
dict[str, Any]
|
Output of :func: |
required |
fit_start_frac
|
float
|
Start of the fit window as a fraction of the number of lags. |
0.2
|
fit_end_frac
|
float
|
End of the fit window as a fraction of the number of lags. |
0.8
|
dimensionality
|
int
|
Spatial dimensionality |
3
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with |
dict[str, Any]
|
input was species-resolved. Each entry holds |
dict[str, Any]
|
|
Example
Source code in amorphouspy/src/amorphouspy/properties/diffusion.py
get_glass_density_from_model(composition: dict[str, float]) -> float
¶
Calculate the room-temperature glass density using Fluegel's empirical model.
The model uses a polynomial expansion based on mole percentages of oxides. Source: Fluegel, A. "Global Model for Calculating Room-Temperature Glass Density from the Composition", J. Am. Ceram. Soc., 90 [8] 2622-2635 (2007).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
composition
|
dict[str, float]
|
A dictionary mapping oxide formulas to their fractions. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The calculated density in g/cm^3. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the composition contains components unsupported by the model or if the format is invalid. |
Example
density = get_glass_density_from_model({"SiO2": 0.75, "Na2O": 0.25})
Source code in amorphouspy/src/amorphouspy/fabrication/density.py
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 | |
get_neighbors(atoms: Atoms | tuple[np.ndarray, np.ndarray, np.ndarray], cutoff: float | dict[tuple[int, int], float], target_types: int | list[int] | None = None, neighbor_types: int | list[int] | None = None, *, return_vectors: bool = False, use_numba: bool | None = None) -> list[tuple]
¶
Find all neighbors within cutoff for each atom.
Returns a list of tuples where all IDs are the real atom IDs from the structure file (e.g. non-sequential LAMMPS/XYZ ids), not array indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atoms
|
Atoms | tuple[ndarray, ndarray, ndarray]
|
Either an ASE Atoms object or a tuple (coords, types, cell_matrix)
where cell_matrix is a (3,3) array with lattice vectors as rows.
For an Atoms object |
required |
cutoff
|
float | dict[tuple[int, int], float]
|
Cutoff radius in Angstrom. Either: - A single float applied uniformly to all pairs. - A dict mapping (atomic_number_i, atomic_number_j) to a pair-specific cutoff in Angstrom. Symmetric: (8, 14) and (14, 8) are equivalent. Pairs not listed default to the maximum cutoff in the dict. The cell list is built on the maximum cutoff so only one build is needed. |
required |
target_types
|
int | list[int] | None
|
Atomic numbers of atoms to find neighbors for. A bare atomic number is accepted and treated as a one-element list. None means all atoms. |
None
|
neighbor_types
|
int | list[int] | None
|
Atomic numbers that count as valid neighbors. A bare atomic number is accepted. None means all types. |
None
|
return_vectors
|
bool
|
If True, each output tuple gains a third element — a (k, 3) float64 array of Cartesian minimum-image bond vectors r_i - r_j in Angstrom, i.e. pointing from the neighbour to the central atom (the opposite sign of ASE's neighbor_list "D"). Scalar distances are np.linalg.norm(vectors, axis=1). |
False
|
use_numba
|
bool | None
|
Force Numba on/off. None = auto-detect. |
None
|
Returns:
| Type | Description |
|---|---|
list[tuple]
|
If return_vectors=False (default): [(central_id, [neighbor_ids]), ...] |
list[tuple]
|
If return_vectors=True: [(central_id, [neighbor_ids], vectors_shape_k3), ...] |
Examples:
Scalar cutoff (backward compatible)::
>>> neighbors = get_neighbors(atoms, cutoff=3.5)
>>> for central_id, nn_ids in neighbors:
... print(central_id, nn_ids)
Per-pair cutoffs for a Na2O-Al2O3-SiO2 glass::
>>> cutoff = {(14, 8): 2.0, (13, 8): 1.9, (11, 8): 2.7}
>>> neighbors = get_neighbors(atoms, cutoff=cutoff)
With bond vectors for Steinhardt parameters::
>>> result = get_neighbors(atoms, cutoff=3.5, return_vectors=True)
>>> for central_id, nn_ids, vecs in result:
... distances = np.linalg.norm(vecs, axis=1)
... print(f"atom {central_id}: mean bond length = {distances.mean():.3f} A")
Quick lookup by original atom ID::
>>> nl = {cid: nn for cid, nn, *_ in get_neighbors(atoms, cutoff=3.5)}
>>> nl[43586]
Source code in amorphouspy/src/amorphouspy/atoms/neighbors.py
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 | |
get_structure_dict(composition: dict[str, float], n_molecules: int | None = None, target_atoms: int | None = None, mode: str = 'molar', density: float | None = None, min_distance: float = 1.6, max_attempts_per_atom: int = 10000, random_seed: int = 42) -> dict
¶
Generate a structure dictionary for a given composition.
Supports both n_molecules and target_atoms input modes, and both molar and weight composition modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
composition
|
dict[str, float]
|
A dictionary mapping oxide formulas to their fractions, e.g. {"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}. |
required |
n_molecules
|
int | None
|
Total number of molecules (traditional mode). |
None
|
target_atoms
|
int | None
|
Target number of atoms (new mode). |
None
|
mode
|
str
|
Composition mode: "molar" for mol%, "weight" for weight%. |
'molar'
|
density
|
float | None
|
Density in g/cm^3, default is calculated from model. |
None
|
min_distance
|
float
|
Minimum distance between any two atoms in angstroms, default is 1.6 Å. |
1.6
|
max_attempts_per_atom
|
int
|
Maximum attempts to place an atom before giving up, default is 10000. |
10000
|
random_seed
|
int
|
Random seed for reproducibility, default is 42. |
42
|
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary containing: - "atoms": A list of atom dictionaries with keys "element" and "position" - "box": The length of the cubic box in angstroms - "formula_units": Dictionary of oxide formula units - "total_atoms": Total number of atoms - "element_counts": Dictionary of element counts (if target_atoms mode) - "mol_fraction": Dictionary of molar fractions (if target_atoms mode) |
Example
struct_dict = get_structure_dict( ... composition={"CaO": 0.25, "Al2O3": 0.25, "SiO2": 0.5}, ... target_atoms=1000, ... mode="molar" ... )
Source code in amorphouspy/src/amorphouspy/fabrication/geometry.py
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 | |
get_viscosity(result: dict[str, Any], timestep: float = 1.0, output_frequency: int = 1, max_lag: int | None = 1000000, cutoff_method: str = 'noise_threshold') -> dict[str, float]
¶
Compute viscosity using the Green-Kubo formalism from MD stress data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
dict[str, Any]
|
Parsed output dictionary from |
required |
timestep
|
float
|
MD integration time step in femtoseconds. |
1.0
|
output_frequency
|
int
|
Number of MD steps between stored frames in the output. |
1
|
max_lag
|
int | None
|
Maximum correlation lag (number of steps). Defaults to 1,000,000. |
1000000
|
cutoff_method
|
str
|
Method passed to |
'noise_threshold'
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
A dictionary containing: - temperature: Mean simulation temperature (K) - viscosity: Computed viscosity (Pa·s) - max_lag: Cutoff time per stress component (ps) - lag_time_ps: Array of lag times in picoseconds - sacf: Averaged normalized stress autocorrelation function - viscosity_integral: Cumulative viscosity integral (Pa·s) vs lag time |
Example
result_dict = get_viscosity(simulation_output, timestep=1.0, output_frequency=1, max_lag=1000000) print(result_dict['viscosity']) print(result_dict['sacf']) print(result_dict['viscosity_integral'])
Source code in amorphouspy/src/amorphouspy/properties/viscosity.py
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 | |
harmonic_vdos_simulation(structure: Atoms, potential: pd.DataFrame, server_kwargs: dict[str, Any] | None = None, *, max_atoms: int = 10000, displacement: float = 1e-05, force_tolerance: float = 1e-06, max_iter: int = 100000, broadening_thz: float = 0.2, frequency_grid_thz: ArrayLike | None = None, normalization: HarmonicNormalization = 'unit', temperatures_k: ArrayLike | None = None, cutoff: CutoffSpec | None = None, former_types: list[int] | None = None, o_type: int = 8, driver: EigenDriver = 'evr', imaginary_threshold_thz: float = 0.01, tmp_working_directory: str | Path | None = None, keep_dynamical_matrix: bool = False, keep_eigenvectors: bool = False, infrared: bool = False, charges: ArrayLike | None = None, eps_inf: float = 1.0, ir_damping_thz: float = 0.5) -> dict[str, Any]
¶
Minimise a structure, compute its finite-difference dynamical matrix and return the harmonic VDOS and modes.
The harmonic counterpart of :func:vdos_simulation: the VDOS of the 0 K inherent structure from its normal modes,
with no MD and no statistical noise. Steps:
- Minimisation at fixed cell and the dynamical matrix, both in LAMMPS (
_run_lammps_dynamical_matrix). - The atom groups (element, oxygen class, \(\mathrm{Q}^n\)) with :func:
classify_vibrational_groupsand the masses, both from the minimised structure. - The matrix is read with :func:
read_dynamical_matrixand diagonalised in place with :func:diagonalize_dynamical_matrix, which drops the three translations. - The broadened VDOS and its group partials with :func:
compute_harmonic_vdos, the participation ratio of every mode with :func:compute_participation_ratioand, withtemperatures_k, the harmonic thermodynamics with :func:compute_vibrational_thermodynamics.
The structure is used as given. Preparing it (melt-quench, NPT relaxation to the target pressure) is the caller's
job; this function adds only the minimisation. The minimisation uses FIRE at fixed cell
(min_style="fire", no box/relax) down to force_tolerance, the LAMMPS ftol: the 2-norm of the global
force vector in eV/Å, not a per-atom maximum. A fixed cell leaves a residual pressure, reported in
"minimization" ("pressure_gpa" and "mean_pressure_gpa"; for FIRE they also hold the kinetic term of
the residual velocities), together with the iteration count, the stopping criterion and the final forces. If the
tolerance is not reached, the minimiser warns and the result is still returned; the step-0 forces of the
structure that was differentiated are in "dynamical_matrix" ("max_force_ev_per_a").
Finite differences: each entry of the matrix is a central difference of the forces with step displacement.
Imaginary modes are reported as negative frequencies in "mode_frequencies_thz". Those below
-imaginary_threshold_thz are counted in "diagonalization" ("n_imaginary", with a warning that names
the asymmetry atoms); they point at an incomplete minimisation or a corrupted entry. Every negative frequency is
left out of the VDOS ("n_imaginary_excluded" and "imaginary_weight") and of the thermodynamics.
max_atoms guards against an accidental large run: above it the function raises before anything runs, and the
message gives the matrix size and the expected peak. It can be raised deliberately.
The groups are classified on the minimised structure, the one whose modes are computed. Errors in cutoff,
former_types or o_type therefore surface only after the LAMMPS runs.
The thermodynamics is computed from the broadened total VDOS on the frequency grid, not from a sum over the modes,
with lowest_frequency_thz set to the smallest positive mode frequency, the lowest mode the box supports: the
values below its temperature are flagged as unreliable. With normalization="3N" the total is divided by 3N
first, as :func:compute_vibrational_thermodynamics needs a VDOS normalised to 1. On the 300-atom PMMCS glass at
300 K with the default 0.2 THz broadening, the values differ from an exact sum over the modes by -1.3e-5 (C_V),
8.5e-4 (S), 3.0e-5 (U) and -3.7e-4 (F), relative. The default grid starts at 0, so modes within a few
broadening_thz of 0 lose part of their weight ("excluded_weight" and "vdos_integral" report it).
Disk and memory: the matrix file takes 9 N² x 8 bytes (2.6 GB at 6000 atoms, 7.2 GB at 10,000) and is deleted once
it is read unless keep_dynamical_matrix. It is written under tmp_working_directory or, if that is None,
under the system temporary directory (tempfile.gettempdir(), set by TMPDIR); the free space there is
checked before anything runs. The peak in memory is still 2 matrices, during the diagonalisation.
Without the eigenvectors, the result holds only O(M x number of labels) floats (the mode frequencies, participation
ratios and group weights) plus the VDOS curves on the frequency grid. An eigenvector-based analysis later needs
keep_eigenvectors=True or a rerun.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
The structure, e.g. a quenched and NPT-relaxed glass, used as given. It is not modified. |
required |
potential
|
DataFrame
|
LAMMPS potential as a pandas DataFrame. |
required |
server_kwargs
|
dict[str, Any] | None
|
Additional arguments for the LAMMPS server (e.g. |
None
|
max_atoms
|
int
|
Largest number of atoms accepted, a positive integer. |
10000
|
displacement
|
float
|
Finite-difference displacement in Å. |
1e-05
|
force_tolerance
|
float
|
FIRE stops when the 2-norm of the global force vector is below this, in eV/Å. |
1e-06
|
max_iter
|
int
|
Maximum number of FIRE iterations. |
100000
|
broadening_thz
|
float
|
Standard deviation of the Gaussian broadening of each mode in THz (not the FWHM). |
0.2
|
frequency_grid_thz
|
ArrayLike | None
|
Frequencies in THz at which the VDOS is evaluated, 1-D, finite and strictly increasing.
|
None
|
normalization
|
HarmonicNormalization
|
|
'unit'
|
temperatures_k
|
ArrayLike | None
|
Temperatures in K for the harmonic thermodynamics, a scalar or a 1-D array of finite values
|
None
|
cutoff
|
CutoffSpec | None
|
Former-O cutoff in Å for the groups, as in :func: |
None
|
former_types
|
list[int] | None
|
Atomic numbers of the network formers. Derived from the composition if |
None
|
o_type
|
int
|
Atomic number of oxygen. |
8
|
driver
|
EigenDriver
|
LAPACK driver of |
'evr'
|
imaginary_threshold_thz
|
float
|
A mode below |
0.01
|
tmp_working_directory
|
str | Path | None
|
Directory for the LAMMPS runs and the matrix file. The run directories, with their
logs, input and data files, are kept. The matrix file goes to its own |
None
|
keep_dynamical_matrix
|
bool
|
Keep the matrix file, in |
False
|
keep_eigenvectors
|
bool
|
Return the eigenvectors in |
False
|
infrared
|
bool
|
Also compute the infrared response of the modes: oscillator strengths, dielectric function and
optical constants, returned in |
False
|
charges
|
ArrayLike | None
|
Atomic charges in units of the elementary charge for the infrared response, shape \((N,)\) or Born
tensors \((N, 3, 3)\), in the order of the atoms. |
None
|
eps_inf
|
float
|
The high-frequency dielectric constant \(\varepsilon_\infty\) of the infrared response; see
:func: |
1.0
|
ir_damping_thz
|
float
|
The damping \(\gamma\) of the dielectric function in THz; see
:func: |
0.5
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dict with:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Before any LAMMPS run, if |
RuntimeError
|
If a LAMMPS run fails or the matrix file is missing or has the wrong size. |
Warns:
| Type | Description |
|---|---|
UserWarning
|
If the minimisation stops on a criterion other than the force or energy tolerance, the
diagonalisation finds imaginary modes or dropped modes that are not translations, a caller's
|
Example
>>> out = harmonic_vdos_simulation(glass, potential, temperatures_k=[300.0]) # doctest: +SKIP
>>> out["minimization"]["converged"], out["diagonalization"]["asymmetry"] # doctest: +SKIP
>>> out["diagonalization"]["n_imaginary"], out["grid_integral"] # doctest: +SKIP
>>> out["vdos"]["oxygen"]["O_BO"] # doctest: +SKIP
>>> out["thermodynamics"]["heat_capacity_kb_per_atom"] # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/harmonic_simulation.py
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 | |
load_lammps_dump(path: str | Path, type_map: dict[int, str] | None = None, *, frame: int | None = None, start: int | None = None, stop: int | None = None, step: int | None = None, return_atoms_dict: bool = False) -> Atoms | list[Atoms] | tuple[Atoms, dict[str, Any]] | list[tuple[Atoms, dict[str, Any]]]
¶
Read a LAMMPS dump file and return ASE Atoms object(s) with correct chemical symbols.
By default the full trajectory is returned as a list. Pass frame to get a single frame, or start / stop / step to slice the trajectory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the LAMMPS dump file. |
required |
type_map
|
dict[int, str] | None
|
Mapping from LAMMPS integer type to element symbol,
e.g. |
None
|
frame
|
int | None
|
Zero-based index of a single frame to read. Mutually exclusive with start / stop / step. |
None
|
start
|
int | None
|
First frame index of the slice (inclusive, default 0). |
None
|
stop
|
int | None
|
Last frame index of the slice (exclusive, default end of file). |
None
|
step
|
int | None
|
Stride between selected frames (default 1). |
None
|
return_atoms_dict
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
Atoms | list[Atoms] | tuple[Atoms, dict[str, Any]] | list[tuple[Atoms, dict[str, Any]]]
|
|
Atoms | list[Atoms] | tuple[Atoms, dict[str, Any]] | list[tuple[Atoms, dict[str, Any]]]
|
|
Atoms | list[Atoms] | tuple[Atoms, dict[str, Any]] | list[tuple[Atoms, dict[str, Any]]]
|
|
Atoms | list[Atoms] | tuple[Atoms, dict[str, Any]] | list[tuple[Atoms, dict[str, Any]]]
|
|
Atoms | list[Atoms] | tuple[Atoms, dict[str, Any]] | list[tuple[Atoms, dict[str, Any]]]
|
Each |
Raises:
| Type | Description |
|---|---|
ValueError
|
If frame is combined with start / stop / step. |
ValueError
|
If type_map is |
Example
Full trajectory¶
frames = load_lammps_dump("run.lammpstrj", type_map={1: "O", 2: "Si"})
Single frame¶
ase_atoms = load_lammps_dump("run.lammpstrj", type_map={1: "O", 2: "Si"}, frame=0)
Frames 30-49¶
frames = load_lammps_dump("run.lammpstrj", type_map={1: "O", 2: "Si"}, start=30, stop=50)
Every 10th frame from 0 to 99¶
frames = load_lammps_dump("run.lammpstrj", type_map={1: "O", 2: "Si"}, start=0, stop=100, step=10)
Source code in amorphouspy/src/amorphouspy/lammps/io.py
log_linear_dump_steps(total_steps: int, *, crossover_steps: int, points_per_decade: int = 9, linear_interval_steps: int, first_step: int = 0) -> list[int]
¶
Return the timesteps of a log-then-linear dump schedule.
Below crossover_steps the spacing is decade-logarithmic (the LAMMPS logfreq pattern): with
the default points_per_decade=9 the steps are 1, 2, ..., 9, 10, 20, ..., 90, 100, 200, ...; at
and above the crossover the spacing is uniform (linear_interval_steps). This reproduces,
bit-for-bit, the schedule realised in LAMMPS by :func:_log_linear_dump_variable, so it can be
used to recover the exact per-frame times of a log-dumped trajectory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
total_steps
|
int
|
Number of production MD steps. |
required |
crossover_steps
|
int
|
Step count corresponding to the log/linear crossover. |
required |
points_per_decade
|
int
|
Log-spaced points per decade below the crossover (9 gives 1..9, 10..90, ...). |
9
|
linear_interval_steps
|
int
|
Uniform dump interval (in steps) at and above the crossover. |
required |
first_step
|
int
|
First dumped step (usually 0). |
0
|
Returns:
| Type | Description |
|---|---|
list[int]
|
Sorted list of dump timesteps (inclusive of first_step, up to total_steps). |
Example
Source code in amorphouspy/src/amorphouspy/properties/diffusion.py
md_simulation(structure: Atoms, potential: pd.DataFrame, temperature_sim: float | None = None, timestep: float = 1.0, production_steps: int = 10000000, n_dump: int | None = 1000, n_print_thermo: int | None = None, server_kwargs: dict | None = None, *, ensemble: Ensemble, temperature_end: float | None = None, npt_pressure: float | None = None, npt_pressure_end: float | None = None, seed: int = 12345, tmp_working_directory: str | Path | None = None, input_control_file: dict | None = None) -> dict
¶
Perform a molecular dynamics simulation using LAMMPS.
This function equilibrates a structure at a predefined temperature and pressure, with optional linear ramps for temperature and/or pressure over the course of the simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
The initial atomic structure to be melted and quenched. |
required |
potential
|
DataFrame
|
The potential file to be used for the simulation. |
required |
temperature_sim
|
float | None
|
Start temperature in K (or constant temperature when |
None
|
timestep
|
float
|
Time step for integration in femtoseconds (default is 1.0 fs). |
1.0
|
production_steps
|
int
|
The number of steps for the production. |
10000000
|
n_dump
|
int | None
|
Interval in MD steps for dumping. If None, only the last frame is dumped. |
1000
|
n_print_thermo
|
int | None
|
Interval in MD steps for printing thermodynamic information.
If None, uses |
None
|
server_kwargs
|
dict | None
|
Additional arguments for the server. |
None
|
ensemble
|
Ensemble
|
Thermodynamic ensemble, one of |
required |
temperature_end
|
float | None
|
End temperature in K for a linear ramp from |
None
|
npt_pressure
|
float | None
|
Start pressure in GPa. Required for |
None
|
npt_pressure_end
|
float | None
|
End pressure in GPa for a linear pressure ramp ( |
None
|
seed
|
int
|
Random seed for velocity initialization (default is 12345). Ignored if |
12345
|
tmp_working_directory
|
str | Path | None
|
Specifies the location of the temporary directory to run the simulations.
Per default (None), the directory is located in the operating systems location for temporary files
and is removed automatically once the run finishes.
With the specification of tmp_working_directory, a uniquely-named sub-directory is created inside
it and left in place afterwards (the caller owns it and is responsible for removing it), so the run
artefacts such as |
None
|
input_control_file
|
dict | None
|
Optional LAMMPS input overrides merged on top of the default generated controls. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary containing the simulation steps and temperature data. |
Source code in amorphouspy/src/amorphouspy/lammps/md.py
melt_quench_simulation(structure: Atoms, potential: pd.DataFrame, temperature_high: float | None = None, temperature_low: float = 300.0, timestep: float = 1.0, cooling_rate: float | None = None, n_dump: int | None = None, n_print_thermo: int | None = 100, equilibration_steps: int | None = None, *, server_kwargs: dict | None = None, thermostat: Thermostat, seed: int = 12345, tmp_working_directory: str | Path | None = None, pre_equilibrate: bool = True, pre_equilibration_seed: int = DEFAULT_PRE_EQUILIBRATION_SEED) -> dict
¶
Perform a melt-quench simulation using LAMMPS.
This function equilibrates the liquid directly at a high temperature and
then cools it down to a low temperature, simulating a melt-quench process.
There is no heating ramp: every protocol optionally pre-equilibrates the
random structure at temperature_high (stage 0) and then equilibrates the
melt at that temperature. The cooling rate is given in K/s, and the
conversion into simulation steps is done automatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
The initial atomic structure to be melted and quenched. |
required |
potential
|
DataFrame
|
The potential file to be used for the simulation. |
required |
temperature_high
|
float | None
|
The melt temperature at which the liquid is equilibrated. If None, the protocol's default melt temperature is used (e.g. 4000 K for SHIK, 5000 K for others). |
None
|
temperature_low
|
float
|
The low temperature to which the structure will be cooled. |
300.0
|
timestep
|
float
|
Time step for integration in femtoseconds. |
1.0
|
cooling_rate
|
float | None
|
The rate at which the temperature is decreased during the cooling phase, in K/s. If None, the protocol's default cooling rate is used (1e13 K/s for GRACE, 1e12 K/s for others). |
None
|
n_dump
|
int | None
|
Dump frequency in simulation steps. If None, falls back to the final step so only the last structure is dumped. |
None
|
n_print_thermo
|
int | None
|
Thermodynamic print frequency in simulation steps. If None, uses n_dump. |
100
|
equilibration_steps
|
int | None
|
Override for all fixed equilibration stages inside the protocol. If None, each protocol uses its own hardcoded defaults. |
None
|
server_kwargs
|
dict | None
|
Additional keyword arguments for the server. |
None
|
thermostat
|
Thermostat
|
Thermostat of all protocol stages, |
required |
seed
|
int
|
Random seed for velocity initialization. Ignored if |
12345
|
tmp_working_directory
|
str | Path | None
|
Specifies the location of the temporary directory to run the simulations. |
None
|
pre_equilibrate
|
bool
|
Run a Langevin + nve/limit pre-equilibration block at
|
True
|
pre_equilibration_seed
|
int
|
Seed of the Langevin random forces of the pre-equilibration
stage. Independent of |
DEFAULT_PRE_EQUILIBRATION_SEED
|
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary containing the simulation steps and temperature data. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the resolved |
Example
result = melt_quench_simulation( ... structure=my_atoms, ... potential=my_potential, ... temperature_high=5000.0, ... temperature_low=300.0, ... cooling_rate=1e12, ... thermostat="nose_hoover", ... )
Source code in amorphouspy/src/amorphouspy/fabrication/meltquench.py
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 | |
parse_formula(formula: str) -> dict[str, int]
¶
Parse a chemical formula and returns a dictionary of element counts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formula
|
str
|
A string representing the chemical formula (e.g., "Al2O3"). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict[str, int]
|
A dictionary mapping element symbols to their counts. |
|
Example |
dict[str, int]
|
{"Al": 2, "O": 3} for "Al2O3". |
Source code in amorphouspy/src/amorphouspy/fabrication/composition.py
plan_system(composition: dict[str, float], target: int, mode: str = 'molar', target_type: str = 'atoms') -> dict
¶
Generate a comprehensive plan for the system composition and size.
This unified planner handles both 'atoms' and 'molecules' target types, converting them into a concrete allocation of formula units and atoms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
composition
|
dict[str, float]
|
A dictionary mapping oxide formulas to their fractions. |
required |
target
|
int
|
The target count (atoms or molecules depending on |
required |
mode
|
str
|
The composition mode ('molar' or 'weight'). Defaults to "molar". |
'molar'
|
target_type
|
str
|
The type of target ('atoms' or 'molecules'). Defaults to "atoms". |
'atoms'
|
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary containing: - "mol_fraction": Dictionary of molar fractions. - "formula_units": Dictionary of allocated integer formula units. - "total_atoms": The actual total number of atoms. - "element_counts": Dictionary of total counts per element. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in amorphouspy/src/amorphouspy/fabrication/planner.py
plot_analysis_results_plotly(structure_data: StructureData) -> go.Figure
¶
Generate interactive Plotly plots for structural analysis results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure_data
|
StructureData
|
Structural analysis results. |
required |
Returns:
| Type | Description |
|---|---|
Figure
|
Interactive Plotly figure object. |
Example
fig = plot_analysis_results_plotly(structure_data) fig.show()
Source code in amorphouspy/src/amorphouspy/properties/structural/all.py
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 | |
read_dynamical_matrix(path: str | Path, n_atoms: int, *, binary: bool = True, style: DynamicalMatrixStyle = 'regular') -> NDArray[np.float64]
¶
Read a dynamical-matrix file written by the LAMMPS dynamical_matrix command.
The dynamical matrix is the mass-weighted Hessian
with \(E\) the potential energy, \(r_{i\alpha}\) the coordinates and \(m_i\) the masses. It is returned in eV/Ų/amu
(LAMMPS regular in metal units). An eigenvalue \(\lambda\) of \(D\) gives the angular frequency
\(\omega = \sqrt{\lambda}\) and the frequency \(\nu = \sqrt{\lambda} / (2\pi)\), where
\(\sqrt{1\ \mathrm{eV/Å^2/amu}}\) corresponds to \(\nu = 15.633\) THz. Row and column \(3i + \alpha\) belong to atom
\(i\) (0-based, the LAMMPS atom id minus one) and \(\alpha \in \{x, y, z\}\) (\(0, 1, 2\)), so the atom order is the
LAMMPS id order. For files written by _run_lammps_dynamical_matrix that is the order of the atoms in the
structure.
The matrix is returned as written, NOT symmetrised. A finite-difference matrix is symmetric only to the difference error, and a larger asymmetry \(\max|D - D^\mathsf{T}| / \max|D|\) flags corrupted entries, for example a pair that crosses a cutoff with a force jump during a displacement. The asymmetry is therefore left for the caller to measure before symmetrising.
File formats (verified on LAMMPS 29 Aug 2024):
binary=True(binary yes): raw float64 in native byte order, no header, exactly \(9 N^2 \times 8\) bytes. It is read withnp.fromfileand reshaped without a copy.binary=False(binary no): three values per line in%.8f, one line per atom of a row, so each matrix row spans \(N\) lines. Eight fixed decimals limit the precision to \(5 \times 10^{-9}\) eV/Ų/amu absolute. The text is parsed withnp.loadtxt, which is about six times faster thannp.fromfile(sep=" ")here.
With style="eskm" the file holds the matrix in 10 J/mol/Ų/(g/mol); it is divided in place by 9648.5, the
factor LAMMPS uses (the CODATA value \(e N_\mathrm{A} / 10 = 9648.533\) differs by \(3.4 \times 10^{-6}\)), and
returned in eV/Ų/amu.
Memory: the result is one array of \(9 N^2 \times 8\) bytes, 2.6 GB at 6000 atoms and 7.2 GB at 10,000. A binary
read needs nothing more. Parsing text peaks at about 2.2 times the matrix (numpy allocations measured at 1000 and
2000 atoms), about 16 GB at 10,000 atoms. Non-finite values are checked in blocks of rows, so the check adds at
most _CHUNK_BYTES / 8 bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The dynamical-matrix file. |
required |
n_atoms
|
int
|
Number of atoms \(N\) in the structure the matrix was computed on. |
required |
binary
|
bool
|
True for a file written with |
True
|
style
|
DynamicalMatrixStyle
|
The LAMMPS style the file was written with, |
'regular'
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
The \((3N, 3N)\) dynamical matrix in eV/Ų/amu, float64, C-contiguous and writable. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
FileNotFoundError
|
If |
Example
Source code in amorphouspy/src/amorphouspy/properties/vibrational/dynamical_matrix.py
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 | |
run_melt_quench(structure: Atoms, potential: pd.DataFrame, *, potential_type: str = 'pmmcs', cooling_rate: float | None = None, timestep: float = 1.0, temperature_high: float | None = None, temperature_low: float = 300.0, equilibration_steps: int | None = None, n_dump: int | None = 100000, n_print_thermo: int | None = None, server_kwargs: dict[str, Any] | None = None, pre_equilibrate: bool = True) -> dict[str, Any]
¶
Run a LAMMPS melt-quench simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
Initial ASE Atoms object. |
required |
potential
|
DataFrame
|
LAMMPS potential object from |
required |
potential_type
|
str
|
Potential name, used for default |
'pmmcs'
|
cooling_rate
|
float | None
|
Cooling rate in K/s; |
None
|
timestep
|
float
|
MD timestep in fs. |
1.0
|
temperature_high
|
float | None
|
Melt temperature in K; |
None
|
temperature_low
|
float
|
Final quench temperature in K. |
300.0
|
equilibration_steps
|
int | None
|
Override for equilibration step count; |
None
|
n_dump
|
int | None
|
Trajectory dump frequency (steps). |
100000
|
n_print_thermo
|
int | None
|
Thermodynamic output frequency (steps). |
None
|
server_kwargs
|
dict[str, Any] | None
|
LAMMPS server/resource configuration. |
None
|
pre_equilibrate
|
bool
|
Run a Langevin + nve/limit pre-equilibration block at
|
True
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with |
dict[str, Any]
|
|
Source code in amorphouspy/src/amorphouspy/pipelines/meltquench.py
run_structural_analysis(final_structure: Atoms, potential: LammpsPotential | None = None, timestep: float = 1.0, n_averaging_frames: int = 1, n_jobs: int | None = None, temperature: float = 300.0, server_kwargs: dict[str, Any] | None = None, r_max: float = 10.0, n_bins: int = 500) -> tuple[StructureData, StructureData | None, int, list[dict[str, Any]] | None]
¶
Run structural analysis, optionally averaging over trajectory frames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
final_structure
|
Atoms
|
Structure to be analyzed or to use as starting structure for a NVT simulation. |
required |
potential
|
LammpsPotential | None
|
LAMMPS potential (str, pd.DataFrame, or dict). Required when |
None
|
timestep
|
float
|
MD timestep in fs. |
1.0
|
n_averaging_frames
|
int
|
Number of frames to collect for averaging. If set to 1, then no MD simulation and only the provided structure is analyzed. If set to >1, then an additional NVT simulation is run to collect frames for averaging. |
1
|
n_jobs
|
int | None
|
Number of worker processes for frame-averaging post-processing.
|
None
|
temperature
|
float
|
Temperature (K) for NVT equilibration/production simulation. |
300.0
|
server_kwargs
|
dict[str, Any] | None
|
LAMMPS server configuration dict. |
None
|
r_max
|
float
|
Maximum radius in Å for RDF calculation (default 10.0). |
10.0
|
n_bins
|
int
|
Number of bins for RDF calculation (default 500). |
500
|
Returns:
| Type | Description |
|---|---|
StructureData
|
Tuple of |
StructureData | None
|
sem_data is always returned as |
int
|
values are computed from a single sample and are typically zero) and |
list[dict[str, Any]] | None
|
sampling_history is the raw NVT parsed output wrapped as a single |
tuple[StructureData, StructureData | None, int, list[dict[str, Any]] | None]
|
stage list when |
Source code in amorphouspy/src/amorphouspy/properties/structural/all.py
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 | |
running_mean(data: list | np.ndarray, n: int) -> np.ndarray
¶
Calculate running mean of an array-like dataset.
The initial and final values of the returned array are NaN, as the running mean is not defined for those points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
list | ndarray
|
Input data for which the running mean should be calculated. |
required |
n
|
int
|
Width of the averaging window. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of same size as input data containing the running mean values. |
Source code in amorphouspy/src/amorphouspy/atoms/shared.py
save_frames(frames: list[Atoms], path: str | Path) -> Path
¶
Write a trajectory to extended XYZ (gzipped when path ends in .gz).
Per-atom arrays (including unwrapped_positions) and per-frame info (step,
temperature) are preserved, so the file round-trips back into :func:compute_msd.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frames
|
list[Atoms]
|
Trajectory as a list of :class: |
required |
path
|
str | Path
|
Output path; a |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The path written. |
Example
save_frames(out["frames"], "trajectory.xyz.gz") # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/diffusion.py
structure_from_parsed_output(initial_structure: Atoms, parsed_output: dict, *, wrap: bool = False) -> Atoms
¶
Construct an Atoms object from parsed output data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_structure
|
Atoms
|
The initial atomic structure to use as a template. |
required |
parsed_output
|
dict
|
Parsed output containing atomic positions, cell, and indices. |
required |
wrap
|
bool
|
Whether to wrap the atomic positions to the simulation cell (default is False). Keeping the unwrapped positions is more beneficial if structures are passed between different LAMMPS simulations in one workflow to ensure continuity. |
False
|
Returns:
| Type | Description |
|---|---|
Atoms
|
An |
Example
new_atoms = structure_from_parsed_output(atoms, lammps_output)
Source code in amorphouspy/src/amorphouspy/lammps/io.py
temperature_scan_simulation(structure: Atoms, potential: pd.DataFrame, temperature: list[int | float] | None = None, npt_pressure: float = 0.0001, timestep: float = 1.0, equilibration_steps: int = 100000, production_steps: int = 200000, n_dump: int | None = None, n_print_thermo: int = 10, server_kwargs: dict[str, Any] | None = None, *, aniso: bool = False, seed: int | None = 12345, tmp_working_directory: str | Path | None = None) -> dict[Any, Any]
¶
Perform a temperature scan and collect structural data.
This workflow performs a temperature scan at the given list of temperatures. For each temperature, it equilibrates the structure at the target temperature and pressure and then performs a production MD run to collect the average volume and box lengths, needed to compute the CTE via V-T data. There differen CTEs often discussed, for example: - CTE20-300: Computed between solely as the slope from the two datapoints at 20°C and 300°C. - CTE20-600: Computed between solely as the slope from the two datapoints at 20°C and 600°C. - CTE over other arbitrary temperature range - CTE at a specific temperature based on the slope of the V-T curve at this temperature. This is often doen by fitting a linear model or higher polynomials fit to the V-T data and then taking the derivative at the temperature of interest. Because of the various options and methods to compute the CTE from V-T data, and because the actual CTE calculation is rather straightforward once the data is collected, we do not compute it directly in this workflow, but rather return the collected data for each temperature and leave the actual CTE calculation to the user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
Input structure (assumed pre-equilibrated). |
required |
potential
|
DataFrame
|
LAMMPS potential file. |
required |
temperature
|
list[int | float] | None
|
Simulation temperature in Kelvin (default 300 K). |
None
|
npt_pressure
|
float
|
Target pressure in GPa for NPT simulations. (default 10-4 GPa = 10^5 Pa = 1 bar). |
0.0001
|
timestep
|
float
|
MD integration timestep in femtoseconds (default 1.0 fs). |
1.0
|
equilibration_steps
|
int
|
Number of MD steps for the equilibration runs (default 100,000). |
100000
|
production_steps
|
int
|
Number of MD steps for the production runs (default 200,000). |
200000
|
n_dump
|
int | None
|
Interval for structure dumping in MD steps for the production run. If set to None (default), only the last frame of the production run is dumped. |
None
|
n_print_thermo
|
int
|
Interval for writing thermodynamic data in MD steps (default 10). |
10
|
server_kwargs
|
dict[str, Any] | None
|
Additional server configuration arguments. |
None
|
aniso
|
bool
|
If false, an isotropic NPT calculation is performed and the simulation box is scaled uniformly. If True, anisotropic NPT calculation is performed and the simulation box can change shape and size independently along each axis (default False). |
False
|
seed
|
int | None
|
Random seed for velocity initialization (default 12345). |
12345
|
tmp_working_directory
|
str | Path | None
|
Temporary directory for job execution. |
None
|
Returns:
| Type | Description |
|---|---|
dict[Any, Any]
|
Dictionary containing the "data" key. The "data" holds the collected thermodynamic and |
dict[Any, Any]
|
structural data from the production run at each temperature. "run_index" identifies which |
dict[Any, Any]
|
temperature step the data belongs to (1, 2, 3, ...). Thermodynamic and structural quantities |
dict[Any, Any]
|
are averaged over each production run and these averages are listed under the respective key. |
dict[Any, Any]
|
The CTE is not computed in this workflow — the returned data is intended for subsequent |
dict[Any, Any]
|
CTE analysis by the user. Example: |
dict[Any, Any]
|
{ 'data': {"run_index" : [1, 2, 3, ...], "steps" : [...], "T" : [...], "E_tot" : [...], "ptot" : [...], "pxx" : [...], "pyy" : [...], "pzz" : [...], "V" : [...], "Lx" : [...], "Ly" : [...], "Lz" : [...], } |
dict[Any, Any]
|
} |
Notes
- For every temperature, the structure is first pre-equilibrated with short (10 ps) NVT.
- Simulation settings for the NVT equilibration run are hard-coded.
- Temperatures are simulated sequentially. Alternatively, multiple jobs with independent temperatures can be submitted to achieve parallelization.
Example
result = temperature_scan_simulation( ... structure=my_atoms, ... potential=my_potential, ... temperature=[300, 400, 500], ... production_steps=500000 ... )
Source code in amorphouspy/src/amorphouspy/properties/cte.py
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 | |
type_to_dict(types: np.ndarray) -> dict[int, str]
¶
Generate a dictionary mapping atomic numbers (types) to element symbols from an ASE Atoms structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
types
|
ndarray
|
Array containing atom types in the simulation. |
required |
Returns:
| Type | Description |
|---|---|
dict[int, str]
|
Dictionary mapping atomic numbers to corresponding element symbols. |
Example
type_map = type_to_dict(np.array([14, 8]))
Source code in amorphouspy/src/amorphouspy/atoms/shared.py
vdos_simulation(structure: Atoms, potential: pd.DataFrame, temperature_sim: float = 300.0, timestep: float = 1.0, server_kwargs: dict[str, Any] | None = None, *, thermostat: Thermostat, equilibration_steps: int = 100000, production_ps: float = 200.0, block_ps: float = 10.0, dump_every: int = 5, normalization: Literal['unit', '3N'] = 'unit', window: VdosWindow = 'hann', cutoff: CutoffSpec | None = None, former_types: list[int] | None = None, o_type: int = 8, seed: int = 12345, tmp_working_directory: str | Path | None = None, keep_trajectory: bool = False, infrared: bool = False, charges: ArrayLike | None = None, eps_inf: float = 1.0) -> dict[str, Any]
¶
Equilibrate a structure, run consecutive NVE blocks and average their VDOS and VACF, total and per atom group.
Three MD stages run in LAMMPS at the constant volume of the input cell:
- Langevin thermalisation at
temperature_simfor 10,000 steps, with velocities created attemperature_sim(as in :func:diffusion_simulation). - NVT equilibration with
thermostatforequilibration_stepssteps, with velocities created again attemperature_sim.equilibration_steps=0skips this stage. - NVE production of
production_ps, run asn_blocks = production_steps // block_stepsconsecutive blocks ofblock_ps, i.e.block_steps = block_ps * 1000 / timestepsteps each, with velocities and thermo output everydump_everysteps. The first block starts from the velocities of the previous stage and every later block from the end of the block before it, as a new LAMMPS run.
The production is microcanonical because a thermostat perturbs the velocities and distorts the spectrum. LAMMPS
also writes the frame of step 0 of every block, which is the end state of the previous stage or block. It is
dropped, so the kept frames of consecutive blocks do not overlap. Each block holds n_frames = block_steps //
dump_every frames spaced by dt_fs = timestep * dump_every fs, and the frequency resolution is exactly
1 / block_ps THz. If the parsed output of a block does not hold n_frames + 1 frames, a RuntimeError is
raised; no frame is trimmed silently. The Nyquist frequency is 1 / (2 dt_fs): 100 THz for the defaults (1 fs,
every 5 steps).
From the kept frames of each block (velocities in Å/fs, masses from structure.get_masses() in amu) the function
computes:
- The VDOS without a window and, unless
windowisNone, withwindow(Hann by default), both with :func:compute_partial_vdos, the givennormalizationand one shared frequency axis. The total is computed as the partial VDOS of a group of all atoms, so it is the total VDOS of :func:compute_vdos_from_velocitiesand integrates to 1 ("unit") or3 * n_atoms("3N"); within each grouping the partials add up to it. - The VACF with :func:
compute_partial_vacf, unwindowed, normalised so that the total \(C(0) = 1\), with lags up to half the block.
The centre-of-mass velocity of the whole system is removed from every frame in both.
Every returned curve is the mean over blocks, with the block standard error std(ddof=1) / sqrt(n_blocks) in
"vdos_sem" and "vacf_sem"; with one block the standard error is NaN. Each block's VDOS and VACF are
normalised by that block's own kinetic energy, so the mean of the block curves integrates exactly to the
normalisation, the total VACF has \(C(0) = 1\) exactly, and within each grouping the mean partials still add up to
the mean total. The standard errors are not additive: the standard error of a total is not the sum of those of
its partials.
The standard error is the scatter between the blocks of this run, and it assumes that they are independent. The blocks come from one NVE trajectory of one glass, so it contains no glass-to-glass variation at all, and nothing that stays constant over the run: neither the energy of the run nor a nearly harmonic mode that keeps its energy between blocks. A calibration compared the means of two independent thermal histories of one 300-atom \(\mathrm{SiO_2}\) glass (PMMCS, 300 K, 10 blocks of 10 ps each), where exact standard errors put 94 % of the bins within two combined standard errors. Between 5 and 34 THz this held for 93 % (no window) and 95 % (Hann) of the bins. Below 5 THz it held for 96 % and 98 %, so no low-frequency underestimate was seen, although 50 bins would not show a small one. Between 34 and 40 THz, above the top of the spectrum, it held for only 75 % and 78 %: the weight there differed by 4 to 5 %, as did the temperature of the two runs. The lag-1 correlation of the block residuals was close to the -0.1 of independent blocks, but a part that is constant over the run cannot show up in it. One pair of runs says nothing about larger boxes, lower temperatures or shorter blocks.
The atom groups (element, oxygen class, \(\mathrm{Q}^n\)) come from :func:classify_vibrational_groups on the input
structure, before any MD, so thermal motion of bonds near the cutoff cannot change them. They stay fixed for
all blocks.
Memory: the velocities of one block take n_frames * n_atoms * 3 * 8 bytes as float64, e.g. 0.29 GB for 2000
frames (10 ps at 5 fs) of 6000 atoms. The parsed LAMMPS output holds three more arrays of that size (positions,
unwrapped positions and forces), and parsing it needs more still: a 10 ps block of 5400 atoms peaked 4.5 GB above
the baseline, 17 times its velocities (measured). The peak scales with one block, not with the whole production: a
block's parsed output is freed before the next block starts, and only the spectra and the thermo output accumulate.
Not all freed memory goes back to the system, though: over 8 blocks of 2 ps the resident size levelled off at 1.7
times the peak of the first block (measured on macOS).
Disk: with tmp_working_directory=None every run removes its files. In a caller-supplied directory every run
keeps a sub-directory, and each NVE block runs in its own vdos_nve_block_<block>_<random> directory. Its dump
(dump.out, 88 bytes per atom per frame, measured: 0.47 MB per frame and 0.95 GB per 10 ps block at 5400 atoms)
is deleted once the block's spectra and thermo output are extracted, before the next block starts, so at most one
dump is on disk at a time. log.lammps, the input script and the data file stay, as do all files of the Langevin
and NVT stages. keep_trajectory=True keeps every dump (20 for the defaults). A block that fails keeps its dump,
and the error names it. If no dump is found to delete, a warning is raised and the result is still returned.
Drift: "nve_drift" reports the energy and temperature of the kept NVE frames, frame k (0-based over all
blocks) at t = (k + 1) * dt_fs fs. Each block restarts from the positions and velocities of the previous
block's dump, written with 6 significant digits, so the total energy can jump at a block boundary. The jump is
measured between the last kept frame of a block and the step-0 frame of the next, which hold the same state, so it
is the restart loss alone. The thermo output has 8 significant digits, so energies are resolved to about
|E_tot| / N * 1e-5 meV/atom, one unit in the last digit (measured for \(\mathrm{SiO_2}\) with PMMCS: 3.3e-4
meV/atom at 300 atoms, 1.9e-4 at 5400). In those runs (300 K, blocks of 2 and 10 ps) every jump was within two
such units, at most 6.7e-4 meV/atom, and smaller than the drift within any block over the block length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
Input structure, e.g. a quenched glass. Its cell sets the volume of every stage, and the atom groups and masses are taken from it. |
required |
potential
|
DataFrame
|
LAMMPS potential as a pandas DataFrame. |
required |
temperature_sim
|
float
|
Temperature of the Langevin and NVT stages in K. |
300.0
|
timestep
|
float
|
MD timestep in fs. |
1.0
|
server_kwargs
|
dict[str, Any] | None
|
Additional arguments for the LAMMPS server (e.g. |
None
|
thermostat
|
Thermostat
|
Thermostat of the NVT stage, |
required |
equilibration_steps
|
int
|
Length of the NVT stage in MD steps; 0 skips it. Use a small value for quick demos and the default for production-quality runs. |
100000
|
production_ps
|
float
|
Total length of the NVE production in ps, a whole number of timesteps and a multiple of
|
200.0
|
block_ps
|
float
|
Length of one NVE block in ps, a whole number of timesteps. It sets the resolution 1 / |
10.0
|
dump_every
|
int
|
Interval between dumped frames in MD steps, a positive integer that divides the block. |
5
|
normalization
|
Literal['unit', '3N']
|
|
'unit'
|
window
|
VdosWindow
|
Window of the second VDOS, as in :func: |
'hann'
|
cutoff
|
CutoffSpec | None
|
Former-O cutoff in Å for the groups, as in :func: |
None
|
former_types
|
list[int] | None
|
Atomic numbers of the network formers. Derived from the composition if |
None
|
o_type
|
int
|
Atomic number of oxygen. |
8
|
seed
|
int
|
Random seed for the velocities created in the Langevin and NVT stages. |
12345
|
tmp_working_directory
|
str | Path | None
|
Directory for temporary simulation files. If None, every run removes its files. |
None
|
keep_trajectory
|
bool
|
Keep the dump of every NVE block in |
False
|
infrared
|
bool
|
Also compute the infrared response from the charge current of every block, with |
False
|
charges
|
ArrayLike | None
|
Atomic charges in units of the elementary charge for the infrared response, shape \((N,)\) or Born
tensors \((N, 3, 3)\), in the order of the atoms. |
None
|
eps_inf
|
float
|
The high-frequency dielectric constant \(\varepsilon_\infty\) of the infrared response; see
:func: |
1.0
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dict with:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Before any MD, if the potential is empty, |
RuntimeError
|
If the output of an NVE block does not hold |
Warns:
| Type | Description |
|---|---|
UserWarning
|
If the Nyquist frequency is below 50 THz, or if no dump of a block is found to delete. |
Example
>>> out = vdos_simulation(structure, potential, thermostat="nose_hoover") # doctest: +SKIP
>>> out["n_blocks"], out["n_frames"], out["resolution_thz"], out["nyquist_thz"] # doctest: +SKIP
(20, 2000, 0.1, 100.0)
>>> out["vdos"]["windowed"]["element"]["Si"] # doctest: +SKIP
>>> out["vdos_sem"]["windowed"]["element"]["Si"] # doctest: +SKIP
>>> out["nve_drift"]["energy_drift_mev_per_atom_ps"] # doctest: +SKIP
Source code in amorphouspy/src/amorphouspy/properties/vibrational/simulation.py
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 | |
viscosity_ensemble(structure: Atoms, potential: pd.DataFrame, n_replicas: int = 3, seeds: list[int] | None = None, base_seed: int = 12345, temperature_sim: float = 5000.0, timestep: float = 1.0, initial_production_steps: int = 10000000, n_dump: int | None = None, n_print_thermo: int | None = 1, max_total_time_ns: float = 50.0, max_iterations: int = 40, eta_rel_tol: float = 0.05, eta_stable_iters: int = 3, server_kwargs: dict[str, Any] | None = None, *, thermostat: Thermostat, parallel: bool = False, executor: Executor | None = None, tmp_working_directory: str | Path | None = None) -> dict[str, Any]
¶
Run multiple independent viscosity simulations and return ensemble-averaged results.
Each replica starts from the same structure but uses a different random seed for velocity initialisation, producing statistically independent trajectories. The viscosity (and other properties) are averaged across replicas and the inter-replica standard deviation is reported as the uncertainty.
Execution modes (mutually exclusive; executor takes priority):
executorprovided — each replica is submitted via the executor's.submit()method. Pass any executorlib executor (SlurmJobExecutor,SlurmClusterExecutor,SingleNodeExecutor, …) to run replicas on an HPC cluster. The executor'sresource_dictis automatically populated with the MPI core count fromserver_kwargs["cores"]. The executor's lifecycle is managed by the caller.parallel=True— replicas run simultaneously on the local machine usingThreadPoolExecutor. Requiresn_replicas * server_kwargs["cores"]total cores to be available.- default (sequential) — replicas run one after another on the local machine.
Seeds are written to tmp_working_directory/viscosity_ensemble_seeds.json
immediately after generation so they are preserved even if the run is interrupted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
Input structure (assumed pre-equilibrated). |
required |
potential
|
DataFrame
|
LAMMPS potential DataFrame. |
required |
n_replicas
|
int
|
Number of independent replicas to run. Default 3. |
3
|
seeds
|
list[int] | None
|
Explicit list of integer seeds, one per replica. If |
None
|
base_seed
|
int
|
Master seed used to generate per-replica seeds when |
12345
|
temperature_sim
|
float
|
Simulation temperature in Kelvin. |
5000.0
|
timestep
|
float
|
MD timestep in fs. |
1.0
|
initial_production_steps
|
int
|
Steps for the first production run per replica. |
10000000
|
n_dump
|
int | None
|
Dump output frequency. |
None
|
n_print_thermo
|
int | None
|
Thermodynamic output frequency. |
1
|
max_total_time_ns
|
float
|
Maximum total production time per replica in nanoseconds. |
50.0
|
max_iterations
|
int
|
Maximum number of 100 ps extension iterations per replica. |
40
|
eta_rel_tol
|
float
|
Relative change threshold for eta-stability check. |
0.05
|
eta_stable_iters
|
int
|
Consecutive stable iterations required per replica. |
3
|
server_kwargs
|
dict[str, Any] | None
|
Additional server arguments forwarded to LAMMPS (e.g.
|
None
|
thermostat
|
Thermostat
|
Thermostat of the equilibration and production runs, |
required |
parallel
|
bool
|
If |
False
|
executor
|
Executor | None
|
Optional executorlib (or compatible) executor. When provided,
each replica is submitted as |
None
|
tmp_working_directory
|
str | Path | None
|
Directory for LAMMPS runs and seed file. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary containing:
- viscosity: Mean shear viscosity across replicas (Pa·s)
- viscosity_fit_residual: Sample standard deviation across replicas (Pa·s, ddof=1)
- viscosity_sem: Standard error of the mean (Pa·s)
- shear_modulus_inf: Mean infinite-frequency shear modulus (Pa)
- bulk_viscosity: Mean bulk viscosity (Pa·s)
- maxwell_relaxation_time_ps: Mean Maxwell relaxation time (ps)
- mean_pressure_gpa: Mean pressure averaged across replicas (GPa)
- temperature: Mean temperature across all replicas (K)
- n_replicas: Number of replicas run
- seeds: List of seeds actually used
- viscosities: Per-replica shear viscosity values (Pa·s)
- converged: Per-replica convergence flags
- results: Full |
Example
out = viscosity_ensemble( ... structure=my_atoms, ... potential=my_potential_df, ... n_replicas=3, ... temperature_sim=4000.0, ... n_print_thermo=10, ... server_kwargs={"cores": 4}, ... thermostat="nose_hoover", ... ) print(out["viscosity"], "±", out["viscosity_sem"], "Pa·s")
Source code in amorphouspy/src/amorphouspy/properties/viscosity.py
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 | |
viscosity_simulation(structure: Atoms, potential: pd.DataFrame, temperature_sim: float = 5000.0, timestep: float = 1.0, initial_production_steps: int = 10000000, n_dump: int | None = None, n_print_thermo: int | None = 1, max_total_time_ns: float = 50.0, max_iterations: int = 40, eta_rel_tol: float = 0.05, eta_stable_iters: int = 3, server_kwargs: dict[str, Any] | None = None, *, thermostat: Thermostat, seed: int = 12345, tmp_working_directory: str | Path | None = None) -> dict[str, Any]
¶
Perform an autonomous viscosity simulation using the Helfand moment method.
Runs an initial NVT production MD (default 10 ns) and iteratively extends it by 100 ps until viscosity converges or limits are reached.
Convergence requires both conditions to be true simultaneously:
- eta-stability -
|eta_new - eta_prev| / eta_prev < eta_rel_tolforeta_stable_itersconsecutive iterations. - MSD linearity - the local slope of the Helfand moment MSD is flat
in the last 30 % of the lag window (
_viscosity_plateauedcheck), confirming that the diffusive regime has been reached.
Extensions stop when either max_total_time_ns or max_iterations
is exhausted. get_viscosity is retained as a legacy cross-check in
the return dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Atoms
|
Input structure (assumed pre-equilibrated). |
required |
potential
|
DataFrame
|
LAMMPS potential DataFrame. |
required |
temperature_sim
|
float
|
Simulation temperature in Kelvin. |
5000.0
|
timestep
|
float
|
MD timestep in fs. |
1.0
|
initial_production_steps
|
int
|
Steps for the first production run. Default 10,000,000 (= 10 ns at 1 fs timestep). |
10000000
|
n_dump
|
int | None
|
Dump output frequency. |
None
|
n_print_thermo
|
int | None
|
Thermodynamic output frequency. |
1
|
max_total_time_ns
|
float
|
Maximum total production time in nanoseconds. Default 50 ns. |
50.0
|
max_iterations
|
int
|
Maximum number of 100 ps extension iterations. Default 40. |
40
|
eta_rel_tol
|
float
|
Relative change threshold for eta-stability check. Default 0.05 (5 %). |
0.05
|
eta_stable_iters
|
int
|
Consecutive stable iterations required. Default 3. |
3
|
server_kwargs
|
dict[str, Any] | None
|
Additional server arguments forwarded to LAMMPS. |
None
|
thermostat
|
Thermostat
|
Thermostat of the equilibration and production runs, |
required |
seed
|
int
|
Random seed for velocity initialization. |
12345
|
tmp_working_directory
|
str | Path | None
|
Temporary directory for LAMMPS runs. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary containing:
- viscosity_data: Output of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the potential DataFrame is empty. |
Example
result = viscosity_simulation( ... structure=my_atoms, ... potential=my_potential_df, ... temperature_sim=3000.0, ... thermostat="nose_hoover", ... ) converged = result["converged"] print(converged)
Source code in amorphouspy/src/amorphouspy/properties/viscosity.py
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 | |
write_angle_distribution(bin_centers: np.ndarray, angle_hist: np.ndarray, composition: float, filepath: str, *, append: bool = False) -> None
¶
Write angle distribution to a text file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bin_centers
|
ndarray
|
Angle bin centers in degrees. |
required |
angle_hist
|
ndarray
|
Normalized angle histogram. |
required |
composition
|
float
|
Composition value (e.g., % modifier). |
required |
filepath
|
str
|
Output filepath. |
required |
append
|
bool
|
Whether to append to file. |
False
|
Example
write_angle_distribution(centers, hist, 0.5, "angles.txt")
Source code in amorphouspy/src/amorphouspy/atoms/io.py
write_distribution_to_file(composition: float | str, filepath: str, dist: dict[int, int], label: str, *, append: bool = False) -> None
¶
Write a coordination/Qn histogram to a text file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
composition
|
float | str
|
Composition value to label row. |
required |
filepath
|
str
|
Output filepath. |
required |
dist
|
dict[int, int]
|
Histogram data. |
required |
label
|
str
|
Prefix for headers (e.g., Si or Q). |
required |
append
|
bool
|
Append mode; writes header only if file does not exist. |
False
|
Example
write_distribution_to_file(0.5, "qn.txt", qn_dist, "Q")
Source code in amorphouspy/src/amorphouspy/atoms/io.py
write_xyz(filename: str, coords: np.ndarray, types: np.ndarray, box_size: np.ndarray | None = None, type_dict: dict[int, str] | None = None) -> None
¶
Write atomic configuration to an XYZ file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Output XYZ file name. |
required |
coords
|
ndarray
|
Atomic coordinates. |
required |
types
|
ndarray
|
Atomic types as integers. |
required |
box_size
|
ndarray | None
|
Simulation box size in x, y, z. |
None
|
type_dict
|
dict[int, str] | None
|
Dictionary mapping atomic type integers to element symbols. |
None
|
Example
write_xyz("output.xyz", coords, types, box, {14: "Si", 8: "O"})