usif 0.12.0__py3-none-any.whl

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.

Potentially problematic release.


This version of usif might be problematic. Click here for more details.

Files changed (55) hide show
  1. usif/__init__.py +78 -0
  2. usif/agent/__init__.py +36 -0
  3. usif/agent/config.py +212 -0
  4. usif/agent/discover.py +352 -0
  5. usif/agent/llm.py +133 -0
  6. usif/agent/plan.py +441 -0
  7. usif/agent/session.py +109 -0
  8. usif/agent/tools.py +718 -0
  9. usif/backends/__init__.py +23 -0
  10. usif/backends/ase.py +166 -0
  11. usif/backends/base.py +219 -0
  12. usif/backends/matsimpy.py +140 -0
  13. usif/backends/pymatgen.py +154 -0
  14. usif/cli/__init__.py +12 -0
  15. usif/cli/__main__.py +5 -0
  16. usif/cli/agent.py +250 -0
  17. usif/cli/common.py +49 -0
  18. usif/cli/dataset.py +245 -0
  19. usif/cli/plans.py +70 -0
  20. usif/cli/root.py +221 -0
  21. usif/codec/__init__.py +25 -0
  22. usif/codec/columns.py +140 -0
  23. usif/codec/compression.py +130 -0
  24. usif/codec/jsondoc.py +126 -0
  25. usif/codec/record.py +492 -0
  26. usif/codec/wire.py +139 -0
  27. usif/dataset/__init__.py +6 -0
  28. usif/dataset/dataset.py +694 -0
  29. usif/dataset/query.py +226 -0
  30. usif/dataset/sql.py +160 -0
  31. usif/elements.py +149 -0
  32. usif/errors.py +63 -0
  33. usif/fileio.py +56 -0
  34. usif/formula.py +109 -0
  35. usif/io.py +208 -0
  36. usif/model/__init__.py +25 -0
  37. usif/model/cell.py +125 -0
  38. usif/model/properties.py +468 -0
  39. usif/model/structure.py +285 -0
  40. usif/symmetry/__init__.py +50 -0
  41. usif/symmetry/expand.py +116 -0
  42. usif/symmetry/reduce.py +168 -0
  43. usif/symmetry/spacegroup.py +250 -0
  44. usif/symmetry/tables.py +298 -0
  45. usif/units.py +188 -0
  46. usif/upgrade/__init__.py +21 -0
  47. usif/upgrade/container_v2.py +272 -0
  48. usif/upgrade/format6.py +464 -0
  49. usif/version.py +95 -0
  50. usif-0.12.0.dist-info/METADATA +218 -0
  51. usif-0.12.0.dist-info/RECORD +55 -0
  52. usif-0.12.0.dist-info/WHEEL +5 -0
  53. usif-0.12.0.dist-info/entry_points.txt +2 -0
  54. usif-0.12.0.dist-info/licenses/LICENSE +20 -0
  55. usif-0.12.0.dist-info/top_level.txt +1 -0
