vibe-sketcherDocumentation
Source code for vibesketcher.document.periodic_formats
"""Periodic interchange adapters with explicit loss contracts (#209).
Three plain-text formats used by solid-state workflows, read and written in
pure Python:
``poscar``
VASP POSCAR/CONTCAR, VASP 5 layout (species names line required).
G. Kresse, J. Furthmueller, Phys. Rev. B 54, 11169 (1996); the layout is
the one documented on the VASP wiki "POSCAR" page.
``extxyz``
Extended XYZ as written by ASE and libAtoms/QUIP: ``Lattice``,
``Properties`` and ``pbc`` on the comment line. A. H. Larsen et al.,
J. Phys.: Condens. Matter 29, 273002 (2017).
``gen``
The DFTB+ "Gen" geometry format (S supercell and F fractional types).
B. Hourahine et al., J. Chem. Phys. 152, 124101 (2020); layout from the
DFTB+ manual, appendix "Gen format".
The contract, the same for every format:
* Reading never guesses. A POSCAR without a species names line, an XYZ
without ``Lattice`` and ``pbc``, or a GEN type name that is not an element
is refused. Per-axis constraints, magnetic moments, per-site charges,
isotopic masses, partial occupancy and nonzero velocities, which the model
cannot hold, are refused with the line number.
* Writing returns text only; it never changes or replaces the source
document. Partial occupancy is always refused. Anything else the format
cannot carry (image bonds, parent mapping, a nonperiodic axis, site IDs,
fixed sites, charge/spin, the space-group description, anisotropic
displacement tensors) is a *loss*: the
writer refuses unless ``reduced=True``, and then returns the list of
losses with the text. Every written text is read back and compared before
it is returned.
Unlisted formats (SHELX RES, periodic PDB, CSSR, LAMMPS data) are assessed
in the manual but not implemented, and nothing here offers them.
"""
from __future__ import annotations
import hashlib
import math
import re
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any, Literal
import numpy as np
from vibesketcher.document import crystal
from vibesketcher.document.model import PeriodicStructure
from vibesketcher.elements import SYMBOLS
Format = Literal["poscar", "extxyz", "gen"]
#: The implemented formats; nothing else is discoverable.
FORMATS: tuple[Format, ...] = ("poscar", "extxyz", "gen")
_MAX_SITES = 25000
_POSITION_TOLERANCE = 1e-8 # angstrom, read-back check
_REFERENCES = {
"poscar": "G. Kresse, J. Furthmueller, Phys. Rev. B 54, 11169 (1996)",
"extxyz": "A. H. Larsen et al., J. Phys.: Condens. Matter 29, 273002 (2017)",
"gen": "B. Hourahine et al., J. Chem. Phys. 152, 124101 (2020)",
}
_LABELS = {"poscar": "POSCAR", "extxyz": "extended XYZ", "gen": "GEN"}
#: What each format can carry beyond lattice, species and positions.
CAPABILITIES: dict[Format, dict[str, bool]] = {
"poscar": {"partial_pbc": False, "site_ids": False, "fixed_sites": True,
"charge": False, "multiplicity": False},
"extxyz": {"partial_pbc": True, "site_ids": True, "fixed_sites": True,
"charge": True, "multiplicity": True},
"gen": {"partial_pbc": False, "site_ids": False, "fixed_sites": False,
"charge": False, "multiplicity": False},
} # fmt: skip
[docs]
@dataclass(frozen=True)
class Export:
"""Text in ``format`` and what it could not carry (empty when lossless)."""
format: Format
text: str
losses: list[str] = field(default_factory=list)
[docs]
def describe() -> list[dict[str, Any]]:
"""The implemented formats with what they carry, for listings."""
return [
{"format": name, "label": _LABELS[name], "read": True, "write": True,
"carries": dict(CAPABILITIES[name]), "reference": _REFERENCES[name]}
for name in FORMATS
] # fmt: skip
def _check_format(name: str) -> Format:
if name not in FORMATS:
raise ValueError(f"periodic format {name!r} is not available (choose {', '.join(FORMATS)})")
return name
# --- shared helpers ------------------------------------------------------------------
_NUMBER = re.compile(r"[+-]?(\d+\.?\d*|\.\d+)([eEdD][+-]?\d+)?")
def _float(text: str, where: str) -> float:
if not _NUMBER.fullmatch(text):
raise ValueError(f"{where}: {text!r} is not a number")
value = float(text.replace("d", "e").replace("D", "e"))
if not math.isfinite(value):
raise ValueError(f"{where}: {text!r} is not a finite number")
return value
def _int(text: str, where: str) -> int:
if not re.fullmatch(r"[+-]?\d{1,9}", text):
raise ValueError(f"{where}: {text!r} is not an integer")
return int(text)
def _element(name: str, where: str) -> str:
"""An element symbol, exactly; labels are never mapped to elements."""
symbol = name[:1].upper() + name[1:].lower()
if symbol not in SYMBOLS or not name.isalpha():
raise ValueError(f"{where}: {name!r} is not an element symbol")
return symbol
def _lines(text: str, label: str) -> list[str]:
from vibesketcher.limits import check_size
check_size(text, label)
return text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
def _site_count(count: int, where: str) -> None:
if count < 1:
raise ValueError(f"{where}: a periodic structure needs at least one site")
if count > _MAX_SITES:
raise ValueError(f"{where}: {count} sites exceed the limit of {_MAX_SITES}")
def _handed(lattice: np.ndarray) -> None:
if not float(np.linalg.det(lattice)) > 1e-10:
raise ValueError(
"the cell is left-handed or singular; vibe-sketcher does not reflect it "
"(that would invert the structure's handedness)"
)
def _make(
identifier: str,
lattice: np.ndarray,
symbols: list[str],
fractional: np.ndarray,
pbc: tuple[bool, bool, bool],
record: dict[str, Any],
*,
site_ids: list[str] | None = None,
charge: int | None = None,
multiplicity: int | None = None,
) -> PeriodicStructure:
_handed(lattice)
structure = crystal._structure(
identifier, lattice, list(zip(symbols, fractional, strict=True)), pbc, "unspecified",
record, site_ids=site_ids, charge=charge, multiplicity=multiplicity,
) # fmt: skip
provenance = dict(structure.provenance)
provenance["format"] = record["format"]
return structure.model_copy(update={"provenance": provenance})
def _record(fmt: Format, text: str, **extra: Any) -> dict[str, Any]:
return {"kind": f"{fmt}_import", "format": fmt,
"sha256": hashlib.sha256(text.encode()).hexdigest(),
"reference": _REFERENCES[fmt], **extra} # fmt: skip
def _fixed_sites(structure: PeriodicStructure) -> list[str]:
builder = structure.provenance.get("builder")
recorded = builder.get("fixed_sites") if isinstance(builder, dict) else None
if not isinstance(recorded, list):
return []
known = {s.id for s in structure.sites}
return [str(x) for x in recorded if str(x) in known]
def _fixed_indices(structure: PeriodicStructure) -> set[int]:
fixed = set(_fixed_sites(structure))
return {k for k, site in enumerate(structure.sites) if site.id in fixed}
def _number(x: float) -> str:
value = float(x)
return "0.0" if value == 0 else repr(value)
# --- POSCAR / CONTCAR ------------------------------------------------------------------
[docs]
def read_poscar(text: str, *, identifier: str) -> PeriodicStructure:
"""A 3-D periodic structure from VASP 5 POSCAR/CONTCAR text."""
lines = _lines(text, "POSCAR")
while lines and not lines[-1].strip():
lines.pop()
where: Callable[[int], str] = lambda n: f"POSCAR line {n + 1}" # noqa: E731
if len(lines) < 8:
raise ValueError("POSCAR needs a comment, a scale, three cell vectors, species, "
"counts, a coordinate mode and positions") # fmt: skip
comment = lines[0].strip()
scale_words = lines[1].split()
if len(scale_words) not in (1, 3):
raise ValueError(f"{where(1)}: give one scaling factor or three")
scale = [_float(w, where(1)) for w in scale_words]
rows = []
for n in range(2, 5):
words = lines[n].split()
if len(words) < 3:
raise ValueError(f"{where(n)}: a cell vector needs three numbers")
rows.append([_float(w, where(n)) for w in words[:3]])
lattice = np.array(rows, dtype=float)
if len(scale) == 1 and scale[0] < 0:
volume = abs(float(np.linalg.det(lattice)))
if volume <= 0:
raise ValueError(f"{where(1)}: a target volume needs a nonsingular cell")
factor = np.full(3, (-scale[0] / volume) ** (1 / 3))
elif any(s <= 0 for s in scale):
raise ValueError(f"{where(1)}: scaling factors must be positive (or one negative volume)")
else:
factor = np.array(scale * 3 if len(scale) == 1 else scale, dtype=float)
# VASP applies three factors per Cartesian component, one factor to the whole cell.
lattice = lattice * factor[None, :]
names = lines[5].split()
if not names:
raise ValueError(f"{where(5)}: the species names line is missing")
if all(re.fullmatch(r"\d+", w) for w in names):
raise ValueError(
f"{where(5)}: this is a VASP 4 POSCAR without species names; vibe-sketcher "
"does not guess species from the comment or a POTCAR, so add the names line"
)
species = []
labels = []
for word in names:
# VASP 6 may write POTCAR labels such as Si_GW or Fe/1a2b; the element precedes them.
base = re.split(r"[_/]", word, maxsplit=1)[0]
species.append(_element(base, where(5)))
labels.append(word)
count_words = lines[6].split()
if len(count_words) != len(species):
raise ValueError(f"{where(6)}: {len(species)} species but {len(count_words)} counts")
counts = [_int(w, where(6)) for w in count_words]
if any(c < 1 for c in counts):
raise ValueError(f"{where(6)}: species counts must be positive")
total = sum(counts)
_site_count(total, where(6))
n = 7
selective = lines[n].strip()[:1].lower() == "s"
if selective:
n += 1
if n >= len(lines) or not lines[n].strip():
raise ValueError(f"{where(n)}: the coordinate mode (Direct or Cartesian) is missing")
mode = lines[n].strip()[:1].lower()
if mode not in ("d", "c", "k"):
raise ValueError(f"{where(n)}: coordinate mode {lines[n].strip()!r} is not Direct "
"or Cartesian") # fmt: skip
cartesian = mode in ("c", "k")
n += 1
if len(lines) < n + total:
raise ValueError(f"POSCAR announces {total} sites but lists {max(0, len(lines) - n)}")
positions = np.zeros((total, 3))
fixed: list[int] = []
for k in range(total):
words = lines[n + k].split()
if len(words) < 3:
raise ValueError(f"{where(n + k)}: a position needs three numbers")
positions[k] = [_float(w, where(n + k)) for w in words[:3]]
if selective:
flags = [w.upper() for w in words[3:6]]
if len(flags) != 3 or any(f not in ("T", "F") for f in flags):
raise ValueError(f"{where(n + k)}: selective dynamics needs three T/F flags")
if flags == ["F", "F", "F"]:
fixed.append(k)
elif flags != ["T", "T", "T"]:
raise ValueError(
f"{where(n + k)}: per-axis constraint {' '.join(flags)} cannot be "
"represented; only fully fixed (F F F) or free (T T T) sites are admitted"
)
n += total
# CONTCAR: an optional velocity block (and MD predictor data) may follow.
tail = [(m, lines[m].split()) for m in range(n, len(lines)) if lines[m].strip()]
if tail:
first = tail[0][1]
if first[0][:1].lower() in ("c", "k", "d") and not _NUMBER.fullmatch(first[0]):
tail = tail[1:] # the velocity block's coordinate mode line
for m, words in tail[:total]:
try:
velocity = [_float(w, where(m)) for w in words[:3]]
except ValueError:
raise ValueError(f"{where(m)}: unexpected text after the positions") from None
if any(v != 0 for v in velocity):
raise ValueError(
f"{where(m)}: nonzero velocities cannot be carried; remove the velocity "
"block to import the positions"
)
if len(tail) > total:
raise ValueError(
f"{where(tail[total][0])}: MD predictor-corrector data cannot be carried; "
"remove it to import the positions"
)
symbols = [s for s, c in zip(species, counts, strict=True) for _ in range(c)]
_handed(lattice)
if cartesian:
positions = positions * factor[None, :]
fractional = positions @ np.linalg.inv(lattice)
else:
fractional = positions
ids = crystal._site_ids(symbols)
record = _record("poscar", text, comment=comment, species_labels=labels,
scale=scale_words, coordinates="cartesian" if cartesian else "direct",
selective_dynamics=selective, fixed_sites=[ids[k] for k in fixed],
pbc_assumed="POSCAR cells are periodic in three directions") # fmt: skip
return _make(identifier, lattice, symbols, fractional, (True, True, True), record,
site_ids=ids) # fmt: skip
def _write_poscar(structure: PeriodicStructure) -> str:
symbols = [s.symbol for s in structure.sites]
runs: list[list[Any]] = []
for symbol in symbols:
if runs and runs[-1][0] == symbol:
runs[-1][1] += 1
else:
runs.append([symbol, 1])
fixed = set(_fixed_sites(structure))
comment = re.sub(r"\s+", " ", structure.id)
out = [comment, "1.0"]
out += [" " + " ".join(_number(x) for x in row) for row in structure.lattice_angstrom]
out.append(" ".join(str(r[0]) for r in runs))
out.append(" ".join(str(r[1]) for r in runs))
if fixed:
out.append("Selective dynamics")
out.append("Direct")
for site in structure.sites:
line = " " + " ".join(_number(x) for x in site.fractional)
if fixed:
line += " F F F" if site.id in fixed else " T T T"
out.append(line)
return "\n".join(out) + "\n"
# --- extended XYZ ----------------------------------------------------------------------
_PAIR = re.compile(r'\s*([A-Za-z_][\w-]*)\s*(?:=\s*("(?:[^"\\]|\\.)*"|\{[^}]*\}|[^\s"]+))?')
_TRUE = {"t": True, "true": True, "1": True, "f": False, "false": False, "0": False}
# Per-atom data that would change the physical model if dropped.
_REFUSED_PROPERTY = re.compile(r"magmom|charge|occupanc|mass|spin", re.IGNORECASE)
def _info(comment: str, where: str) -> dict[str, str]:
info: dict[str, str] = {}
pos = 0
while pos < len(comment):
if comment[pos:].strip() == "":
break
match = _PAIR.match(comment, pos)
if match is None or match.end() == pos:
raise ValueError(f"{where}: cannot read the key=value pairs near "
f"{comment[pos:pos + 20]!r}") # fmt: skip
key, value = match[1], match[2]
if value is None:
value = "T"
elif value[:1] in ('"', "{"):
value = value[1:-1]
if key.lower() in {k.lower() for k in info}:
raise ValueError(f"{where}: key {key!r} is given twice")
info[key] = value
pos = match.end()
return info
def _get(info: dict[str, str], key: str) -> tuple[str, str] | None:
for name, value in info.items():
if name.lower() == key.lower():
return name, value
return None
[docs]
def read_extxyz(text: str, *, identifier: str) -> PeriodicStructure:
"""A periodic structure from one extended-XYZ frame with Lattice and pbc."""
lines = _lines(text, "extended XYZ")
where: Callable[[int], str] = lambda n: f"extended XYZ line {n + 1}" # noqa: E731
if len(lines) < 2:
raise ValueError("extended XYZ needs an atom count and a comment line")
count = _int(lines[0].strip(), where(0))
_site_count(count, where(0))
info = _info(lines[1], where(1))
lattice_item = _get(info, "Lattice")
if lattice_item is None:
raise ValueError(
f"{where(1)}: no Lattice= key; this is a molecular XYZ. vibe-sketcher never "
"infers periodicity from a comment line, so open it as xyz instead"
)
pbc_item = _get(info, "pbc")
if pbc_item is None:
raise ValueError(f"{where(1)}: state the periodic directions explicitly, "
'e.g. pbc="T T T"') # fmt: skip
cell_words = lattice_item[1].split()
if len(cell_words) != 9:
raise ValueError(f"{where(1)}: Lattice needs nine numbers (rows a, b, c)")
lattice = np.array([_float(w, where(1)) for w in cell_words]).reshape(3, 3)
pbc_words = pbc_item[1].split()
if len(pbc_words) == 1:
pbc_words *= 3
if len(pbc_words) != 3 or any(w.lower() not in _TRUE for w in pbc_words):
raise ValueError(f"{where(1)}: pbc needs three T/F flags")
pbc = (_TRUE[pbc_words[0].lower()], _TRUE[pbc_words[1].lower()],
_TRUE[pbc_words[2].lower()]) # fmt: skip
if not any(pbc):
raise ValueError(f"{where(1)}: pbc is F F F; this is a molecule, open it as xyz")
properties_item = _get(info, "Properties")
spec = properties_item[1] if properties_item else "species:S:1:pos:R:3"
parts = spec.split(":")
if len(parts) % 3:
raise ValueError(f"{where(1)}: Properties must be name:type:columns triples")
columns: dict[str, tuple[str, int, int]] = {}
offset = 0
for i in range(0, len(parts), 3):
name, kind, width_text = parts[i : i + 3]
width = _int(width_text, where(1))
if kind not in ("S", "R", "I", "L") or not 1 <= width <= 9:
raise ValueError(f"{where(1)}: property {name}:{kind}:{width_text} is not valid")
if name in columns:
raise ValueError(f"{where(1)}: property {name!r} is given twice")
columns[name] = (kind, offset, width)
offset += width
if "species" not in columns or "pos" not in columns:
raise ValueError(f"{where(1)}: Properties needs species:S:1 and pos:R:3")
if columns["pos"][0] != "R" or columns["pos"][2] != 3 or columns["species"][2] != 1:
raise ValueError(f"{where(1)}: Properties needs species:S:1 and pos:R:3")
for name in columns:
if _REFUSED_PROPERTY.search(name):
raise ValueError(
f"{where(1)}: per-site {name!r} cannot be carried by a periodic structure; "
"remove the column to import the positions"
)
if len(lines) < 2 + count:
raise ValueError(f"extended XYZ announces {count} atoms but lists "
f"{max(0, len(lines) - 2)}") # fmt: skip
if any(line.strip() for line in lines[2 + count :]):
raise ValueError(f"{where(2 + count)}: only one frame is read; split trajectories first")
symbols: list[str] = []
positions = np.zeros((count, 3))
ids: list[str] = []
fixed: list[int] = []
for k in range(count):
n = 2 + k
words = lines[n].split()
if len(words) != offset:
raise ValueError(f"{where(n)}: expected {offset} columns, found {len(words)}")
_kind, start, _width = columns["species"]
symbols.append(_element(words[start], where(n)))
_kind, start, _width = columns["pos"]
positions[k] = [_float(w, where(n)) for w in words[start : start + 3]]
if "site_id" in columns:
ids.append(words[columns["site_id"][1]])
if "velocities" in columns or "momenta" in columns:
key = "velocities" if "velocities" in columns else "momenta"
_kind, start, width = columns[key]
if any(_float(w, where(n)) != 0 for w in words[start : start + width]):
raise ValueError(f"{where(n)}: nonzero {key} cannot be carried; "
"remove the column to import the positions") # fmt: skip
if "move_mask" in columns:
_kind, start, width = columns["move_mask"]
mask = [w.lower() for w in words[start : start + width]]
if any(m not in _TRUE for m in mask):
raise ValueError(f"{where(n)}: move_mask needs T/F flags")
if not any(_TRUE[m] for m in mask):
fixed.append(k)
elif not all(_TRUE[m] for m in mask):
raise ValueError(f"{where(n)}: a partial move_mask cannot be represented; "
"only fully fixed or free sites are admitted") # fmt: skip
origin = np.zeros(3)
origin_item = _get(info, "Origin")
if origin_item is not None:
words = origin_item[1].split()
if len(words) != 3:
raise ValueError(f"{where(1)}: Origin needs three numbers")
origin = np.array([_float(w, where(1)) for w in words])
_handed(lattice)
fractional = (positions - origin) @ np.linalg.inv(lattice)
if ids:
bad = [i for i in ids if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_-]{0,63}", i)]
if bad or len(set(ids)) != len(ids):
raise ValueError(f"{where(1)}: site_id values must be unique identifiers")
else:
ids = crystal._site_ids(symbols)
charge = multiplicity = None
used = {"lattice", "pbc", "properties", "origin"}
charge_item = _get(info, "charge")
if charge_item is not None:
charge = _int(charge_item[1], where(1))
used.add("charge")
spin_item = _get(info, "multiplicity")
if spin_item is not None:
multiplicity = _int(spin_item[1], where(1))
if multiplicity < 1:
raise ValueError(f"{where(1)}: multiplicity must be at least 1")
used.add("multiplicity")
for key in info:
if _REFUSED_PROPERTY.search(key) and key.lower() not in used:
raise ValueError(f"{where(1)}: {key!r} cannot be carried by a periodic "
"structure; remove it to import the positions") # fmt: skip
interpreted = {"species", "pos", "site_id", "move_mask", "velocities", "momenta"}
ignored = sorted({*(k for k in info if k.lower() not in used),
*(f"Properties:{c}" for c in columns if c not in interpreted)}) # fmt: skip
record = _record("extxyz", text, origin_angstrom=origin.tolist(),
fixed_sites=[ids[k] for k in fixed], ignored=ignored) # fmt: skip
if ignored:
record["warnings"] = [f"not interpreted and not kept: {', '.join(ignored)}"]
return _make(identifier, lattice, symbols, fractional, pbc, record, site_ids=ids,
charge=charge, multiplicity=multiplicity) # fmt: skip
def _write_extxyz(structure: PeriodicStructure) -> str:
fixed = set(_fixed_sites(structure))
lattice = " ".join(_number(x) for row in structure.lattice_angstrom for x in row)
pbc = " ".join("T" if p else "F" for p in structure.pbc)
properties = "species:S:1:pos:R:3:site_id:S:1" + (":move_mask:L:1" if fixed else "")
header = f'Lattice="{lattice}" Properties={properties} pbc="{pbc}"'
if structure.charge is not None:
header += f" charge={structure.charge}"
if structure.multiplicity is not None:
header += f" multiplicity={structure.multiplicity}"
out = [str(len(structure.sites)), header]
for site in structure.sites:
xyz = " ".join(_number(x) for x in structure.cartesian(site))
line = f"{site.symbol} {xyz} {site.id}"
if fixed:
line += " F" if site.id in fixed else " T"
out.append(line)
return "\n".join(out) + "\n"
# --- DFTB+ GEN --------------------------------------------------------------------------
[docs]
def read_gen(text: str, *, identifier: str) -> PeriodicStructure:
"""A 3-D periodic structure from DFTB+ GEN text (types S or F)."""
lines = _lines(text, "GEN")
numbered = [(n, raw.split("#", 1)[0].split()) for n, raw in enumerate(lines)]
numbered = [(n, w) for n, w in numbered if w]
where: Callable[[int], str] = lambda n: f"GEN line {n + 1}" # noqa: E731
if len(numbered) < 2:
raise ValueError("GEN needs the atom count and type, and the element names")
n_head, head = numbered[0]
if len(head) < 2:
raise ValueError(f"{where(n_head)}: give the atom count and the geometry type")
count = _int(head[0], where(n_head))
_site_count(count, where(n_head))
kind = head[1].upper()
if kind == "C":
raise ValueError(f"{where(n_head)}: type C is a cluster without a cell; "
"it is not a periodic structure") # fmt: skip
if kind == "H":
raise ValueError(f"{where(n_head)}: helical (H) geometries are not admitted")
if kind not in ("S", "F"):
raise ValueError(f"{where(n_head)}: geometry type {head[1]!r} is not S or F")
n_names, names = numbered[1]
species = [_element(w, where(n_names)) for w in names]
body = numbered[2:]
if len(body) < count + 4:
raise ValueError(f"GEN announces {count} atoms and needs the origin and three cell "
f"vectors after them; it has {len(body)} lines") # fmt: skip
if len(body) > count + 4:
raise ValueError(f"{where(body[count + 4][0])}: unexpected text after the cell")
symbols = []
positions = np.zeros((count, 3))
for k in range(count):
n, words = body[k]
if len(words) != 5:
raise ValueError(f"{where(n)}: give index, type, x, y, z")
if _int(words[0], where(n)) != k + 1:
raise ValueError(f"{where(n)}: atoms must be numbered 1 to {count} in order")
type_index = _int(words[1], where(n))
if not 1 <= type_index <= len(species):
raise ValueError(f"{where(n)}: type {type_index} is not among the "
f"{len(species)} element names") # fmt: skip
symbols.append(species[type_index - 1])
positions[k] = [_float(w, where(n)) for w in words[2:]]
rows = []
for n, words in body[count:]:
if len(words) != 3:
raise ValueError(f"{where(n)}: give three numbers")
rows.append([_float(w, where(n)) for w in words])
origin = np.array(rows[0])
lattice = np.array(rows[1:])
_handed(lattice)
# F: fractional as given; S: Cartesian angstrom relative to the stated origin.
fractional = positions if kind == "F" else (positions - origin) @ np.linalg.inv(lattice)
record = _record("gen", text, geometry_type=kind, origin_angstrom=origin.tolist(),
pbc_assumed="GEN supercells are periodic in three directions") # fmt: skip
return _make(identifier, lattice, symbols, fractional, (True, True, True), record)
def _write_gen(structure: PeriodicStructure) -> str:
species: list[str] = []
for site in structure.sites:
if site.symbol not in species:
species.append(site.symbol)
out = [f"{len(structure.sites)} F", " ".join(species)]
for k, site in enumerate(structure.sites, 1):
xyz = " ".join(_number(x) for x in site.fractional)
out.append(f"{k} {species.index(site.symbol) + 1} {xyz}")
out.append("0.0 0.0 0.0")
out += [" ".join(_number(x) for x in row) for row in structure.lattice_angstrom]
return "\n".join(out) + "\n"
# --- dispatch, losses and read-back -----------------------------------------------------
_READERS: dict[Format, Callable[..., PeriodicStructure]] = {
"poscar": read_poscar,
"extxyz": read_extxyz,
"gen": read_gen,
}
_WRITERS: dict[Format, Callable[[PeriodicStructure], str]] = {
"poscar": _write_poscar,
"extxyz": _write_extxyz,
"gen": _write_gen,
}
[docs]
def read(text: str, fmt: str, *, identifier: str) -> PeriodicStructure:
"""A periodic structure read from ``text`` in an implemented format."""
return _READERS[_check_format(fmt)](text, identifier=identifier)
[docs]
def refusals(structure: PeriodicStructure, fmt: str) -> list[str]:
"""What no export flag can admit: losing these would change the chemistry."""
from vibesketcher.chem.reticular import assembly_refusals
_check_format(fmt)
unjoined = assembly_refusals(structure) # connection markers never become atoms (#202)
if unjoined:
return unjoined
partial = [s.id for s in structure.sites if s.occupancy < 1]
if partial:
return [f"partially occupied sites ({', '.join(partial[:8])}) cannot be written; "
"resolve the disorder first"] # fmt: skip
return []
[docs]
def losses(structure: PeriodicStructure, fmt: str) -> list[str]:
"""What ``fmt`` cannot carry from ``structure`` (empty when lossless)."""
name = _check_format(fmt)
can = CAPABILITIES[name]
label = _LABELS[name]
out: list[str] = []
if not all(structure.pbc) and not can["partial_pbc"]:
axes = "".join("abc"[i] for i, p in enumerate(structure.pbc) if not p)
out.append(f"nonperiodic direction {axes}: {label} cells are periodic in 3-D")
symbols = [s.symbol for s in structure.sites]
if not can["site_ids"] and [s.id for s in structure.sites] != crystal._site_ids(symbols):
out.append(f"site IDs: {label} has none; reading renumbers them by element")
if _fixed_sites(structure) and not can["fixed_sites"]:
out.append(f"fixed sites: {label} has no constraints")
if structure.charge is not None and not can["charge"]:
out.append(f"total charge {structure.charge}")
if structure.multiplicity is not None and not can["multiplicity"]:
out.append(f"spin multiplicity {structure.multiplicity}")
if structure.bonds:
out.append(f"{len(structure.bonds)} periodic bonds and their lattice images")
if structure.parent is not None or any(
s.parent_site is not None or s.image != (0, 0, 0) for s in structure.sites
):
out.append("parent cell, supercell matrix and parent-site mapping")
if any(s.disorder_group is not None for s in structure.sites):
out.append("disorder groups")
if structure.cell_setting != "unspecified":
out.append(f"cell setting label ({structure.cell_setting})")
builder = structure.provenance.get("builder")
if isinstance(builder, dict) and (builder.get("space_group") or builder.get("asymmetric_unit")):
out.append("space-group symmetry and asymmetric unit (written as P1)")
from vibesketcher.document import displacements
tensors = displacements.loss(structure) # none of these formats has a tensor field
if tensors is not None:
out.append(tensors)
return out
[docs]
def write(structure: PeriodicStructure, fmt: str, *, reduced: bool = False) -> Export:
"""``structure`` as ``fmt`` text; refuses losses unless ``reduced`` is set.
The text is read back and compared with ``structure`` (lattice, species,
positions and every field the format claims to carry) before it is
returned. The source structure and its document are not changed.
"""
name = _check_format(fmt)
refused = refusals(structure, name)
if refused:
raise ValueError("; ".join(refused))
lost = losses(structure, name)
if lost and not reduced:
raise ValueError(
f"{_LABELS[name]} cannot carry: {'; '.join(lost)}. Export a deliberately reduced "
"copy with reduced=True (--reduced), or save VSK/QVF to keep everything"
)
text = _WRITERS[name](structure)
_verify(structure, name, text)
return Export(format=name, text=text, losses=lost)
def _verify(structure: PeriodicStructure, fmt: Format, text: str) -> None:
back = read(text, fmt, identifier=structure.id)
can = CAPABILITIES[fmt]
problems = []
a = np.array(structure.lattice_angstrom)
if not np.allclose(a, np.array(back.lattice_angstrom), rtol=0, atol=1e-10):
problems.append("lattice")
if [s.symbol for s in back.sites] != [s.symbol for s in structure.sites]:
problems.append("species")
else:
source = np.array([structure.cartesian(s) for s in structure.sites])
again = np.array([back.cartesian(s) for s in back.sites])
if not np.allclose(source, again, rtol=0, atol=_POSITION_TOLERANCE):
problems.append("positions")
if (can["partial_pbc"] or all(structure.pbc)) and back.pbc != structure.pbc:
problems.append("pbc")
if can["site_ids"] and [s.id for s in back.sites] != [s.id for s in structure.sites]:
problems.append("site IDs")
if can["fixed_sites"] and _fixed_indices(back) != _fixed_indices(structure):
problems.append("fixed sites")
if can["charge"] and back.charge != structure.charge:
problems.append("charge")
if can["multiplicity"] and back.multiplicity != structure.multiplicity:
problems.append("multiplicity")
if problems:
raise ValueError(f"{_LABELS[fmt]} output did not read back: {', '.join(problems)}")
[docs]
def add_to_document(document: Any, structure: PeriodicStructure) -> Any:
"""A copy of ``document`` with ``structure`` added; its ID must be new."""
from vibesketcher.document.periodic import with_periodic
if any(s.id == structure.id for s in document.periodic_structures):
raise ValueError(f"periodic structure {structure.id!r} already exists")
return with_periodic(document, structure)