GraphAtoms 3.1.0__tar.gz → 3.1.1__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 (40) hide show
  1. {graphatoms-3.1.0 → graphatoms-3.1.1}/PKG-INFO +1 -1
  2. {graphatoms-3.1.0 → graphatoms-3.1.1}/pyproject.toml +1 -1
  3. {graphatoms-3.1.0 → graphatoms-3.1.1}/pyproject.toml.orig +6 -6
  4. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/system/bonds.py +105 -18
  5. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/system/graph.py +187 -2
  6. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/system/sysCluster.py +6 -3
  7. {graphatoms-3.1.0 → graphatoms-3.1.1}/README.md +0 -0
  8. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/LICENSE +0 -0
  9. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/__init__.py +0 -0
  10. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/arrayapi/__init__.py +0 -0
  11. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/arrayapi/compat.py +0 -0
  12. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/arrayapi/typing.py +0 -0
  13. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/dataclasses/__init__.py +0 -0
  14. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/dataclasses/_numpydantic.py +0 -0
  15. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/dataclasses/_pydantic2pyarrow.py +0 -0
  16. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/dataclasses/_pydanticMixin.py +0 -0
  17. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/dataclasses/_pydanticModel.py +0 -0
  18. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/dataclasses/graph.py +0 -0
  19. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/geometry/__init__.py +0 -0
  20. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/geometry/_bond_list.py +0 -0
  21. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/geometry/_inner_outer.py +0 -0
  22. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/geometry/itlee.py +0 -0
  23. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/geometry/mic.py +0 -0
  24. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/geometry/rotation.py +0 -0
  25. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/geometry/sample.py +0 -0
  26. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/system/__init__.py +0 -0
  27. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/system/atoms.py +0 -0
  28. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/system/database/__init__.py +0 -0
  29. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/system/database/abc.py +0 -0
  30. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/system/database/dict.py +0 -0
  31. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/system/database/dir.py +0 -0
  32. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/system/database/hdf5.py +0 -0
  33. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/system/database/sqliteASE.py +0 -0
  34. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/system/sysGas.py +0 -0
  35. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/system/system.py +0 -0
  36. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/utils/__init__.py +0 -0
  37. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/utils/bytestool.py +0 -0
  38. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/utils/parser.py +0 -0
  39. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/utils/rdutils.py +0 -0
  40. {graphatoms-3.1.0 → graphatoms-3.1.1}/src/graphatoms/utils/subgraph.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: graphatoms
3
- Version: 3.1.0
3
+ Version: 3.1.1
4
4
  Summary: The Chemical Core Class for Graph Theory Analysis.
5
5
  Keywords: chemistry,graph theory,reaction,event,KMC
6
6
  Author: LiuGaoyong
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "graphatoms"
7
- version = "3.1.0"
7
+ version = "3.1.1"
8
8
  readme = "README.md"
9
9
  description = "The Chemical Core Class for Graph Theory Analysis."
10
10
  license-files = ["src/LICENSE"]
@@ -8,7 +8,7 @@ Repository = "https://github.com/LiuGaoyong/GraphAtoms"
8
8
  Issues = "https://github.com/LiuGaoyong/GraphAtoms/issues/"
9
9
  [project]
10
10
  name = "graphatoms"
11
- version = "3.1.0"
11
+ version = "3.1.1"
12
12
  readme = "README.md"
13
13
  description = "The Chemical Core Class for Graph Theory Analysis."
14
14
  authors = [{ name = "LiuGaoyong", email = "liugaoyong_88@163.com" }]
@@ -43,9 +43,9 @@ dependencies = [
43
43
  "h5py>=3.16",
44
44
  "numpydantic",
45
45
  "pydantic>=2.10",
46
- "tomli; python_version < '3.11'", # use tomllib in python>=3.11
47
- "tomli-w", # TOML writer
48
- "pyyaml>=6.0", # YAML parser
46
+ "tomli; python_version < '3.11'", # use tomllib in python>=3.11
47
+ "tomli-w", # TOML writer
48
+ "pyyaml>=6.0", # YAML parser
49
49
  "hydra-core>=1.1", # Hydra config parser
50
50
  "typing-extensions",
51
51
  ]
