symcrys 0.8.0 → 0.9.0

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 (105) hide show
  1. package/README.md +11 -2
  2. package/dist/cell.d.ts +5 -2
  3. package/dist/cell.d.ts.map +1 -1
  4. package/dist/cell.js +7 -7
  5. package/dist/cell.js.map +1 -1
  6. package/dist/crystalClasses.d.ts +13 -8
  7. package/dist/crystalClasses.d.ts.map +1 -1
  8. package/dist/crystalClasses.js +13 -8
  9. package/dist/crystalClasses.js.map +1 -1
  10. package/dist/indices.d.ts +3 -1
  11. package/dist/indices.d.ts.map +1 -1
  12. package/dist/indices.js +6 -2
  13. package/dist/indices.js.map +1 -1
  14. package/dist/linalg.d.ts +7 -1
  15. package/dist/linalg.d.ts.map +1 -1
  16. package/dist/linalg.js +20 -3
  17. package/dist/linalg.js.map +1 -1
  18. package/dist/operations.d.ts +6 -0
  19. package/dist/operations.d.ts.map +1 -1
  20. package/dist/operations.js +19 -0
  21. package/dist/operations.js.map +1 -1
  22. package/dist/plane.d.ts +225 -0
  23. package/dist/plane.d.ts.map +1 -0
  24. package/dist/plane.js +219 -0
  25. package/dist/plane.js.map +1 -0
  26. package/dist/pointGroups/identify.d.ts +4 -2
  27. package/dist/pointGroups/identify.d.ts.map +1 -1
  28. package/dist/pointGroups/identify.js +5 -18
  29. package/dist/pointGroups/identify.js.map +1 -1
  30. package/dist/pointGroups/orbits.d.ts +1 -1
  31. package/dist/pointGroups/orbits.d.ts.map +1 -1
  32. package/dist/pointGroups/orbits.js +3 -3
  33. package/dist/pointGroups/orbits.js.map +1 -1
  34. package/dist/pointGroups/properties.d.ts +6 -2
  35. package/dist/pointGroups/properties.d.ts.map +1 -1
  36. package/dist/pointGroups/properties.js +6 -2
  37. package/dist/pointGroups/properties.js.map +1 -1
  38. package/dist/siteSymmetry.d.ts +5 -3
  39. package/dist/siteSymmetry.d.ts.map +1 -1
  40. package/dist/siteSymmetry.js +6 -2
  41. package/dist/siteSymmetry.js.map +1 -1
  42. package/dist/spaceGroups/affine.d.ts +81 -0
  43. package/dist/spaceGroups/affine.d.ts.map +1 -0
  44. package/dist/spaceGroups/affine.js +245 -0
  45. package/dist/spaceGroups/affine.js.map +1 -0
  46. package/dist/spaceGroups/cell.d.ts +58 -0
  47. package/dist/spaceGroups/cell.d.ts.map +1 -0
  48. package/dist/spaceGroups/cell.js +297 -0
  49. package/dist/spaceGroups/cell.js.map +1 -0
  50. package/dist/spaceGroups/describe.d.ts +44 -0
  51. package/dist/spaceGroups/describe.d.ts.map +1 -0
  52. package/dist/spaceGroups/describe.js +92 -0
  53. package/dist/spaceGroups/describe.js.map +1 -0
  54. package/dist/spaceGroups/planeGroupData.d.ts +44 -0
  55. package/dist/spaceGroups/planeGroupData.d.ts.map +1 -0
  56. package/dist/spaceGroups/planeGroupData.js +371 -0
  57. package/dist/spaceGroups/planeGroupData.js.map +1 -0
  58. package/dist/spaceGroups/planeGroups.d.ts +28 -0
  59. package/dist/spaceGroups/planeGroups.d.ts.map +1 -0
  60. package/dist/spaceGroups/planeGroups.js +61 -0
  61. package/dist/spaceGroups/planeGroups.js.map +1 -0
  62. package/dist/spaceGroups/planePointGroups.d.ts +31 -0
  63. package/dist/spaceGroups/planePointGroups.d.ts.map +1 -0
  64. package/dist/spaceGroups/planePointGroups.js +77 -0
  65. package/dist/spaceGroups/planePointGroups.js.map +1 -0
  66. package/dist/spaceGroups/positions.d.ts +65 -0
  67. package/dist/spaceGroups/positions.d.ts.map +1 -0
  68. package/dist/spaceGroups/positions.js +183 -0
  69. package/dist/spaceGroups/positions.js.map +1 -0
  70. package/dist/spaceGroups/rational.d.ts +43 -0
  71. package/dist/spaceGroups/rational.d.ts.map +1 -0
  72. package/dist/spaceGroups/rational.js +95 -0
  73. package/dist/spaceGroups/rational.js.map +1 -0
  74. package/dist/tensors/tensorForm.d.ts +3 -1
  75. package/dist/tensors/tensorForm.d.ts.map +1 -1
  76. package/dist/tensors/tensorForm.js +3 -1
  77. package/dist/tensors/tensorForm.js.map +1 -1
  78. package/dist/tensors/tensorProperties.d.ts +4 -2
  79. package/dist/tensors/tensorProperties.d.ts.map +1 -1
  80. package/dist/tensors/tensorProperties.js +4 -2
  81. package/dist/tensors/tensorProperties.js.map +1 -1
  82. package/dist/version.d.ts +1 -1
  83. package/dist/version.js +1 -1
  84. package/package.json +7 -2
  85. package/src/cell.ts +9 -8
  86. package/src/crystalClasses.ts +13 -8
  87. package/src/indices.ts +5 -2
  88. package/src/linalg.ts +21 -2
  89. package/src/operations.ts +20 -0
  90. package/src/plane.ts +455 -0
  91. package/src/pointGroups/identify.ts +5 -19
  92. package/src/pointGroups/orbits.ts +3 -3
  93. package/src/pointGroups/properties.ts +6 -2
  94. package/src/siteSymmetry.ts +6 -3
  95. package/src/spaceGroups/affine.ts +315 -0
  96. package/src/spaceGroups/cell.ts +371 -0
  97. package/src/spaceGroups/describe.ts +133 -0
  98. package/src/spaceGroups/planeGroupData.ts +407 -0
  99. package/src/spaceGroups/planeGroups.ts +75 -0
  100. package/src/spaceGroups/planePointGroups.ts +90 -0
  101. package/src/spaceGroups/positions.ts +237 -0
  102. package/src/spaceGroups/rational.ts +115 -0
  103. package/src/tensors/tensorForm.ts +3 -1
  104. package/src/tensors/tensorProperties.ts +4 -2
  105. package/src/version.ts +1 -1
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  import { det, multiply, trace, type Mat3, type Vec3 } from '../linalg.js';
8
- import { checkOrthogonal, checkTimeReversal, type Operation } from '../operations.js';
8
+ import { checkOrthogonalWithin, checkTimeReversal, type Operation } from '../operations.js';
9
9
  import { EPSILON } from '../tolerances.js';
