symcrys 0.8.1 → 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 (50) hide show
  1. package/README.md +11 -2
  2. package/dist/plane.d.ts +225 -0
  3. package/dist/plane.d.ts.map +1 -0
  4. package/dist/plane.js +219 -0
  5. package/dist/plane.js.map +1 -0
  6. package/dist/spaceGroups/affine.d.ts +81 -0
  7. package/dist/spaceGroups/affine.d.ts.map +1 -0
  8. package/dist/spaceGroups/affine.js +245 -0
  9. package/dist/spaceGroups/affine.js.map +1 -0
  10. package/dist/spaceGroups/cell.d.ts +58 -0
  11. package/dist/spaceGroups/cell.d.ts.map +1 -0
  12. package/dist/spaceGroups/cell.js +297 -0
  13. package/dist/spaceGroups/cell.js.map +1 -0
  14. package/dist/spaceGroups/describe.d.ts +44 -0
  15. package/dist/spaceGroups/describe.d.ts.map +1 -0
  16. package/dist/spaceGroups/describe.js +92 -0
  17. package/dist/spaceGroups/describe.js.map +1 -0
  18. package/dist/spaceGroups/planeGroupData.d.ts +44 -0
  19. package/dist/spaceGroups/planeGroupData.d.ts.map +1 -0
  20. package/dist/spaceGroups/planeGroupData.js +371 -0
  21. package/dist/spaceGroups/planeGroupData.js.map +1 -0
  22. package/dist/spaceGroups/planeGroups.d.ts +28 -0
  23. package/dist/spaceGroups/planeGroups.d.ts.map +1 -0
  24. package/dist/spaceGroups/planeGroups.js +61 -0
  25. package/dist/spaceGroups/planeGroups.js.map +1 -0
  26. package/dist/spaceGroups/planePointGroups.d.ts +31 -0
  27. package/dist/spaceGroups/planePointGroups.d.ts.map +1 -0
  28. package/dist/spaceGroups/planePointGroups.js +77 -0
  29. package/dist/spaceGroups/planePointGroups.js.map +1 -0
  30. package/dist/spaceGroups/positions.d.ts +65 -0
  31. package/dist/spaceGroups/positions.d.ts.map +1 -0
  32. package/dist/spaceGroups/positions.js +183 -0
  33. package/dist/spaceGroups/positions.js.map +1 -0
  34. package/dist/spaceGroups/rational.d.ts +43 -0
  35. package/dist/spaceGroups/rational.d.ts.map +1 -0
  36. package/dist/spaceGroups/rational.js +95 -0
  37. package/dist/spaceGroups/rational.js.map +1 -0
  38. package/dist/version.d.ts +1 -1
  39. package/dist/version.js +1 -1
  40. package/package.json +7 -2
  41. package/src/plane.ts +455 -0
  42. package/src/spaceGroups/affine.ts +315 -0
  43. package/src/spaceGroups/cell.ts +371 -0
  44. package/src/spaceGroups/describe.ts +133 -0
  45. package/src/spaceGroups/planeGroupData.ts +407 -0
  46. package/src/spaceGroups/planeGroups.ts +75 -0
  47. package/src/spaceGroups/planePointGroups.ts +90 -0
  48. package/src/spaceGroups/positions.ts +237 -0
  49. package/src/spaceGroups/rational.ts +115 -0
  50. package/src/version.ts +1 -1
