symcrys 0.5.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.
@@ -0,0 +1,11 @@
1
+ node_modules/
2
+ dist/
3
+ coverage/
4
+ *.tgz
5
+ # Python package (packages/python)
6
+ packages/python/src/symcrys/_bundle.js
7
+ __pycache__/
8
+ *.egg-info/
9
+ .pytest_cache/
10
+ .mypy_cache/
11
+ .venv/
symcrys-0.5.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thomas Lottermoser
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
symcrys-0.5.0/PKG-INFO ADDED
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.5
2
+ Name: symcrys
3
+ Version: 0.5.0
4
+ Summary: Crystallographic symmetry calculations: point groups, their settings, symbols, site symmetry and Wyckoff positions, and the forms of property tensors. The TypeScript library symcrys of the same version, in an embedded JavaScript engine.
5
+ Project-URL: Homepage, https://github.com/manganite/symcrys
6
+ Project-URL: Documentation, https://github.com/manganite/symcrys/blob/main/docs/conventions.md
7
+ Project-URL: Issues, https://github.com/manganite/symcrys/issues
8
+ Author: Thomas Lottermoser
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: crystallography,point-groups,second-harmonic-generation,symmetry,tensors
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering :: Physics
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.10
16
+ Requires-Dist: numpy>=1.23
17
+ Requires-Dist: quickjs-ng>=0.18
18
+ Provides-Extra: test
19
+ Requires-Dist: mypy>=1.13; extra == 'test'
20
+ Requires-Dist: pytest>=8; extra == 'test'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # symcrys for Python
24
+
25
+ Crystallographic symmetry calculations: the 32 crystallographic point groups with their settings
26
+ (ITC and Birss conventions), symbols, symmetry elements, site symmetry and Wyckoff positions, and
27
+ the forms of property tensors of rank 0 to 4 they allow, checked against print (ITC, Birss, Yariv).
28
+
29
+ This package is the TypeScript library [symcrys](https://github.com/manganite/symcrys) of the same
30
+ version, run in an embedded JavaScript engine ([quickjs-ng](https://pypi.org/project/quickjs-ng/)).
31
+ The results are those of the TypeScript library (up to rounding in the last bit of a float); the names follow a fixed rule (`tensorForm` →
32
+ `tensor_form`), and matrices and vectors are NumPy arrays.
33
+
34
+ ```bash
35
+ pip install symcrys
36
+ ```
37
+
38
+ ## Example: second-harmonic generation at a surface
39
+
40
+ ```python
41
+ import numpy as np
42
+ import symcrys
43
+
44
+ SHG = {"rank": 3, "parity": "polar", "time_parity": "i", "intrinsic": "jk"}
45
+
46
+ symcrys.tensor_form("m-3m", SHG)["basis"].shape # (0, 27): no SHG from the bulk
47
+
48
+ ops = symcrys.operations("m-3m")
49
+ site = symcrys.site_symmetry(ops, [1, 1, 1]) # symmetry of the (111) surface normal
50
+ form = symcrys.tensor_form_of([ops[i] for i in site["operations"]], SHG)
51
+ form["parameters"] # 4 free components (3m)
52
+
53
+ # The same form in a frame with z along the normal and x along a mirror normal:
54
+ z = np.array([1, 1, 1]) / np.sqrt(3)
55
+ x = np.array([1, -1, 0]) / np.sqrt(2)
56
+ frame = np.array([x, np.cross(z, x), z])
57
+ basis = np.array([symcrys.rotate_tensor(b, frame, SHG) for b in form["basis"]])
58
+ chi = basis.reshape(-1, 3, 3, 3) # chi[k] is the k-th basis tensor chi_ijk
59
+ ```
60
+
61
+ A tensor form has `basis` (rows of length 3**rank in reduced row echelon form, components in C
62
+ order, so `reshape((3,)*rank)` gives the tensor), `parameters` (the free components as index
63
+ lists) and `relations` (rows r with r @ t = 0). Each call costs about a millisecond or more: fetch
64
+ forms and operations once, then compute with NumPy.
65
+
66
+ ## Documentation
67
+
68
+ - Conventions, frames and the print sources of every result:
69
+ [docs/conventions.md](https://github.com/manganite/symcrys/blob/main/docs/conventions.md).
70
+ - Functions: the docstrings here, and the TypeScript API they call (same names in camelCase).
71
+ - Errors from the library raise `symcrys.SymcrysError`, a subclass of `ValueError`.
72
+
73
+ Python 3.10 or later. quickjs-ng has no wheel for macOS on Intel; pip builds it from source there
74
+ (a C compiler is needed). Licence: MIT.
@@ -0,0 +1,52 @@
1
+ # symcrys for Python
2
+
3
+ Crystallographic symmetry calculations: the 32 crystallographic point groups with their settings
4
+ (ITC and Birss conventions), symbols, symmetry elements, site symmetry and Wyckoff positions, and
5
+ the forms of property tensors of rank 0 to 4 they allow, checked against print (ITC, Birss, Yariv).
6
+
7
+ This package is the TypeScript library [symcrys](https://github.com/manganite/symcrys) of the same
8
+ version, run in an embedded JavaScript engine ([quickjs-ng](https://pypi.org/project/quickjs-ng/)).
9
+ The results are those of the TypeScript library (up to rounding in the last bit of a float); the names follow a fixed rule (`tensorForm` →
10
+ `tensor_form`), and matrices and vectors are NumPy arrays.
11
+
12
+ ```bash
13
+ pip install symcrys
14
+ ```
15
+
16
+ ## Example: second-harmonic generation at a surface
17
+
18
+ ```python
19
+ import numpy as np
20
+ import symcrys
21
+
22
+ SHG = {"rank": 3, "parity": "polar", "time_parity": "i", "intrinsic": "jk"}
23
+
24
+ symcrys.tensor_form("m-3m", SHG)["basis"].shape # (0, 27): no SHG from the bulk
25
+
26
+ ops = symcrys.operations("m-3m")
27
+ site = symcrys.site_symmetry(ops, [1, 1, 1]) # symmetry of the (111) surface normal
28
+ form = symcrys.tensor_form_of([ops[i] for i in site["operations"]], SHG)
29
+ form["parameters"] # 4 free components (3m)
30
+
31
+ # The same form in a frame with z along the normal and x along a mirror normal:
32
+ z = np.array([1, 1, 1]) / np.sqrt(3)
33
+ x = np.array([1, -1, 0]) / np.sqrt(2)
34
+ frame = np.array([x, np.cross(z, x), z])
35
+ basis = np.array([symcrys.rotate_tensor(b, frame, SHG) for b in form["basis"]])
36
+ chi = basis.reshape(-1, 3, 3, 3) # chi[k] is the k-th basis tensor chi_ijk
37
+ ```
38
+
39
+ A tensor form has `basis` (rows of length 3**rank in reduced row echelon form, components in C
40
+ order, so `reshape((3,)*rank)` gives the tensor), `parameters` (the free components as index
41
+ lists) and `relations` (rows r with r @ t = 0). Each call costs about a millisecond or more: fetch
42
+ forms and operations once, then compute with NumPy.
43
+
44
+ ## Documentation
45
+
46
+ - Conventions, frames and the print sources of every result:
47
+ [docs/conventions.md](https://github.com/manganite/symcrys/blob/main/docs/conventions.md).
48
+ - Functions: the docstrings here, and the TypeScript API they call (same names in camelCase).
49
+ - Errors from the library raise `symcrys.SymcrysError`, a subclass of `ValueError`.
50
+
51
+ Python 3.10 or later. quickjs-ng has no wheel for macOS on Intel; pip builds it from source there
52
+ (a C compiler is needed). Licence: MIT.
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "symcrys"
7
+ # Equal to packages/ts/package.json (one version for both packages; checked by the tests of both).
8
+ version = "0.5.0"
9
+ description = "Crystallographic symmetry calculations: point groups, their settings, symbols, site symmetry and Wyckoff positions, and the forms of property tensors. The TypeScript library symcrys of the same version, in an embedded JavaScript engine."
10
+ readme = "README.md"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Thomas Lottermoser" }]
14
+ requires-python = ">=3.10"
15
+ dependencies = ["quickjs-ng>=0.18", "numpy>=1.23"]
16
+ keywords = ["crystallography", "symmetry", "point-groups", "tensors", "second-harmonic-generation"]
17
+ classifiers = [
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Scientific/Engineering :: Physics",
20
+ "Typing :: Typed",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/manganite/symcrys"
25
+ Documentation = "https://github.com/manganite/symcrys/blob/main/docs/conventions.md"
26
+ Issues = "https://github.com/manganite/symcrys/issues"
27
+
28
+ [project.optional-dependencies]
29
+ test = ["pytest>=8", "mypy>=1.13"]
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["src/symcrys"]
33
+ # Built by `npm run bundle:python` and not committed (ignored by git), so named here explicitly.
34
+ artifacts = ["src/symcrys/_bundle.js"]
35
+
36
+ [tool.hatch.build.targets.sdist]
37
+ include = ["src/symcrys", "README.md", "LICENSE"]
38
+ artifacts = ["src/symcrys/_bundle.js"]
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+
43
+ [tool.mypy]
44
+ strict = true
45
+ files = ["src/symcrys"]
@@ -0,0 +1,274 @@
1
+ """symcrys: crystallographic symmetry calculations, from Python.
2
+
3
+ A thin layer over the TypeScript library symcrys of the same version, which runs in an embedded
4
+ JavaScript engine (quickjs-ng). Every function here calls the function of the same name in the
5
+ library (camelCase there, snake_case here) and returns its result as plain Python data, matrices
6
+ and vectors as NumPy arrays (rules in ``symcrys._convert``). The conventions, frames and print
7
+ sources are documented once, for both languages: https://github.com/manganite/symcrys/blob/main/docs/conventions.md
8
+
9
+ Each call costs about a millisecond or more (the forms of rank-4 tensors up to a few tenths of a
10
+ second); fetch operations or forms once and compute with NumPy, rather than calling in a loop.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from typing import Any, Literal, Mapping, Optional, Sequence, TypedDict
16
+
17
+ import numpy as np
18
+ from numpy.typing import ArrayLike, NDArray
19
+
20
+ from . import _engine
21
+ from ._convert import from_js, to_js
22
+ from ._engine import SymcrysError
23
+
24
+ Convention = Literal["itc", "birss"]
25
+ TensorParity = Literal["polar", "axial"]
26
+ TimeParity = Literal["i", "c"]
27
+ IntrinsicSymmetry = Literal["none", "ij", "jk", "ij_kl", "voigt"]
28
+
29
+
30
+ class TensorSpec(TypedDict):
31
+ """The kind of tensor (keys also accepted in camelCase, e.g. ``timeParity``)."""
32
+
33
+ rank: int
34
+ parity: TensorParity
35
+ time_parity: TimeParity
36
+ intrinsic: IntrinsicSymmetry
37
+
38
+
39
+ class Operation(TypedDict):
40
+ matrix: NDArray[np.float64]
41
+ time_reversal: bool
42
+
43
+
44
+ class TensorForm(TypedDict):
45
+ rank: int
46
+ basis: NDArray[np.float64]
47
+ """Shape (number of parameters, 3**rank): reduced row echelon form, flat index in C order."""
48
+ parameters: NDArray[np.int64]
49
+ """Shape (number of parameters, rank): the components that are the free parameters."""
50
+ relations: NDArray[np.float64]
51
+ """Shape (3**rank - number of parameters, 3**rank): rows r with r @ t = 0 for every allowed t."""
52
+
53
+
54
+ class SiteSymmetry(TypedDict):
55
+ operations: NDArray[np.int64]
56
+ direction: NDArray[np.float64]
57
+ multiplicity: int
58
+ general: bool
59
+
60
+
61
+ __all__ = [
62
+ "LATTICE_SYMMETRY_DIRECTIONS",
63
+ "POINT_GROUP_KEYS",
64
+ "VERSION",
65
+ "SymcrysError",
66
+ "TensorForm",
67
+ "TensorSpec",
68
+ "crystal_family",
69
+ "describe_operations",
70
+ "find_point_group",
71
+ "generators",
72
+ "is_centrosymmetric",
73
+ "is_chiral",
74
+ "is_piezoelectric",
75
+ "is_point_group_key",
76
+ "is_polar",
77
+ "lattice_basis",
78
+ "laue_class",
79
+ "operations",
80
+ "point_group",
81
+ "point_groups",
82
+ "rotate_tensor",
83
+ "settings",
84
+ "site_symmetry",
85
+ "symbol",
86
+ "symmetry_directions",
87
+ "tensor_form",
88
+ "tensor_form_of",
89
+ "wyckoff_position_of",
90
+ "wyckoff_positions",
91
+ ]
92
+
93
+ VERSION: str = _engine.value("VERSION")
94
+ __version__ = VERSION
95
+ POINT_GROUP_KEYS: tuple[str, ...] = tuple(_engine.value("POINT_GROUP_KEYS"))
96
+ LATTICE_SYMMETRY_DIRECTIONS: dict[str, list[NDArray[np.int64]]] = {
97
+ family: [np.asarray(d, dtype=np.int64).reshape(-1, 3) for d in positions]
98
+ for family, positions in _engine.value("LATTICE_SYMMETRY_DIRECTIONS").items()
99
+ }
100
+ """Per crystal family, per position of the symbol: the lattice directions [uvw], shape (n, 3)."""
101
+
102
+
103
+ def _options(**kwargs: Any) -> dict[str, Any]:
104
+ """An options object: the keyword arguments that were given, keys in camelCase."""
105
+ options: dict[str, Any] = to_js({k: v for k, v in kwargs.items() if v is not None})
106
+ return options
107
+
108
+
109
+ def _call(name: str, *args: Any, floats: bool = False) -> Any:
110
+ return from_js(_engine.invoke(name, *(to_js(a) for a in args)), floats=floats)
111
+
112
+
113
+ # --- point groups -------------------------------------------------------------------------------
114
+
115
+
116
+ def point_groups() -> list[dict[str, Any]]:
117
+ """The 32 crystal classes: key, type, crystal system, order."""
118
+ return list(_call("pointGroups"))
119
+
120
+
121
+ def point_group(key: str) -> dict[str, Any]:
122
+ """One crystal class by its key (ITC short symbol, e.g. ``'-3m'``)."""
123
+ return dict(_call("pointGroup", key))
124
+
125
+
126
+ def is_point_group_key(key: str) -> bool:
127
+ return bool(_call("isPointGroupKey", key))
128
+
129
+
130
+ def find_point_group(hm: str, convention: Optional[Convention] = None) -> Optional[dict[str, Any]]:
131
+ """Key and setting for a Hermann–Mauguin symbol, or None."""
132
+ args = [hm] if convention is None else [hm, convention]
133
+ result = _call("findPointGroup", *args)
134
+ return None if result is None else dict(result)
135
+
136
+
137
+ def settings(key: str, convention: Optional[Convention] = None) -> list[dict[str, Any]]:
138
+ """The settings of a class: index, symbols, unique axis, whether default in the convention."""
139
+ args = [key] if convention is None else [key, convention]
140
+ return list(_call("settings", *args))
141
+
142
+
143
+ def operations(key: str, *, convention: Optional[Convention] = None, setting: Optional[int] = None) -> list[Operation]:
144
+ """All operations of a class in a setting: Cartesian 3×3 matrices and time reversal."""
145
+ return list(_call("operations", key, _options(convention=convention, setting=setting)))
146
+
147
+
148
+ def generators(key: str, *, convention: Optional[Convention] = None, setting: Optional[int] = None) -> list[Operation]:
149
+ return list(_call("generators", key, _options(convention=convention, setting=setting)))
150
+
151
+
152
+ def symbol(
153
+ key: str,
154
+ *,
155
+ convention: Optional[Convention] = None,
156
+ setting: Optional[int] = None,
157
+ form: Optional[Literal["short", "full", "schoenflies"]] = None,
158
+ ) -> str:
159
+ return str(_call("symbol", key, _options(convention=convention, setting=setting, form=form)))
160
+
161
+
162
+ def is_centrosymmetric(key: str) -> bool:
163
+ return bool(_call("isCentrosymmetric", key))
164
+
165
+
166
+ def is_polar(key: str) -> bool:
167
+ return bool(_call("isPolar", key))
168
+
169
+
170
+ def is_chiral(key: str) -> bool:
171
+ return bool(_call("isChiral", key))
172
+
173
+
174
+ def is_piezoelectric(key: str) -> bool:
175
+ return bool(_call("isPiezoelectric", key))
176
+
177
+
178
+ def laue_class(key: str) -> str:
179
+ return str(_call("laueClass", key))
180
+
181
+
182
+ def crystal_family(system: str) -> str:
183
+ return str(_call("crystalFamily", system))
184
+
185
+
186
+ def lattice_basis(family: str) -> NDArray[np.float64]:
187
+ """Columns a, b, c of the conventional basis in the Cartesian frame (families with fixed angles)."""
188
+ return np.asarray(_call("latticeBasis", family, floats=True), dtype=np.float64)
189
+
190
+
191
+ def describe_operations(
192
+ key: str, *, convention: Optional[Convention] = None, setting: Optional[int] = None
193
+ ) -> list[dict[str, Any]]:
194
+ """Kind, order, axis, sense and time reversal of each operation, in the order of ``operations``."""
195
+ return list(_call("describeOperations", key, _options(convention=convention, setting=setting)))
196
+
197
+
198
+ def symmetry_directions(
199
+ key: str, *, convention: Optional[Convention] = None, setting: Optional[int] = None
200
+ ) -> list[dict[str, Any]]:
201
+ return list(_call("symmetryDirections", key, _options(convention=convention, setting=setting)))
202
+
203
+
204
+ # --- site symmetry and Wyckoff positions ----------------------------------------------------------
205
+
206
+
207
+ def site_symmetry(
208
+ operations: Sequence[Mapping[str, Any]], direction: ArrayLike, *, tolerance: Optional[float] = None
209
+ ) -> SiteSymmetry:
210
+ """The operations (indices into ``operations``) that leave a direction fixed, and its multiplicity."""
211
+ result: SiteSymmetry = _call("siteSymmetry", list(operations), np.asarray(direction), _options(tolerance=tolerance))
212
+ result["operations"] = np.asarray(result["operations"], dtype=np.int64)
213
+ return result
214
+
215
+
216
+ def wyckoff_positions(
217
+ key: str, *, convention: Optional[Convention] = None, setting: Optional[int] = None
218
+ ) -> list[dict[str, Any]]:
219
+ """ITA's Wyckoff positions of a class for directions (ITC convention)."""
220
+ return list(_call("wyckoffPositions", key, _options(convention=convention, setting=setting)))
221
+
222
+
223
+ def wyckoff_position_of(
224
+ key: str,
225
+ direction: ArrayLike,
226
+ *,
227
+ convention: Optional[Convention] = None,
228
+ setting: Optional[int] = None,
229
+ tolerance: Optional[float] = None,
230
+ ) -> dict[str, Any]:
231
+ return dict(
232
+ _call(
233
+ "wyckoffPositionOf",
234
+ key,
235
+ np.asarray(direction),
236
+ _options(convention=convention, setting=setting, tolerance=tolerance),
237
+ )
238
+ )
239
+
240
+
241
+ # --- tensors -------------------------------------------------------------------------------------
242
+
243
+
244
+ def _form(result: dict[str, Any]) -> TensorForm:
245
+ rank = int(result["rank"])
246
+ dim = 3**rank
247
+ n = len(result["basis"])
248
+ return {
249
+ "rank": rank,
250
+ "basis": np.asarray(result["basis"], dtype=np.float64).reshape(n, dim),
251
+ "parameters": np.asarray(result["parameters"], dtype=np.int64).reshape(n, rank),
252
+ "relations": np.asarray(result["relations"], dtype=np.float64).reshape(dim - n, dim),
253
+ }
254
+
255
+
256
+ def tensor_form(
257
+ key: str, spec: TensorSpec | Mapping[str, Any], *, convention: Optional[Convention] = None, setting: Optional[int] = None
258
+ ) -> TensorForm:
259
+ """The form of a property tensor under a point group (docs/conventions.md, "Tensors").
260
+
261
+ ``spec``: ``{"rank": 3, "parity": "polar", "time_parity": "i", "intrinsic": "jk"}``.
262
+ """
263
+ return _form(_call("tensorForm", key, dict(spec), _options(convention=convention, setting=setting)))
264
+
265
+
266
+ def tensor_form_of(operations: Sequence[Mapping[str, Any]], spec: TensorSpec | Mapping[str, Any]) -> TensorForm:
267
+ """The form under the group generated by any Cartesian operations, e.g. a site symmetry."""
268
+ return _form(_call("tensorFormOf", list(operations), dict(spec)))
269
+
270
+
271
+ def rotate_tensor(tensor: ArrayLike, rotation: ArrayLike, spec: TensorSpec | Mapping[str, Any]) -> NDArray[np.float64]:
272
+ """The components (flat, length 3**rank) in a frame rotated by the orthogonal matrix ``rotation``."""
273
+ flat = np.asarray(tensor, dtype=np.float64).reshape(-1)
274
+ return np.asarray(_call("rotateTensor", flat, np.asarray(rotation), dict(spec), floats=True), dtype=np.float64)