pymdkit 1.5.4__tar.gz → 1.5.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. {pymdkit-1.5.4 → pymdkit-1.5.6}/PKG-INFO +21 -8
  2. {pymdkit-1.5.4 → pymdkit-1.5.6}/README.md +21 -8
  3. {pymdkit-1.5.4 → pymdkit-1.5.6}/pyproject.toml +1 -1
  4. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/__init__.py +1 -1
  5. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/_cifio.py +4 -3
  6. pymdkit-1.5.6/src/pymdkit/commands/_oxidation.py +46 -0
  7. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/realloc_occ.py +242 -41
  8. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit.egg-info/PKG-INFO +21 -8
  9. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit.egg-info/SOURCES.txt +3 -1
  10. pymdkit-1.5.6/tests/test_realloc_occ.py +208 -0
  11. {pymdkit-1.5.4 → pymdkit-1.5.6}/LICENSE +0 -0
  12. {pymdkit-1.5.4 → pymdkit-1.5.6}/setup.cfg +0 -0
  13. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/__init__.py +0 -0
  14. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/_extxyz.py +0 -0
  15. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/_fileio.py +0 -0
  16. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/_geometry.py +0 -0
  17. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/_gpumd.py +0 -0
  18. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/_precision.py +0 -0
  19. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/_reduction.py +0 -0
  20. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/_vasp_output.py +0 -0
  21. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/_vaspset.py +0 -0
  22. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/add_config_type.py +0 -0
  23. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/chemsys_entry.py +0 -0
  24. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/compute_ehull.py +0 -0
  25. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/compute_rmsd.py +0 -0
  26. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/convert.py +0 -0
  27. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/ewald.py +0 -0
  28. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/gather_fs.py +0 -0
  29. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/gpumd_group.py +0 -0
  30. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/gpumd_msd.py +0 -0
  31. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/gpumd_relax.py +0 -0
  32. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/gpumd_thermo.py +0 -0
  33. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/gpumd_trjcat.py +0 -0
  34. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/nep_rmse.py +0 -0
  35. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/pca.py +0 -0
  36. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/perturb.py +0 -0
  37. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/submit_vasp.py +0 -0
  38. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/substitute.py +0 -0
  39. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/supercell.py +0 -0
  40. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/symmetrize.py +0 -0
  41. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/trj_extract.py +0 -0
  42. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/trj_sparse.py +0 -0
  43. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/umap.py +0 -0
  44. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/vasp2xyz.py +0 -0
  45. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/vasp_fe.py +0 -0
  46. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/vasp_relax.py +0 -0
  47. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/commands/vasp_static.py +0 -0
  48. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit/pymdkit_main.py +0 -0
  49. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit.egg-info/dependency_links.txt +0 -0
  50. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit.egg-info/entry_points.txt +0 -0
  51. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit.egg-info/requires.txt +0 -0
  52. {pymdkit-1.5.4 → pymdkit-1.5.6}/src/pymdkit.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pymdkit
3
- Version: 1.5.4
3
+ Version: 1.5.6
4
4
  Summary: A unified command-line toolkit for atomistic / MD structure workflows.
5
5
  Author-email: Yueda Wang <ydwang0608@ustc.edu.cn>
6
6
  License-Expression: GPL-3.0-or-later
@@ -137,6 +137,7 @@ nohup pmk submit-vasp -subscript sub_vasp -queue slurm -max-job-num 30 > submit-
137
137
  pmk realloc-occ -i 66-Li4YCl6-5.cif -of chg-balance -formula Li3YCl6
138
138
  pmk realloc-occ -if cifs -of chg-balance -formula Li3YCl6
139
139
  pmk realloc-occ -i 66-Li4YCl6-5.cif -of chg-balance -formula Li3YCl6 -occ 0 0.125 0.25 0.375 0.5 0.625 0.75 0.875 1
140
+ pmk realloc-occ -if cifs -of chg-balance -formula Li3YCl6 -occ 0.25 0.5 0.75 1 -max-supercell 2x2x2
140
141
  pmk substitute -i Li3YCl6.cif -se Li -sn 3 -we Na -wn 3 -on 100
141
142
  pmk substitute -i Li3YCl6.cif -se Li -sn 3 -we none -on 100
142
143
  pmk substitute -i Li96Ta6La11Cl72.cif -se Li1 Li2 -sn 20 67 -we none -on 100
