GraphAtoms 3.0.0__tar.gz → 3.1.0__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 (42) hide show
  1. {graphatoms-3.0.0 → graphatoms-3.1.0}/PKG-INFO +2 -1
  2. {graphatoms-3.0.0 → graphatoms-3.1.0}/pyproject.toml +3 -1
  3. {graphatoms-3.0.0 → graphatoms-3.1.0}/pyproject.toml.orig +3 -1
  4. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/geometry/__init__.py +0 -4
  5. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/geometry/_bond_list.py +8 -32
  6. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/geometry/_inner_outer.py +25 -5
  7. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/system/bonds.py +37 -0
  8. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/system/graph.py +3 -10
  9. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/system/sysCluster.py +1 -1
  10. graphatoms-3.0.0/src/graphatoms/geometry/_distance_pairs.py +0 -306
  11. graphatoms-3.0.0/src/graphatoms/geometry/_neighbor_list.py +0 -287
  12. {graphatoms-3.0.0 → graphatoms-3.1.0}/README.md +0 -0
  13. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/LICENSE +0 -0
  14. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/__init__.py +0 -0
  15. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/arrayapi/__init__.py +0 -0
  16. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/arrayapi/compat.py +0 -0
  17. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/arrayapi/typing.py +0 -0
  18. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/dataclasses/__init__.py +0 -0
  19. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/dataclasses/_numpydantic.py +0 -0
  20. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/dataclasses/_pydantic2pyarrow.py +0 -0
  21. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/dataclasses/_pydanticMixin.py +0 -0
  22. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/dataclasses/_pydanticModel.py +0 -0
  23. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/dataclasses/graph.py +0 -0
  24. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/geometry/itlee.py +0 -0
  25. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/geometry/mic.py +0 -0
  26. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/geometry/rotation.py +0 -0
  27. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/geometry/sample.py +0 -0
  28. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/system/__init__.py +0 -0
  29. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/system/atoms.py +0 -0
  30. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/system/database/__init__.py +0 -0
  31. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/system/database/abc.py +0 -0
  32. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/system/database/dict.py +0 -0
  33. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/system/database/dir.py +0 -0
  34. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/system/database/hdf5.py +0 -0
  35. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/system/database/sqliteASE.py +0 -0
  36. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/system/sysGas.py +0 -0
  37. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/system/system.py +0 -0
  38. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/utils/__init__.py +0 -0
  39. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/utils/bytestool.py +0 -0
  40. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/utils/parser.py +0 -0
  41. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/utils/rdutils.py +0 -0
  42. {graphatoms-3.0.0 → graphatoms-3.1.0}/src/graphatoms/utils/subgraph.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: graphatoms
3
- Version: 3.0.0
3
+ Version: 3.1.0
4
4
  Summary: The Chemical Core Class for Graph Theory Analysis.
5
5
  Keywords: chemistry,graph theory,reaction,event,KMC
6
6
  Author: LiuGaoyong
@@ -11,6 +11,7 @@ Classifier: Development Status :: 5 - Production/Stable
11
11
  Classifier: Topic :: Scientific/Engineering :: Chemistry
12
12
  Classifier: Intended Audience :: Science/Research
13
13
  Requires-Dist: ase
14
+ Requires-Dist: arrayff>=0.0.1
14
15
  Requires-Dist: pymatgen>2023.6
15
16
  Requires-Dist: rdkit>=2025
16
17
  Requires-Dist: numpy>=2,<3
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "graphatoms"
7
- version = "3.0.0"
7
+ version = "3.1.0"
8
8
  readme = "README.md"
9
9
  description = "The Chemical Core Class for Graph Theory Analysis."
10
10
  license-files = ["src/LICENSE"]
@@ -24,6 +24,7 @@ classifiers = [
24
24
  ]