@@ -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
+ }
@@ -0,0 +1,371 @@
1
+ /**
2
+ * The asymmetric unit of a plane group and its symmetry elements in the conventional cell, as numbers
3
+ * (CLAUDE.md, "The API of `symcrys/plane`"): the asymmetric unit as inequalities with its vertices,
4
+ * the elements as rotation centres with their order and as mirror and glide lines with the segment
5
+ * that lies in the cell [0, 1]². Exact, in the lattice basis; drawing them stays with the
6
+ * applications. Internal for now.
7
+ */
8
+
9
+ import { type ExactOperation } from './affine.js';
10
+ import { describePlaneOperation } from './describe.js';
11
+ import { planeGroupEntry, planeGroupOperations } from './planeGroups.js';
12
+ import {
13
+ ONE,
14
+ safeProduct,
15
+ safeSum,
16
+ ZERO,
17
+ add,
18
+ multiply,
19
+ parseRational,
20
+ rational,
21
+ rationalsEqual,
22
+ scale,
23
+ subtract,
24
+ toNumber,
25
+ type Rational,
26
+ } from './rational.js';
27
+
28
+ /** An inequality a·x + b·y ≤ c with integer coefficients without a common factor. */
29
+ export type Inequality = readonly [a: number, b: number, c: number];
30
+
31
+ /** The asymmetric unit of a plane group, a convex polygon in the lattice basis. */
32
+ export interface AsymmetricUnit {
33
+ /** Its vertices, counter-clockwise in the lattice basis (a towards b), starting at the vertex with the smallest y, then x. */
34
+ readonly vertices: readonly (readonly Rational[])[];
35
+ /** Its edges as inequalities: inequality i holds the edge from vertex i to vertex i + 1. */
36
+ readonly inequalities: readonly Inequality[];
37
+ }
38
+
39
+ /** A rotation centre in the cell. */
40
+ export interface RotationCentre {
41
+ /** The highest order of a rotation about it. */
42
+ readonly order: number;
43
+ /** Its position in [0, 1]². */
44
+ readonly point: readonly Rational[];
45
+ }
46
+
47
+ /** A mirror or glide line, the part of it in the cell. */
48
+ export interface SymmetryLine {
49
+ /** `'mirror'` or `'glide'`. */
50
+ readonly kind: 'mirror' | 'glide';
51
+ /** The direction of the line, the shortest integer vector, first non-zero component positive. */
52
+ readonly direction: readonly [number, number];
53
+ /** For a glide line: its glide vector s·direction with 0 < s < 1; for a mirror line (0, 0). */
54
+ readonly glide: readonly Rational[];
55
+ /** The ends of the segment of the line in the cell [0, 1]², in the order of `direction`. */
56
+ readonly segment: readonly [readonly Rational[], readonly Rational[]];
57
+ }
58
+
59
+ /** The symmetry elements of a plane group in the cell [0, 1]². */
60
+ export interface CellElements {
61
+ /** The rotation centres, by descending order, then by y and x. */
62
+ readonly rotations: readonly RotationCentre[];
63
+ /** The mirror and glide lines with a segment of non-zero length in the cell, by direction, then by the start of the segment (y, then x). */
64
+ readonly lines: readonly SymmetryLine[];
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------------------------
68
+ // Asymmetric unit
69
+
70
+ /** A linear expression c₀ + cx·x + cy·y. */
71
+ type Linear = readonly [cx: Rational, cy: Rational, c0: Rational];
72
+
73
+ const linAdd = (p: Linear, q: Linear): Linear => [add(p[0], q[0]), add(p[1], q[1]), add(p[2], q[2])];
74
+ const linScale = (k: Rational, p: Linear): Linear => [multiply(k, p[0]), multiply(k, p[1]), multiply(k, p[2])];
75
+ const isConstant = (p: Linear): boolean => p[0][0] === 0 && p[1][0] === 0;
76
+
77
+ /**
78
+ * Reads a linear expression as ITA prints the bounds of an asymmetric unit: `x`, `2/3`, `1/2 - x`,
79
+ * `(1 + y)/2`, `x/2`, `2x`. Throws on anything else.
80
+ */
81
+ function parseLinear(text: string): Linear {
82
+ const s = text.replace(/\s+/g, '');
83
+ let i = 0;
84
+ const fail = (): never => {
85
+ throw new RangeError(`Cannot read the linear expression "${text}"`);
86
+ };
87
+ function number(): Rational | undefined {
88
+ const m = /^\d+(?:\/\d+)?/.exec(s.slice(i));
89
+ if (!m) return undefined;
90
+ i += m[0].length;
91
+ return parseRational(m[0]);
92
+ }
93
+ function factor(): Linear {
94
+ if (s[i] === '(') {
95
+ i++;
96
+ const e = sum();
97
+ if (s[i++] !== ')') fail();
98
+ return e;
99
+ }
100
+ const k = number();
101
+ if (s[i] === 'x' || s[i] === 'y') {
102
+ const v = s[i++];
103
+ const c = k ?? ONE;
104
+ return v === 'x' ? [c, ZERO, ZERO] : [ZERO, c, ZERO];
105
+ }
106
+ if (k === undefined) return fail();
107
+ return [ZERO, ZERO, k];
108
+ }
109
+ function term(): Linear {
110
+ let e = factor();
111
+ while (s[i] === '/') {
112
+ i++;
113
+ const d = number() ?? fail();
114
+ e = linScale(rational(d[1], d[0]), e);
115
+ }
116
+ return e;
117
+ }
118
+ function sum(): Linear {
119
+ let sign = 1;
120
+ if (s[i] === '-' || s[i] === '+') sign = s[i++] === '-' ? -1 : 1;
121
+ let e = linScale(rational(sign), term());
122
+ while (s[i] === '+' || s[i] === '-') {
123
+ const k = s[i++] === '-' ? -1 : 1;
124
+ e = linAdd(e, linScale(rational(k), term()));
125
+ }
126
+ return e;
127
+ }
128
+ const e = sum();
129
+ if (i !== s.length) fail();
130
+ return e;
131
+ }
132
+
133
+ function gcd(a: number, b: number): number {
134
+ return b === 0 ? Math.abs(a) : gcd(b, a % b);
135
+ }
136
+
137
+ /** p ≤ 0 as an inequality with integer coefficients without a common factor. */
138
+ function toInequality(p: Linear): Inequality {
139
+ const lcm = p.reduce((l, r) => safeProduct(l, r[1]) / gcd(l, r[1]), 1);
140
+ const [a, b, c0] = p.map((r) => safeProduct(r[0], lcm / r[1]));
141
+ const g = gcd(gcd(a, b), c0) || 1;
142
+ return [a / g + 0, b / g + 0, -c0 / g + 0];
143
+ }
144
+
145
+ /** Reads the printed block "Asymmetric unit", e.g. `0 <= x <= 1/2; y <= min(1 - x, (1 + x)/2)`. */
146
+ export function parseAsymmetricUnit(text: string): Inequality[] {
147
+ const out: Inequality[] = [];
148
+ for (const clause of text.split(';')) {
149
+ const sides = clause.split('<=').map((side) => {
150
+ const m = /^\s*min\((.*)\)\s*$/.exec(side);
151
+ if (!m) return [parseLinear(side)];
152
+ // min(A, B): split at the comma outside parentheses.
153
+ let depth = 0;
154
+ const inner = m[1];
155
+ for (let k = 0; k < inner.length; k++) {
156
+ if (inner[k] === '(') depth++;
157
+ else if (inner[k] === ')') depth--;
158
+ else if (inner[k] === ',' && depth === 0)
159
+ return [parseLinear(inner.slice(0, k)), parseLinear(inner.slice(k + 1))];
160
+ }
161
+ throw new RangeError(`Cannot read "${side}"`);
162
+ });
163
+ if (sides.length < 2) throw new RangeError(`Not an inequality: "${clause}"`);
164
+ for (let k = 0; k + 1 < sides.length; k++) {
165
+ for (const lhs of sides[k]) {
166
+ for (const rhs of sides[k + 1]) {
167
+ const p = linAdd(lhs, linScale(rational(-1), rhs));
168
+ if (isConstant(p)) throw new RangeError(`No variable in "${clause}"`);
169
+ out.push(toInequality(p));
170
+ }
171
+ }
172
+ }
173
+ }
174
+ return out;
175
+ }
176
+
177
+ const r = (n: number): Rational => rational(n);
178
+
179
+ /** a·x + b·y − c for a point. */
180
+ const excess = (q: Inequality, p: readonly Rational[]): Rational =>
181
+ subtract(add(scale(q[0], p[0]), scale(q[1], p[1])), r(q[2]));
182
+
183
+ /** The vertices of the polygon {q_i ≤ 0}, counter-clockwise from the lowest (y, then x). */
184
+ function polygon(inequalities: readonly Inequality[]): Rational[][] {
185
+ const points: Rational[][] = [];
186
+ for (let i = 0; i < inequalities.length; i++) {
187
+ for (let j = i + 1; j < inequalities.length; j++) {
188
+ const [a1, b1, c1] = inequalities[i];
189
+ const [a2, b2, c2] = inequalities[j];
190
+ const cross = (u: number, v: number, x: number, y: number) => safeSum(safeProduct(u, v), -safeProduct(x, y));
191
+ const det = cross(a1, b2, a2, b1);
192
+ if (det === 0) continue;
193
+ const p = [rational(cross(c1, b2, c2, b1), det), rational(cross(a1, c2, a2, c1), det)];
194
+ if (inequalities.every((q) => excess(q, p)[0] <= 0) && !points.some((v) => samePoint(v, p))) points.push(p);
195
+ }
196
+ }
197
+ if (points.length < 3) throw new RangeError('The asymmetric unit is not a polygon');
198
+ const cx = points.reduce((s, p) => s + toNumber(p[0]), 0) / points.length;
199
+ const cy = points.reduce((s, p) => s + toNumber(p[1]), 0) / points.length;
200
+ const angle = (p: readonly Rational[]) => Math.atan2(toNumber(p[1]) - cy, toNumber(p[0]) - cx);
201
+ points.sort((p, q) => angle(p) - angle(q));
202
+ const lowest = points.reduce((k, p, i) => {
203
+ const q = points[k];
204
+ const dy = toNumber(subtract(p[1], q[1]));
205
+ return dy < 0 || (dy === 0 && toNumber(subtract(p[0], q[0])) < 0) ? i : k;
206
+ }, 0);
207
+ return [...points.slice(lowest), ...points.slice(0, lowest)];
208
+ }
209
+
210
+ const samePoint = (p: readonly Rational[], q: readonly Rational[]): boolean =>
211
+ rationalsEqual(p[0], q[0]) && rationalsEqual(p[1], q[1]);
212
+
213
+ const unitCache = new Map<string, AsymmetricUnit>();
214
+
215
+ /**
216
+ * The asymmetric unit of a plane group as ITA prints it, a convex polygon: its vertices and, for each
217
+ * edge, the inequality a·x + b·y ≤ c that holds it. Printed inequalities that hold no edge are
218
+ * left out. Frozen.
219
+ */
220
+ export function planeAsymmetricUnit(key: string | number): AsymmetricUnit {
221
+ const entry = planeGroupEntry(key);
222
+ let unit = unitCache.get(entry.symbol);
223
+ if (!unit) {
224
+ const printed = parseAsymmetricUnit(entry.asymmetricUnit);
225
+ const vertices = polygon(printed);
226
+ const inequalities = vertices.map((p, i) => {
227
+ const q = vertices[(i + 1) % vertices.length];
228
+ const edge = printed.find((e) => excess(e, p)[0] === 0 && excess(e, q)[0] === 0);
229
+ if (!edge) throw new Error(`No printed inequality of ${entry.symbol} holds an edge`);
230
+ return Object.freeze(edge);
231
+ });
232
+ unit = Object.freeze({
233
+ vertices: Object.freeze(vertices.map((v) => Object.freeze(v))),
234
+ inequalities: Object.freeze(inequalities),
235
+ });
236
+ unitCache.set(entry.symbol, unit);
237
+ }
238
+ return unit;
239
+ }
240
+
241
+ // ---------------------------------------------------------------------------------------------
242
+ // Symmetry elements in the cell
243
+
244
+ const inCell = (p: readonly Rational[]): boolean => p.every((v) => v[0] >= 0 && v[0] <= v[1]);
245
+
246
+ /**
247
+ * The lattice shifts t, |t_i| ≤ 3, added to each coset representative (W, w), w in [0, 1). Enough to
248
+ * reach every element that meets the cell: a centre p in [0, 1]² of (W, w + t) has
249
+ * t = (I − W)p − w, and the entries of I − W (at most 2 on the diagonal, 1 off it) give
250
+ * (I − W)p in [−2, 3]; a line through p in the cell, taken with its glide g along it reduced to
251
+ * g = d/2 (in a plane group s is 0 or 1/2, and |d_i| ≤ 2, so |g_i| ≤ 1), has t = (I − W)p + g − w, where for a reflection (I − W)p lies in [−1, 2].
252
+ */
253
+ const SHIFTS: Rational[][] = [];
254
+ for (let i = -3; i <= 3; i++) for (let j = -3; j <= 3; j++) SHIFTS.push([r(i), r(j)]);
255
+
256
+ /**
257
+ * The segment of the line through p along d in [0, 1]², or undefined if it has no length there.
258
+ * Exact: the parameter λ of p + λd is bounded by each coordinate.
259
+ */
260
+ function clip(
261
+ p: readonly Rational[],
262
+ d: readonly [number, number],
263
+ ): [readonly Rational[], readonly Rational[]] | undefined {
264
+ let lo: Rational | undefined;
265
+ let hi: Rational | undefined;
266
+ for (let k = 0; k < 2; k++) {
267
+ if (d[k] === 0) {
268
+ if (p[k][0] < 0 || p[k][0] > p[k][1]) return undefined;
269
+ continue;
270
+ }
271
+ // 0 ≤ p_k + λ d_k ≤ 1
272
+ const a = rational(-p[k][0], p[k][1] * d[k]);
273
+ const b = rational(p[k][1] - p[k][0], p[k][1] * d[k]);
274
+ const [l, h] = d[k] > 0 ? [a, b] : [b, a];
275
+ if (lo === undefined || toNumber(subtract(l, lo)) > 0) lo = l;
276
+ if (hi === undefined || toNumber(subtract(h, hi)) < 0) hi = h;
277
+ }
278
+ if (lo === undefined || hi === undefined || toNumber(subtract(hi, lo)) <= 0) return undefined;
279
+ const at = (lambda: Rational) => [add(p[0], scale(d[0], lambda)), add(p[1], scale(d[1], lambda))];
280
+ return [at(lo), at(hi)];
281
+ }
282
+
283
+ /** s mod 1 in [0, 1). */
284
+ function frac(s: Rational): Rational {
285
+ const n = Math.floor(s[0] / s[1]);
286
+ return subtract(s, r(n));
287
+ }
288
+
289
+ const elementCache = new Map<string, CellElements>();
290
+
291
+ /**
292
+ * The symmetry elements of a plane group in its conventional cell [0, 1]², boundary included: every
293
+ * rotation centre with the highest order of a rotation about it, and every mirror and glide line
294
+ * that crosses the cell, with the segment inside it. A line that carries a glide is a glide line
295
+ * with its shortest glide vector along the line (between 0 and the lattice vector). Frozen.
296
+ */
297
+ export function planeCellElements(key: string | number): CellElements {
298
+ const entry = planeGroupEntry(key);
299
+ const cached = elementCache.get(entry.symbol);
300
+ if (cached) return cached;
301
+ const rotations: { order: number; point: Rational[] }[] = [];
302
+ const lines: {
303
+ kind: 'mirror' | 'glide';
304
+ direction: [number, number];
305
+ s: Rational;
306
+ c: Rational;
307
+ segment: [readonly Rational[], readonly Rational[]];
308
+ }[] = [];
309
+ for (const op of planeGroupOperations(entry.symbol)) {
310
+ for (const t of SHIFTS) {
311
+ const shifted: ExactOperation = {
312
+ matrix: op.matrix,
313
+ translation: [add(op.translation[0], t[0]), add(op.translation[1], t[1])],
314
+ };
315
+ const d = describePlaneOperation(shifted);
316
+ if (d.kind === 'rotation') {
317
+ const p = [...(d.location ?? [])];
318
+ if (!inCell(p)) continue;
319
+ const known = rotations.find((x) => samePoint(x.point, p));
320
+ if (!known) rotations.push({ order: d.order, point: p });
321
+ else known.order = Math.max(known.order, d.order);
322
+ } else if (d.kind === 'mirror' || d.kind === 'glide') {
323
+ const dir = d.direction ?? [0, 0];
324
+ const p = d.location ?? [];
325
+ // The glide vector is s·dir; s modulo 1, since a lattice translation along the line changes nothing.
326
+ const g = d.glide ?? [ZERO, ZERO];
327
+ const s = frac(dir[0] !== 0 ? rational(g[0][0], g[0][1] * dir[0]) : rational(g[1][0], g[1][1] * dir[1]));
328
+ // The line is n·x = c with the normal n = (−dir_y, dir_x).
329
+ const c = add(scale(-dir[1], p[0]), scale(dir[0], p[1]));
330
+ if (
331
+ lines.some(
332
+ (l) =>
333
+ l.direction[0] === dir[0] &&
334
+ l.direction[1] === dir[1] &&
335
+ rationalsEqual(l.c, c) &&
336
+ rationalsEqual(l.s, s),
337
+ )
338
+ ) {
339
+ continue;
340
+ }
341
+ const segment = clip(p, dir);
342
+ if (!segment) continue;
343
+ lines.push({ kind: s[0] === 0 ? 'mirror' : 'glide', direction: [dir[0], dir[1]], s, c, segment });
344
+ }
345
+ }
346
+ }
347
+ const num = (v: Rational) => toNumber(v);
348
+ rotations.sort((a, b) => b.order - a.order || num(a.point[1]) - num(b.point[1]) || num(a.point[0]) - num(b.point[0]));
349
+ lines.sort(
350
+ (a, b) =>
351
+ a.direction[0] - b.direction[0] ||
352
+ a.direction[1] - b.direction[1] ||
353
+ num(a.segment[0][1]) - num(b.segment[0][1]) ||
354
+ num(a.segment[0][0]) - num(b.segment[0][0]),
355
+ );
356
+ const result: CellElements = Object.freeze({
357
+ rotations: Object.freeze(rotations.map((x) => Object.freeze({ order: x.order, point: Object.freeze(x.point) }))),
358
+ lines: Object.freeze(
359
+ lines.map((l) =>
360
+ Object.freeze({
361
+ kind: l.kind,
362
+ direction: Object.freeze(l.direction) as readonly [number, number],
363
+ glide: Object.freeze([scale(l.direction[0], l.s), scale(l.direction[1], l.s)]),
364
+ segment: Object.freeze(l.segment.map((p) => Object.freeze([...p]))) as unknown as SymmetryLine['segment'],
365
+ }),
366
+ ),
367
+ ),
368
+ });
369
+ elementCache.set(entry.symbol, result);
370
+ return result;
371
+ }