@@ -230,16 +231,25 @@ the mean triclinic-box volume over that run; for NVT ensembles (`nvt_bdp`,
230
231
  Boltzmann constant, and a final `* 1000` conversion from S/cm to mS/cm.
231
232
 
232
233
  `realloc-occ -i INPUT.cif -of OUTPUT -formula FORMULA` computes atom counts as
233
- Wyckoff multiplicity times occupancy and uses `_cell_formula_units_Z` to map the
234
- target reduced formula into the existing cell. It enumerates finite site-wise
234
+ Wyckoff multiplicity times occupancy. Because source `_cell_formula_units_Z`
235
+ belongs to the source formula, PMK infers a new target Z from the available site
236
+ capacities and current atom counts, then writes that target Z to each output CIF.
237
+ It enumerates finite site-wise
235
238
  occupancy allocations, retains only charge-balanced candidates using the CIF
236
239
  oxidation-number loop, and preserves the original symmetry, coordinates,
237
- Wyckoff labels, and CIF layout. Every input receives `OUTPUT/INPUT_STEM/`; for
240
+ Wyckoff labels, and CIF layout. A missing all-zero oxidation assignment is
241
+ replaced by pymatgen's highest-ranked charge-balanced composition guess.
242
+ Every input receives `OUTPUT/INPUT_STEM/`; for
238
243
  the supplied Li4YCl6 example, the two outputs are `...-d1.cif` with `Li1=0.50`
239
244
  and `...-d2.cif` with `Li2=0.50`. Folder mode uses `-if` with the same `-of` and
240
245
  `-formula` options. Add `-occ` followed by the only permitted occupancy values;
241
- three decimal places are supported, so grids containing `0.125`, `0.375`,
242
- `0.625`, and `0.875` are preserved exactly in generated CIF files.
246
+ input grids support three decimal places, including `0.125`, `0.375`, `0.625`,
247
+ and `0.875`. Generated CIF occupancy fields use two decimal places.
248
+ `-max-supercell AxBxC` searches bounded diagonal supercells, smallest volume
249
+ first, until every multiplicity times occupancy times supercell determinant is
250
+ an integer. Equal-volume choices favor the most isotropic resulting cell.
251
+ All selections, site atom counts, oxidation states, charges, and failures are
252
+ recorded in `OUTPUT/realloc-occ.txt`.
243
253
 
244
254
  `gather-fs` recursively scans all job folders below the current directory. For
245
255
  VASP it follows the global `vaspout.h5 > vasprun.xml > OUTCAR` priority and
@@ -301,12 +311,15 @@ inequivalent-site identifiers such as `Li1`, `Y1`, `Cl1`, and `Cl2`.
301
311
  The final atom-site loop starts with `_atom_site_label`, followed by
302
312
  `_atom_site_type_symbol`, whose values are plain elements such as `Li`, `Y`,
303
313
  and `Cl`. Oxidation numbers remain in the separate
304
- `_atom_type_oxidation_number` column. PMK does not add an
314
+ `_atom_type_oxidation_number` column. When a generated multi-element CIF has
315
+ no oxidation states or only zero-valued states, PMK infers the highest-ranked
316
+ charge-balanced element assignment with pymatgen; explicit nonzero oxidation
317
+ states are preserved. PMK does not add an
305
318
  `_audit_creation_method` block or a generated-by header comment.
306
319
 
307
320
  Newly serialized floating-point values use eight digits after the decimal
308
321
  point across PMK structure, trajectory, data, report, and screen output. CIF
309
- `_atom_site_occupancy` values use three digits and
322
+ `_atom_site_occupancy` values use two digits and
310
323
  `_atom_type_oxidation_number` values use one digit. In extended XYZ, zero components
311
324
  inside the second-line `Lattice="..."` value remain `0.0`; other generated
312
325
  floating-point values use eight digits. Commands that select or concatenate
@@ -109,7 +109,8 @@ pmk submit-vasp -subscript sub_vasp -queue slurm -max-job-num 30
109
109
  nohup pmk submit-vasp -subscript sub_vasp -queue slurm -max-job-num 30 > submit-vasp.log 2>&1 &
110
110
  pmk realloc-occ -i 66-Li4YCl6-5.cif -of chg-balance -formula Li3YCl6
111
111
  pmk realloc-occ -if cifs -of chg-balance -formula Li3YCl6
112
- pmk realloc-occ -i 66-Li4YCl6-5.cif -of chg-balance -formula Li3YCl6 -occ 0 0.125 0.25 0.375 0.5 0.625 0.75 0.875 1
112
+ pmk realloc-occ -i 66-Li4YCl6-5.cif -of chg-balance -formula Li3YCl6 -occ 0 0.125 0.25 0.375 0.5 0.625 0.75 0.875 1
113
+ pmk realloc-occ -if cifs -of chg-balance -formula Li3YCl6 -occ 0.25 0.5 0.75 1 -max-supercell 2x2x2
113
114
  pmk substitute -i Li3YCl6.cif -se Li -sn 3 -we Na -wn 3 -on 100
114
115
  pmk substitute -i Li3YCl6.cif -se Li -sn 3 -we none -on 100
115
116
  pmk substitute -i Li96Ta6La11Cl72.cif -se Li1 Li2 -sn 20 67 -we none -on 100
@@ -203,16 +204,25 @@ the mean triclinic-box volume over that run; for NVT ensembles (`nvt_bdp`,
203
204
  Boltzmann constant, and a final `* 1000` conversion from S/cm to mS/cm.
204
205
 
205
206
  `realloc-occ -i INPUT.cif -of OUTPUT -formula FORMULA` computes atom counts as
206
- Wyckoff multiplicity times occupancy and uses `_cell_formula_units_Z` to map the
207
- target reduced formula into the existing cell. It enumerates finite site-wise
207
+ Wyckoff multiplicity times occupancy. Because source `_cell_formula_units_Z`
208
+ belongs to the source formula, PMK infers a new target Z from the available site
209
+ capacities and current atom counts, then writes that target Z to each output CIF.
210
+ It enumerates finite site-wise
208
211
  occupancy allocations, retains only charge-balanced candidates using the CIF
209
212
  oxidation-number loop, and preserves the original symmetry, coordinates,
210
- Wyckoff labels, and CIF layout. Every input receives `OUTPUT/INPUT_STEM/`; for
213
+ Wyckoff labels, and CIF layout. A missing all-zero oxidation assignment is
214
+ replaced by pymatgen's highest-ranked charge-balanced composition guess.
215
+ Every input receives `OUTPUT/INPUT_STEM/`; for
211
216
  the supplied Li4YCl6 example, the two outputs are `...-d1.cif` with `Li1=0.50`
212
217
  and `...-d2.cif` with `Li2=0.50`. Folder mode uses `-if` with the same `-of` and
213
218
  `-formula` options. Add `-occ` followed by the only permitted occupancy values;
214
- three decimal places are supported, so grids containing `0.125`, `0.375`,
215
- `0.625`, and `0.875` are preserved exactly in generated CIF files.
219
+ input grids support three decimal places, including `0.125`, `0.375`, `0.625`,
220
+ and `0.875`. Generated CIF occupancy fields use two decimal places.
221
+ `-max-supercell AxBxC` searches bounded diagonal supercells, smallest volume
222
+ first, until every multiplicity times occupancy times supercell determinant is
223
+ an integer. Equal-volume choices favor the most isotropic resulting cell.
224
+ All selections, site atom counts, oxidation states, charges, and failures are
225
+ recorded in `OUTPUT/realloc-occ.txt`.
216
226
 
217
227
  `gather-fs` recursively scans all job folders below the current directory. For
218
228
  VASP it follows the global `vaspout.h5 > vasprun.xml > OUTCAR` priority and
@@ -274,12 +284,15 @@ inequivalent-site identifiers such as `Li1`, `Y1`, `Cl1`, and `Cl2`.
274
284
  The final atom-site loop starts with `_atom_site_label`, followed by
275
285
  `_atom_site_type_symbol`, whose values are plain elements such as `Li`, `Y`,
276
286
  and `Cl`. Oxidation numbers remain in the separate
277
- `_atom_type_oxidation_number` column. PMK does not add an
287
+ `_atom_type_oxidation_number` column. When a generated multi-element CIF has
288
+ no oxidation states or only zero-valued states, PMK infers the highest-ranked
289
+ charge-balanced element assignment with pymatgen; explicit nonzero oxidation
290
+ states are preserved. PMK does not add an
278
291
  `_audit_creation_method` block or a generated-by header comment.
279
292
 
280
293
  Newly serialized floating-point values use eight digits after the decimal
281
294
  point across PMK structure, trajectory, data, report, and screen output. CIF
282
- `_atom_site_occupancy` values use three digits and
295
+ `_atom_site_occupancy` values use two digits and
283
296
  `_atom_type_oxidation_number` values use one digit. In extended XYZ, zero components
284
297
  inside the second-line `Lattice="..."` value remain `0.0`; other generated
285
298
  floating-point values use eight digits. Commands that select or concatenate
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pymdkit"
7
- version = "1.5.4"
7
+ version = "1.5.6"
8
8
  description = "A unified command-line toolkit for atomistic / MD structure workflows."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -1,3 +1,3 @@
1
1
  """pymdkit -- a unified CLI for atomistic / MD structure workflows."""
2
2
 
3
- __version__ = "1.5.4"
3
+ __version__ = "1.5.6"
@@ -7,8 +7,9 @@ import warnings
7
7
  from pathlib import Path
8
8
 
9
9
  try:
10
- from . import _precision
10
+ from . import _oxidation, _precision
11
11
  except ImportError:
12
+ import _oxidation
12
13
  import _precision
13
14
 
14
15
  DEFAULT_SYMPREC = 0.02
@@ -198,7 +199,7 @@ def _format_cif_scalar(value, precision, force=False):
198
199
  def _format_cif_numbers(block):
199
200
  for tag, value in list(block.data.items()):
200
201
  if tag == OCCUPANCY_TAG:
201
- precision = 3
202
+ precision = 2
202
203
  elif tag == OXIDATION_TAG:
203
204
  precision = 1
204
205
  else:
@@ -349,7 +350,7 @@ def write_cif(
349
350
  from pymatgen.io.cif import CifWriter
350
351
  from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
351
352
 
352
- structure = as_pymatgen_structure(structure)
353
+ structure = _oxidation.decorate_structure(as_pymatgen_structure(structure))
353
354
  analyzer = SpacegroupAnalyzer(
354
355
  structure,
355
356
  symprec=float(symprec),
@@ -0,0 +1,46 @@
1
+ """Shared oxidation-state inference for generated CIF files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+
7
+
8
+ def infer_oxidation_states(amounts: Mapping[str, float]) -> dict[str, float]:
9
+ """Return the highest-ranked charge-balanced oxidation-state assignment."""
10
+ clean = {str(symbol): float(amount) for symbol, amount in amounts.items() if amount > 0}
11
+ if not clean:
12
+ return {}
13
+ if len(clean) == 1:
14
+ return {next(iter(clean)): 0.0}
15
+
16
+ from pymatgen.core import Composition
17
+
18
+ guesses = Composition(clean).oxi_state_guesses(max_sites=-1)
19
+ if not guesses:
20
+ return {symbol: 0.0 for symbol in clean}
21
+ return {str(symbol): float(value) for symbol, value in guesses[0].items()}
22
+
23
+
24
+ def decorate_structure(structure):
25
+ """Add inferred oxidation states when a structure has none or only zeros."""
26
+ existing = []
27
+ for site in structure:
28
+ for species, _occupancy in site.species.items():
29
+ oxidation = getattr(species, "oxi_state", None)
30
+ if oxidation is not None:
31
+ existing.append(float(oxidation))
32
+ if any(abs(value) > 1e-8 for value in existing):
33
+ return structure
34
+
35
+ amounts = structure.composition.element_composition.get_el_amt_dict()
36
+ inferred = infer_oxidation_states(amounts)
37
+ if not any(abs(value) > 1e-8 for value in inferred.values()):
38
+ return structure
39
+
40
+ decorated = structure.copy()
41
+ try:
42
+ decorated.remove_oxidation_states()
43
+ except (AttributeError, ValueError):
44
+ pass
45
+ decorated.add_oxidation_state_by_element(inferred)
46
+ return decorated
@@ -17,6 +17,12 @@ from collections import OrderedDict
17
17
  from dataclasses import dataclass
18
18
  from pathlib import Path
19
19
 
20
+ try:
21
+ from . import _cifio, _oxidation
22
+ except ImportError:
23
+ import _cifio
24
+ import _oxidation
25
+
20
26
  COMMAND = "realloc-occ"
21
27
  HELP = "Reallocate CIF site occupancies to a target formula and charge balance."
22
28
  MULTIPLICITY_TAGS = (
@@ -214,6 +220,13 @@ def parse_cif(path):
214
220
  sites.append(Site(row, label, element, multiplicity, occupancy, oxidation))
215
221
  counts[element] = counts.get(element, 0.0) + multiplicity * occupancy
216
222
 
223
+ if len(counts) > 1 and not any(
224
+ abs(site.oxidation) > TOLERANCE for site in sites
225
+ ):
226
+ inferred = _oxidation.infer_oxidation_states(counts)
227
+ for site in sites:
228
+ site.oxidation = inferred.get(site.element, 0.0)
229
+
217
230
  z = 0
218
231
  if "_cell_formula_units_Z" in tags:
219
232
  z_value = _number(tags["_cell_formula_units_Z"][1])
@@ -223,10 +236,43 @@ def parse_cif(path):
223
236
  return ParsedCif(path, lines, loops, sites, z, counts, tags)
224
237
 
225
238
 
226
- def _infer_z(parsed, target):
227
- capacities = {element: sum(site.multiplicity for site in parsed.sites
228
- if site.element == element)
229
- for element in target}
239
+ def _parse_supercell_limit(value):
240
+ match = re.fullmatch(
241
+ r"([1-9]\d*)[xX]([1-9]\d*)[xX]([1-9]\d*)",
242
+ str(value).strip(),
243
+ )
244
+ if not match:
245
+ raise ValueError("-max-supercell must use AxBxC, for example 2x2x2")
246
+ return tuple(int(number) for number in match.groups())
247
+
248
+
249
+ def _lattice_lengths(parsed):
250
+ tags = ("_cell_length_a", "_cell_length_b", "_cell_length_c")
251
+ try:
252
+ return tuple(_number(parsed.tag_lines[tag][1]) for tag in tags)
253
+ except KeyError as exc:
254
+ raise ValueError(f"CIF is missing {exc.args[0]}") from exc
255
+
256
+
257
+ def _supercell_candidates(parsed, maximum):
258
+ lengths = _lattice_lengths(parsed)
259
+ candidates = []
260
+ for matrix in itertools.product(*(range(1, limit + 1) for limit in maximum)):
261
+ determinant = math.prod(matrix)
262
+ expanded = [length * factor for length, factor in zip(lengths, matrix)]
263
+ anisotropy = max(expanded) / min(expanded)
264
+ candidates.append((determinant, anisotropy, matrix))
265
+ candidates.sort()
266
+ return [matrix for _determinant, _anisotropy, matrix in candidates]
267
+
268
+
269
+ def _infer_z(parsed, target, determinant=1):
270
+ capacities = {
271
+ element: determinant * sum(
272
+ site.multiplicity for site in parsed.sites if site.element == element
273
+ )
274
+ for element in target
275
+ }
230
276
  missing = [element for element, capacity in capacities.items()
231
277
  if capacity <= TOLERANCE]
232
278
  if missing:
@@ -237,12 +283,15 @@ def _infer_z(parsed, target):
237
283
  raise ValueError("target formula does not fit the CIF site capacities")
238
284
  scores = []
239
285
  for z in range(1, maximum + 1):
240
- matches = sum(abs(parsed.counts.get(element, 0.0) - amount * z)
241
- <= TOLERANCE for element, amount in target.items())
242
- change = sum(abs(parsed.counts.get(element, 0.0) - amount * z)
243
- for element, amount in target.items())
244
- scores.append((-matches, change, z))
245
- return min(scores)[2]
286
+ matches = sum(abs(
287
+ determinant * parsed.counts.get(element, 0.0) - amount * z
288
+ ) <= TOLERANCE for element, amount in target.items())
289
+ change = sum(abs(
290
+ determinant * parsed.counts.get(element, 0.0) - amount * z
291
+ ) for element, amount in target.items())
292
+ source_z = determinant * parsed.z if parsed.z else z
293
+ scores.append((-matches, change, abs(z - source_z), z))
294
+ return min(scores)[-1]
246
295
 
247
296
 
248
297
  def _normalize_occupancies(values):
@@ -363,16 +412,9 @@ def _adjustment_options(sites, target_count, allowed_occupancies=None):
363
412
  return options
364
413
 
365
414
 
366
- def generate_candidates(parsed, target_formula, allowed_occupancies=None):
367
- target = _parse_formula(target_formula)
368
- sites_by_element = OrderedDict()
369
- for index, site in enumerate(parsed.sites):
370
- sites_by_element.setdefault(site.element, []).append((index, site))
371
- missing = [element for element in target if element not in sites_by_element]
372
- if missing:
373
- raise ValueError("target contains absent element(s): " + ", ".join(missing))
374
-
375
- z = parsed.z or _infer_z(parsed, target)
415
+ def _generate_for_matrix(parsed, target, sites_by_element, allowed_occupancies, matrix):
416
+ determinant = math.prod(matrix)
417
+ z = _infer_z(parsed, target, determinant)
376
418
  target_counts = OrderedDict((element, amount * z)
377
419
  for element, amount in target.items())
378
420
  for element in parsed.counts:
@@ -380,12 +422,26 @@ def generate_candidates(parsed, target_formula, allowed_occupancies=None):
380
422
 
381
423
  element_options = []
382
424
  for element, indexed_sites in sites_by_element.items():
425
+ base_target = target_counts.get(element, 0.0) / determinant
383
426
  options = _adjustment_options(
384
427
  [site for _, site in indexed_sites],
385
- target_counts.get(element, 0.0),
428
+ base_target,
386
429
  allowed_occupancies,
387
430
  )
388
- element_options.append((indexed_sites, options))
431
+ integer_options = [
432
+ values for values in options
433
+ if all(abs(site.multiplicity * occupancy * determinant
434
+ - round(site.multiplicity * occupancy * determinant))
435
+ <= TOLERANCE
436
+ for (_, site), occupancy in zip(indexed_sites, values))
437
+ ]
438
+ if not integer_options:
439
+ raise ValueError(
440
+ f"{element} site atom counts are non-integer in "
441
+ f"{'x'.join(map(str, matrix))}"
442
+ )
443
+ element_options.append((indexed_sites, integer_options))
444
+
389
445
  output_count = math.prod(len(options) for _, options in element_options)
390
446
  if output_count > MAX_OUTPUTS:
391
447
  raise ValueError(f"target has {output_count} allocations; limit is {MAX_OUTPUTS}")
@@ -400,15 +456,45 @@ def generate_candidates(parsed, target_formula, allowed_occupancies=None):
400
456
  if key in seen:
401
457
  continue
402
458
  seen.add(key)
403
- charge = sum(site.multiplicity * occupancy * site.oxidation
404
- for site, occupancy in zip(parsed.sites, occupancies))
459
+ charge = determinant * sum(
460
+ site.multiplicity * occupancy * site.oxidation
461
+ for site, occupancy in zip(parsed.sites, occupancies)
462
+ )
405
463
  if abs(charge) <= TOLERANCE:
406
464
  balanced.append((occupancies, charge))
407
465
  if not balanced:
408
466
  raise ValueError("no formula-matching allocation is charge balanced")
409
- return target, target_counts, z, balanced
467
+ return target_counts, z, balanced
410
468
 
411
469
 
470
+ def generate_candidates(
471
+ parsed,
472
+ target_formula,
473
+ allowed_occupancies=None,
474
+ max_supercell=(1, 1, 1),
475
+ ):
476
+ target = _parse_formula(target_formula)
477
+ sites_by_element = OrderedDict()
478
+ for index, site in enumerate(parsed.sites):
479
+ sites_by_element.setdefault(site.element, []).append((index, site))
480
+ missing = [element for element in target if element not in sites_by_element]
481
+ if missing:
482
+ raise ValueError("target contains absent element(s): " + ", ".join(missing))
483
+
484
+ failures = []
485
+ for matrix in _supercell_candidates(parsed, max_supercell):
486
+ try:
487
+ target_counts, z, balanced = _generate_for_matrix(
488
+ parsed, target, sites_by_element, allowed_occupancies, matrix
489
+ )
490
+ return target, target_counts, z, balanced, matrix
491
+ except ValueError as exc:
492
+ failures.append(f"{'x'.join(map(str, matrix))}: {exc}")
493
+ raise ValueError(
494
+ "no valid allocation within -max-supercell "
495
+ f"{'x'.join(map(str, max_supercell))}; " + " | ".join(failures)
496
+ )
497
+
412
498
  def _replace_scalar(lines, tag, value):
413
499
  for index, line in enumerate(lines):
414
500
  tokens = _tokenize(line.strip()) if line.strip().startswith("_") else []
@@ -420,15 +506,40 @@ def _replace_scalar(lines, tag, value):
420
506
  lines.insert(first_loop, f"{tag} {value}")
421
507
 
422
508
 
509
+ def _update_oxidation_rows(lines, parsed):
510
+ oxidation_by_label = {site.label: site.oxidation for site in parsed.sites}
511
+ oxidation_by_element = {}
512
+ for site in parsed.sites:
513
+ oxidation_by_element.setdefault(site.element, set()).add(round(site.oxidation, 12))
514
+ for loop in parsed.loops:
515
+ if ("_atom_type_symbol" not in loop.headers
516
+ or "_atom_type_oxidation_number" not in loop.headers):
517
+ continue
518
+ symbol_index = loop.headers.index("_atom_type_symbol")
519
+ oxidation_index = loop.headers.index("_atom_type_oxidation_number")
520
+ for row in loop.rows:
521
+ tokens = list(row.tokens)
522
+ symbol = tokens[symbol_index]
523
+ oxidation = oxidation_by_label.get(symbol)
524
+ if oxidation is None:
525
+ values = oxidation_by_element.get(_element(symbol), set())
526
+ if len(values) == 1:
527
+ oxidation = next(iter(values))
528
+ if oxidation is not None:
529
+ tokens[oxidation_index] = f"{oxidation:.1f}"
530
+ lines[row.line_index] = " " + " ".join(tokens)
531
+
532
+
423
533
  def render_candidate(parsed, occupancies, target, target_counts, z, output):
424
534
  lines = list(parsed.lines)
535
+ _update_oxidation_rows(lines, parsed)
425
536
  site_loop = next(loop for loop in parsed.loops
426
537
  if "_atom_site_label" in loop.headers
427
538
  and "_atom_site_occupancy" in loop.headers)
428
539
  occupancy_index = site_loop.headers.index("_atom_site_occupancy")
429
540
  for site, occupancy in zip(parsed.sites, occupancies):
430
541
  tokens = list(site.row.tokens)
431
- tokens[occupancy_index] = f"{occupancy:.3f}"
542
+ tokens[occupancy_index] = f"{occupancy:.2f}"
432
543
  lines[site.row.line_index] = " " + " ".join(tokens)
433
544
 
434
545
  output = Path(output)
@@ -452,6 +563,37 @@ def render_candidate(parsed, occupancies, target, target_counts, z, output):
452
563
  raise
453
564
 
454
565
 
566
+ def _write_candidate(
567
+ parsed,
568
+ occupancies,
569
+ target,
570
+ target_counts,
571
+ z,
572
+ matrix,
573
+ output,
574
+ ):
575
+ output = Path(output)
576
+ if tuple(matrix) == (1, 1, 1):
577
+ render_candidate(parsed, occupancies, target, target_counts, z, output)
578
+ return
579
+
580
+ temporary = output.with_name(f".{output.stem}.base.cif")
581
+ try:
582
+ render_candidate(parsed, occupancies, target, target_counts, z, temporary)
583
+ from pymatgen.core import Structure
584
+
585
+ structure = Structure.from_file(temporary)
586
+ structure.make_supercell(list(matrix))
587
+ _cifio.write_cif(structure, output, data_name=output.stem, refine=False)
588
+ finally:
589
+ temporary.unlink(missing_ok=True)
590
+
591
+
592
+ def _emit(report, message):
593
+ print(message)
594
+ report.append(message)
595
+
596
+
455
597
  def _detected_formula(parsed):
456
598
  composition = OrderedDict((element, amount / parsed.z)
457
599
  for element, amount in parsed.counts.items()) \
@@ -459,26 +601,61 @@ def _detected_formula(parsed):
459
601
  return _format_formula(composition)
460
602
 
461
603
 
462
- def process_one(source, output_root, target_formula, allowed_occupancies=None):
604
+ def process_one(
605
+ source,
606
+ output_root,
607
+ target_formula,
608
+ allowed_occupancies=None,
609
+ max_supercell=(1, 1, 1),
610
+ report=None,
611
+ ):
612
+ report = [] if report is None else report
463
613
  parsed = parse_cif(source)
464
- target, target_counts, z, candidates = generate_candidates(
465
- parsed, target_formula, allowed_occupancies
614
+ target, target_counts, z, candidates, matrix = generate_candidates(
615
+ parsed, target_formula, allowed_occupancies, max_supercell
466
616
  )
617
+ determinant = math.prod(matrix)
618
+ matrix_text = "x".join(map(str, matrix))
467
619
  destination = Path(output_root) / Path(source).stem
468
620
  if destination.exists() and (not destination.is_dir()
469
621
  or any(destination.iterdir())):
470
622
  raise ValueError(f"output folder must be empty: {destination}")
471
623
  destination.mkdir(parents=True, exist_ok=True)
472
- print(f"{source}: detected {_detected_formula(parsed)}; "
473
- f"target {_format_formula(target)}; Z={z}; "
474
- f"{len(candidates)} charge-balanced allocation(s)")
624
+
625
+ oxidation_by_element = OrderedDict()
626
+ for site in parsed.sites:
627
+ oxidation_by_element.setdefault(site.element, site.oxidation)
628
+ oxidation_text = ", ".join(
629
+ f"{element}={value:.1f}" for element, value in oxidation_by_element.items()
630
+ )
631
+ _emit(
632
+ report,
633
+ f"{source}: detected {_detected_formula(parsed)}; "
634
+ f"target {_format_formula(target)}; supercell={matrix_text}; Z={z}; "
635
+ f"oxidation=[{oxidation_text}]; "
636
+ f"{len(candidates)} charge-balanced allocation(s)",
637
+ )
475
638
  for number, (occupancies, charge) in enumerate(candidates, start=1):
476
639
  output = destination / f"{Path(source).stem}-d{number}.cif"
477
- render_candidate(parsed, occupancies, target, target_counts, z, output)
478
- changes = [f"{site.label}={occupancy:.3f}"
479
- for site, occupancy in zip(parsed.sites, occupancies)
480
- if abs(site.occupancy - occupancy) > TOLERANCE]
481
- print(f" {output.name}: {', '.join(changes)}; charge={charge:.8f}")
640
+ _write_candidate(
641
+ parsed, occupancies, target, target_counts, z, matrix, output
642
+ )
643
+ changes = [
644
+ f"{site.label}={occupancy:.2f}"
645
+ for site, occupancy in zip(parsed.sites, occupancies)
646
+ if abs(site.occupancy - occupancy) > TOLERANCE
647
+ ]
648
+ atom_counts = [
649
+ f"{site.label}=" + _format_amount(
650
+ site.multiplicity * occupancy * determinant, True
651
+ )
652
+ for site, occupancy in zip(parsed.sites, occupancies)
653
+ ]
654
+ _emit(
655
+ report,
656
+ f" {output.name}: {', '.join(changes) or 'unchanged'}; "
657
+ f"site atoms=[{', '.join(atom_counts)}]; charge={charge:.8f}",
658
+ )
482
659
  return len(candidates)
483
660
 
484
661
 
@@ -493,6 +670,10 @@ def add_arguments(parser):
493
670
  "-occ", nargs="+", type=float,
494
671
  help="Allowed site occupancies, for example 0 0.125 0.25 ... 0.875 1.",
495
672
  )
673
+ parser.add_argument(
674
+ "-max-supercell", default="1x1x1",
675
+ help="Maximum diagonal supercell searched as AxBxC (default: 1x1x1).",
676
+ )
496
677
 
497
678
 
498
679
  def run(args):
@@ -510,22 +691,42 @@ def run(args):
510
691
 
511
692
  try:
512
693
  allowed_occupancies = _normalize_occupancies(args.occ)
694
+ max_supercell = _parse_supercell_limit(
695
+ getattr(args, "max_supercell", "1x1x1")
696
+ )
513
697
  except ValueError as exc:
514
698
  raise SystemExit(f"Error: {exc}") from exc
515
699
 
516
700
  output_root = Path(args.output_folder)
517
701
  output_root.mkdir(parents=True, exist_ok=True)
702
+ report = [
703
+ "PMK realloc-occ summary",
704
+ f"Target formula: {args.formula}",
705
+ f"Maximum supercell: {'x'.join(map(str, max_supercell))}",
706
+ "",
707
+ ]
518
708
  files_written, inputs_done = 0, 0
519
709
  for source in sources:
520
710
  try:
521
711
  files_written += process_one(
522
- source, output_root, args.formula, allowed_occupancies
712
+ source,
713
+ output_root,
714
+ args.formula,
715
+ allowed_occupancies,
716
+ max_supercell,
717
+ report,
523
718
  )
524
719
  inputs_done += 1
525
720
  except Exception as exc:
526
- print(f"{source}: failed ({exc})")
527
- print(f"Done: wrote {files_written} CIF(s) for {inputs_done}/{len(sources)} "
528
- f"input structure(s) to {output_root}.")
721
+ _emit(report, f"{source}: failed ({exc})")
722
+ summary = (
723
+ f"Done: wrote {files_written} CIF(s) for {inputs_done}/{len(sources)} "
724
+ f"input structure(s) to {output_root}."
725
+ )
726
+ _emit(report, summary)
727
+ report_path = output_root / "realloc-occ.txt"
728
+ report_path.write_text("\n".join(report) + "\n", encoding="utf-8")
729
+ print(f"Wrote {report_path}")
529
730
  return 0 if inputs_done == len(sources) else 1
530
731
 
531
732
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pymdkit
3
- Version: 1.5.4
3
+ Version: 1.5.6
4
4
  Summary: A unified command-line toolkit for atomistic / MD structure workflows.
5
5
  Author-email: Yueda Wang <ydwang0608@ustc.edu.cn>
6
6
  License-Expression: GPL-3.0-or-later
@@ -137,6 +137,7 @@ nohup pmk submit-vasp -subscript sub_vasp -queue slurm -max-job-num 30 > submit-
137
137
  pmk realloc-occ -i 66-Li4YCl6-5.cif -of chg-balance -formula Li3YCl6
138
138
  pmk realloc-occ -if cifs -of chg-balance -formula Li3YCl6
139
139
  pmk realloc-occ -i 66-Li4YCl6-5.cif -of chg-balance -formula Li3YCl6 -occ 0 0.125 0.25 0.375 0.5 0.625 0.75 0.875 1
140
+ pmk realloc-occ -if cifs -of chg-balance -formula Li3YCl6 -occ 0.25 0.5 0.75 1 -max-supercell 2x2x2
140
141
  pmk substitute -i Li3YCl6.cif -se Li -sn 3 -we Na -wn 3 -on 100
141
142
  pmk substitute -i Li3YCl6.cif -se Li -sn 3 -we none -on 100
142
143
  pmk substitute -i Li96Ta6La11Cl72.cif -se Li1 Li2 -sn 20 67 -we none -on 100
@@ -230,16 +231,25 @@ the mean triclinic-box volume over that run; for NVT ensembles (`nvt_bdp`,
230
231
  Boltzmann constant, and a final `* 1000` conversion from S/cm to mS/cm.
231
232
 
232
233
  `realloc-occ -i INPUT.cif -of OUTPUT -formula FORMULA` computes atom counts as
233
- Wyckoff multiplicity times occupancy and uses `_cell_formula_units_Z` to map the
234
- target reduced formula into the existing cell. It enumerates finite site-wise
234
+ Wyckoff multiplicity times occupancy. Because source `_cell_formula_units_Z`
235
+ belongs to the source formula, PMK infers a new target Z from the available site
236
+ capacities and current atom counts, then writes that target Z to each output CIF.
237
+ It enumerates finite site-wise
235
238
  occupancy allocations, retains only charge-balanced candidates using the CIF
236
239
  oxidation-number loop, and preserves the original symmetry, coordinates,
237
- Wyckoff labels, and CIF layout. Every input receives `OUTPUT/INPUT_STEM/`; for
240
+ Wyckoff labels, and CIF layout. A missing all-zero oxidation assignment is
241
+ replaced by pymatgen's highest-ranked charge-balanced composition guess.
242
+ Every input receives `OUTPUT/INPUT_STEM/`; for
238
243
  the supplied Li4YCl6 example, the two outputs are `...-d1.cif` with `Li1=0.50`
239
244
  and `...-d2.cif` with `Li2=0.50`. Folder mode uses `-if` with the same `-of` and
240
245
  `-formula` options. Add `-occ` followed by the only permitted occupancy values;
241
- three decimal places are supported, so grids containing `0.125`, `0.375`,
242
- `0.625`, and `0.875` are preserved exactly in generated CIF files.
246
+ input grids support three decimal places, including `0.125`, `0.375`, `0.625`,
247
+ and `0.875`. Generated CIF occupancy fields use two decimal places.
248
+ `-max-supercell AxBxC` searches bounded diagonal supercells, smallest volume
249
+ first, until every multiplicity times occupancy times supercell determinant is
250
+ an integer. Equal-volume choices favor the most isotropic resulting cell.
251
+ All selections, site atom counts, oxidation states, charges, and failures are
252
+ recorded in `OUTPUT/realloc-occ.txt`.
243
253
 
244
254
  `gather-fs` recursively scans all job folders below the current directory. For
245
255
  VASP it follows the global `vaspout.h5 > vasprun.xml > OUTCAR` priority and
@@ -301,12 +311,15 @@ inequivalent-site identifiers such as `Li1`, `Y1`, `Cl1`, and `Cl2`.
301
311
  The final atom-site loop starts with `_atom_site_label`, followed by
302
312
  `_atom_site_type_symbol`, whose values are plain elements such as `Li`, `Y`,
303
313
  and `Cl`. Oxidation numbers remain in the separate
304
- `_atom_type_oxidation_number` column. PMK does not add an
314
+ `_atom_type_oxidation_number` column. When a generated multi-element CIF has
315
+ no oxidation states or only zero-valued states, PMK infers the highest-ranked
316
+ charge-balanced element assignment with pymatgen; explicit nonzero oxidation
317
+ states are preserved. PMK does not add an
305
318
  `_audit_creation_method` block or a generated-by header comment.
306
319
 
307
320
  Newly serialized floating-point values use eight digits after the decimal
308
321
  point across PMK structure, trajectory, data, report, and screen output. CIF
309
- `_atom_site_occupancy` values use three digits and
322
+ `_atom_site_occupancy` values use two digits and
310
323
  `_atom_type_oxidation_number` values use one digit. In extended XYZ, zero components
311
324
  inside the second-line `Lattice="..."` value remain `0.0`; other generated
312
325
  floating-point values use eight digits. Commands that select or concatenate
@@ -15,6 +15,7 @@ src/pymdkit/commands/_extxyz.py
15
15
  src/pymdkit/commands/_fileio.py
16
16
  src/pymdkit/commands/_geometry.py
17
17
  src/pymdkit/commands/_gpumd.py
18
+ src/pymdkit/commands/_oxidation.py
18
19
  src/pymdkit/commands/_precision.py
19
20
  src/pymdkit/commands/_reduction.py
20
21
  src/pymdkit/commands/_vasp_output.py
@@ -45,4 +46,5 @@ src/pymdkit/commands/umap.py
45
46
  src/pymdkit/commands/vasp2xyz.py
46
47
  src/pymdkit/commands/vasp_fe.py
47
48
  src/pymdkit/commands/vasp_relax.py
48
- src/pymdkit/commands/vasp_static.py
49
+ src/pymdkit/commands/vasp_static.py
50
+ tests/test_realloc_occ.py
@@ -0,0 +1,208 @@
1
+ import sys
2
+ import tempfile
3
+ import types
4
+ import unittest
5
+ from pathlib import Path
6
+ from unittest.mock import patch
7
+
8
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
9
+
10
+ from pymdkit.commands import _cifio, _oxidation, realloc_occ
11
+
12
+
13
+ OXIDATION = {"Li": 1.0, "Y": 3.0, "Cl": -1.0}
14
+
15
+
16
+ def cif_text(lengths, z, rows):
17
+ site_rows = "\n".join(
18
+ f"{label} {element} {multiplicity} {occupancy} 0 0 0"
19
+ for label, element, multiplicity, occupancy in rows
20
+ )
21
+ return f"""data_test
22
+ _cell_length_a {lengths[0]}
23
+ _cell_length_b {lengths[1]}
24
+ _cell_length_c {lengths[2]}
25
+ _cell_formula_units_Z {z}
26
+ loop_
27
+ _atom_type_symbol
28
+ _atom_type_oxidation_number
29
+ Li1 0.0
30
+ Y1 0.0
31
+ Cl1 0.0
32
+ Cl2 0.0
33
+ Cl3 0.0
34
+ loop_
35
+ _atom_site_label
36
+ _atom_site_type_symbol
37
+ _atom_site_site_symmetry_multiplicity
38
+ _atom_site_occupancy
39
+ _atom_site_fract_x
40
+ _atom_site_fract_y
41
+ _atom_site_fract_z
42
+ {site_rows}
43
+ """
44
+
45
+
46
+ class ReallocOccTests(unittest.TestCase):
47
+ def parse(self, text, name):
48
+ folder = tempfile.TemporaryDirectory()
49
+ self.addCleanup(folder.cleanup)
50
+ path = Path(folder.name) / name
51
+ path.write_text(text, encoding="utf-8")
52
+ with patch.object(
53
+ realloc_occ._oxidation,
54
+ "infer_oxidation_states",
55
+ return_value=OXIDATION,
56
+ ):
57
+ return realloc_occ.parse_cif(path)
58
+
59
+ def test_88_structure_needs_no_supercell(self):
60
+ parsed = self.parse(
61
+ cif_text(
62
+ (9.07355330, 12.82494197, 5.00151748),
63
+ 4,
64
+ [
65
+ ("Li1", "Li", 8, 1),
66
+ ("Y1", "Y", 4, 1),
67
+ ("Cl1", "Cl", 8, 1),
68
+ ("Cl2", "Cl", 4, 1),
69
+ ],
70
+ ),
71
+ "88.cif",
72
+ )
73
+ target, counts, z, candidates, matrix = realloc_occ.generate_candidates(
74
+ parsed, "Li3YCl6", (0.25, 0.5, 0.75, 1.0), (2, 2, 2)
75
+ )
76
+ self.assertEqual(matrix, (1, 1, 1))
77
+ self.assertEqual(z, 2)
78
+ self.assertEqual(candidates[0][0][:2], [0.75, 0.5])
79
+ self.assertAlmostEqual(candidates[0][1], 0.0)
80
+
81
+ def test_119_structure_selects_b_axis_supercell(self):
82
+ parsed = self.parse(
83
+ cif_text(
84
+ (6.32126668, 3.65475462, 6.33072831),
85
+ 1,
86
+ [
87
+ ("Li1", "Li", 1, 1),
88
+ ("Li2", "Li", 1, 1),
89
+ ("Y1", "Y", 1, 1),
90
+ ("Cl1", "Cl", 1, 1),
91
+ ("Cl2", "Cl", 1, 1),
92
+ ("Cl3", "Cl", 1, 1),
93
+ ],
94
+ ),
95
+ "119.cif",
96
+ )
97
+ result = realloc_occ.generate_candidates(
98
+ parsed, "Li3YCl6", (0.25, 0.5, 0.75, 1.0), (2, 2, 2)
99
+ )
100
+ matrix, occupancies = result[4], result[3][0][0]
101
+ self.assertEqual(matrix, (1, 2, 1))
102
+ determinant = 2
103
+ for site, occupancy in zip(parsed.sites, occupancies):
104
+ count = site.multiplicity * occupancy * determinant
105
+ self.assertAlmostEqual(count, round(count))
106
+
107
+ def test_render_repairs_oxidation_and_uses_two_digit_occupancy(self):
108
+ parsed = self.parse(
109
+ cif_text(
110
+ (9, 12, 5),
111
+ 4,
112
+ [
113
+ ("Li1", "Li", 8, 1),
114
+ ("Y1", "Y", 4, 1),
115
+ ("Cl1", "Cl", 8, 1),
116
+ ("Cl2", "Cl", 4, 1),
117
+ ],
118
+ ),
119
+ "input.cif",
120
+ )
121
+ target, counts, z, candidates, _matrix = realloc_occ.generate_candidates(
122
+ parsed, "Li3YCl6", (0.25, 0.5, 0.75, 1.0), (1, 1, 1)
123
+ )
124
+ output = parsed.path.parent / "output.cif"
125
+ realloc_occ.render_candidate(
126
+ parsed, candidates[0][0], target, counts, z, output
127
+ )
128
+ text = output.read_text(encoding="utf-8")
129
+ self.assertIn("Li1 1.0", text)
130
+ self.assertIn("Y1 3.0", text)
131
+ self.assertIn("Cl1 -1.0", text)
132
+ self.assertIn("Li1 Li 8 0.75", text)
133
+ self.assertIn("Y1 Y 4 0.50", text)
134
+
135
+ def test_shared_cif_precision_is_two_digits(self):
136
+ block = types.SimpleNamespace(
137
+ data={
138
+ _cifio.OCCUPANCY_TAG: [0.5],
139
+ _cifio.OXIDATION_TAG: [1],
140
+ }
141
+ )
142
+ _cifio._format_cif_numbers(block)
143
+ self.assertEqual(block.data[_cifio.OCCUPANCY_TAG], ["0.50"])
144
+ self.assertEqual(block.data[_cifio.OXIDATION_TAG], ["1.0"])
145
+
146
+ def test_run_writes_realloc_report(self):
147
+ with tempfile.TemporaryDirectory() as folder:
148
+ root = Path(folder)
149
+ source = root / "88.cif"
150
+ output = root / "out"
151
+ source.write_text(
152
+ cif_text(
153
+ (9.07355330, 12.82494197, 5.00151748),
154
+ 4,
155
+ [
156
+ ("Li1", "Li", 8, 1),
157
+ ("Y1", "Y", 4, 1),
158
+ ("Cl1", "Cl", 8, 1),
159
+ ("Cl2", "Cl", 4, 1),
160
+ ],
161
+ ),
162
+ encoding="utf-8",
163
+ )
164
+ args = types.SimpleNamespace(
165
+ input=str(source),
166
+ input_folder=None,
167
+ output_folder=str(output),
168
+ formula="Li3YCl6",
169
+ occ=[0.25, 0.5, 0.75, 1.0],
170
+ max_supercell="2x2x2",
171
+ )
172
+ with patch.object(
173
+ realloc_occ._oxidation,
174
+ "infer_oxidation_states",
175
+ return_value=OXIDATION,
176
+ ):
177
+ self.assertEqual(realloc_occ.run(args), 0)
178
+ report = (output / "realloc-occ.txt").read_text(encoding="utf-8")
179
+ self.assertIn("supercell=1x1x1", report)
180
+ self.assertIn("Li1=6", report)
181
+ self.assertIn("charge=0.00000000", report)
182
+
183
+ class OxidationTests(unittest.TestCase):
184
+ def test_uses_highest_ranked_pymatgen_guess(self):
185
+ class Composition:
186
+ def __init__(self, amounts):
187
+ self.amounts = amounts
188
+
189
+ def oxi_state_guesses(self, max_sites):
190
+ self.max_sites = max_sites
191
+ return [OXIDATION]
192
+
193
+ core = types.ModuleType("pymatgen.core")
194
+ core.Composition = Composition
195
+ pymatgen = types.ModuleType("pymatgen")
196
+ pymatgen.core = core
197
+ with patch.dict(
198
+ sys.modules,
199
+ {"pymatgen": pymatgen, "pymatgen.core": core},
200
+ ):
201
+ result = _oxidation.infer_oxidation_states(
202
+ {"Li": 8, "Y": 4, "Cl": 12}
203
+ )
204
+ self.assertEqual(result, OXIDATION)
205
+
206
+
207
+ if __name__ == "__main__":
208
+ unittest.main()
File without changes
File without changes