@@ -53,7 +53,7 @@ dependencies = [
53
53
  [dependency-groups]
54
54
  dev = [
55
55
  "ruff>=0.11",
56
- "python-snappy>=0.7.3", # More Fase Data Compression
56
+ "python-snappy>=0.7.3", # More Fase Data Compression
57
57
  "array-api-strict",
58
58
  "pytest>=8.3",
59
59
  "pytest-xdist",
@@ -152,4 +152,4 @@ ruff = ">=0.11"
152
152
  chemiscope = ">=0.1.0"
153
153
  pyyaml = ">=6.0"
154
154
  hydra-core = ">=1.1"
155
- typing-extensions = ">=4.12.0"
155
+ typing-extensions = ">=4.12.0"
@@ -17,7 +17,7 @@ from graphatoms.utils.rdutils import get_rdmol
17
17
  __all__ = ["BondGraph"]
18
18
 
19
19
 
20
- def _canonicalize_pair(pair: np.ndarray) -> np.ndarray:
20
+ def _canonicalize_pair(pair: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
21
21
  """Normalize a bond pair array to canonical upper-triangular form.
22
22
 
23
23
  Any input shape (upper-triangular, lower-triangular, symmetric
@@ -34,17 +34,28 @@ def _canonicalize_pair(pair: np.ndarray) -> np.ndarray:
34
34
  pair: (nbonds, 2) int32 array of atom indices.
35
35
 
36
36
  Returns:
37
- A new ``int32`` array with shape ``(n_unique_bonds, 2)`` where each
38
- row satisfies ``row[0] < row[1]``.
37
+ A tuple ``(pair, take)``. The first element is a new ``int32``
38
+ array with shape ``(n_unique_bonds, 2)`` where each row satisfies
39
+ ``row[0] < row[1]``. The second element contains, for every output
40
+ row, the index of the input row it came from, so a per-bond array
41
+ ``values`` of length ``len(pair)`` is re-aligned by
42
+ ``values[take]``.
39
43
  """
40
44
  pair = np.asarray(pair, dtype="int32")
41
45
  # Canonicalize each edge direction to (min, max).
42
46
  pair = np.sort(pair, axis=1)
43
- # Drop symmetric (i, j)/(j, i) and accidental duplicate rows.
44
- pair = np.unique(pair, axis=0)
47
+ # Drop symmetric (i, j)/(j, i) and accidental duplicate rows, remembering
48
+ # which input rows are equivalent afterwards.
49
+ uniq, inverse = np.unique(pair, axis=0, return_inverse=True)
45
50
  # Ascending (i, j) order for deterministic serialization.
46
- order = np.lexsort((pair[:, 1], pair[:, 0]))
47
- return pair[order]
51
+ order = np.lexsort((uniq[:, 1], uniq[:, 0]))
52
+ rank = np.empty(order.size, dtype=int)
53
+ rank[order] = np.arange(order.size)
54
+ slots = rank[np.asarray(inverse).reshape(-1)]
55
+ # First input row of every output slot keeps the job of supplying the
56
+ # per-bond values, so duplicated input rows do not raise.
57
+ take = np.unique(slots, return_index=True)[1]
58
+ return uniq[order], np.asarray(take, dtype=int)
48
59
 
49
60
 
50
61
  class BondGraph(Matter, OurFrozenModel):
@@ -62,12 +73,13 @@ class BondGraph(Matter, OurFrozenModel):
62
73
  f"{len(v)} but natoms={self.natoms}."
63
74
  )
64
75
  if self.pair is not None:
65
- normalized = _canonicalize_pair(self.pair)
76
+ normalized, take = _canonicalize_pair(self.pair)
66
77
  if normalized.shape != self.pair.shape or not np.array_equal(
67
78
  normalized, self.pair
68
79
  ):
69
80
  # Frozen model — mutate via object.__setattr__.
70
81
  object.__setattr__(self, "pair", normalized)
82
+ self._after_pair_canonicalized(take)
71
83
  if self.nbonds != 0:
72
84
  assert isinstance(self.pair, np.ndarray), (
73
85
  "The `pair` should be a numpy array if nbonds > 0."
@@ -97,6 +109,15 @@ class BondGraph(Matter, OurFrozenModel):
97
109
  assert self.__IGRAPH.is_simple(), "The graph should be simple."
98
110
  return self
99
111
 
112
+ def _after_pair_canonicalized(self, take: np.ndarray) -> None:
113
+ """Re-align per-bond subclass fields with the canonical ``pair``.
114
+
115
+ Called by the model validator whenever ``pair`` had to be reordered or
116
+ deduplicated; ``take[i]`` is the input row that supplies output row
117
+ ``i``. Subclasses that add a field holding one value per bond must
118
+ override this to apply ``values[take]`` to it.
119
+ """
120
+
100
121
  @override
101
122
  def _string(self) -> str:
102
123
  lst = [f"{self.nbonds}Bonds"]
@@ -365,6 +386,8 @@ class BondGraph(Matter, OurFrozenModel):
365
386
  def _weisfeiler_lehman_step(
366
387
  self,
367
388
  atomcolor: list[str | int] | np.ndarray | None = None,
389
+ distance: np.ndarray | None = None,
390
+ distance_digits: int = 2,
368
391
  ) -> np.ndarray | list[str]:
369
392
  """Return hash string for each vertex by weisfeiler lehman algorithm.
370
393
 
@@ -374,10 +397,15 @@ class BondGraph(Matter, OurFrozenModel):
374
397
  https://www.cnblogs.com/cyz666/p/9167507.html
375
398
 
376
399
  Args:
377
- digest_size (int, optional): The size of output str. Default to 6.
378
400
  atomcolor (list[str] | list[ int] | np.ndarray | None, optional):
379
401
  The vertex color in interger or string type. Defaults to None.
380
402
  If it is None, the value will be set as atomic number.
403
+ distance (np.ndarray | None, optional): one value per bond, row
404
+ aligned with ``pair``. When given, the quantized incident
405
+ bond lengths join the vertex label. Defaults to None, which
406
+ keeps the plain topology-only label.
407
+ distance_digits (int, optional): decimal places the bond lengths
408
+ are rounded to. Defaults to 2.
381
409
 
382
410
  Returns:
383
411
  np.ndarray | list[str]: the hash string for each vertex.
@@ -386,28 +414,87 @@ class BondGraph(Matter, OurFrozenModel):
386
414
  atomcolor = self.numbers
387
415
  igcolor = np.asarray(atomcolor, dtype=str)
388
416
  assert len(igcolor) == self.natoms
417
+ if distance is None:
418
+ return np.asarray(
419
+ [
420
+ hash_string(
421
+ label
422
+ + "".join(
423
+ np.sort(igcolor[self._get_neighbors_numpy(i)])
424
+ ),
425
+ )
426
+ for i, label in enumerate(igcolor)
427
+ ]
428
+ )
429
+ quantized = np.round(
430
+ np.asarray(distance, dtype="float64"), distance_digits
431
+ )
432
+ assert len(quantized) == self.nbonds, (
433
+ f"The `distance` should have {self.nbonds} values, "
434
+ f"but {len(quantized)} got."
435
+ )
436
+ incident: list[list[tuple[int, str]]] = [[] for _ in range(self.natoms)]
437
+ for (i, j), d in zip(self.P, quantized, strict=True):
438
+ text = f"{d:08.{distance_digits}f}"
439
+ incident[int(i)].append((int(j), text))
440
+ incident[int(j)].append((int(i), text))
389
441
  return np.asarray(
390
442
  [
391
443
  hash_string(
392
- label
393
- + "".join(np.sort(igcolor[self._get_neighbors_numpy(i)])),
444
+ "\x00".join(
445
+ [
446
+ label,
447
+ # Sorted multisets only: any atom/bond ordering
448
+ # must leave the label unchanged.
449
+ "|".join(sorted(igcolor[j] for j, _ in items)),
450
+ "|".join(sorted(text for _, text in items)),
451
+ ]
452
+ ),
453
+ )
454
+ for i, (label, items) in enumerate(
455
+ zip(igcolor, incident, strict=True)
394
456
  )
395
- for i, label in enumerate(igcolor)
396
457
  ]
397
458
  )
398
459
 
460
+ def _weisfeiler_lehman_labels(
461
+ self,
462
+ atomcolor: list[str | int] | np.ndarray | None = None,
463
+ hash_depth: int = 3,
464
+ distance: np.ndarray | None = None,
465
+ distance_digits: int = 2,
466
+ ) -> np.ndarray:
467
+ """Iterate the weisfeiler lehman step and return the final labels.
468
+
469
+ Unlike :meth:`get_weisfeiler_lehman_hashes` this never writes the
470
+ ``hashes`` field, so a distance-aware run cannot poison the cached
471
+ topology-only hashes.
472
+ """
473
+ labels: np.ndarray = (
474
+ np.asarray(self.__COLOR)
475
+ if atomcolor is None
476
+ else np.asarray(atomcolor, dtype=str)
477
+ )
478
+ for _ in range(hash_depth):
479
+ labels = np.asarray(
480
+ self._weisfeiler_lehman_step(
481
+ atomcolor=labels,
482
+ distance=distance,
483
+ distance_digits=distance_digits,
484
+ )
485
+ )
486
+ return labels
487
+
399
488
  @pydantic.validate_call
400
489
  def get_weisfeiler_lehman_hashes(
401
490
  self,
402
491
  hash_depth: pydantic.PositiveInt = 3,
403
492
  ) -> list[str]:
404
493
  """Return hash value for each atom."""
405
- labels = self.__COLOR
406
- for _ in range(hash_depth):
407
- labels = self._weisfeiler_lehman_step(
408
- atomcolor=np.asarray(labels),
409
- )
410
- result = [str(i) for i in labels]
494
+ result = [
495
+ str(i)
496
+ for i in self._weisfeiler_lehman_labels(hash_depth=hash_depth)
497
+ ]
411
498
  object.__setattr__(self, "hashes", result)
412
499
  assert self.hashes is not None
413
500
  return self.hashes
@@ -10,7 +10,7 @@ from ase.constraints import FixAtoms
10
10
  from ase.symbols import Symbols
11
11
  from igraph import Graph as IGraph
12
12
  from pandas import DataFrame
13
- from pydantic import Field, model_validator
13
+ from pydantic import Field, ValidationInfo, field_validator, model_validator
14
14
  from rdkit import Chem
15
15
  from scipy import sparse as sp
16
16
 
@@ -136,6 +136,37 @@ class SysGraph(BondGraph, Structure, AtomTag, GasMixin):
136
136
  FQ (frequencies): Vibrational frequencies.
137
137
  """
138
138
 
139
+ distance: Annotated[NDArray, numpy_validator("float32", (-1,))] | None = (
140
+ None
141
+ )
142
+
143
+ @field_validator("distance", mode="after")
144
+ @classmethod
145
+ def __check_distance(
146
+ cls, value: np.ndarray | None, info: ValidationInfo
147
+ ) -> np.ndarray | None:
148
+ """Check `distance` against the input bond rows of `pair`.
149
+
150
+ The `pair` field is declared before `distance`, so `info.data` still
151
+ holds the raw (not yet canonicalized) rows here.
152
+ """
153
+ pair = info.data.get("pair")
154
+ ninput = 0 if pair is None else len(pair)
155
+ if value is not None:
156
+ assert len(value) == ninput, (
157
+ f"Invalid shape for `distance`: Len(distance)="
158
+ f"{len(value)} but the number of bond rows is {ninput}."
159
+ )
160
+ return value
161
+
162
+ @override
163
+ def _after_pair_canonicalized(self, take: np.ndarray) -> None:
164
+ """Keep `distance` row aligned when `pair` rows are reordered."""
165
+ if self.distance is not None:
166
+ object.__setattr__(
167
+ self, "distance", np.asarray(self.distance)[take]
168
+ )
169
+
139
170
  @override
140
171
  @classmethod
141
172
  def from_str(cls, data: str, **kw) -> Self:
@@ -152,6 +183,131 @@ class SysGraph(BondGraph, Structure, AtomTag, GasMixin):
152
183
  lst.append(AtomTag._string(self))
153
184
  return ",".join(lst)
154
185
 
186
+ ###################################################
187
+ # Canonical key (distance aware)
188
+ ###################################################
189
+ @staticmethod
190
+ def _check_distance_digits(distance_digits: int) -> None:
191
+ """Validate the decimal-place argument used by the key methods."""
192
+ if isinstance(distance_digits, bool) or not isinstance(
193
+ distance_digits, int
194
+ ):
195
+ raise ValueError(
196
+ "The `distance_digits` must be an integer, but "
197
+ f"{distance_digits!r} got."
198
+ )
199
+ if distance_digits < 0:
200
+ raise ValueError(
201
+ "The `distance_digits` must be non-negative, but "
202
+ f"{distance_digits} got."
203
+ )
204
+
205
+ def get_bond_distance_from_positions(self) -> np.ndarray:
206
+ """Return the minimum-image bond lengths, row aligned with `pair`.
207
+
208
+ The values are computed from :attr:`positions` and :attr:`pair`, so
209
+ they stay consistent with the geometry, and periodic systems use the
210
+ minimum image convention. Use them to fill :attr:`distance`
211
+
212
+ >>> lengths = obj.get_bond_distance_from_positions()
213
+ >>> obj = type(obj).from_dict({**obj.to_dict(), "distance": lengths})
214
+ """
215
+ assert self.pair is not None, "The `pair` should not be None."
216
+ delta = self.positions[self.target] - self.positions[self.source]
217
+ if self.is_periodic:
218
+ cell = self.ase_cell
219
+ frac = cell.scaled_positions(delta)
220
+ delta = cell.cartesian_positions(np.asarray(frac) - np.round(frac))
221
+ return np.linalg.norm(delta, axis=1).astype("float32")
222
+
223
+ def get_distance_signature(self, distance_digits: int = 2) -> str:
224
+ """Return a permutation-invariant signature of the bond lengths.
225
+
226
+ Every atom contributes the sorted multiset of its incident bond
227
+ lengths, and the per-atom strings are sorted before hashing. Both
228
+ steps are multiset operations, so the signature ignores the atom
229
+ ordering and the bond ordering entirely — attaching distances by
230
+ canonical position instead would only be defined up to
231
+ ``Aut(coloured graph)`` and would therefore break relabeling
232
+ invariance.
233
+
234
+ Args:
235
+ distance_digits (int, optional): decimal places the bond lengths
236
+ are rounded to. Defaults to 2.
237
+
238
+ Returns:
239
+ str: the hash of the bond-length signature.
240
+ """
241
+ if self.distance is None:
242
+ raise ValueError(
243
+ "The `distance` is None, so no distance signature is "
244
+ "available. Fill it with `get_bond_distance_from_positions()`."
245
+ )
246
+ self._check_distance_digits(distance_digits)
247
+ quantized = np.round(self.distance.astype("float64"), distance_digits)
248
+ per_atom: list[list[str]] = [[] for _ in range(self.natoms)]
249
+ for (i, j), d in zip(self.P, quantized, strict=True):
250
+ # Fixed width: concatenating variable width floats is ambiguous
251
+ # ("1.2" + "3.4" vs "1.23" + "4").
252
+ text = f"{d:08.{distance_digits}f}"
253
+ per_atom[int(i)].append(text)
254
+ per_atom[int(j)].append(text)
255
+ return hash_string(
256
+ "\n".join(sorted("|".join(sorted(items)) for items in per_atom))
257
+ )
258
+
259
+ @override
260
+ def get_canonical_key(
261
+ self,
262
+ method: Literal["bliss", "weisfeiler_lehman"] | str = "bliss",
263
+ distance_digits: int | None = None,
264
+ ) -> str:
265
+ """Return the canonical key for the system.
266
+
267
+ Args:
268
+ method (Literal["bliss", "weisfeiler_lehman"] | str, optional):
269
+ The canonicalization algorithm. Defaults to "bliss".
270
+ distance_digits (int | None, optional): decimal places the bond
271
+ lengths are rounded to before they join the key. ``None``
272
+ (the default) keeps the key purely topological, i.e. the
273
+ value is exactly :meth:`BondGraph.get_canonical_key`.
274
+
275
+ Returns:
276
+ str: the canonical key.
277
+
278
+ Note:
279
+ :attr:`hash` never passes ``distance_digits``, so two structures
280
+ that agree on the coloured topology but differ in bond length
281
+ keep the same ``hash`` and only part ways here.
282
+
283
+ The result is a *bond-length decorated* topological key, not a
284
+ 3D structure key: enantiomers and conformers with equal bond
285
+ lengths still collapse.
286
+ """
287
+ if distance_digits is None:
288
+ return super().get_canonical_key(method)
289
+ if self.distance is None:
290
+ raise ValueError(
291
+ "The `distance` is None, so `distance_digits` cannot be used. "
292
+ "Fill it with `get_bond_distance_from_positions()` first."
293
+ )
294
+ self._check_distance_digits(distance_digits)
295
+ if method == "weisfeiler_lehman":
296
+ labels = self._weisfeiler_lehman_labels(
297
+ hash_depth=3,
298
+ distance=self.distance,
299
+ distance_digits=distance_digits,
300
+ )
301
+ return hash_string(",".join(sorted(str(i) for i in labels)))
302
+ elif method == "bliss":
303
+ # Sum of two strings: the baseline node-coloured key, plus the
304
+ # permutation-invariant bond-length signature.
305
+ return hash_string(
306
+ super().get_canonical_key("bliss")
307
+ + self.get_distance_signature(distance_digits)
308
+ )
309
+ raise ValueError(f"Unknown method for `get_canonical_key`: {method}")
310
+
155
311
  ###################################################
156
312
  # Equivalence helpers
157
313
  ###################################################
@@ -467,6 +623,15 @@ class SysGraph(BondGraph, Structure, AtomTag, GasMixin):
467
623
  dct["is_fix"] = np.append(self.is_fix, is_fix)
468
624
 
469
625
  obj = self.from_dict(dct, parse_bonds=parse_bonds)
626
+ if self.distance is not None and obj.pair is not None:
627
+ # Keep the field alive so that `update_geometry` recomputes it for
628
+ # the rebonded structure instead of silently dropping it.
629
+ obj = obj.from_dict(
630
+ {
631
+ **obj.to_dict(),
632
+ "distance": obj.get_bond_distance_from_positions(),
633
+ }
634
+ )
470
635
  return obj.update_geometry(
471
636
  obj.positions,
472
637
  parse_bonds=parse_bonds,
@@ -500,6 +665,10 @@ class SysGraph(BondGraph, Structure, AtomTag, GasMixin):
500
665
  ).model_copy(deep=deep)
501
666
  assert new.coordination is None
502
667
  new_dct = new.to_dict()
668
+ if self.distance is not None and new.pair is not None:
669
+ # `distance` is derived from `positions`, so it is excluded above
670
+ # and recomputed here instead of being carried over stale.
671
+ new_dct["distance"] = new.get_bond_distance_from_positions()
503
672
  if self.coordination is not None:
504
673
  assert self.is_fix is not None and self.nfix != 0, (
505
674
  "The number of fixed atoms is 0. Please provide `is_fix`."
@@ -615,6 +784,7 @@ class SysGraph(BondGraph, Structure, AtomTag, GasMixin):
615
784
  else (
616
785
  set(BondGraph.__pydantic_fields__.keys())
617
786
  - set(Matter.__pydantic_fields__.keys())
787
+ | {"distance"}
618
788
  )
619
789
  )
620
790
  ),
@@ -724,6 +894,8 @@ class SysGraph(BondGraph, Structure, AtomTag, GasMixin):
724
894
  df_atoms[k] = v
725
895
  df_bonds = DataFrame({"source": self.source})
726
896
  df_bonds["target"] = self.target
897
+ if self.distance is not None:
898
+ df_bonds["distance"] = self.distance
727
899
  G = IGraph.DataFrame(
728
900
  edges=df_bonds,
729
901
  directed=True, # use directed graph to avoid duplicate edges
@@ -737,7 +909,20 @@ class SysGraph(BondGraph, Structure, AtomTag, GasMixin):
737
909
  v = getattr(self, k)
738
910
  if v is not None:
739
911
  G[k] = v
740
- return G.as_undirected()
912
+ undirected = G.as_undirected()
913
+ if self.distance is not None:
914
+ # `as_undirected()` drops the edge attributes, so attach them on
915
+ # the undirected graph, keyed by the bond instead of relying on
916
+ # the edge order surviving.
917
+ lengths = {
918
+ (int(i), int(j)): float(d)
919
+ for (i, j), d in zip(self.P, self.distance, strict=True)
920
+ }
921
+ undirected.es["distance"] = np.asarray(
922
+ [lengths[tuple(sorted(e))] for e in undirected.get_edgelist()],
923
+ dtype="float32",
924
+ )
925
+ return undirected
741
926
 
742
927
  @override
743
928
  @classmethod
@@ -173,13 +173,16 @@ class Cluster(SysGraph):
173
173
  relabel_nodes=True,
174
174
  return_edge_mask=True,
175
175
  )
176
+ # Per-bond arrays are identified by name, not by length: `natoms` and
177
+ # `nbonds` may coincide, which would otherwise slice a bond array as
178
+ # if it were an atom array.
176
179
  for k, v in dct.items():
177
- if v is not None and k != "pair":
180
+ if v is not None and k not in {"pair", "distance"}:
178
181
  assert isinstance(v, np.ndarray)
179
182
  if len(v) == sys.natoms:
180
183
  dct[k] = v[idxs]
181
- elif len(v) == sys.nbonds:
182
- dct[k] = v[pair_mask]
184
+ if dct.get("distance") is not None:
185
+ dct["distance"] = np.asarray(dct["distance"])[pair_mask]
183
186
  if not exclude_energetics:
184
187
  dct = dct | dct_eng # type: ignore
185
188
 
File without changes
File without changes