symcrys 0.8.1 → 0.10.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 (57) hide show
  1. package/README.md +11 -2
  2. package/dist/plane.d.ts +262 -0
  3. package/dist/plane.d.ts.map +1 -0
  4. package/dist/plane.js +300 -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 +60 -0
  11. package/dist/spaceGroups/cell.d.ts.map +1 -0
  12. package/dist/spaceGroups/cell.js +305 -0
  13. package/dist/spaceGroups/cell.js.map +1 -0
  14. package/dist/spaceGroups/describe.d.ts +51 -0
  15. package/dist/spaceGroups/describe.d.ts.map +1 -0
  16. package/dist/spaceGroups/describe.js +101 -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 +200 -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/spaceGroups/snap.d.ts +20 -0
  39. package/dist/spaceGroups/snap.d.ts.map +1 -0
  40. package/dist/spaceGroups/snap.js +103 -0
  41. package/dist/spaceGroups/snap.js.map +1 -0
  42. package/dist/version.d.ts +1 -1
  43. package/dist/version.d.ts.map +1 -1
  44. package/dist/version.js +1 -1
  45. package/dist/version.js.map +1 -1
  46. package/package.json +7 -2
  47. package/src/plane.ts +562 -0
  48. package/src/spaceGroups/affine.ts +315 -0
  49. package/src/spaceGroups/cell.ts +382 -0
  50. package/src/spaceGroups/describe.ts +149 -0
  51. package/src/spaceGroups/planeGroupData.ts +407 -0
  52. package/src/spaceGroups/planeGroups.ts +75 -0
  53. package/src/spaceGroups/planePointGroups.ts +90 -0
  54. package/src/spaceGroups/positions.ts +267 -0
  55. package/src/spaceGroups/rational.ts +115 -0
  56. package/src/spaceGroups/snap.ts +121 -0
  57. package/src/version.ts +1 -1
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The ten plane point groups (ITA 6th ed., Table 3.2.1.1, p. 720), `3m` in its two orientations
3
+ * `3m1` and `31m` (Ch. 3.2, p. 721, item (d)). Their operations are the linear parts of the
4
+ * symmorphic plane group of each, in ITA's order (pm for m, p3m1 and p31m for the two settings of
5
+ * 3m), so that the point group of a plane group is its linear part and one data source serves both.
6
+ * Internal; exported through `symcrys/plane`.
7
+ */
8
+
9
+ import { type ExactOperation } from './affine.js';
10
+ import { type PlaneSystem } from './planeGroupData.js';
11
+ import { planeGroupEntry, planeGroupGenerators, planeGroupOperations } from './planeGroups.js';
12
+ import { ZERO } from './rational.js';
13
+
14
+ /** The keys of the ten plane point groups, in the order of ITA Table 3.2.1.1. */
15
+ export const PLANE_POINT_GROUP_KEYS = ['1', '2', 'm', '2mm', '4', '4mm', '3', '3m', '6', '6mm'] as const;
16
+
17
+ /** The key of a plane point group. */
18
+ export type PlanePointGroupKey = (typeof PLANE_POINT_GROUP_KEYS)[number];
19
+
20
+ /** The symmorphic plane group of each point group and setting, whose linear parts it is. */
21
+ const SOURCE: Record<PlanePointGroupKey, readonly string[]> = {
22
+ '1': ['p1'],
23
+ '2': ['p2'],
24
+ m: ['pm'],
25
+ '2mm': ['p2mm'],
26
+ '4': ['p4'],
27
+ '4mm': ['p4mm'],
28
+ '3': ['p3'],
29
+ '3m': ['p3m1', 'p31m'],
30
+ '6': ['p6'],
31
+ '6mm': ['p6mm'],
32
+ };
33
+
34
+ /** The point group of a plane group and its setting: the key under which the plane group's symbol appears in `SOURCE`. */
35
+ export function planePointGroupOf(groupSymbol: string): { key: PlanePointGroupKey; setting: number } {
36
+ for (const key of PLANE_POINT_GROUP_KEYS) {
37
+ const i = SOURCE[key].indexOf(groupSymbol);
38
+ if (i >= 0) return { key, setting: i + 1 };
39
+ }
40
+ // A plane group that is not symmorphic has the setting of the symmorphic group of its point group.
41
+ const entry = planeGroupEntry(groupSymbol);
42
+ return { key: entry.pointGroup as PlanePointGroupKey, setting: 1 };
43
+ }
44
+
45
+ /** True if `key` is the key of a plane point group. */
46
+ export function isPlanePointGroupKey(key: unknown): key is PlanePointGroupKey {
47
+ return typeof key === 'string' && (PLANE_POINT_GROUP_KEYS as readonly string[]).includes(key);
48
+ }
49
+
50
+ /** The symmorphic plane group for a point group and a setting (1-based); throws for an unknown one. */
51
+ function source(key: PlanePointGroupKey, setting = 1): string {
52
+ const list = SOURCE[key];
53
+ if (!Number.isInteger(setting) || setting < 1 || setting > list.length) {
54
+ throw new RangeError(`The plane point group ${key} has no setting ${String(setting)}`);
55
+ }
56
+ return list[setting - 1];
57
+ }
58
+
59
+ /** The number of settings of a plane point group: 2 for `3m`, otherwise 1. */
60
+ export function planePointGroupSettingCount(key: PlanePointGroupKey): number {
61
+ return SOURCE[key].length;
62
+ }
63
+
64
+ /** The symbol of a plane point group in a setting: `3m1` or `31m` for `3m`, otherwise the key. */
65
+ export function planePointGroupSymbol(key: PlanePointGroupKey, setting = 1): string {
66
+ const full = planeGroupEntry(source(key, setting)).fullSymbol.slice(1);
67
+ return key === '3m' ? full : key;
68
+ }
69
+
70
+ /** The crystal system of a plane point group. */
71
+ export function planePointGroupSystem(key: PlanePointGroupKey): PlaneSystem {
72
+ return planeGroupEntry(source(key)).system;
73
+ }
74
+
75
+ const linear = (op: ExactOperation): ExactOperation => ({
76
+ matrix: op.matrix,
77
+ translation: op.translation.map(() => ZERO),
78
+ });
79
+
80
+ /** The operations of a plane point group in a setting, in ITA's order, as operations without translation. */
81
+ export function planePointGroupOperations(key: PlanePointGroupKey, setting = 1): ExactOperation[] {
82
+ return planeGroupOperations(source(key, setting)).map(linear);
83
+ }
84
+
85
+ /** The generators of a plane point group: the linear parts of ITA's selected generators of its symmorphic plane group. */
86
+ export function planePointGroupGenerators(key: PlanePointGroupKey, setting = 1): ExactOperation[] {
87
+ return planeGroupGenerators(source(key, setting))
88
+ .filter((op) => !(op.matrix[0][0] === 1 && op.matrix[0][1] === 0 && op.matrix[1][0] === 0 && op.matrix[1][1] === 1))
89
+ .map(linear);
90
+ }
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Points of a plane group: their orbit, site symmetry and Wyckoff position (CLAUDE.md, "Plane
3
+ * groups (and later space groups)"). Points come from callers as floating-point coordinates in the
4
+ * lattice basis; whether an operation fixes a point is decided within a tolerance, as for the
5
+ * point groups (`siteSymmetry`). Internal for now.
6
+ */
7
+
8
+ import { compose, equalModLattice, parseOperation, toPlain, type PlainOperation } from './affine.js';
9
+ import { planeGroupEntry, planeGroupOperations } from './planeGroups.js';
10
+ import { EPSILON } from '../tolerances.js';
11
+
12
+ /** Options of the functions that take a point. */
13
+ export interface PointOptions {
14
+ /**
15
+ * Two points count as the same, modulo the lattice, if each coordinate differs by less than this
16
+ * from an integer (coordinates in the lattice basis). Default 10⁻⁶.
17
+ */
18
+ readonly tolerance?: number;
19
+ }
20
+
21
+ /** The site symmetry of a point under a plane group. */
22
+ export interface PlaneSiteSymmetry {
23
+ /**
24
+ * Indices into the operations of the group (`planeGroupOperations`) of those that map the point
25
+ * to itself modulo the lattice, ascending.
26
+ */
27
+ readonly operations: readonly number[];
28
+ /**
29
+ * The operations of the site symmetry, each with the lattice translation that makes it fix the
30
+ * point (not only modulo the lattice).
31
+ */
32
+ readonly fixing: readonly PlainOperation[];
33
+ /**
34
+ * The point set onto the fixed space of its site symmetry (the mean of its images under the
35
+ * fixing operations), in [0, 1), which removes rounding errors within the tolerance.
36
+ */
37
+ readonly point: readonly number[];
38
+ /** The number of points in the conventional cell equivalent to it. */
39
+ readonly multiplicity: number;
40
+ }
41
+
42
+ /** The Wyckoff position of a point. */
43
+ export interface PlaneWyckoffPosition {
44
+ /** The Wyckoff letter, as ITA prints it. */
45
+ readonly letter: string;
46
+ /** The multiplicity, as ITA prints it. */
47
+ readonly multiplicity: number;
48
+ /** The oriented site-symmetry symbol, as ITA prints it. */
49
+ readonly siteSymmetry: string;
50
+ }
51
+
52
+ function tolerance(options?: PointOptions): number {
53
+ const t = options?.tolerance ?? EPSILON;
54
+ // Modulo the lattice two coordinates differ by at most 1/2, so a tolerance of 1/2 or more says nothing.
55
+ if (!(typeof t === 'number' && t > 0 && t < 0.5)) {
56
+ throw new RangeError(`The tolerance must lie between 0 and 1/2, not ${String(t)}`);
57
+ }
58
+ return t;
59
+ }
60
+
61
+ function checkPoint(point: readonly number[]): void {
62
+ if (point.length !== 2 || !point.every(Number.isFinite)) {
63
+ throw new RangeError(`A point of the plane has two finite coordinates, not ${JSON.stringify(point)}`);
64
+ }
65
+ }
66
+
67
+ const mod1 = (v: number): number => {
68
+ const r = v - Math.floor(v);
69
+ return r >= 1 ? 0 : r + 0;
70
+ };
71
+
72
+ function image(op: PlainOperation, p: readonly number[]): number[] {
73
+ return op.matrix.map((row, i) => row[0] * p[0] + row[1] * p[1] + op.translation[i]);
74
+ }
75
+
76
+ /** True if the two points agree modulo the lattice within `tol` in each coordinate. */
77
+ function sameModLattice(p: readonly number[], q: readonly number[], tol: number): boolean {
78
+ return p.every((v, i) => {
79
+ const d = v - q[i];
80
+ return Math.abs(d - Math.round(d)) < tol;
81
+ });
82
+ }
83
+
84
+ /**
85
+ * Per plane group, computed once: its operations as plain numbers and its group table modulo the
86
+ * lattice (`table[a][b]` is the index of the operation that equals a∘b modulo the lattice), so that
87
+ * closing a set of operations works on indices (#86).
88
+ */
89
+ interface GroupData {
90
+ readonly ops: readonly PlainOperation[];
91
+ readonly table: readonly (readonly number[])[];
92
+ }
93
+
94
+ const groupCache = new Map<string, GroupData>();
95
+ function groupData(key: string): GroupData {
96
+ const k = planeGroupEntry(key).symbol;
97
+ let data = groupCache.get(k);
98
+ if (!data) {
99
+ const exact = planeGroupOperations(k);
100
+ const table = exact.map((a) =>
101
+ exact.map((b) => {
102
+ const product = compose(a, b);
103
+ const i = exact.findIndex((op) => equalModLattice(op, product));
104
+ if (i < 0) throw new Error(`The operations of ${k} are not closed modulo the lattice`);
105
+ return i;
106
+ }),
107
+ );
108
+ data = { ops: exact.map(toPlain), table };
109
+ groupCache.set(k, data);
110
+ }
111
+ return data;
112
+ }
113
+
114
+ const plainOperations = (key: string): readonly PlainOperation[] => groupData(key).ops;
115
+
116
+ /**
117
+ * The orbit of a point under a plane group: its distinct images in the conventional cell, each in
118
+ * [0, 1), in the order of the operations that first produce them. Coinciding images (within the
119
+ * tolerance) are merged.
120
+ */
121
+ export function planeOrbit(key: string, point: readonly number[], options?: PointOptions): number[][] {
122
+ checkPoint(point);
123
+ const tol = tolerance(options);
124
+ const out: number[][] = [];
125
+ for (const op of plainOperations(key)) {
126
+ const q = image(op, point).map(mod1);
127
+ if (!out.some((r) => sameModLattice(r, q, tol))) out.push(q);
128
+ }
129
+ return out;
130
+ }
131
+
132
+ /** Indices of `set` closed under products, modulo the lattice, within the operations of the group. */
133
+ function closeWithin(key: string, set: readonly number[]): number[] {
134
+ const { table } = groupData(key);
135
+ const out = [...new Set(set)];
136
+ const member = new Set(out);
137
+ // Every product of two members is a member once each new member has been combined with all others.
138
+ for (let i = 0; i < out.length; i++) {
139
+ for (let j = 0; j <= i; j++) {
140
+ for (const k of [table[out[i]][out[j]], table[out[j]][out[i]]]) {
141
+ if (!member.has(k)) {
142
+ member.add(k);
143
+ out.push(k);
144
+ }
145
+ }
146
+ }
147
+ }
148
+ return out.sort((a, b) => a - b);
149
+ }
150
+
151
+ /** The operations of `indices`, each shifted by the lattice translation that brings its image of `p` nearest to `p`. */
152
+ function fixingOperations(ops: readonly PlainOperation[], indices: readonly number[], p: readonly number[]) {
153
+ return indices.map((i) => {
154
+ const op = ops[i];
155
+ const n = image(op, p).map((v, k) => Math.round(v - p[k]));
156
+ return { matrix: op.matrix.map((r) => [...r]), translation: op.translation.map((t, k) => t - n[k]) };
157
+ });
158
+ }
159
+
160
+ /**
161
+ * The site symmetry of a point under a plane group. The operations that fix the point modulo the
162
+ * lattice within the tolerance are closed under products and the point is set onto the fixed space
163
+ * of the closure (the mean of its images), repeated until stable, as `siteSymmetry` does for the point
164
+ * groups; so the result is always a subgroup and the set point lies exactly on its elements. Throws a
165
+ * RangeError if that does not settle (a tolerance far too large).
166
+ */
167
+ export function planeSiteSymmetry(key: string, point: readonly number[], options?: PointOptions): PlaneSiteSymmetry {
168
+ checkPoint(point);
169
+ const tol = tolerance(options);
170
+ const ops = plainOperations(key);
171
+ const fixingAt = (p: readonly number[]): number[] =>
172
+ ops.flatMap((op, i) => (sameModLattice(image(op, p), p, tol) ? [i] : []));
173
+ let p: readonly number[] = point;
174
+ let set = closeWithin(key, fixingAt(p));
175
+ for (let pass = 0; pass < 8; pass++) {
176
+ const fixing = fixingOperations(ops, set, p);
177
+ const mean = [0, 1].map((k) => fixing.reduce((s, op) => s + image(op, p)[k], 0) / fixing.length);
178
+ const next = closeWithin(key, fixingAt(mean));
179
+ const settled = fixing.every((op) => sameModLattice(image(op, mean), mean, 1e-9));
180
+ if (settled && next.length === set.length && next.every((x, i) => x === set[i])) {
181
+ const q = mean.map(mod1);
182
+ return {
183
+ operations: set,
184
+ fixing: fixingOperations(ops, set, q),
185
+ point: q,
186
+ multiplicity: ops.length / set.length,
187
+ };
188
+ }
189
+ p = mean;
190
+ set = next;
191
+ }
192
+ throw new RangeError(
193
+ `No common fixed point for the operations fixing ${JSON.stringify(point)} within ${tol} (tolerance too large?)`,
194
+ );
195
+ }
196
+
197
+ /** A printed coordinate expression, parsed once. */
198
+ const expressionCache = new Map<string, PlainOperation>();
199
+ function parsed(expression: string): PlainOperation {
200
+ let op = expressionCache.get(expression);
201
+ if (!op) {
202
+ op = toPlain(parseOperation(expression));
203
+ expressionCache.set(expression, op);
204
+ }
205
+ return op;
206
+ }
207
+
208
+ /**
209
+ * True if some parameters x, y make the printed coordinate expression (e.g. `x,2x`, `-x+1/2,y`) give
210
+ * the point modulo the lattice within `tol`: least squares over the nearby lattice translations.
211
+ */
212
+ function onExpression(expression: string, p: readonly number[], tol: number): boolean {
213
+ const { matrix, translation } = parsed(expression);
214
+ const c = translation;
215
+ const ex = [matrix[0][0], matrix[1][0]];
216
+ const ey = [matrix[0][1], matrix[1][1]];
217
+ for (let i = -2; i <= 2; i++) {
218
+ for (let j = -2; j <= 2; j++) {
219
+ const r = [p[0] - c[0] - i, p[1] - c[1] - j];
220
+ // Solve min |a·ex + b·ey − r| over the columns that are not zero.
221
+ const cols = [ex, ey].filter((v) => v[0] !== 0 || v[1] !== 0);
222
+ let fit = [0, 0];
223
+ if (cols.length === 1) {
224
+ const v = cols[0];
225
+ const t = (v[0] * r[0] + v[1] * r[1]) / (v[0] * v[0] + v[1] * v[1]);
226
+ fit = [t * v[0], t * v[1]];
227
+ } else if (cols.length === 2) {
228
+ const det = ex[0] * ey[1] - ex[1] * ey[0];
229
+ if (Math.abs(det) < 1e-12) {
230
+ const v = ex;
231
+ const t = (v[0] * r[0] + v[1] * r[1]) / (v[0] * v[0] + v[1] * v[1]);
232
+ fit = [t * v[0], t * v[1]];
233
+ } else {
234
+ fit = r;
235
+ }
236
+ }
237
+ if (Math.abs(fit[0] - r[0]) < tol && Math.abs(fit[1] - r[1]) < tol) return true;
238
+ }
239
+ }
240
+ return false;
241
+ }
242
+
243
+ /**
244
+ * The Wyckoff position of a point under a plane group, as ITA prints it: the point is first set
245
+ * onto the fixed space of its site symmetry (`planeSiteSymmetry`), then found among the printed
246
+ * coordinates of the positions with its multiplicity, the centring included.
247
+ */
248
+ export function planeWyckoffPositionOf(
249
+ key: string,
250
+ point: readonly number[],
251
+ options?: PointOptions,
252
+ ): PlaneWyckoffPosition {
253
+ const tol = tolerance(options);
254
+ const site = planeSiteSymmetry(key, point, options);
255
+ const entry = planeGroupEntry(key);
256
+ const centrings = [[0, 0], ...entry.centring.map((t) => parsed(t).translation)];
257
+ for (const [multiplicity, letter, siteSymmetry, coordinates] of entry.wyckoff) {
258
+ if (multiplicity !== site.multiplicity) continue;
259
+ for (const t of centrings) {
260
+ const shifted = [site.point[0] - t[0], site.point[1] - t[1]];
261
+ if (coordinates.some((expression) => onExpression(expression, shifted, tol))) {
262
+ return { letter, multiplicity, siteSymmetry };
263
+ }
264
+ }
265
+ }
266
+ throw new RangeError(`No Wyckoff position of ${entry.symbol} holds the point ${JSON.stringify(point)}`);
267
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Exact rational numbers for the translations of space and plane groups (CLAUDE.md, "Plane groups
3
+ * (and later space groups)"). A rational is a pair [numerator, denominator] of safe integers with
4
+ * a positive denominator and no common factor, so that two equal numbers have equal pairs. Every
5
+ * intermediate product is checked: a result outside the safe integers throws instead of rounding.
6
+ */
7
+
8
+ /** A rational number n/d: d > 0, gcd(n, d) = 1, both safe integers. */
9
+ export type Rational = readonly [numerator: number, denominator: number];
10
+
11
+ /** The rational 0. */
12
+ export const ZERO: Rational = [0, 1];
13
+
14
+ /** The rational 1. */
15
+ export const ONE: Rational = [1, 1];
16
+
17
+ function gcd(a: number, b: number): number {
18
+ let x = Math.abs(a);
19
+ let y = Math.abs(b);
20
+ while (y !== 0) {
21
+ [x, y] = [y, x % y];
22
+ }
23
+ return x;
24
+ }
25
+
26
+ /** Throws unless `value` is a safe integer. */
27
+ export function checkSafeInteger(value: number, what: string): number {
28
+ if (!Number.isSafeInteger(value)) {
29
+ throw new RangeError(`${what} must be a safe integer, not ${String(value)}`);
30
+ }
31
+ return value;
32
+ }
33
+
34
+ /** The product a·b of two safe integers; throws if it leaves the safe integers. */
35
+ export function safeProduct(a: number, b: number): number {
36
+ return checkSafeInteger(a * b, 'An intermediate product');
37
+ }
38
+
39
+ /** The sum a + b of two safe integers; throws if it leaves the safe integers. */
40
+ export function safeSum(a: number, b: number): number {
41
+ return checkSafeInteger(a + b, 'An intermediate sum');
42
+ }
43
+
44
+ /** The rational n/d in lowest terms; throws if d is 0 or a part is not a safe integer. */
45
+ export function rational(numerator: number, denominator = 1): Rational {
46
+ checkSafeInteger(numerator, 'Numerator');
47
+ checkSafeInteger(denominator, 'Denominator');
48
+ if (denominator === 0) {
49
+ throw new RangeError('Denominator must not be 0');
50
+ }
51
+ const g = gcd(numerator, denominator);
52
+ const sign = denominator < 0 ? -1 : 1;
53
+ // `+ 0` turns −0 into 0, so that equal numbers have equal pairs.
54
+ return [(sign * numerator) / g + 0, (sign * denominator) / g];
55
+ }
56
+
57
+ /** The sum a + b. */
58
+ export function add(a: Rational, b: Rational): Rational {
59
+ return rational(safeSum(safeProduct(a[0], b[1]), safeProduct(b[0], a[1])), safeProduct(a[1], b[1]));
60
+ }
61
+
62
+ /** The difference a − b. */
63
+ export function subtract(a: Rational, b: Rational): Rational {
64
+ return add(a, negate(b));
65
+ }
66
+
67
+ /** The product a·b. */
68
+ export function multiply(a: Rational, b: Rational): Rational {
69
+ return rational(safeProduct(a[0], b[0]), safeProduct(a[1], b[1]));
70
+ }
71
+
72
+ /** The product of an integer k and a rational a. */
73
+ export function scale(k: number, a: Rational): Rational {
74
+ return rational(safeProduct(k, a[0]), a[1]);
75
+ }
76
+
77
+ /** The negative −a. */
78
+ export function negate(a: Rational): Rational {
79
+ return rational(-a[0], a[1]);
80
+ }
81
+
82
+ /** True if a and b are the same number. */
83
+ export function rationalsEqual(a: Rational, b: Rational): boolean {
84
+ return a[0] === b[0] && a[1] === b[1];
85
+ }
86
+
87
+ /** True if a is an integer. */
88
+ export function isInteger(a: Rational): boolean {
89
+ return a[1] === 1;
90
+ }
91
+
92
+ /** The representative of a modulo 1, in [0, 1). */
93
+ export function mod1(a: Rational): Rational {
94
+ const r = ((a[0] % a[1]) + a[1]) % a[1];
95
+ return rational(r, a[1]);
96
+ }
97
+
98
+ /** The nearest double. */
99
+ export function toNumber(a: Rational): number {
100
+ return a[0] / a[1];
101
+ }
102
+
103
+ /** Reads a rational as ITA prints it: an integer or a fraction such as `1/2` or `-2/3`. */
104
+ export function parseRational(text: string): Rational {
105
+ const m = /^([+-]?\d+)(?:\/(\d+))?$/.exec(text.trim());
106
+ if (!m) {
107
+ throw new RangeError(`Not a rational number: "${text}"`);
108
+ }
109
+ return rational(Number(m[1]), m[2] === undefined ? 1 : Number(m[2]));
110
+ }
111
+
112
+ /** Writes a rational as ITA prints it: `0`, `1`, `-1/2`, `2/3`. */
113
+ export function formatRational(a: Rational): string {
114
+ return a[1] === 1 ? String(a[0]) : `${a[0]}/${a[1]}`;
115
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Snapping a point of the plane onto the nearest Wyckoff position of a plane group, by the distance
3
+ * of the point to the position (#85; CLAUDE.md, "Snapping onto a Wyckoff position"). Unlike the site
4
+ * symmetry (`positions.ts`), which asks whether the images of a point lie within a tolerance of it,
5
+ * this asks whether the point lies within the tolerance of the point set of a position. Internal.
6
+ */
7
+
8
+ import { parseOperation, toPlain, type PlainOperation } from './affine.js';
9
+ import { planeGroupEntry } from './planeGroups.js';
10
+ import { EPSILON } from '../tolerances.js';
11
+
12
+ /** The point set of one printed coordinate expression, x ↦ M·(x, y) + c, with the columns of M that are not zero. */
13
+ interface Expression {
14
+ readonly matrix: readonly (readonly number[])[];
15
+ readonly translation: readonly number[];
16
+ /** The number of free parameters: 0 for a point, 1 for a line, 2 for the general position. */
17
+ readonly freedom: number;
18
+ }
19
+
20
+ const cache = new Map<string, readonly { row: number; expressions: Expression[] }[]>();
21
+
22
+ function expression(op: PlainOperation, shift: readonly number[]): Expression {
23
+ const m = op.matrix;
24
+ const columns = [0, 1].filter((k) => m[0][k] !== 0 || m[1][k] !== 0);
25
+ const det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
26
+ return {
27
+ matrix: m,
28
+ translation: [op.translation[0] + shift[0], op.translation[1] + shift[1]],
29
+ freedom: columns.length === 2 && det === 0 ? 1 : columns.length,
30
+ };
31
+ }
32
+
33
+ /** Per printed Wyckoff row (index into `wyckoff`), its coordinate expressions with every centring. */
34
+ function positionsOf(symbol: string) {
35
+ let rows = cache.get(symbol);
36
+ if (!rows) {
37
+ const entry = planeGroupEntry(symbol);
38
+ const shifts = [[0, 0], ...entry.centring.map((t) => toPlain(parseOperation(t)).translation)];
39
+ rows = entry.wyckoff.map(([, , , coordinates], row) => ({
40
+ row,
41
+ expressions: coordinates.flatMap((c) => shifts.map((s) => expression(toPlain(parseOperation(c)), s))),
42
+ }));
43
+ cache.set(symbol, rows);
44
+ }
45
+ return rows;
46
+ }
47
+
48
+ /**
49
+ * The nearest point of the set of `e` to `p` modulo the lattice: the parameters by least squares in
50
+ * the lattice coordinates, over the lattice translations that can reach it. Returns the point and
51
+ * its distance, the larger of the two coordinate differences.
52
+ */
53
+ function nearest(e: Expression, p: readonly number[]): { point: number[]; distance: number } {
54
+ if (e.freedom === 2) return { point: [...p], distance: 0 };
55
+ const m = e.matrix;
56
+ const c = e.translation;
57
+ let best = { point: [0, 0], distance: Infinity };
58
+ // c lies in [0, 2) (a printed coordinate in [0, 1) plus a centring), p in [0, 1).
59
+ for (let i = -2; i <= 2; i++) {
60
+ for (let j = -2; j <= 2; j++) {
61
+ const v = [p[0] - c[0] - i, p[1] - c[1] - j];
62
+ let r: number[];
63
+ if (e.freedom === 0) {
64
+ r = [0, 0];
65
+ } else {
66
+ const k = m[0][0] !== 0 || m[1][0] !== 0 ? 0 : 1;
67
+ const col = [m[0][k], m[1][k]];
68
+ const t = (col[0] * v[0] + col[1] * v[1]) / (col[0] * col[0] + col[1] * col[1]);
69
+ r = [t * col[0], t * col[1]];
70
+ }
71
+ const distance = Math.max(Math.abs(r[0] - v[0]), Math.abs(r[1] - v[1]));
72
+ if (distance < best.distance) best = { point: [r[0] + c[0] + i, r[1] + c[1] + j], distance };
73
+ }
74
+ }
75
+ return best;
76
+ }
77
+
78
+ const mod1 = (v: number): number => {
79
+ const r = v - Math.floor(v);
80
+ return r >= 1 ? 0 : r + 0;
81
+ };
82
+
83
+ /** A point snapped onto a Wyckoff position: the index of the printed row and the point on it, in [0, 1). */
84
+ export interface SnappedPoint {
85
+ readonly row: number;
86
+ readonly point: readonly number[];
87
+ }
88
+
89
+ /**
90
+ * Snaps a point (lattice basis) onto the most special Wyckoff position of a plane group that lies
91
+ * within `tolerance` of it (per coordinate, modulo the lattice): positions without a free parameter
92
+ * first, then lines, then the general position, which always holds the point. Among positions with
93
+ * the same number of free parameters the nearest wins. Throws a RangeError for a point that is not
94
+ * two finite numbers or a tolerance outside (0, 1/2).
95
+ */
96
+ export function planeSnapToWyckoffPosition(
97
+ key: string,
98
+ point: readonly number[],
99
+ tolerance: number = EPSILON,
100
+ ): SnappedPoint {
101
+ if (point.length !== 2 || !point.every(Number.isFinite)) {
102
+ throw new RangeError(`A point of the plane has two finite coordinates, not ${JSON.stringify(point)}`);
103
+ }
104
+ if (!(typeof tolerance === 'number' && tolerance > 0 && tolerance < 0.5)) {
105
+ throw new RangeError(`The tolerance must lie between 0 and 1/2, not ${String(tolerance)}`);
106
+ }
107
+ const p = point.map(mod1);
108
+ const rows = positionsOf(planeGroupEntry(key).symbol);
109
+ for (const freedom of [0, 1, 2]) {
110
+ let best: { row: number; point: number[]; distance: number } | undefined;
111
+ for (const { row, expressions } of rows) {
112
+ for (const e of expressions) {
113
+ if (e.freedom !== freedom) continue;
114
+ const n = nearest(e, p);
115
+ if (n.distance < tolerance && (!best || n.distance < best.distance)) best = { row, ...n };
116
+ }
117
+ }
118
+ if (best) return { row: best.row, point: best.point.map(mod1) };
119
+ }
120
+ throw new Error(`The general position of ${key} does not hold ${JSON.stringify(point)}`);
121
+ }
package/src/version.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  *
4
4
  * @remarks Kept equal to `version` in package.json (checked by version.test.ts).
5
5
  */
6
- export const VERSION = '0.8.1';
6
+ export const VERSION = '0.10.0';