25
25
  dependencies = [
26
26
  "ase",
27
+ "arrayff>=0.0.1",
27
28
  "pymatgen>2023.6",
28
29
  "rdkit>=2025",
29
30
  "numpy>=2,<3",
@@ -135,6 +136,7 @@ benchmark = "pytest -s src/tests-benchmark/*.py"
135
136
  [tool.pixi.dependencies]
136
137
  python = ">=3.12"
137
138
  pytest = ">=8"
139
+ arrayff = ">=0.0.1"
138
140
  array-api-compat = ">=1.15.0"
139
141
  array-api-extra = ">=0.11.0"
140
142
  array-api-strict = ">=2.5"
@@ -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.0.0"
11
+ version = "3.1.0"
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" }]
@@ -29,6 +29,7 @@ classifiers = [
29
29
  ]
30
30
  dependencies = [
31
31
  "ase",
32
+ "arrayff>=0.0.1",
32
33
  "pymatgen>2023.6",
33
34
  "rdkit>=2025",
34
35
  "numpy>=2,<3",
@@ -127,6 +128,7 @@ benchmark = "pytest -s src/tests-benchmark/*.py"
127
128
  [tool.pixi.dependencies]
128
129
  python = ">=3.12"
129
130
  pytest = ">=8"
131
+ arrayff = ">=0.0.1"
130
132
  array-api-compat = ">=1.15.0"
131
133
  array-api-extra = ">=0.11.0"
132
134
  array-api-strict = ">=2.5"
@@ -1,8 +1,6 @@
1
1
  """Geometry."""
2
2
 
3
3
  from graphatoms.geometry._bond_list import bond_list
4
- from graphatoms.geometry._distance_pairs import distance_pairs
5
- from graphatoms.geometry._neighbor_list import neighbor_list
6
4
  from graphatoms.geometry.itlee import (
7
5
  ITLIEEResult,
8
6
  delta_from_energy_error,
@@ -15,9 +13,7 @@ __all__ = [
15
13
  "ITLIEEResult",
16
14
  "bond_list",
17
15
  "delta_from_energy_error",
18
- "distance_pairs",
19
16
  "itlee_check_permutation",
20
17
  "itlee_equiv",
21
18
  "max_safe_delta",
22
- "neighbor_list",
23
19
  ]
@@ -3,13 +3,13 @@ from typing import Literal
3
3
 
4
4
  import networkx as nx
5
5
  import numpy as np
6
+ from arrayff.neighbors import neighbor_list
6
7
  from ase import Atoms
7
8
  from ase.data import covalent_radii as COV_R
8
9
  from pymatgen.core.structure import Molecule, Structure
9
10
  from pymatgen.io.ase import AseAtomsAdaptor
10
11
  from scipy import sparse as sp
11
12
 
12
- from graphatoms.geometry._neighbor_list import neighbor_list
13
13
  from graphatoms.utils.parser import DictConfig, hydra_parse
14
14
  from graphatoms.utils.rdutils import get_adjacency_by_rdkit
15
15
 
@@ -53,7 +53,13 @@ def bond_list(
53
53
  plus_factor = cfg.get("plus_factor", 0.3)
54
54
  multiply_factor = cfg.get("multiply_factor", 1.0)
55
55
  max_d: float = 2 * np.max(COV_R[atoms.numbers]) + 5
56
- i, j, d = neighbor_list("ijd", atoms, max_d, False, bothways=False)
56
+ i, j, d = neighbor_list(
57
+ "ijd",
58
+ atoms,
59
+ max_d,
60
+ self_interaction=False,
61
+ bothways=False,
62
+ )
57
63
  deq = COV_R[atoms.numbers[i]] + COV_R[atoms.numbers[j]]
58
64
  deq = deq * multiply_factor + plus_factor
59
65
  mask = np.logical_and(1e-3 < d, d < deq)
@@ -134,33 +140,3 @@ def bond_list(
134
140
  infer_order=False,
135
141
  )
136
142
  return matrix
137
-
138
-
139
- def test_bond_order():
140
- from ase.build import molecule
141
- from ase.cluster import Octahedron
142
-
143
- atoms = molecule("CH3CH2OH")
144
- atoms = Octahedron("Cu", 3, 1)
145
- m = bond_list(atoms=atoms)
146
-
147
- m = sp.coo_array(m)
148
- edges, data = m.coords, m.data
149
- print(edges[0], edges[1], data)
150
- m2 = get_adjacency_by_rdkit(
151
- numbers=np.array(
152
- [
153
- 1
154
- if z not in (1, 5, 6, 7, 8, 9, 14, 15, 16, 17, 32, 35, 53)
155
- else z
156
- for z in atoms.numbers
157
- ]
158
- ),
159
- geometry=atoms.positions,
160
- source=edges[0],
161
- target=edges[1],
162
- order=data,
163
- infer_order=True,
164
- charge=-59,
165
- )
166
- print(m2)
@@ -1,11 +1,11 @@
1
1
  """Distance calculation factory for atomic configurations."""
2
2
 
3
3
  import numpy as np
4
+ from arrayff.neighbors import distance_pairs
4
5
  from ase.cell import Cell
5
6
  from ase.data import covalent_radii as COV_R
6
7
  from scipy import sparse as sp
7
8
 
8
- from graphatoms.geometry._distance_pairs import distance_pairs
9
9
  from graphatoms.geometry.sample import (
10
10
  fibonacci_lattice as inverse_3d_sphere_surface_sampling,
11
11
  )
@@ -31,10 +31,25 @@ def check_atom_is_inner( # noqa: D417
31
31
  bool: whether the given atom is inner.
32
32
  """
33
33
  geometry = np.asarray(geometry, dtype=float)
34
- # get neighbors of the index atom
35
- nbr = sp.coo_array(adjacency_array)
34
+ # `bond_list` stores bonds once as an upper-triangular CSR. Callers
35
+ # pass either the full matrix or a single-row slice. Either way, we
36
+ # need the symmetric view to enumerate all neighbors of `index` —
37
+ # e.g. when only row `index` is provided, an upper-triangular matrix
38
+ # would silently drop neighbors with j < index.
39
+ coo = sp.csr_matrix(adjacency_array).tocoo()
40
+ # Expand to full symmetric view within the row being queried so that
41
+ # neighbors on both sides of `index` are visible. For a full matrix
42
+ # input we pass it through unchanged (the caller may already have the
43
+ # symmetric view).
44
+ if coo.shape[0] == 1:
45
+ col = np.concatenate([coo.col, coo.row])
46
+ row = np.zeros_like(col) # all belong to row `index`
47
+ data = np.concatenate([coo.data, coo.data])
48
+ nbr = sp.coo_matrix((data, (row, col)), shape=(1, coo.shape[1]))
49
+ else:
50
+ nbr = sp.coo_matrix(adjacency_array)
36
51
  assert nbr.shape == (1, len(numbers)), nbr.shape
37
- idxs_neighbor = np.setdiff1d(nbr.coords[1], [index])
52
+ idxs_neighbor = np.setdiff1d(nbr.col, [index])
38
53
  if len(idxs_neighbor) == 0:
39
54
  return False
40
55
  else:
@@ -71,10 +86,11 @@ def check_atom_is_inner( # noqa: D417
71
86
  # Test
72
87
  #######################################################################
73
88
  def _test_inner(atoms) -> None:
74
- from ._bond_list import Atoms, bond_list
89
+ from graphatoms.geometry._bond_list import Atoms, bond_list
75
90
 
76
91
  assert isinstance(atoms, Atoms)
77
92
  m: sp.csr_matrix = bond_list(atoms)
93
+ m = m + m.T # make it symmetric
78
94
  print(len(atoms))
79
95
  for i in range(len(atoms)):
80
96
  is_inner = check_atom_is_inner(
@@ -91,3 +107,7 @@ def test_inner() -> None: # noqa: D103
91
107
  from ase.cluster import Octahedron
92
108
 
93
109
  _test_inner(Octahedron("Cu", 3, 1))
110
+
111
+
112
+ if __name__ == "__main__":
113
+ test_inner()
@@ -17,6 +17,36 @@ from graphatoms.utils.rdutils import get_rdmol
17
17
  __all__ = ["BondGraph"]
18
18
 
19
19
 
20
+ def _canonicalize_pair(pair: np.ndarray) -> np.ndarray:
21
+ """Normalize a bond pair array to canonical upper-triangular form.
22
+
23
+ Any input shape (upper-triangular, lower-triangular, symmetric
24
+ bidirectional (i, j)/(j, i), or mixed) is reduced to exactly one row
25
+ per bond, with the convention ``(min(i, j), max(i, j))``. Rows are
26
+ then sorted ascending so the output is deterministic.
27
+
28
+ The SysGraph contract is that ``pair`` stores one row per unique bond.
29
+ Consumers that need a symmetric adjacency view build it locally (e.g.
30
+ ``MATRIX + MATRIX.T``, or feeding the single-direction edge list into
31
+ an igraph directed graph and calling ``as_undirected()``).
32
+
33
+ Args:
34
+ pair: (nbonds, 2) int32 array of atom indices.
35
+
36
+ Returns:
37
+ A new ``int32`` array with shape ``(n_unique_bonds, 2)`` where each
38
+ row satisfies ``row[0] < row[1]``.
39
+ """
40
+ pair = np.asarray(pair, dtype="int32")
41
+ # Canonicalize each edge direction to (min, max).
42
+ pair = np.sort(pair, axis=1)
43
+ # Drop symmetric (i, j)/(j, i) and accidental duplicate rows.
44
+ pair = np.unique(pair, axis=0)
45
+ # Ascending (i, j) order for deterministic serialization.
46
+ order = np.lexsort((pair[:, 1], pair[:, 0]))
47
+ return pair[order]
48
+
49
+
20
50
  class BondGraph(Matter, OurFrozenModel):
21
51
  coordination: Annotated[NDArray, numpy_validator("uint8")] | None = None
22
52
  pair: Annotated[NDArray, numpy_validator("int32", (-1, 2))] | None = None
@@ -31,6 +61,13 @@ class BondGraph(Matter, OurFrozenModel):
31
61
  f"Invalid shape for `{k}`: Len({k})="
32
62
  f"{len(v)} but natoms={self.natoms}."
33
63
  )
64
+ if self.pair is not None:
65
+ normalized = _canonicalize_pair(self.pair)
66
+ if normalized.shape != self.pair.shape or not np.array_equal(
67
+ normalized, self.pair
68
+ ):
69
+ # Frozen model — mutate via object.__setattr__.
70
+ object.__setattr__(self, "pair", normalized)
34
71
  if self.nbonds != 0:
35
72
  assert isinstance(self.pair, np.ndarray), (
36
73
  "The `pair` should be a numpy array if nbonds > 0."
@@ -706,16 +706,9 @@ class SysGraph(BondGraph, Structure, AtomTag, GasMixin):
706
706
  for k in set(df.columns[2:]) & {"order", "distance"}
707
707
  if not df[k].isnull().all()
708
708
  }
709
- if not graph.is_directed():
710
- # An undirected igraph keeps one edge per bond, while
711
- # `BondGraph.pair` uses the symmetric (i, j) / (j, i) form.
712
- # Rebuild it from the edge list here so the round-trip is
713
- # lossless without storing a second copy of the bond list on
714
- # the graph object.
715
- pair = np.vstack([pair, pair[:, ::-1]])
716
- perm = np.lexsort((pair[:, 1], pair[:, 0]))
717
- pair = pair[perm]
718
- attrs = {k: np.concatenate([v, v])[perm] for k, v in attrs.items()}
709
+ # igraph stores each bond once regardless of directedness. BondGraph
710
+ # canonicalizes pair to upper-triangular single-direction form in its
711
+ # model_validator, so we just pass the raw edge list here.
719
712
  dct["pair"] = pair
720
713
  dct.update(attrs)
721
714
  return cls.from_dict(dct, **kwargs)
@@ -1,9 +1,9 @@
1
1
  from typing import Literal, Self, override
2
2
 
3
3
  import numpy as np
4
+ from arrayff.neighbors import distance_pairs
4
5
  from pydantic import model_validator
5
6
 
6
- from graphatoms.geometry import distance_pairs
7
7
  from graphatoms.system.atoms import Energetics
8
8
  from graphatoms.system.graph import GasMixin, SysGraph
9
9
  from graphatoms.system.system import System
@@ -1,306 +0,0 @@
1
- """Calculate pairs."""
2
-
3
- import itertools
4
- from typing import Literal
5
-
6
- import numpy as np
7
- from ase.cell import Cell
8
- from ase.geometry import minkowski_reduce, wrap_positions
9
- from scipy import sparse as sp
10
- from scipy.linalg import norm, pinv
11
- from sklearn.neighbors import NearestNeighbors
12
-
13
-
14
- #############################################################
15
- # scikit-learn
16
- def _sklearn_get_nn(X) -> NearestNeighbors:
17
- nn = NearestNeighbors()
18
- nn.fit(X=X, y=None)
19
- return nn
20
-
21
-
22
- def _sklearn_get_sparse_matrix(
23
- nn: NearestNeighbors,
24
- points: np.ndarray,
25
- radius: float,
26
- return_distance: bool = False,
27
- ) -> sp.csr_matrix:
28
- """Get sparse matrix by distance.
29
-
30
- Args:
31
- nn (NearestNeighbors): The sklearn NearestNeighbors object.
32
- points (np.ndarray): The query point or points.
33
- radius (float): Radius of neighborhoods.
34
- return_distance (bool, optional): Defaults to False.
35
-
36
- Returns:
37
- sp.csr_matrix: The shape is (len(points), len(nn.X)).
38
- """
39
- return nn.radius_neighbors_graph(
40
- X=points,
41
- radius=radius,
42
- mode="distance" if return_distance else "connectivity",
43
- )
44
-
45
-
46
- def _sklearn_get_distance_pairs(
47
- p1: np.ndarray,
48
- p2: np.ndarray | None = None,
49
- cell: np.ndarray | Cell | None = None,
50
- max_distance: float = float("inf"),
51
- return_distance: bool = True,
52
- ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
53
- if not isinstance(cell, Cell):
54
- cell = Cell.new(cell=cell)
55
- p1 = np.asarray(p1, dtype=float)
56
- if p2 is None:
57
- p2 = p1
58
- else:
59
- p2 = np.asarray(p2, dtype=float)
60
- assert p1.ndim == p2.ndim == 2
61
- assert p1.shape[1] == p2.shape[1] == 3
62
- l1, l2 = p1.shape[0], p2.shape[0]
63
- if p1.shape[0] >= p2.shape[0]:
64
- swap = False
65
- else:
66
- swap, p1, p2 = True, p2, p1
67
- assert p1.shape[0] >= p2.shape[0]
68
- max_distance = float(max_distance)
69
- assert max_distance > 0
70
-
71
- distance = _sklearn_get_sparse_matrix(
72
- nn=_sklearn_get_nn(X=p1),
73
- points=p2,
74
- radius=max_distance,
75
- return_distance=bool(return_distance),
76
- ) # shape = (len(p2), len(p1))
77
- result: dict[tuple[int, int, int], sp.csr_matrix] = {
78
- (0, 0, 0): distance.T if swap else distance
79
- }
80
- if cell.rank != 0:
81
- cell, _ = minkowski_reduce(cell)
82
- assert isinstance(p2, np.ndarray)
83
- p2 = wrap_positions(p2, cell, eps=0)
84
- p1 = wrap_positions(p1, cell, eps=0)
85
- assert max_distance != float("inf")
86
- nn = _sklearn_get_nn(X=p1)
87
- cell_pinv_T = np.transpose(pinv(cell))
88
- n = [int(max_distance * norm(i)) + 1 for i in cell_pinv_T]
89
- nrange3 = [range(-i, i + 1) for i in n]
90
- for n1, n2, n3 in itertools.product(*nrange3):
91
- # if n1 <= 0 and (n2 < 0 or n2 == 0 and n3 < 0):
92
- # continue
93
- shift_idxs = np.array([n1, n2, n3])
94
- distance = _sklearn_get_sparse_matrix(
95
- nn=nn,
96
- radius=max_distance,
97
- return_distance=bool(return_distance),
98
- points=(p2 - shift_idxs @ cell), # type: ignore
99
- )
100
- result[(n1, n2, n3)] = distance.T if swap else distance
101
-
102
- shift, dist = np.empty((0, 3), int), np.array([], float)
103
- source, target = np.array([], int), np.array([], int)
104
- for shift_idxs, matrix in result.items():
105
- assert matrix.shape == (l2, l1)
106
- distance = sp.coo_matrix(matrix)
107
- if len(distance.data) != 0:
108
- source = np.append(source, distance.col)
109
- target = np.append(target, distance.row)
110
- if return_distance:
111
- dist = np.append(dist, distance.data)
112
- shift_idxs_lst = [tuple(shift_idxs)] * distance.nnz
113
- shift = np.vstack([shift, np.asarray(shift_idxs_lst, int)])
114
- assert shift.ndim == 2 and shift.shape[1] == 3
115
- assert source.max() < l1 and target.max() < l2, (
116
- f"{source.max()} {l1}, {target.max()} {l2}"
117
- )
118
- return source, target, shift, dist
119
-
120
-
121
- #############################################################
122
- # pymatgen
123
- def _pymatgen_get_distance_pairs(
124
- p1: np.ndarray,
125
- p2: np.ndarray | None = None,
126
- cell: np.ndarray | Cell | None = None,
127
- max_distance: float = float("inf"),
128
- return_distance: bool = True,
129
- ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
130
- if not isinstance(cell, Cell):
131
- cell = Cell.new(cell=cell)
132
- p1 = np.asarray(p1, dtype=float)
133
- if p2 is None:
134
- p2 = p1
135
- else:
136
- p2 = np.asarray(p2, dtype=float)
137
- assert p1.ndim == p2.ndim == 2
138
- assert p1.shape[1] == p2.shape[1] == 3
139
- l1, l2 = p1.shape[0], p2.shape[0]
140
- max_distance = float(max_distance)
141
- assert max_distance > 0
142
-
143
- if cell.rank == 0:
144
- return _sklearn_get_distance_pairs(
145
- p1=p1,
146
- p2=p2,
147
- cell=cell,
148
- max_distance=max_distance,
149
- return_distance=return_distance,
150
- )
151
- else:
152
- try:
153
- from pymatgen.optimization.neighbors import (
154
- find_points_in_spheres,
155
- )
156
-
157
- target, source, shift, distance = find_points_in_spheres(
158
- np.ascontiguousarray(p1, dtype=float),
159
- np.ascontiguousarray(p2, dtype=float),
160
- r=max_distance,
161
- pbc=np.ascontiguousarray(cell.array.any(1), dtype=np.int64),
162
- lattice=np.ascontiguousarray(cell.array, dtype=float),
163
- tol=1e-8,
164
- )
165
- shift = np.asarray(shift, int)
166
- target = np.asarray(target, int)
167
- source = np.asarray(source, int)
168
- distance = np.asarray(distance, float)
169
- assert distance.shape == (len(source),), "Impossible"
170
- assert source.shape == (len(source),), "Impossible"
171
- assert target.shape == (len(target),), "Impossible"
172
- assert shift.shape == (len(source), 3), "Impossible"
173
- except ImportError:
174
- raise ImportError(
175
- "Cannot import `find_points_in_spheres` from "
176
- "`pymatgen.optimization.neighbors` module. Please "
177
- "upgrade your pymatgen to 2022.0.10 or later."
178
- )
179
- assert source.max() < l1 and target.max() < l2
180
- self_pair = (source == target) & (distance <= 1e-5)
181
- cond = np.logical_not(self_pair) # exclude self pair
182
- return (
183
- source[cond],
184
- target[cond],
185
- shift[cond] if cell.rank != 0 else None, # type: ignore
186
- distance[cond] if return_distance else None,
187
- )
188
-
189
-
190
- #############################################################
191
- # interface
192
-
193
-
194
- def distance_pairs(
195
- quantities: str,
196
- p1: np.ndarray,
197
- p2: np.ndarray | None = None,
198
- cell: np.ndarray | Cell | None = None,
199
- cutoff: float = 6.0,
200
- backend: str | Literal["sklearn", "pmg", "pymatgen"] = "pmg",
201
- ) -> tuple[np.ndarray, ...]:
202
- """Compute distance pairs for two points set.
203
-
204
- Parameters
205
- ----------
206
- quantities: str
207
- Quantities to compute by the neighbor list algorithm. Each character
208
- in this string defines a quantity. They are returned in a tuple of
209
- the same order. Possible quantities are:
210
-
211
- * 'i' : first atom index
212
- * 'j' : second atom index
213
- * 'd' : absolute distance
214
- * 'D' : distance vector
215
- * 'S' : shift vector (number of cell boundaries crossed by the bond
216
- between atom i and j). With the shift vector S, the
217
- distances D between atoms can be computed from:
218
- D = p2[j] - p1[i] + S @ a.cell
219
- p1: np.ndarray
220
- the first points set.
221
- p2: np.ndarray | None
222
- the second points set. if none, p2 is p1.
223
- cell: np.ndarray | Cell | None
224
- the periodic lattice.
225
- cutoff: float
226
- This is a global cutoff for all points pair.
227
- backend: str
228
- The backend for computation.
229
-
230
- Returns:
231
- -------
232
- i, j, ...: array
233
- Tuple with arrays for each quantity specified above. Indices in `i`
234
- are returned in ascending order 0..len(a), but the order of (i,j)
235
- pairs is not guaranteed.
236
- """
237
- p1 = np.asarray(p1, dtype=float)
238
- if p2 is None:
239
- p2 = p1
240
- else:
241
- p2 = np.asarray(p2, dtype=float)
242
- assert p1.ndim == p2.ndim == 2
243
- assert p1.shape[1] == p2.shape[1] == 3
244
- cell = Cell.new(cell)
245
- if cell.rank != 0:
246
- assert np.isfinite(cutoff), (
247
- "The `cutoff` must is finite number for periodic cell."
248
- )
249
-
250
- if backend.lower() == "sklearn":
251
- i, j, S, d = _sklearn_get_distance_pairs(
252
- p1=p1,
253
- p2=p2,
254
- cell=cell,
255
- max_distance=cutoff,
256
- return_distance=bool("d" in quantities),
257
- )
258
- elif backend.lower() in ("pmg", "pymatgen"):
259
- j, i, S, d = _pymatgen_get_distance_pairs(
260
- p1=p2,
261
- p2=p1,
262
- cell=cell,
263
- max_distance=cutoff,
264
- return_distance=bool("d" in quantities),
265
- )
266
- # Swap i-j & p1-p2 for that the result match:
267
- # D = p2[j] - p1[i] + S @ a.cell
268
- else:
269
- raise NotImplementedError(
270
- f"Invalid backend='{backend}', only 'sklearn',"
271
- " 'pmg' and 'pymatgen' are supported."
272
- )
273
- dct = dict(zip("ijSd", [i, j, S, d]))
274
- if "D" in quantities:
275
- dct["D"] = p2[j] - p1[i] + S @ cell
276
- return tuple(dct[q] for q in quantities)
277
-
278
-
279
- #######################################################################
280
- # Test
281
- #######################################################################
282
- def test_distance_pairs_atoms(c: float = 5) -> None:
283
- from ase.build import fcc111
284
-
285
- atoms = fcc111(
286
- "Cu",
287
- [6, 8, 1],
288
- vacuum=10,
289
- orthogonal=True,
290
- periodic=True,
291
- )
292
- p2 = atoms.positions.copy()
293
- cell = atoms.cell.array.copy()
294
-
295
- p1 = p2[:2, :]
296
- i, j, S, D, d = distance_pairs("ijSDd", p1, p2, cell, 3, "pmg")
297
- for k in range(len(S)):
298
- print(p1[i[k]], p2[j[k]], sep="\n")
299
- print(S[k], D[k], d[k])
300
- print()
301
-
302
- np.testing.assert_array_almost_equal(d, np.linalg.norm(D, axis=1))
303
-
304
-
305
- if __name__ == "__main__":
306
- test_distance_pairs_atoms()
@@ -1,287 +0,0 @@
1
- from typing import Literal
2
-
3
- import numpy as np
4
- from ase.atoms import Atoms
5
- from ase.neighborlist import build_neighbor_list as __build_neighbor_list_ase
6
- from ase.neighborlist import neighbor_list as _ase_neighbor_list_3loop
7
- from numpy.typing import ArrayLike
8
-
9
- from graphatoms.geometry._distance_pairs import distance_pairs
10
-
11
- __all__ = ["neighbor_list"]
12
-
13
-
14
- #############################################################
15
- # ASE
16
- def _ase_neighbor_list_kdtree(
17
- quantities: str,
18
- a: Atoms,
19
- cutoff: float,
20
- indices: np.ndarray | None = None,
21
- self_interaction: bool = False,
22
- bothways: bool = True,
23
- sorted: bool = True,
24
- ) -> tuple[np.ndarray, ...]:
25
- if indices is None:
26
- indices = np.arange(len(a))
27
- nl = __build_neighbor_list_ase(
28
- atoms=a,
29
- cutoffs=[float(cutoff / 2)] * len(a),
30
- self_interaction=self_interaction,
31
- bothways=bothways,
32
- sorted=sorted,
33
- skin=0,
34
- )
35
- i = np.array([], dtype=int)
36
- j = np.array([], dtype=int)
37
- S = np.zeros(shape=(0, 3), dtype=int)
38
- for idx in indices:
39
- jj, SS = nl.get_neighbors(idx)
40
- j = np.append(j, jj)
41
- S = np.vstack([S, SS])
42
- i = np.append(i, np.full(len(jj), idx))
43
- dct: dict[str, np.ndarray] = {
44
- "i": i,
45
- "j": j,
46
- "S": S,
47
- }
48
- if "d" in quantities.lower():
49
- v = a.positions[j] - a.positions[i]
50
- dct["D"] = D = v + S @ a.cell
51
- if "d" in quantities:
52
- dct["d"] = np.linalg.norm(D, axis=1)
53
- return tuple(dct[q] for q in quantities)
54
-
55
-
56
- #############################################################
57
- # matscipy
58
- def _matscipy_neighbor_list(
59
- quantities: str,
60
- a: Atoms,
61
- cutoff: float,
62
- self_interaction: bool = False,
63
- bothways: bool = True,
64
- sorted: bool = True,
65
- ) -> tuple[np.ndarray, ...]:
66
- try:
67
- from matscipy.neighbours import ( # type: ignore # noqa: F401
68
- neighbour_list as _matscipy_neighbour_list,
69
- )
70
- except Exception:
71
- raise Exception(
72
- "Please install `matscipy` to speed up " #
73
- "the calculation of neighbor list.",
74
- )
75
- raise NotImplementedError(
76
- "The `matscipy` neighbor-list backend is not implemented yet."
77
- )
78
-
79
-
80
- #############################################################
81
- # VESIN
82
- def _vesin_neighbor_list(
83
- quantities: str,
84
- a: Atoms,
85
- cutoff: float,
86
- self_interaction: bool = False,
87
- max_nbins: int = 0,
88
- ) -> tuple[np.ndarray, ...]:
89
- try:
90
- from vesin import ase_neighbor_list # type: ignore
91
- except Exception:
92
- raise Exception(
93
- "Please install `vesin` to speed up " #
94
- "the calculation of neighbor list.",
95
- )
96
- return tuple(
97
- ase_neighbor_list(
98
- quantities=quantities,
99
- a=a,
100
- cutoff=cutoff,
101
- self_interaction=self_interaction,
102
- max_nbins=max_nbins,
103
- )
104
- )
105
-
106
-
107
- #############################################################
108
- # interface
109
- def neighbor_list(
110
- quantities: str,
111
- a: Atoms,
112
- cutoff: float,
113
- self_interaction: bool = False,
114
- max_nbins: int = int(1e6),
115
- bothways: bool = True,
116
- indices: ArrayLike | None = None,
117
- backend: str
118
- | Literal[
119
- "sklearn", "pmg", "pymatgen", "ase_3loop", "ase_kdtree", "vesin"
120
- ] = "pmg",
121
- ) -> tuple[np.ndarray, ...]:
122
- """Compute a neighbor list for an atomic configuration.
123
-
124
- Atoms outside periodic boundaries are mapped into the box. Atoms
125
- outside nonperiodic boundaries are included in the neighbor list
126
- but complexity of neighbor list search for those can become n^2.
127
-
128
- The neighbor list is sorted by first atom index 'i', but not by second
129
- atom index 'j'.
130
-
131
- Parameters
132
- ----------
133
- quantities: str
134
- Quantities to compute by the neighbor list algorithm. Each character
135
- in this string defines a quantity. They are returned in a tuple of
136
- the same order. Possible quantities are:
137
-
138
- * 'i' : first atom index
139
- * 'j' : second atom index
140
- * 'd' : absolute distance
141
- * 'D' : distance vector
142
- * 'S' : shift vector (number of cell boundaries crossed by the bond
143
- between atom i and j). With the shift vector S, the
144
- distances D between atoms can be computed from:
145
- D = a.positions[j] - a.positions[i] + S @ a.cell
146
- a: :class:`ase.Atoms`
147
- Atomic configuration.
148
- cutoff: float or dict
149
- This is a global cutoff for all elements.
150
- self_interaction: bool
151
- Return the atom itself as its own neighbor if set to true.
152
- Default: False
153
- max_nbins: int
154
- Maximum number of bins used in neighbor search. This is used to limit
155
- the maximum amount of memory required by the neighbor list.
156
- bothways: bool
157
- Return all neighbors. Default is to return only "half" of
158
- the neighbors.
159
- indices: np.ndarray | None
160
- Indices of atoms to use in the neighbor list.
161
- If None, all atoms are.
162
- backend: str
163
- The backend for computation.
164
-
165
- Returns:
166
- -------
167
- i, j, ...: array
168
- Tuple with arrays for each quantity specified above. Indices in `i`
169
- are returned in ascending order 0..len(a), but the order of (i,j)
170
- pairs is not guaranteed.
171
- """
172
- assert isinstance(a, Atoms), (
173
- f"The `a` must be ase.Atoms, but" #
174
- f" {a.__class__.__name__} got"
175
- )
176
- assert all(i in "ijdDS" for i in quantities), (
177
- "The `quantities` must be an elements of " #
178
- f"'ijdDS', but got {quantities},"
179
- )
180
- if len(a) <= 1 and a.cell.rank == 0:
181
- return tuple(np.array([]) for _ in quantities)
182
-
183
- if indices is not None:
184
- indices = np.asarray(indices, dtype=int)
185
- indices = np.unique(indices.flatten())
186
- if len(indices) == 0:
187
- indices = None
188
- else:
189
- assert 0 <= indices.min() <= indices.max() < len(a), (
190
- "The indices must be in range [0, len(a))."
191
- )
192
- if len(indices) == len(a):
193
- indices = None
194
- if indices is not None:
195
- assert bothways is True, (
196
- "Only support `bothways=True` " #
197
- "for `indices` not None."
198
- )
199
-
200
- msg = "The {} is not support for non-empty indices."
201
- if backend == "ase_3loop":
202
- assert indices is None, msg.format(backend)
203
- return _ase_neighbor_list_3loop(
204
- quantities=quantities,
205
- a=a,
206
- cutoff=float(cutoff),
207
- self_interaction=self_interaction,
208
- max_nbins=int(max_nbins),
209
- ) # type: ignore
210
- elif backend == "vesin":
211
- assert indices is None, msg.format(backend)
212
- return _vesin_neighbor_list(
213
- quantities=quantities,
214
- a=a,
215
- cutoff=float(cutoff),
216
- self_interaction=self_interaction,
217
- max_nbins=int(max_nbins),
218
- ) # type: ignore
219
- elif backend == "matscipy":
220
- return _matscipy_neighbor_list(
221
- quantities=quantities,
222
- a=a,
223
- cutoff=float(cutoff),
224
- self_interaction=self_interaction,
225
- )
226
- elif backend == "ase_kdtree":
227
- return _ase_neighbor_list_kdtree(
228
- quantities=quantities,
229
- a=a,
230
- cutoff=float(cutoff),
231
- indices=indices,
232
- self_interaction=self_interaction,
233
- bothways=bothways,
234
- )
235
- elif backend in ("sklearn", "pmg", "pymatgen"):
236
- if indices is None:
237
- indices = np.arange(len(a))
238
- return distance_pairs(
239
- quantities=quantities,
240
- p1=a.positions,
241
- p2=a.positions[indices],
242
- cell=a.cell,
243
- cutoff=cutoff,
244
- backend=backend,
245
- )
246
- else:
247
- raise RuntimeError(f"Unknown neighbor list backend: {backend}")
248
-
249
-
250
- #######################################################################
251
- # Test
252
- #######################################################################
253
-
254
-
255
- def _test_neighbor_list_for_atoms(a: Atoms, c: float, idx=[0, 1]) -> None:
256
-
257
- print()
258
- print(a)
259
- print("=============================================================")
260
- print("Full neighbor list")
261
- print(*_ase_neighbor_list_3loop("ijd", a, c), sep="\n")
262
- print(*neighbor_list("ijd", a, c), sep="\n")
263
- print("=============================================================")
264
- print("Half neighbor list")
265
- print(*neighbor_list("ijd", a, c, bothways=False), sep="\n")
266
- print(*_ase_neighbor_list_kdtree("ijd", a, c, bothways=False), sep="\n")
267
- print("=============================================================")
268
- print(f"Neighbor list with indices: {idx}")
269
- print(*neighbor_list("ijd", a, c, indices=idx), sep="\n")
270
-
271
-
272
- def test_neighbor_list_for_atoms() -> None:
273
- from ase.build import fcc111
274
-
275
- a = fcc111(
276
- "Cu",
277
- [2, 2, 1],
278
- vacuum=10,
279
- orthogonal=True,
280
- periodic=True,
281
- )
282
- c = 3.0
283
- _test_neighbor_list_for_atoms(a, c)
284
-
285
-
286
- if __name__ == "__main__":
287
- test_neighbor_list_for_atoms()
File without changes
File without changes