Harden UppASD input parsing
Browse filesFiles changed (5)
71 unmodified lines72737475767771 unmodified linesperiodic offset reduction or free-boundary range checks. Cell vectors are rowsand all mapped exchange vectors are stored as Cartesian vectors internally.`momfile` stores the reference moment in `mu_B`, optionally followed by aspin direction:71 unmodified lines72737475767778798081828371 unmodified linesperiodic offset reduction or free-boundary range checks. Cell vectors are rowsand all mapped exchange vectors are stored as Cartesian vectors internally.The input readers consume the required leading fields and ignore trailingcolumns or text. This applies to recognized `inpsd.dat` records, `posfile`,`momfile`, and `jfile` rows. `inpsd.dat` keywords not used by this package arealso silently ignored, so a deck may retain settings intended for otherUppASD executables.`momfile` stores the reference moment in `mu_B`, optionally followed by aspin direction:
167 unmodified lines1681691701711721731741751761771781791801811821831841851861871881 unmodified line1901911921931941951961971981992002012022032042052062072084 unmodified lines2132142152162172182192202212222232242253 unmodified lines22923023123223323423523623723823924024124259 unmodified lines30230330430530630730819 unmodified lines32832933033133233333433533633733833934034111 unmodified lines353354355356357358359360361362363364365167 unmodified linescontinuekey = tokens[0].lower()if key == "alat":if len(tokens) != 2:raise InputFormatError(f"{input_file}:{line_number}: alat must contain one numeric value in metres")alat = _float(tokens[1], path=input_file, line=line_number, field="alat")if alat <= 0:raise 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 == "maptype":if len(tokens) != 2:raise InputFormatError(f"{input_file}:{line_number}: maptype must contain one value (1, 2, or 3)")maptype = _integer(tokens[1], path=input_file, line=line_number, field="maptype")if maptype not in {1, 2, 3}:1 unmodified linevalues[key] = [str(maptype)]continueif key == "ncell":if len(tokens) != 4:raise InputFormatError(f"{input_file}:{line_number}: ncell must contain three positive integers")ncell_values = tuple(_integer(token, path=input_file, line=line_number, field="ncell") for token in tokens[1:])if any(value <= 0 for value in ncell_values):raise InputFormatError(f"{input_file}:{line_number}: ncell must contain three positive integers")ncell = ncell_valuesvalues[key] = tokens[1:]continueif key == "bc":if len(tokens) != 4:raise InputFormatError(f"{input_file}:{line_number}: BC must contain three values (P or F)")aliases = {"P": "P", "PERIODIC": "P", "F": "F", "FREE": "F", "O": "F", "OPEN": "F"}normalized_bc = tuple(token.upper() for token in tokens[1:])if any(value not in aliases for value in normalized_bc):raise InputFormatError(f"{input_file}:{line_number}: BC values must be P or F")bc = tuple(aliases[value] for value in normalized_bc) # type: ignore[assignment]4 unmodified lines# UppASD examples commonly separate cell components with commas.# Commas are punctuation here, not part of the numeric value.first = [token.strip(",") for token in tokens[1:]]if first:if len(first) == 9 and all(_is_float(token) for token in first):cell = np.asarray([float(token) for token in first], dtype=float).reshape(3, 3)continueif len(first) != 3 or not all(_is_float(token) for token in first):raise InputFormatError(f"{input_file}:{line_number}: cell must contain three numeric values per row")rows.append([float(token) for token in first])while len(rows) < 3:if index >= len(lines):raise InputFormatError(f"{input_file}:{line_number}: incomplete multiline cell")3 unmodified linesif not continuation:continuecontinuation_tokens = [token.strip(",") for token in shlex.split(continuation)]if len(continuation_tokens) != 3 or not all(_is_float(token) for token in continuation_tokens):raise InputFormatError(f"{input_file}:{continuation_number}: cell continuation must contain three numeric values")rows.append([float(token) for token in continuation_tokens])cell = np.asarray(rows, dtype=float)continuevalues[key] = tokens[1:]if key not in _KNOWN_KEYWORDS:warnings.append(f"{input_file}:{line_number}: ignored unknown UppASD keyword {tokens[0]!r}")if cell is None:raise InputFormatError(f"{input_file}: missing cell")59 unmodified linesraise 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:raise InputFormatError(f"{source}:{line}: expected 5 columns: site atom_type x y z")site = _integer(tokens[0], path=source, line=line, field="site")if site in records:19 unmodified linessource = Path(path).expanduser().resolve()records: dict[int, MomentRecord] = {}for line, tokens in _rows(source):if len(tokens) not in (3, 6):raise InputFormatError(f"{source}:{line}: expected 3 or 6 columns: site atom_type moment [sx sy sz]")site = _integer(tokens[0], path=source, line=line, field="site")if site in records:raise InputFormatError(f"{source}:{line}: duplicate site index {site}")moment = _float(tokens[2], path=source, line=line, field="moment")direction = Noneif len(tokens) == 6:direction = tuple(_float(token, path=source, line=line, field="spin direction") for token in tokens[3:6])records[site] = MomentRecord(site, tokens[1], moment, direction, line)return records11 unmodified linesbonds: list[ExchangeBond] = []for line, tokens in _rows(source):try:if len(tokens) not in (6, 7):raise InputFormatError(f"{source}:{line}: expected 6 or 7 columns: i j rx ry rz Jij [distance]")i = _integer(tokens[0], path=source, line=line, field="i")j = _integer(tokens[1], path=source, line=line, field="j")displacement = tuple(_float(token, path=source, line=line, field="displacement") for token in tokens[2:5])jij = _float(tokens[5], path=source, line=line, field="Jij")supplied_distance = _float(tokens[6], path=source, line=line, field="distance") if len(tokens) == 7 else Nonebond = ExchangeBond(i, j, displacement, jij, supplied_distance, line)if supplied_distance is not None and not np.isclose(supplied_distance, bond.distance, rtol=1e-6, atol=1e-8):if report is not None:167 unmodified lines1681691701711721731741751761771781791801811821831841851861871881 unmodified line1901911921931941951961971981992002012022032042052062072084 unmodified lines2132142152162172182192202212222232243 unmodified lines22822923023123223323423523623723823924024124224324459 unmodified lines30430530630730830931019 unmodified lines33033133233333433533633733833934034134234311 unmodified lines355356357358359360361362363364365366367167 unmodified linescontinuekey = tokens[0].lower()if key == "alat":if len(tokens) < 2:raise InputFormatError(f"{input_file}:{line_number}: alat must contain one numeric value in metres")alat = _float(tokens[1], path=input_file, line=line_number, field="alat")if alat <= 0:raise InputFormatError(f"{input_file}:{line_number}: alat must be positive")values[key] = tokens[1:2]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 == "maptype":if len(tokens) < 2:raise InputFormatError(f"{input_file}:{line_number}: maptype must contain one value (1, 2, or 3)")maptype = _integer(tokens[1], path=input_file, line=line_number, field="maptype")if maptype not in {1, 2, 3}:1 unmodified linevalues[key] = [str(maptype)]continueif key == "ncell":if len(tokens) < 4:raise InputFormatError(f"{input_file}:{line_number}: ncell must contain three positive integers")ncell_values = tuple(_integer(token, path=input_file, line=line_number, field="ncell") for token in tokens[1:4])if any(value <= 0 for value in ncell_values):raise InputFormatError(f"{input_file}:{line_number}: ncell must contain three positive integers")ncell = ncell_valuesvalues[key] = tokens[1:4]continueif key == "bc":if len(tokens) < 4:raise InputFormatError(f"{input_file}:{line_number}: BC must contain three values (P or F)")aliases = {"P": "P", "PERIODIC": "P", "F": "F", "FREE": "F", "O": "F", "OPEN": "F"}normalized_bc = tuple(token.upper() for token in tokens[1:4])if any(value not in aliases for value in normalized_bc):raise InputFormatError(f"{input_file}:{line_number}: BC values must be P or F")bc = tuple(aliases[value] for value in normalized_bc) # type: ignore[assignment]4 unmodified lines# UppASD examples commonly separate cell components with commas.# Commas are punctuation here, not part of the numeric value.first = [token.strip(",") for token in tokens[1:]]if len(first) >= 9 and all(_is_float(token) for token in first[:9]):cell = np.asarray([float(token) for token in first[:9]], dtype=float).reshape(3, 3)continueif len(first) < 3 or not all(_is_float(token) for token in first[:3]):raise InputFormatError(f"{input_file}:{line_number}: cell must contain three numeric values per row")rows.append([float(token) for token in first[:3]])while len(rows) < 3:if index >= len(lines):raise InputFormatError(f"{input_file}:{line_number}: incomplete multiline cell")3 unmodified linesif not continuation:continuecontinuation_tokens = [token.strip(",") for token in shlex.split(continuation)]if len(continuation_tokens) < 3 or not all(_is_float(token) for token in continuation_tokens[:3]):raise InputFormatError(f"{input_file}:{continuation_number}: cell continuation must contain three numeric values")rows.append([float(token) for token in continuation_tokens[:3]])cell = np.asarray(rows, dtype=float)continueif key not in _KNOWN_KEYWORDS:# UppASD decks are often shared across executables and contain# keywords this reader does not need. They are intentionally# ignored without becoming validation noise.continuevalues[key] = tokens[1:]if cell is None:raise InputFormatError(f"{input_file}: missing cell")59 unmodified linesraise 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:raise InputFormatError(f"{source}:{line}: expected 5 columns: site atom_type x y z")site = _integer(tokens[0], path=source, line=line, field="site")if site in records:19 unmodified linessource = Path(path).expanduser().resolve()records: dict[int, MomentRecord] = {}for line, tokens in _rows(source):if len(tokens) < 3:raise InputFormatError(f"{source}:{line}: expected 3 or 6 columns: site atom_type moment [sx sy sz]")site = _integer(tokens[0], path=source, line=line, field="site")if site in records:raise InputFormatError(f"{source}:{line}: duplicate site index {site}")moment = _float(tokens[2], path=source, line=line, field="moment")direction = Noneif len(tokens) >= 6 and all(_is_float(token) for token in tokens[3:6]):direction = tuple(_float(token, path=source, line=line, field="spin direction") for token in tokens[3:6])records[site] = MomentRecord(site, tokens[1], moment, direction, line)return records11 unmodified linesbonds: list[ExchangeBond] = []for line, tokens in _rows(source):try:if len(tokens) < 6:raise InputFormatError(f"{source}:{line}: expected 6 or 7 columns: i j rx ry rz Jij [distance]")i = _integer(tokens[0], path=source, line=line, field="i")j = _integer(tokens[1], path=source, line=line, field="j")displacement = tuple(_float(token, path=source, line=line, field="displacement") for token in tokens[2:5])jij = _float(tokens[5], path=source, line=line, field="Jij")supplied_distance = _float(tokens[6], path=source, line=line, field="distance") if len(tokens) >= 7 and _is_float(tokens[6]) else Nonebond = ExchangeBond(i, j, displacement, jij, supplied_distance, line)if supplied_distance is not None and not np.isclose(supplied_distance, bond.distance, rtol=1e-6, atol=1e-8):if report is not None:
371 unmodified lines37237337437537637729 unmodified lines4074084094104114124134144154164174184194206 unmodified lines4274284294304314321 unmodified line434435436437438439440371 unmodified linesreturn valuedef _parse_int(token: str, *, source: Path, line: int, field: str) -> int:try:return int(token)29 unmodified linescontinuetokens = line.split()try:if len(tokens) not in {6, 7, 8, 9}:raise VectorMappingError(f"{source}:{line_number}: expected 6/7 non-alloy or 8/9 random-alloy columns",code="malformed_jfile_row",source=source,line=line_number,)random_alloy = len(tokens) in {8, 9}if random_alloy:site_i = _parse_int(tokens[0], source=source, line=line_number, field="site_i")site_j = _parse_int(tokens[1], source=source, line=line_number, field="site_j")6 unmodified lineschemical_i = Nonechemical_j = Nonevector_start = 2input_vector = tuple(_parse_float(tokens[index], source=source, line=line_number, field="Rij")for index in range(vector_start, vector_start + 3)1 unmodified lineJij = _parse_float(tokens[vector_start + 3], source=source, line=line_number, field="Jij")supplied_distance = (_parse_float(tokens[vector_start + 4], source=source, line=line_number, field="distance")if len(tokens) == vector_start + 5else None)rows.append(JFileRow(site_i, site_j, input_vector, Jij, supplied_distance, chemical_i, chemical_j, line_number))371 unmodified lines37237337437537637737837938038138238338438529 unmodified lines4154164174184194204214224234244254264274284294304314324334344356 unmodified lines4424434444454464474484494504514524534541 unmodified line456457458459460461462371 unmodified linesreturn valuedef _is_finite_float(token: str) -> bool:try:value = float(token)except ValueError:return Falsereturn bool(np.isfinite(value))def _parse_int(token: str, *, source: Path, line: int, field: str) -> int:try:return int(token)29 unmodified linescontinuetokens = line.split()try:if len(tokens) < 6:raise VectorMappingError(f"{source}:{line_number}: expected at least 6 columns",code="malformed_jfile_row",source=source,line=line_number,)# A normal jfile row is six required fields, optionally followed# by a distance and/or arbitrary trailing data. Random-alloy# rows are recognized by their two non-numeric chemical fields;# this avoids mistaking trailing text on a normal row for alloy# metadata.random_alloy = len(tokens) >= 8 and (not _is_finite_float(tokens[2]) or not _is_finite_float(tokens[3]))if random_alloy:site_i = _parse_int(tokens[0], source=source, line=line_number, field="site_i")site_j = _parse_int(tokens[1], source=source, line=line_number, field="site_j")6 unmodified lineschemical_i = Nonechemical_j = Nonevector_start = 2if len(tokens) < vector_start + 4:raise VectorMappingError(f"{source}:{line_number}: incomplete exchange row",code="malformed_jfile_row",source=source,line=line_number,)input_vector = tuple(_parse_float(tokens[index], source=source, line=line_number, field="Rij")for index in range(vector_start, vector_start + 3)1 unmodified lineJij = _parse_float(tokens[vector_start + 3], source=source, line=line_number, field="Jij")supplied_distance = (_parse_float(tokens[vector_start + 4], source=source, line=line_number, field="distance")if len(tokens) > vector_start + 4 and _is_finite_float(tokens[vector_start + 4])else None)rows.append(JFileRow(site_i, site_j, input_vector, Jij, supplied_distance, chemical_i, chemical_j, line_number))
34 unmodified lines35363738394034 unmodified linesassert loaded.report.pair_completedef test_distance_mismatch_is_a_structured_warning(tmp_path: Path):loaded = load_uppasd(write_input(tmp_path, exchange="1 1 1 0 0 3 99\n"))assert any(issue.code == "distance_mismatch" for issue in loaded.report.warnings)34 unmodified lines3536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979834 unmodified linesassert loaded.report.pair_completedef test_unknown_inpsd_keywords_are_silently_ignored(tmp_path: Path):inpsd = write_input(tmp_path)inpsd.write_text("future_solver_keyword arbitrary trailing data\n" + inpsd.read_text(), encoding="utf-8")config = parse_inpsd(inpsd)loaded = load_uppasd(inpsd)assert config.warnings == []assert not any(issue.code == "unknown_keyword" for issue in loaded.report.issues)def test_input_readers_ignore_trailing_columns_and_text(tmp_path: Path):inpsd = write_input(tmp_path,exchange="1 1 0 0 0 1 trailing distance text\n",pos="1 1 0 0 0 trailing position text\n",mom="1 1 2.0 0 0 1 trailing moment text\n",)inpsd.write_text("simid demo trailing text\n""alat 2.0 trailing text\n""posfiletype C trailing text\n""maptype 1 trailing text\n""ncell 2 3 4 trailing text\n""BC P F P trailing text\n""cell 1 0 0 trailing cell text\n"" 0 1 0 trailing cell text\n"" 0 0 1 trailing cell text\n""posfile posfile trailing path text\n""momfile momfile trailing path text\n""exchange jfile trailing path text\n",encoding="utf-8",)loaded = load_uppasd(inpsd)assert loaded.report.okassert loaded.config.alat == 2.0assert loaded.config.ncell == (2, 3, 4)assert loaded.config.bc == ("P", "F", "P")assert len(loaded.model.sites) == 1assert len(loaded.model.exchange_bonds) == 1assert loaded.model.exchange_bonds[0].supplied_distance is Nonedef test_single_line_cell_ignores_trailing_columns(tmp_path: Path):inpsd = write_input(tmp_path)inpsd.write_text("cell 1 0 0 0 1 0 0 0 1 trailing cell text\n"+ "posfile posfile\nmomfile momfile\nexchange jfile\n",encoding="utf-8",)config = parse_inpsd(inpsd)assert np.allclose(config.cell, np.eye(3))def test_distance_mismatch_is_a_structured_warning(tmp_path: Path):loaded = load_uppasd(write_input(tmp_path, exchange="1 1 1 0 0 3 99\n"))assert any(issue.code == "distance_mismatch" for issue in loaded.report.warnings)
77 unmodified lines78798081828377 unmodified linesassert records[0].Jij == 2.0def test_periodic_offsets_are_reduced_and_free_offsets_are_rejected(tmp_path: Path):jfile = tmp_path / "jfile"jfile.write_text("1 1 2 0 0 1\n", encoding="utf-8")77 unmodified lines7879808182838485868788899091929394959697989910010177 unmodified linesassert records[0].Jij == 2.0def test_jfile_reader_ignores_trailing_columns_and_text(tmp_path: Path):jfile = tmp_path / "jfile"jfile.write_text("1 1 1 0 0 2 trailing columns and text\n", encoding="utf-8")parsed = read_jfile(jfile)mapped = map_exchange_file(jfile,positions=[(1, "Fe", 0.0, 0.0, 0.0)],cell=np.eye(3),maptype=1,)assert len(parsed) == 1assert parsed[0].Jij == 2.0assert mapped[0].Jij == 2.0assert mapped[0].supplied_distance is Nonedef test_periodic_offsets_are_reduced_and_free_offsets_are_rejected(tmp_path: Path):jfile = tmp_path / "jfile"jfile.write_text("1 1 2 0 0 1\n", encoding="utf-8")
docs/USAGE.md+6
src/induced_exchange/io_uppasd.py+27-25
src/induced_exchange/vector_mapping.py+26-4
tests/test_io_uppasd.py+58
tests/test_vector_mapping.py+18