Support direct posfile coordinates
Browse filesFiles changed (3)
45 unmodified lines4647484950515245 unmodified lines`posfile`, `momfile`, and `exchange`; `positions`, `moments`, and `jfile` areaccepted as fallback aliases.`posfile` stores a basis-site number, atom type, and Cartesian position:```text# site atom_type x y z45 unmodified lines4647484950515253545556575845 unmodified lines`posfile`, `momfile`, and `exchange`; `positions`, `moments`, and `jfile` areaccepted as fallback aliases.`posfile` stores a basis-site number, atom type, and position. By default thethree position values are Cartesian (`posfiletype C`). With `posfiletype D`,they are direct/fractional coordinates and are converted using the cell:```textposfiletype D``````text# site atom_type x y z
40 unmodified lines41424344454628 unmodified lines7576777879808161 unmodified lines14314414514614714816 unmodified lines16516616716816917042 unmodified lines21321421521621721810 unmodified lines2292302312322332342352362372381 unmodified line24024124224324424524624773 unmodified lines32132232332432532632740 unmodified lineskeywords: dict[str, list[str]] = field(default_factory=dict)warnings: list[str] = field(default_factory=list)alat: float | None = None@dataclass28 unmodified lines_KNOWN_KEYWORDS = {"simid", "ncell", "bc", "posfile", "positions", "momfile", "moments", "exchange", "jfile","cell", "alat", "hamiltonian", "elements", "do", "temperature", "tstep",}# These are the canonical file keywords. Keep the older descriptive61 unmodified lineswarnings: list[str] = []cell: np.ndarray | None = Nonealat: float | None = Noneindex = 0while index < len(lines):line_number = index + 116 unmodified linesraise InputFormatError(f"{input_file}:{line_number}: alat must be positive")values[key] = tokens[1:]continueif key == "cell":rows: list[list[float]] = []# UppASD examples commonly separate cell components with commas.42 unmodified lineskeywords=values,warnings=warnings,alat=alat,)10 unmodified linesraise InputFormatError(f"{source}:{line_number}: {exc}") from excdef parse_posfile(path: str | Path) -> dict[int, PositionRecord]:"""Parse ``site atom_type x y z`` Cartesian position rows."""source = Path(path).expanduser().resolve()records: dict[int, PositionRecord] = {}for line, tokens in _rows(source):if len(tokens) != 5:1 unmodified linesite = _integer(tokens[0], path=source, line=line, field="site")if site in records:raise InputFormatError(f"{source}:{line}: duplicate site index {site}")position = tuple(_float(token, path=source, line=line, field="position") for token in tokens[2:5])records[site] = PositionRecord(site, _identifier(tokens[1]), position, line)return records73 unmodified linesreport = ValidationReport()for warning in config.warnings:report.add_warning("unknown_keyword", warning, source=str(config.input_file))positions = parse_posfile(config.posfile)moments = parse_momfile(config.momfile)bonds = parse_exchange(config.exchange, strict=strict, report=report)40 unmodified lines4142434445464728 unmodified lines7677787980818261 unmodified lines14414514614714814915016 unmodified lines16716816917017117217317417517617717842 unmodified lines22122222322422522622710 unmodified lines2382392402412422432442452462472482492502512522532542552562572582592602612622632642652662671 unmodified line26927027127227327427527627727827928028173 unmodified lines35535635735835936036140 unmodified lineskeywords: dict[str, list[str]] = field(default_factory=dict)warnings: list[str] = field(default_factory=list)alat: float | None = Noneposfiletype: str = "C"@dataclass28 unmodified lines_KNOWN_KEYWORDS = {"simid", "ncell", "bc", "posfile", "positions", "momfile", "moments", "exchange", "jfile","cell", "alat", "posfiletype", "hamiltonian", "elements", "do", "temperature", "tstep",}# These are the canonical file keywords. Keep the older descriptive61 unmodified lineswarnings: list[str] = []cell: np.ndarray | None = Nonealat: float | None = Noneposfiletype = "C"index = 0while index < len(lines):line_number = index + 116 unmodified linesraise InputFormatError(f"{input_file}:{line_number}: alat must be positive")values[key] = tokens[1:]continueif key == "posfiletype":if len(tokens) != 2 or tokens[1].upper() not in {"C", "D"}:raise InputFormatError(f"{input_file}:{line_number}: posfiletype must be either C or D")posfiletype = tokens[1].upper()values[key] = [posfiletype]continueif key == "cell":rows: list[list[float]] = []# UppASD examples commonly separate cell components with commas.42 unmodified lineskeywords=values,warnings=warnings,alat=alat,posfiletype=posfiletype,)10 unmodified linesraise InputFormatError(f"{source}:{line_number}: {exc}") from excdef parse_posfile(path: str | Path,*,posfiletype: str = "C",cell: np.ndarray | None = None,) -> dict[int, PositionRecord]:"""Parse ``site atom_type x y z`` position rows.``C`` interprets the coordinates as Cartesian. ``D`` interprets them asdirect (fractional) coordinates and converts them using the direct-cellvectors stored as rows of ``cell``."""source = Path(path).expanduser().resolve()normalized_type = str(posfiletype).upper()if normalized_type not in {"C", "D"}:raise InputFormatError(f"{source}: posfiletype must be either C or D")direct_cell = Noneif normalized_type == "D":if cell is None:raise InputFormatError(f"{source}: a 3x3 cell is required for posfiletype D")direct_cell = np.asarray(cell, dtype=float)if direct_cell.shape != (3, 3) or not np.isfinite(direct_cell).all():raise InputFormatError(f"{source}: cell must be a finite 3x3 matrix for posfiletype D")records: dict[int, PositionRecord] = {}for line, tokens in _rows(source):if len(tokens) != 5:1 unmodified linesite = _integer(tokens[0], path=source, line=line, field="site")if site in records:raise InputFormatError(f"{source}:{line}: duplicate site index {site}")position = np.asarray([_float(token, path=source, line=line, field="position") for token in tokens[2:5]],dtype=float,)if direct_cell is not None:position = position @ direct_cellrecords[site] = PositionRecord(site, _identifier(tokens[1]), tuple(float(value) for value in position), line)return records73 unmodified linesreport = ValidationReport()for warning in config.warnings:report.add_warning("unknown_keyword", warning, source=str(config.input_file))positions = parse_posfile(config.posfile, posfiletype=config.posfiletype, cell=config.cell)moments = parse_momfile(config.momfile)bonds = parse_exchange(config.exchange, strict=strict, report=report)
26 unmodified lines27282930313242 unmodified lines75767778798026 unmodified linesdef test_loads_multiline_nonorthogonal_input_and_relative_paths(tmp_path: Path):loaded = load_uppasd(write_input(tmp_path))assert np.allclose(loaded.cell, [[1, 0, 0], [0.5, 1, 0], [0, 0, 2]])assert loaded.units.energy == "mRy"assert loaded.model.sites[0].moment == 2.0assert loaded.model.sites[0].spin_direction == (0.0, 0.0, 1.0)42 unmodified linesassert config.cell.shape == (3, 3)def test_legacy_file_keyword_aliases_remain_fallbacks(tmp_path: Path):(tmp_path / "positions").write_text("1 1 0 0 0\n")(tmp_path / "moments").write_text("1 1 2.0 0 0 1\n")26 unmodified lines2728293031323342 unmodified lines76777879808182838485868788899091929326 unmodified linesdef test_loads_multiline_nonorthogonal_input_and_relative_paths(tmp_path: Path):loaded = load_uppasd(write_input(tmp_path))assert np.allclose(loaded.cell, [[1, 0, 0], [0.5, 1, 0], [0, 0, 2]])assert loaded.config.posfiletype == "C"assert loaded.units.energy == "mRy"assert loaded.model.sites[0].moment == 2.0assert loaded.model.sites[0].spin_direction == (0.0, 0.0, 1.0)42 unmodified linesassert config.cell.shape == (3, 3)def test_posfiletype_d_converts_direct_positions_using_the_cell(tmp_path: Path):inpsd = write_input(tmp_path, pos="1 1 0.5 0.5 0.5\n")inpsd.write_text("posfiletype D\n" + inpsd.read_text(), encoding="utf-8")config = parse_inpsd(inpsd)loaded = load_uppasd(inpsd)assert config.posfiletype == "D"assert np.allclose(loaded.model.sites[0].position, [0.75, 0.5, 1.0])assert not any(issue.code == "unknown_keyword" for issue in loaded.report.issues)def test_legacy_file_keyword_aliases_remain_fallbacks(tmp_path: Path):(tmp_path / "positions").write_text("1 1 0 0 0\n")(tmp_path / "moments").write_text("1 1 2.0 0 0 1\n")
docs/USAGE.md+7-1
src/induced_exchange/io_uppasd.py+40-6
tests/test_io_uppasd.py+13