usif/__init__.py ADDED
@@ -0,0 +1,78 @@
1
+ """USIF: exact, compact, queryable storage for atomistic structures.
2
+
3
+ Core objects::
4
+
5
+ from usif import Structure, Cell, read, write, convert, Dataset, Q
6
+
7
+ s = read("POSCAR") # any backend format, .usif or .json
8
+ write(s, "s.usif", symmetry="auto") # format-7 record
9
+ with Dataset("data.usifc") as ds: # SQLite-backed collection
10
+ ds.add(s, "relaxed", "/runs")
11
+ hits = list(ds.query(Q.formula("NaCl") & (Q.prop("energy") < 0)))
12
+
13
+ ``Dataset``/``Q`` and the backends are imported on first use.
14
+ """
15
+
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ from usif.codec import decode, encode
19
+ from usif.errors import (
20
+ ChecksumError,
21
+ DatasetError,
22
+ FormatError,
23
+ MissingDependencyError,
24
+ UnsupportedVersionError,
25
+ USIFError,
26
+ ValidationError,
27
+ )
28
+ from usif.io import convert, read, read_all, write, write_all
29
+ from usif.model import DEFAULT_SCHEMA, Cell, PropertySpec, Schema, Structure
30
+ from usif.version import (
31
+ DATASET_SCHEMA_VERSION,
32
+ FORMAT_VERSION,
33
+ RELEASE_DATE,
34
+ RELEASE_ID,
35
+ RELEASE_RECORD,
36
+ __version__,
37
+ )
38
+
39
+ if TYPE_CHECKING: # pragma: no cover
40
+ from usif.dataset import Dataset, Q
41
+
42
+ __all__ = [
43
+ "RELEASE_DATE",
44
+ "RELEASE_ID",
45
+ "RELEASE_RECORD",
46
+ "DATASET_SCHEMA_VERSION",
47
+ "DEFAULT_SCHEMA",
48
+ "FORMAT_VERSION",
49
+ "Cell",
50
+ "ChecksumError",
51
+ "Dataset",
52
+ "DatasetError",
53
+ "FormatError",
54
+ "MissingDependencyError",
55
+ "PropertySpec",
56
+ "Q",
57
+ "Schema",
58
+ "Structure",
59
+ "USIFError",
60
+ "UnsupportedVersionError",
61
+ "ValidationError",
62
+ "__version__",
63
+ "convert",
64
+ "decode",
65
+ "encode",
66
+ "read",
67
+ "read_all",
68
+ "write",
69
+ "write_all",
70
+ ]
71
+
72
+
73
+ def __getattr__(name: str) -> Any:
74
+ if name in ("Dataset", "Q"):
75
+ from usif import dataset
76
+
77
+ return getattr(dataset, name)
78
+ raise AttributeError(f"module 'usif' has no attribute {name!r}")
usif/agent/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ """The USIF data agent: natural-language access to a local dataset, with human approval.
2
+
3
+ * :mod:`usif.agent.config` - the OpenAI-compatible endpoint (DeepSeek by default);
4
+ * :mod:`usif.agent.llm` - the HTTP chat client (standard library only);
5
+ * :mod:`usif.agent.discover` - finding calculations and structure files in directories;
6
+ * :mod:`usif.agent.plan` - change plans and :func:`apply_plan`, the only write path;
7
+ * :mod:`usif.agent.tools` - the read-only tools and ``propose_*`` tools the model uses;
8
+ * :mod:`usif.agent.session` - the conversation loop.
9
+
10
+ The model can read and propose; a person approves a plan before anything is
11
+ written.
12
+ """
13
+
14
+ from usif.agent.config import LLMConfig, load_config
15
+ from usif.agent.discover import Candidate, ScanResult, scan
16
+ from usif.agent.llm import ChatClient, ChatModel
17
+ from usif.agent.plan import ApplyReport, Operation, Plan, apply_plan, plan_from_scan
18
+ from usif.agent.session import Session
19
+ from usif.agent.tools import Toolbox
20
+
21
+ __all__ = [
22
+ "ApplyReport",
23
+ "Candidate",
24
+ "ChatClient",
25
+ "ChatModel",
26
+ "LLMConfig",
27
+ "Operation",
28
+ "Plan",
29
+ "ScanResult",
30
+ "Session",
31
+ "Toolbox",
32
+ "apply_plan",
33
+ "load_config",
34
+ "plan_from_scan",
35
+ "scan",
36
+ ]
usif/agent/config.py ADDED
@@ -0,0 +1,212 @@
1
+ """Agent settings: the LLM endpoint (DeepSeek by default) and the default dataset.
2
+
3
+ LLM settings come from, in increasing priority: the defaults below, the
4
+ ``[llm]`` table of ``~/.usif/config.toml``, the ``USIF_LLM_*`` environment
5
+ variables, and explicit arguments.
6
+
7
+ The dataset ``usif agent ask/chat`` work on is, in decreasing priority: the
8
+ ``DATASET`` argument, the ``USIF_DATASET`` environment variable, and
9
+ ``dataset`` in the ``[agent]`` table of ``config.toml``. There is no other
10
+ default: no path is guessed, and a configured dataset must already exist.
11
+
12
+ ``~/.usif`` (or ``$USIF_HOME``) is the per-user USIF directory::
13
+
14
+ ~/.usif/
15
+ config.toml [llm] and [agent] settings
16
+ plans/ change plans saved for review (not yet applied)
17
+ plans/applied/ a copy of every applied plan, by id (the change journal)
18
+
19
+ Nothing is created until something is saved there.
20
+
21
+ The API key itself is never stored in the configuration: ``api_key_env`` names
22
+ the environment variable that holds it, and only the HTTP client reads it.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import os
28
+ import sys
29
+ from dataclasses import asdict, dataclass, fields, replace
30
+ from pathlib import Path
31
+ from typing import Any, Dict, Mapping, Optional, Tuple
32
+ from urllib.parse import urlsplit
33
+
34
+ from usif.errors import AgentError
35
+
36
+ if sys.version_info >= (3, 11):
37
+ import tomllib
38
+ else: # pragma: no cover - exercised on Python 3.10
39
+ import tomli as tomllib
40
+
41
+ __all__ = [
42
+ "DATASET_ENV",
43
+ "DEFAULT_CONFIG",
44
+ "LLMConfig",
45
+ "agent_dataset",
46
+ "config_path",
47
+ "default_dataset",
48
+ "load_config",
49
+ "plans_dir",
50
+ "usif_home",
51
+ ]
52
+
53
+ #: Environment variable naming the default dataset of ``usif agent ask/chat``.
54
+ DATASET_ENV = "USIF_DATASET"
55
+ _AGENT_SETTINGS = {"dataset"}
56
+
57
+ _LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}
58
+ _ENV = {
59
+ "base_url": "USIF_LLM_BASE_URL",
60
+ "model": "USIF_LLM_MODEL",
61
+ "api_key_env": "USIF_LLM_API_KEY_ENV",
62
+ "temperature": "USIF_LLM_TEMPERATURE",
63
+ "timeout": "USIF_LLM_TIMEOUT",
64
+ }
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class LLMConfig:
69
+ """Where and how to reach an OpenAI-compatible chat-completions service."""
70
+
71
+ base_url: str = "https://api.deepseek.com"
72
+ model: str = "deepseek-flash"
73
+ api_key_env: str = "DEEPSEEK_API_KEY"
74
+ temperature: float = 0.0
75
+ timeout: float = 120.0
76
+
77
+ def __post_init__(self) -> None:
78
+ url = urlsplit(self.base_url)
79
+ if url.scheme not in ("https", "http") or not url.hostname:
80
+ raise AgentError(f"llm base_url must be an http(s) URL, got {self.base_url!r}")
81
+ if url.scheme == "http" and url.hostname not in _LOCAL_HOSTS:
82
+ # The key travels in a header: only a server on this machine may see it unencrypted.
83
+ raise AgentError(
84
+ f"llm base_url must use https unless the server is local: {self.base_url}"
85
+ )
86
+ if not self.model:
87
+ raise AgentError("llm model must not be empty")
88
+ if not self.api_key_env.replace("_", "").isalnum():
89
+ raise AgentError("llm api_key_env must name an environment variable")
90
+ if self.timeout <= 0:
91
+ raise AgentError("llm timeout must be positive")
92
+
93
+ def api_key(self) -> str:
94
+ """The key from the environment; never logged, printed or sent to the model."""
95
+ key = os.environ.get(self.api_key_env, "").strip()
96
+ if not key:
97
+ raise AgentError(f"set {self.api_key_env} to the API key of {self.base_url}")
98
+ if any(c.isspace() or not c.isprintable() for c in key):
99
+ # Never echo it: a malformed key would otherwise appear in HTTP error messages.
100
+ raise AgentError(f"{self.api_key_env} contains spaces or control characters")
101
+ return key
102
+
103
+ def describe(self) -> Dict[str, Any]:
104
+ """The settings with the key reduced to whether it is set."""
105
+ return {**asdict(self), "api_key_set": bool(os.environ.get(self.api_key_env))}
106
+
107
+
108
+ DEFAULT_CONFIG = LLMConfig()
109
+
110
+
111
+ def usif_home() -> Path:
112
+ """The per-user USIF directory: ``$USIF_HOME`` or ``~/.usif``."""
113
+ return Path(os.environ.get("USIF_HOME") or Path.home() / ".usif").expanduser()
114
+
115
+
116
+ def config_path() -> Path:
117
+ return usif_home() / "config.toml"
118
+
119
+
120
+ def plans_dir(applied: bool = False) -> Path:
121
+ """Where unapproved plans (or, with ``applied``, applied plans) are kept."""
122
+ path = usif_home() / "plans"
123
+ return path / "applied" if applied else path
124
+
125
+
126
+ def _coerce(name: str, value: Any) -> Any:
127
+ kind = {f.name: f.type for f in fields(LLMConfig)}[name]
128
+ try:
129
+ return float(value) if kind in ("float", float) else str(value)
130
+ except (TypeError, ValueError):
131
+ raise AgentError(f"llm {name} must be a number, got {value!r}") from None
132
+
133
+
134
+ def _table(name: str) -> Dict[str, Any]:
135
+ """One table of ``config.toml`` (empty if the file or the table is missing)."""
136
+ path = config_path()
137
+ if not path.is_file():
138
+ return {}
139
+ try:
140
+ table = tomllib.loads(path.read_text(encoding="utf-8")).get(name, {})
141
+ except tomllib.TOMLDecodeError as exc:
142
+ raise AgentError(f"{path}: {exc}") from None
143
+ if not isinstance(table, dict):
144
+ raise AgentError(f"{path}: [{name}] must be a table")
145
+ return table
146
+
147
+
148
+ def load_config(overrides: Optional[Mapping[str, Any]] = None) -> LLMConfig:
149
+ """The effective settings (file, then environment, then ``overrides``)."""
150
+ values: Dict[str, Any] = {}
151
+ table = _table("llm")
152
+ if "api_key" in table:
153
+ raise AgentError(f"{config_path()}: store the key in an environment variable (api_key_env)")
154
+ unknown = set(table) - set(_ENV)
155
+ if unknown:
156
+ raise AgentError(f"{config_path()}: unknown [llm] settings {sorted(unknown)}")
157
+ values.update(table)
158
+ values.update({key: os.environ[env] for key, env in _ENV.items() if os.environ.get(env)})
159
+ values.update({k: v for k, v in (overrides or {}).items() if v is not None})
160
+ return replace(DEFAULT_CONFIG, **{k: _coerce(k, v) for k, v in values.items()})
161
+
162
+
163
+ def default_dataset() -> Optional[Tuple[Path, str]]:
164
+ """The configured default dataset and where it is set, or ``None``.
165
+
166
+ ``USIF_DATASET`` wins over ``[agent] dataset`` in ``config.toml``. The
167
+ path must be absolute (a relative one would depend on the current
168
+ directory) and name a ``.usifc`` file; whether it exists is checked by
169
+ :func:`agent_dataset`.
170
+ """
171
+ value: Any = os.environ.get(DATASET_ENV, "").strip()
172
+ origin = DATASET_ENV
173
+ if not value:
174
+ table = _table("agent")
175
+ unknown = set(table) - _AGENT_SETTINGS
176
+ if unknown:
177
+ raise AgentError(f"{config_path()}: unknown [agent] settings {sorted(unknown)}")
178
+ value = table.get("dataset")
179
+ origin = f"{config_path()} [agent]"
180
+ if value is None:
181
+ return None
182
+ if not isinstance(value, str) or not value.strip():
183
+ raise AgentError(f"{origin}: dataset must be a path")
184
+ path = Path(value).expanduser()
185
+ if not path.is_absolute():
186
+ raise AgentError(f"{origin}: the default dataset must be an absolute path, got {value!r}")
187
+ if path.suffix.lower() != ".usifc":
188
+ raise AgentError(f"{origin}: the default dataset must be a .usifc file, got {value!r}")
189
+ return path, origin
190
+
191
+
192
+ def agent_dataset(explicit: Optional[os.PathLike[str] | str] = None) -> Path:
193
+ """The dataset to work on: ``explicit`` if given, else the configured default.
194
+
195
+ A default is only used if it exists; a new dataset is created only when
196
+ its path is given explicitly (and a plan for it is approved).
197
+ """
198
+ if explicit is not None:
199
+ return Path(explicit)
200
+ found = default_dataset()
201
+ if found is None:
202
+ raise AgentError(
203
+ f"no dataset: pass DATASET, set {DATASET_ENV}, or set dataset in the [agent] "
204
+ f"table of {config_path()}"
205
+ )
206
+ path, origin = found
207
+ if not path.is_file():
208
+ raise AgentError(
209
+ f"the default dataset {path} (from {origin}) does not exist; a default is never "
210
+ "created: pass the path as DATASET to start a new dataset"
211
+ )
212
+ return path
usif/agent/discover.py ADDED
@@ -0,0 +1,352 @@
1
+ """Find computational results in project directories and describe them as dataset entries.
2
+
3
+ Scanning only reads; it never writes. Each structure it finds becomes a
4
+ :class:`Candidate`: the entry it would create (group and name derived from the
5
+ directory layout), the structure summary, and provenance attributes (absolute
6
+ source path, SHA-256 of the file, modification time, code, input parameters,
7
+ and the nearest README/NOTES text). Candidates turn into a change plan with
8
+ :func:`usif.agent.plan.plan_from_scan`.
9
+
10
+ * A VASP calculation directory (``vasprun.xml``, ``OUTCAR``, ``CONTCAR`` or
11
+ ``POSCAR``) is one candidate: the final structure of the best output file,
12
+ with ``INCAR`` parameters and the ``KPOINTS`` header.
13
+ * Every other file with a structure suffix (``.usif``, ``.json``, ``.cif``,
14
+ ``.xyz``, ``.extxyz``, ``.traj``, ...) is one candidate (its last frame), or
15
+ one per frame with ``all_frames=True``.
16
+
17
+ Files that cannot be read are reported in :attr:`ScanResult.skipped`.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import hashlib
23
+ import os
24
+ import re
25
+ from dataclasses import dataclass, field
26
+ from datetime import datetime, timezone
27
+ from pathlib import Path
28
+ from typing import Any, Dict, Iterator, List, Optional, Tuple
29
+
30
+ from usif import io
31
+ from usif.dataset import Dataset, Q
32
+ from usif.dataset.query import MAX_IN_VALUES, normalize_group
33
+ from usif.errors import USIFError
34
+ from usif.model.structure import Structure
35
+
36
+ __all__ = ["Candidate", "ScanResult", "scan"]
37
+
38
+ VASP_OUTPUTS = ("vasprun.xml", "OUTCAR", "CONTCAR", "POSCAR")
39
+ STRUCTURE_SUFFIXES = frozenset(
40
+ {".usif", ".json", ".cif", ".xyz", ".extxyz", ".traj", ".vasp", ".poscar", ".pdb", ".xsf"}
41
+ )
42
+ NOTE_FILES = ("README.md", "README.txt", "README", "NOTES.md", "NOTES.txt", "notes.md", "notes.txt")
43
+ SKIP_DIRS = frozenset({"__pycache__", "node_modules", "site-packages"})
44
+ MAX_NOTES = 2000
45
+ MAX_PARAMETERS = 200
46
+ _INCAR_LINE = re.compile(r"^\s*([A-Za-z][A-Za-z0-9_]*)\s*=\s*(.+?)\s*$")
47
+
48
+
49
+ @dataclass
50
+ class Candidate:
51
+ """One structure that could become the dataset entry ``group/name``."""
52
+
53
+ source: Path
54
+ group: str
55
+ name: str
56
+ frame: int
57
+ frames: int
58
+ sha256: str
59
+ code: str
60
+ formula: str
61
+ natoms: int
62
+ properties: Dict[str, float]
63
+ attrs: Dict[str, Any]
64
+ status: str = "new" # new | registered | conflict | duplicate
65
+
66
+ @property
67
+ def path(self) -> str:
68
+ return f"{self.group.rstrip('/')}/{self.name}"
69
+
70
+ def summary(self) -> Dict[str, Any]:
71
+ return {
72
+ "entry": self.path,
73
+ "source": str(self.source),
74
+ "frame": self.frame,
75
+ "code": self.code,
76
+ "formula": self.formula,
77
+ "natoms": self.natoms,
78
+ "properties": self.properties,
79
+ "status": self.status,
80
+ }
81
+
82
+
83
+ @dataclass
84
+ class ScanResult:
85
+ root: Path
86
+ candidates: List[Candidate] = field(default_factory=list)
87
+ skipped: List[Tuple[str, str]] = field(default_factory=list)
88
+
89
+ @property
90
+ def new(self) -> List[Candidate]:
91
+ return [c for c in self.candidates if c.status == "new"]
92
+
93
+
94
+ def file_sha256(path: Path) -> str:
95
+ digest = hashlib.sha256()
96
+ with open(path, "rb") as handle:
97
+ for block in iter(lambda: handle.read(1 << 20), b""):
98
+ digest.update(block)
99
+ return digest.hexdigest()
100
+
101
+
102
+ def _number(text: str) -> Any:
103
+ for kind in (int, float):
104
+ try:
105
+ return kind(text)
106
+ except ValueError:
107
+ pass
108
+ return text
109
+
110
+
111
+ def parse_incar(path: Path) -> Dict[str, Any]:
112
+ """``KEY = value`` pairs of a VASP INCAR (comments and ``;`` handled)."""
113
+ params: Dict[str, Any] = {}
114
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
115
+ line = re.split(r"[#!]", line, maxsplit=1)[0]
116
+ for part in line.split(";"):
117
+ match = _INCAR_LINE.match(part)
118
+ if match and len(params) < MAX_PARAMETERS:
119
+ params[match.group(1).upper()] = _number(match.group(2))
120
+ return params
121
+
122
+
123
+ def _inside(path: Path, root: Path) -> bool:
124
+ """A regular file that is not a symbolic link and resolves to a place below ``root``.
125
+
126
+ Every file the scanner opens passes this check, so links cannot pull in
127
+ files from outside the scanned (and allowed) directory.
128
+ """
129
+ try:
130
+ if path.is_symlink() or not path.is_file():
131
+ return False
132
+ resolved = path.resolve()
133
+ except OSError:
134
+ return False
135
+ return resolved == root or root in resolved.parents
136
+
137
+
138
+ def _notes(directory: Path, root: Path) -> Optional[str]:
139
+ """The nearest README/NOTES text at or above ``directory`` (within ``root``)."""
140
+ current = directory
141
+ while True:
142
+ for name in NOTE_FILES:
143
+ candidate = current / name
144
+ if _inside(candidate, root):
145
+ text = candidate.read_text(encoding="utf-8", errors="replace").strip()
146
+ return text[:MAX_NOTES] if text else None
147
+ if current == root or root not in current.parents:
148
+ return None
149
+ current = current.parent
150
+
151
+
152
+ def _scalar_properties(structure: Structure) -> Dict[str, float]:
153
+ values = {}
154
+ for name in structure.properties:
155
+ raw = structure.properties.raw(name)
156
+ if getattr(raw, "ndim", None) == 0 and raw.dtype.kind in "fiu":
157
+ values[name] = float(raw)
158
+ return values
159
+
160
+
161
+ def _walk(root: Path) -> Iterator[Tuple[Path, List[str]]]:
162
+ for current, dirs, files in os.walk(root, followlinks=False):
163
+ dirs[:] = sorted(d for d in dirs if not d.startswith(".") and d not in SKIP_DIRS)
164
+ yield Path(current), sorted(f for f in files if not f.startswith("."))
165
+
166
+
167
+ def _group_for(root: Path, directory: Path, prefix: str) -> str:
168
+ rel = directory.relative_to(root).parts
169
+ return normalize_group("/".join((prefix, *rel)))
170
+
171
+
172
+ def scan(
173
+ root: os.PathLike[str] | str,
174
+ *,
175
+ group: str = "/",
176
+ dataset: Optional[os.PathLike[str] | str] = None,
177
+ all_frames: bool = False,
178
+ max_candidates: int = 10000,
179
+ max_file_size: int = 1024**3,
180
+ ) -> ScanResult:
181
+ """Find computational results under ``root`` (a directory or one file).
182
+
183
+ Entries are placed below ``group``: ``root/a/b/calc`` (a VASP directory)
184
+ becomes ``{group}/a/b`` + name ``calc``; ``root/a/x.cif`` becomes
185
+ ``{group}/a`` + name ``x``. With ``dataset``, candidates whose source file
186
+ (same SHA-256 and frame) is already registered are marked ``registered``
187
+ and those whose entry path holds other content ``conflict``.
188
+ """
189
+ base = Path(root).expanduser().resolve()
190
+ if not base.exists():
191
+ raise FileNotFoundError(2, "No such file or directory", str(root))
192
+ result = ScanResult(base)
193
+ if base.is_file():
194
+ walk: Iterator[Tuple[Path, List[str]]] = iter([(base.parent, [base.name])])
195
+ top = base.parent
196
+ else:
197
+ walk, top = _walk(base), base
198
+ for directory, files in walk:
199
+ vasp = [name for name in VASP_OUTPUTS if name in files and _inside(directory / name, top)]
200
+ if vasp and not base.is_file():
201
+ calc_group = _group_for(top, directory.parent, group) if directory != top else None
202
+ name = directory.name
203
+ _add(
204
+ result,
205
+ directory / vasp[0],
206
+ calc_group or normalize_group(group),
207
+ name,
208
+ "vasp",
209
+ top,
210
+ all_frames,
211
+ max_file_size,
212
+ )
213
+ for filename in files:
214
+ path = directory / filename
215
+ if filename in VASP_OUTPUTS and not base.is_file():
216
+ continue
217
+ if Path(filename.lower()).suffix not in STRUCTURE_SUFFIXES and not base.is_file():
218
+ continue
219
+ if not _inside(path, top):
220
+ continue
221
+ stem = path.stem if sum(Path(f).stem == path.stem for f in files) == 1 else path.name
222
+ _add(
223
+ result,
224
+ path,
225
+ _group_for(top, directory, group),
226
+ stem,
227
+ "file",
228
+ top,
229
+ all_frames,
230
+ max_file_size,
231
+ )
232
+ if len(result.candidates) >= max_candidates:
233
+ result.skipped.append((str(directory), f"stopped after {max_candidates} candidates"))
234
+ break
235
+ _resolve_collisions(result)
236
+ if dataset is not None and Path(dataset).exists():
237
+ _mark_known(result, Path(dataset))
238
+ return result
239
+
240
+
241
+ def _resolve_collisions(result: ScanResult) -> None:
242
+ """Give every candidate its own entry path.
243
+
244
+ A VASP directory ``calc/`` and a file ``calc.cif`` next to it, or frame
245
+ names such as ``x-0`` next to a file ``x-0.xyz``, would otherwise share an
246
+ entry. Later candidates are renamed to their full file name (plus the
247
+ frame); what still collides is marked ``duplicate`` and never proposed.
248
+ """
249
+ taken = set()
250
+ for candidate in result.candidates:
251
+ if candidate.path in taken:
252
+ name = candidate.source.name
253
+ if candidate.frames > 1 and name != candidate.name:
254
+ name = f"{name}-{candidate.frame}"
255
+ candidate.name = name
256
+ if candidate.path in taken:
257
+ candidate.status = "duplicate"
258
+ continue
259
+ taken.add(candidate.path)
260
+
261
+
262
+ def _add(
263
+ result: ScanResult,
264
+ path: Path,
265
+ group: str,
266
+ name: str,
267
+ code: str,
268
+ root: Path,
269
+ all_frames: bool,
270
+ max_file_size: int,
271
+ ) -> None:
272
+ try:
273
+ size = path.stat().st_size
274
+ if size > max_file_size:
275
+ result.skipped.append((str(path), f"larger than {max_file_size} bytes"))
276
+ return
277
+ frames = io.read_all(path)
278
+ except (USIFError, OSError, ValueError) as exc:
279
+ result.skipped.append(
280
+ (str(path), str(exc).splitlines()[0][:300] if str(exc) else repr(exc))
281
+ )
282
+ return
283
+ if not frames:
284
+ result.skipped.append((str(path), "no structures"))
285
+ return
286
+ stat = path.stat()
287
+ common: Dict[str, Any] = {
288
+ "source": str(path),
289
+ "source_sha256": file_sha256(path),
290
+ "source_bytes": stat.st_size,
291
+ "source_modified": datetime.fromtimestamp(stat.st_mtime, timezone.utc).isoformat(
292
+ timespec="seconds"
293
+ ),
294
+ }
295
+ if code != "file":
296
+ common["code"] = code
297
+ directory = path.parent
298
+ if code == "vasp":
299
+ if _inside(directory / "INCAR", root):
300
+ common["incar"] = parse_incar(directory / "INCAR")
301
+ if _inside(directory / "KPOINTS", root):
302
+ lines = (directory / "KPOINTS").read_text(errors="replace").splitlines()[:5]
303
+ common["kpoints"] = "\n".join(line.rstrip() for line in lines)
304
+ notes = _notes(directory, root)
305
+ if notes:
306
+ common["notes"] = notes
307
+ indices = range(len(frames)) if all_frames else [len(frames) - 1]
308
+ for index in indices:
309
+ structure = frames[index]
310
+ entry_name = name if not all_frames or len(frames) == 1 else f"{name}-{index}"
311
+ attrs = {**common, "source_frame": index, "source_frames": len(frames)}
312
+ result.candidates.append(
313
+ Candidate(
314
+ source=path,
315
+ group=group,
316
+ name=entry_name,
317
+ frame=index,
318
+ frames=len(frames),
319
+ sha256=common["source_sha256"],
320
+ code=code,
321
+ formula=structure.reduced_formula,
322
+ natoms=structure.natoms,
323
+ properties=_scalar_properties(structure),
324
+ attrs=attrs,
325
+ )
326
+ )
327
+
328
+
329
+ def _mark_known(result: ScanResult, dataset_path: Path) -> None:
330
+ """Mark candidates already registered (same source file, hash and frame) or whose path is taken.
331
+
332
+ Matching includes the source path: two calculation directories holding
333
+ identical input files are still two calculations.
334
+ """
335
+ hashes = sorted({c.sha256 for c in result.candidates})
336
+ registered = set()
337
+ with Dataset(dataset_path, "r") as dataset:
338
+ # One attribute scan per batch of hashes instead of one per candidate.
339
+ for start in range(0, len(hashes), MAX_IN_VALUES):
340
+ batch = Q.attr("source_sha256").isin(hashes[start : start + MAX_IN_VALUES])
341
+ for entry in dataset.query(batch):
342
+ attrs = entry.attrs
343
+ registered.add(
344
+ (attrs.get("source"), attrs.get("source_sha256"), attrs.get("source_frame"))
345
+ )
346
+ for candidate in result.candidates:
347
+ if candidate.status == "duplicate":
348
+ continue
349
+ if (str(candidate.source), candidate.sha256, candidate.frame) in registered:
350
+ candidate.status = "registered"
351
+ elif candidate.path in dataset:
352
+ candidate.status = "conflict"