10
10
  import { axialVector, rotationAxis, type OperationKind } from './elements.js';
11
11
  import {
@@ -62,22 +62,6 @@ export interface CartesianOperationDescription {
62
62
  readonly timeReversal: boolean;
63
63
  }
64
64
 
65
- /** Throws unless mᵀm = 1 within the tolerance (a matrix with rounding errors passes with a larger one). */
66
- function checkOrthogonalWithin(m: Mat3, what: string, tolerance: number): void {
67
- if (tolerance <= EPSILON) {
68
- checkOrthogonal(m, what);
69
- return;
70
- }
71
- for (let i = 0; i < 3; i++) {
72
- for (let j = 0; j < 3; j++) {
73
- const d = m[0][i] * m[0][j] + m[1][i] * m[1][j] + m[2][i] * m[2][j];
74
- if (!(Math.abs(d - (i === j ? 1 : 0)) < tolerance)) {
75
- throw new RangeError(`${what} is not an orthogonal (Cartesian) matrix: ${JSON.stringify(m)}`);
76
- }
77
- }
78
- }
79
- }
80
-
81
65
  /** No point group has more than 96 operations (m-3m1'). */
82
66
  const MAX_ORDER = 96;
83
67
 
@@ -181,7 +165,8 @@ function keyOfSignature(s: string): MagneticPointGroupKey | undefined {
181
165
  * Time reversal counts: a list with time reversal gives a magnetic point group. Returns undefined
182
166
  * if the operations generate no point group (an operation of order 5, a group larger than 96).
183
167
  * Throws a RangeError for a matrix that is not orthogonal (within `tolerance`, at least
184
- * `EPSILON`). The classes `1` and `-1` have one setting and no orientation, so they always have
168
+ * `EPSILON`) and for an operation that does not say whether it is combined with time reversal.
169
+ * The classes `1` and `-1` have one setting and no orientation, so they always have
185
170
  * setting 1.
186
171
  */
187
172
  export function pointGroupOf(
@@ -243,7 +228,8 @@ function describe(op: Operation, i: number, tolerance: number): CartesianOperati
243
228
  * by lattice directions, since the list need not belong to a setting; for a point group given by its
244
229
  * key, `describeOperations` names them. Throws a RangeError for a matrix that is not orthogonal or
245
230
  * not a crystallographic operation (a rotation part by an angle other than 360°/n, n = 1, 2, 3, 4,
246
- * 6), both within `tolerance` (default `EPSILON`, as for `pointGroupOf`).
231
+ * 6), both within `tolerance` (default `EPSILON`, as for `pointGroupOf`), and for an operation that
232
+ * does not say whether it is combined with time reversal.
247
233
  */
248
234
  export function describeOperationsOf(
249
235
  operations: readonly Operation[],
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { crystalFamily, latticeBasis } from '../lattice.js';
7
7
  import { apply, inverse, multiply, type Mat3, type Vec3 } from '../linalg.js';
8
- import { checkOrthogonal, type Operation } from '../operations.js';
8
+ import { checkOrthogonalWithin, type Operation } from '../operations.js';
9
9
  import { siteTolerance } from '../siteSymmetry.js';
10
10
  import type { Uvw } from '../symmetryDirections.js';
11
11
  import {
@@ -196,7 +196,7 @@ export interface OrbitPole {
196
196
  * `siteSymmetry`), in the order in which the operations reach them, each with the indices of the
197
197
  * operations that map the direction there. The list is taken as it is, not closed into a group.
198
198
  * Time reversal is ignored. Throws a RangeError for a zero vector and for a matrix that is not
199
- * orthogonal (Cartesian; not one of `latticeOperations`).
199
+ * orthogonal (Cartesian, not one of `latticeOperations`; within `tolerance`, at least `EPSILON`).
200
200
  */
201
201
  export function orbitOf(
202
202
  operations: readonly { readonly matrix: Mat3 }[],
@@ -204,7 +204,7 @@ export function orbitOf(
204
204
  options?: OrbitOptions,
205
205
  ): readonly OrbitPole[] {
206
206
  const tolerance = siteTolerance(options);
207
- operations.forEach((op, i) => checkOrthogonal(op.matrix, `Operation ${i}`));
207
+ operations.forEach((op, i) => checkOrthogonalWithin(op.matrix, `Operation ${i}`, tolerance));
208
208
  const n = Math.hypot(direction[0], direction[1], direction[2]);
209
209
  if (!(n > 0) || !Number.isFinite(n)) throw new RangeError(`Not a direction: ${JSON.stringify(direction)}`);
210
210
  const u: Vec3 = [direction[0] / n, direction[1] / n, direction[2] / n];
@@ -23,7 +23,9 @@ function check(operations: readonly Operation[]): void {
23
23
  /**
24
24
  * True if the group generated by `operations` contains the inversion, not combined with time
25
25
  * reversal: e.g. for the operations of a distorted crystal. A list that is not closed is closed
26
- * first. For a point group given by its key, read `pointGroup(key).centrosymmetric`.
26
+ * first. For a point group given by its key, read `pointGroup(key).centrosymmetric`. Throws a
27
+ * RangeError for a matrix that is not orthogonal and for an operation that does not say whether it
28
+ * is combined with time reversal.
27
29
  */
28
30
  export function isCentrosymmetricOf(operations: readonly Operation[]): boolean {
29
31
  check(operations);
@@ -33,7 +35,9 @@ export function isCentrosymmetricOf(operations: readonly Operation[]): boolean {
33
35
  /**
34
36
  * True if the group generated by `operations` is chiral: proper rotations only, with or without
35
37
  * time reversal (products of proper rotations are proper, so the list need not be closed). For a
36
- * point group given by its key, read `pointGroup(key).chiral`.
38
+ * point group given by its key, read `pointGroup(key).chiral`. Throws a RangeError for a matrix that
39
+ * is not orthogonal and for an operation that does not say whether it is combined with time
40
+ * reversal.
37
41
  */
38
42
  export function isChiralOf(operations: readonly Operation[]): boolean {
39
43
  check(operations);
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import { apply, matricesEqual, multiply, type Vec3 } from './linalg.js';
7
- import type { Operation } from './operations.js';
7
+ import { checkOrthogonalWithin, type Operation } from './operations.js';
8
8
  import { EPSILON } from './tolerances.js';
9
9
 
10
10
  /** Options of `siteSymmetry` and `wyckoffPositionOf`. */
@@ -119,8 +119,10 @@ export function siteTolerance(options?: SiteSymmetryOptions): number {
119
119
  * within the tolerance are closed under the products found in the list and the direction is set onto
120
120
  * their fixed space, repeated until stable, so that for a group the result is a subgroup and the
121
121
  * set direction lies exactly on its elements. For a list that is not a group, `multiplicity` may
122
- * not be an integer. Throws a RangeError for a zero vector, and if the closed operations fix no
123
- * common direction (a tolerance far too large, e.g. 0.5).
122
+ * not be an integer. The matrices must be Cartesian and orthogonal (not those of
123
+ * `latticeOperations`). Throws a RangeError for a matrix that is not orthogonal (within
124
+ * `tolerance`, at least `EPSILON`), for a zero vector, and if the closed operations fix no common
125
+ * direction (a tolerance far too large, e.g. 0.5).
124
126
  */
125
127
  export function siteSymmetry(
126
128
  operations: readonly Operation[],
@@ -128,6 +130,7 @@ export function siteSymmetry(
128
130
  options?: SiteSymmetryOptions,
129
131
  ): SiteSymmetry {
130
132
  const tolerance = siteTolerance(options);
133
+ operations.forEach((op, i) => checkOrthogonalWithin(op.matrix, `Operation ${i}`, tolerance));
131
134
  const v = unit(direction);
132
135
  const fixing = (w: Vec3): number[] => {
133
136
  const out: number[] = [];
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Exact affine operations of plane and space groups, x' = W·x + w in the lattice basis (ITA
3
+ * notation (W, w)): the matrix W with integer entries and determinant ±1, the translation w with
4
+ * rational components. Written for any dimension d from 1 to 3 (2 for the plane groups, 3 for the
5
+ * space groups). CLAUDE.md, "Plane groups (and later space groups)".
6
+ */
7
+
8
+ import {
9
+ ZERO,
10
+ add,
11
+ checkSafeInteger,
12
+ formatRational,
13
+ isInteger,
14
+ mod1,
15
+ negate,
16
+ parseRational,
17
+ rationalsEqual,
18
+ safeProduct,
19
+ safeSum,
20
+ scale,
21
+ subtract,
22
+ toNumber,
23
+ type Rational,
24
+ } from './rational.js';
25
+
26
+ /** An integer matrix of size d × d, rows first. */
27
+ export type IntMatrix = readonly (readonly number[])[];
28
+
29
+ /** An exact operation (W, w): x' = W·x + w, in the lattice basis. */
30
+ export interface ExactOperation {
31
+ /** The linear part W: integer entries; an operation of a group has determinant ±1. */
32
+ readonly matrix: IntMatrix;
33
+ /** The translation part w, one rational per axis. */
34
+ readonly translation: readonly Rational[];
35
+ }
36
+
37
+ /** The plain form of an operation at the API: integer matrix, translation as the nearest doubles. */
38
+ export interface PlainOperation {
39
+ /** The linear part W, integer entries, rows first. */
40
+ readonly matrix: number[][];
41
+ /** The translation part w as doubles (1/3 as the nearest double). */
42
+ readonly translation: number[];
43
+ }
44
+
45
+ /**
46
+ * The default bound on the cosets of a closure: no plane group has more than 12 cosets of the
47
+ * integer translations, no space group in its conventional cell more than 192 (Fm-3m: 48 × 4). A
48
+ * closure in a larger cell (a supercell, a subgroup of index k) passes a larger bound.
49
+ */
50
+ export const MAX_COSETS = 192;
51
+
52
+ /** The coordinate names in ITA's coordinate triplets. */
53
+ const COORDINATES = ['x', 'y', 'z'] as const;
54
+
55
+ function checkDimension(d: number): number {
56
+ if (!Number.isInteger(d) || d < 1 || d > 3) {
57
+ throw new RangeError(`The dimension must be 1, 2 or 3, not ${String(d)}`);
58
+ }
59
+ return d;
60
+ }
61
+
62
+ /** The dimension d of an operation; throws unless it is consistent (d = 1 to 3, integer matrix). */
63
+ export function dimensionOf(op: ExactOperation): number {
64
+ const d = op.matrix.length;
65
+ if (d < 1 || d > 3 || op.translation.length !== d || op.matrix.some((row) => row.length !== d)) {
66
+ throw new RangeError(`Not an operation of dimension 1 to 3: ${JSON.stringify(op)}`);
67
+ }
68
+ for (const row of op.matrix) {
69
+ for (const v of row) {
70
+ checkSafeInteger(v, 'A matrix entry');
71
+ }
72
+ }
73
+ return d;
74
+ }
75
+
76
+ /** The identity of dimension d. */
77
+ export function identity(d: number): ExactOperation {
78
+ checkDimension(d);
79
+ return {
80
+ matrix: Array.from({ length: d }, (_, i) => Array.from({ length: d }, (_, j) => (i === j ? 1 : 0))),
81
+ translation: Array.from({ length: d }, () => ZERO),
82
+ };
83
+ }
84
+
85
+ /** The pure translation by t, an operation (I, t). */
86
+ export function translationOperation(t: readonly Rational[]): ExactOperation {
87
+ return { matrix: identity(t.length).matrix, translation: [...t] };
88
+ }
89
+
90
+ function applyMatrix(m: IntMatrix, v: readonly Rational[]): Rational[] {
91
+ return m.map((row) => row.reduce<Rational>((sum, mij, j) => add(sum, scale(mij, v[j])), ZERO));
92
+ }
93
+
94
+ function multiplyMatrices(a: IntMatrix, b: IntMatrix): number[][] {
95
+ return a.map((row) =>
96
+ b[0].map((_, j) => row.reduce((sum, aik, k) => safeSum(sum, safeProduct(aik, b[k][j])), 0) + 0),
97
+ );
98
+ }
99
+
100
+ /** The determinant of an integer matrix of size 1 to 3. */
101
+ export function determinant(m: IntMatrix): number {
102
+ checkDimension(m.length);
103
+ const p = safeProduct;
104
+ if (m.length === 1) return m[0][0];
105
+ if (m.length === 2) return safeSum(p(m[0][0], m[1][1]), -p(m[0][1], m[1][0]));
106
+ const minor = (i: number, j: number, k: number, l: number): number =>
107
+ safeSum(p(m[1][i], m[2][j]), -p(m[1][k], m[2][l]));
108
+ return safeSum(safeSum(p(m[0][0], minor(1, 2, 2, 1)), -p(m[0][1], minor(0, 2, 2, 0))), p(m[0][2], minor(0, 1, 1, 0)));
109
+ }
110
+
111
+ /** The trace of an integer matrix. */
112
+ export function trace(m: IntMatrix): number {
113
+ return m.reduce((sum, row, i) => safeSum(sum, row[i]), 0);
114
+ }
115
+
116
+ /** Throws unless det W = ±1, as for every operation of a crystallographic group. */
117
+ export function checkUnimodular(op: ExactOperation): void {
118
+ dimensionOf(op);
119
+ const det = determinant(op.matrix);
120
+ if (det !== 1 && det !== -1) {
121
+ throw new RangeError(`Determinant ${det} is not ±1: ${JSON.stringify(op.matrix)}`);
122
+ }
123
+ }
124
+
125
+ /** The image of the point x (rational coordinates) under the operation, W·x + w. */
126
+ export function applyToPoint(op: ExactOperation, x: readonly Rational[]): Rational[] {
127
+ return applyMatrix(op.matrix, x).map((v, i) => add(v, op.translation[i]));
128
+ }
129
+
130
+ /** The product a·b: first b, then a; (W_a, w_a)(W_b, w_b) = (W_a W_b, W_a w_b + w_a). */
131
+ export function compose(a: ExactOperation, b: ExactOperation): ExactOperation {
132
+ return {
133
+ matrix: multiplyMatrices(a.matrix, b.matrix),
134
+ translation: applyMatrix(a.matrix, b.translation).map((v, i) => add(v, a.translation[i])),
135
+ };
136
+ }
137
+
138
+ /** The inverse (W⁻¹, −W⁻¹w); throws unless det W = ±1, so that W⁻¹ is an integer matrix. */
139
+ export function inverse(op: ExactOperation): ExactOperation {
140
+ checkUnimodular(op);
141
+ const d = op.matrix.length;
142
+ const m = op.matrix;
143
+ const det = determinant(m);
144
+ let inv: number[][];
145
+ if (d === 1) {
146
+ inv = [[det]];
147
+ } else if (d === 2) {
148
+ inv = [
149
+ [m[1][1] * det, -m[0][1] * det],
150
+ [-m[1][0] * det, m[0][0] * det],
151
+ ];
152
+ } else {
153
+ // The adjugate divided by det, i.e. multiplied by det = ±1: inv[i][j] = cofactor(j, i).
154
+ const cofactor = (i: number, j: number): number => {
155
+ const r = [0, 1, 2].filter((k) => k !== i);
156
+ const s = [0, 1, 2].filter((k) => k !== j);
157
+ const minor = safeSum(safeProduct(m[r[0]][s[0]], m[r[1]][s[1]]), -safeProduct(m[r[0]][s[1]], m[r[1]][s[0]]));
158
+ return ((i + j) % 2 === 0 ? minor : -minor) * det;
159
+ };
160
+ inv = [0, 1, 2].map((i) => [0, 1, 2].map((j) => cofactor(j, i)));
161
+ }
162
+ inv = inv.map((row) => row.map((v) => v + 0));
163
+ return { matrix: inv, translation: applyMatrix(inv, op.translation).map(negate) };
164
+ }
165
+
166
+ /** The operation with its translation reduced modulo 1 into [0, 1): the representative of its coset. */
167
+ export function reduceModLattice(op: ExactOperation): ExactOperation {
168
+ return { matrix: op.matrix, translation: op.translation.map(mod1) };
169
+ }
170
+
171
+ function matricesEqual(a: IntMatrix, b: IntMatrix): boolean {
172
+ return a.length === b.length && a.every((row, i) => row.length === b[i].length && row.every((v, j) => v === b[i][j]));
173
+ }
174
+
175
+ /** True if a and b are the same operation, translation included. */
176
+ export function operationsEqual(a: ExactOperation, b: ExactOperation): boolean {
177
+ return (
178
+ matricesEqual(a.matrix, b.matrix) &&
179
+ a.translation.length === b.translation.length &&
180
+ a.translation.every((t, i) => rationalsEqual(t, b.translation[i]))
181
+ );
182
+ }
183
+
184
+ /** True if a and b differ by an integer lattice translation: the same coset of the integer translations. */
185
+ export function equalModLattice(a: ExactOperation, b: ExactOperation): boolean {
186
+ return (
187
+ matricesEqual(a.matrix, b.matrix) &&
188
+ a.translation.length === b.translation.length &&
189
+ a.translation.every((t, i) => isInteger(subtract(t, b.translation[i])))
190
+ );
191
+ }
192
+
193
+ /** Options of `closure`. */
194
+ export interface ClosureOptions {
195
+ /** The dimension; needed only for an empty list of generators. */
196
+ readonly dimension?: number;
197
+ /** The largest number of cosets allowed, `MAX_COSETS` by default. */
198
+ readonly maxCosets?: number;
199
+ }
200
+
201
+ /**
202
+ * The group generated by `generators` together with the integer translations, as one operation per
203
+ * coset of the integer translations (translations in [0, 1)). The identity comes first, the others
204
+ * in the order in which the closure finds them (breadth first, each found operation multiplied by
205
+ * the generators from the left); this order has no meaning of its own. A centring translation is
206
+ * passed as a generator. Throws if a generator has a determinant other than ±1 or the closure
207
+ * exceeds `maxCosets`, which no crystallographic group in its conventional cell does.
208
+ */
209
+ export function closure(generators: readonly ExactOperation[], options: ClosureOptions = {}): ExactOperation[] {
210
+ const d = checkDimension(options.dimension ?? (generators.length > 0 ? dimensionOf(generators[0]) : 0));
211
+ const maxCosets = options.maxCosets ?? MAX_COSETS;
212
+ for (const g of generators) {
213
+ if (dimensionOf(g) !== d) {
214
+ throw new RangeError(`Generators of different dimension: ${d} and ${dimensionOf(g)}`);
215
+ }
216
+ checkUnimodular(g);
217
+ }
218
+ const result: ExactOperation[] = [identity(d)];
219
+ for (let i = 0; i < result.length; i++) {
220
+ for (const g of generators) {
221
+ const product = reduceModLattice(compose(g, result[i]));
222
+ if (!result.some((op) => equalModLattice(op, product))) {
223
+ if (result.length >= maxCosets) {
224
+ throw new RangeError(
225
+ `The closure exceeds ${maxCosets} cosets: the generators form no crystallographic group`,
226
+ );
227
+ }
228
+ result.push(product);
229
+ }
230
+ }
231
+ }
232
+ return result;
233
+ }
234
+
235
+ /**
236
+ * The terms of one coordinate of a triplet. A term is a sign followed by an integer coefficient and
237
+ * a coordinate, or by a rational; only the first term may omit its sign. The terms must cover the
238
+ * whole text, so that a stray sign (`--x`, `x+`) is an error rather than skipped.
239
+ */
240
+ const TERM = /([+-]?)(?:(\d*)([xyz])|(\d+(?:\/\d+)?))/y;
241
+
242
+ /** One row of a coordinate triplet, e.g. `-x+y+1/3`: integer coefficients and a rational constant. */
243
+ function parseRow(text: string, d: number, whole: string): { coefficients: number[]; constant: Rational } {
244
+ const coefficients = Array.from({ length: d }, () => 0);
245
+ let constant: Rational = ZERO;
246
+ const s = text.replace(/\s/g, '');
247
+ if (s === '') {
248
+ throw new RangeError(`Empty coordinate in "${whole}"`);
249
+ }
250
+ TERM.lastIndex = 0;
251
+ let first = true;
252
+ while (TERM.lastIndex < s.length) {
253
+ const start = TERM.lastIndex;
254
+ const m = TERM.exec(s);
255
+ if (!m || m.index !== start || (!first && m[1] === '')) {
256
+ throw new RangeError(`Cannot read "${s.slice(start)}" in "${whole}"`);
257
+ }
258
+ first = false;
259
+ const sign = m[1] === '-' ? -1 : 1;
260
+ if (m[3] !== undefined) {
261
+ const k = COORDINATES.indexOf(m[3] as (typeof COORDINATES)[number]);
262
+ if (k >= d) {
263
+ throw new RangeError(`Coordinate ${m[3]} in a ${d}-dimensional triplet "${whole}"`);
264
+ }
265
+ const c = m[2] === '' ? 1 : checkSafeInteger(Number(m[2]), 'A coefficient');
266
+ coefficients[k] = safeSum(coefficients[k], sign * c);
267
+ } else {
268
+ constant = add(constant, scale(sign, parseRational(m[4])));
269
+ }
270
+ }
271
+ return { coefficients, constant };
272
+ }
273
+
274
+ /**
275
+ * Reads an operation from its coordinate triplet as ITA prints it in the general position, e.g.
276
+ * `-x+1/2,y` (plane) or `-y,x-y,z+1/3` (space), with `-x` for x̄. The dimension is the number of
277
+ * coordinates. Integer coefficients other than ±1 (as in `2x,x` of a Wyckoff position) are read; a
278
+ * group operation is checked for det ±1 where it is used (`closure`, `inverse`).
279
+ */
280
+ export function parseOperation(text: string): ExactOperation {
281
+ const parts = text.split(',');
282
+ const d = parts.length;
283
+ if (d > 3) {
284
+ throw new RangeError(`Not a coordinate triplet: "${text}"`);
285
+ }
286
+ const rows = parts.map((p) => parseRow(p, d, text));
287
+ return { matrix: rows.map((r) => r.coefficients), translation: rows.map((r) => r.constant) };
288
+ }
289
+
290
+ /** Writes an operation as ITA prints its coordinate triplet, e.g. `-x+1/2,y`, `x-y,x,z+5/6`. */
291
+ export function formatOperation(op: ExactOperation): string {
292
+ dimensionOf(op);
293
+ return op.matrix
294
+ .map((row, i) => {
295
+ let s = '';
296
+ row.forEach((c, j) => {
297
+ if (c === 0) return;
298
+ const name = COORDINATES[j];
299
+ const magnitude = Math.abs(c) === 1 ? name : `${Math.abs(c)}${name}`;
300
+ s += c < 0 ? `-${magnitude}` : s === '' ? magnitude : `+${magnitude}`;
301
+ });
302
+ const t = op.translation[i];
303
+ if (t[0] !== 0) {
304
+ const f = formatRational(t);
305
+ s += t[0] < 0 || s === '' ? f : `+${f}`;
306
+ }
307
+ return s === '' ? '0' : s;
308
+ })
309
+ .join(',');
310
+ }
311
+
312
+ /** The operation as plain data for the API: integer matrix, translation as the nearest doubles. */
313
+ export function toPlain(op: ExactOperation): PlainOperation {
314
+ return { matrix: op.matrix.map((row) => [...row]), translation: op.translation.map(toNumber) };
315
+ }