symcrys 0.6.1 → 0.7.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 +2 -2
  2. package/dist/crystalClasses.d.ts +94 -0
  3. package/dist/crystalClasses.d.ts.map +1 -1
  4. package/dist/crystalClasses.js +79 -0
  5. package/dist/crystalClasses.js.map +1 -1
  6. package/dist/index.d.ts +4 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1 -1
  9. package/dist/index.js.map +1 -1
  10. package/dist/magnetic.d.ts +2 -0
  11. package/dist/magnetic.d.ts.map +1 -1
  12. package/dist/magnetic.js +2 -0
  13. package/dist/magnetic.js.map +1 -1
  14. package/dist/pointGroups/crystalForms.d.ts +70 -0
  15. package/dist/pointGroups/crystalForms.d.ts.map +1 -0
  16. package/dist/pointGroups/crystalForms.js +69 -0
  17. package/dist/pointGroups/crystalForms.js.map +1 -0
  18. package/dist/pointGroups/crystalFormsData.d.ts +32 -0
  19. package/dist/pointGroups/crystalFormsData.d.ts.map +1 -0
  20. package/dist/pointGroups/crystalFormsData.js +518 -0
  21. package/dist/pointGroups/crystalFormsData.js.map +1 -0
  22. package/dist/pointGroups/elements.d.ts +5 -1
  23. package/dist/pointGroups/elements.d.ts.map +1 -1
  24. package/dist/pointGroups/elements.js +6 -2
  25. package/dist/pointGroups/elements.js.map +1 -1
  26. package/dist/pointGroups/identify.d.ts +75 -0
  27. package/dist/pointGroups/identify.d.ts.map +1 -0
  28. package/dist/pointGroups/identify.js +193 -0
  29. package/dist/pointGroups/identify.js.map +1 -0
  30. package/dist/pointGroups/orbits.d.ts +85 -0
  31. package/dist/pointGroups/orbits.d.ts.map +1 -0
  32. package/dist/pointGroups/orbits.js +134 -0
  33. package/dist/pointGroups/orbits.js.map +1 -0
  34. package/dist/pointGroups/wyckoff.d.ts +40 -1
  35. package/dist/pointGroups/wyckoff.d.ts.map +1 -1
  36. package/dist/pointGroups/wyckoff.js +55 -27
  37. package/dist/pointGroups/wyckoff.js.map +1 -1
  38. package/dist/version.d.ts +1 -1
  39. package/dist/version.js +1 -1
  40. package/package.json +1 -1
  41. package/src/crystalClasses.ts +146 -0
  42. package/src/index.ts +12 -0
  43. package/src/magnetic.ts +17 -0
  44. package/src/pointGroups/crystalForms.ts +143 -0
  45. package/src/pointGroups/crystalFormsData.ts +539 -0
  46. package/src/pointGroups/elements.ts +6 -2
  47. package/src/pointGroups/identify.ts +255 -0
  48. package/src/pointGroups/orbits.ts +228 -0
  49. package/src/pointGroups/wyckoff.ts +59 -26
  50. package/src/version.ts +1 -1
@@ -0,0 +1,255 @@
1
+ /**
2
+ * The point group of a list of operations, and the operations described geometrically, for any
3
+ * list (for instance the operations left after distorting a crystal; docs/conventions.md, "Point
4
+ * group of a list of operations"). Shared by both entry points.
5
+ */
6
+
7
+ import { det, multiply, trace, type Mat3, type Vec3 } from '../linalg.js';
8
+ import { checkOrthogonal, checkTimeReversal, type Operation } from '../operations.js';
9
+ import { EPSILON } from '../tolerances.js';
10
+ import { axialVector, rotationAxis, type OperationKind } from './elements.js';
11
+ import {
12
+ MAGNETIC_POINT_GROUP_KEYS,
13
+ operations as groupOperations,
14
+ settings,
15
+ type MagneticPointGroupKey,
16
+ } from './pointGroups.js';
17
+
18
+ /** Options of `pointGroupOf` and `describeOperationsOf`. */
19
+ export interface PointGroupOfOptions {
20
+ /**
21
+ * Two matrices are the same operation if no entry differs by this much or more, and a matrix
22
+ * counts as orthogonal and crystallographic within it. Default `EPSILON` (10⁻⁶); a caller whose
23
+ * matrices carry rounding errors passes a larger value, below 0.1.
24
+ */
25
+ readonly tolerance?: number;
26
+ }
27
+
28
+ /** The point group of a list of operations: its key, and the setting if the operations are exactly those of one. */
29
+ export interface IdentifiedPointGroup {
30
+ /** The key of the point group the operations generate. */
31
+ readonly key: MagneticPointGroupKey;
32
+ /**
33
+ * The 1-based index of the setting whose operations the group equals, in the Cartesian frame of
34
+ * symcrys; absent if the group is the point group in another orientation.
35
+ */
36
+ readonly setting?: number;
37
+ }
38
+
39
+ /** An axis in the Cartesian frame only, for operations that are not tied to a lattice. */
40
+ export interface CartesianAxis {
41
+ /** Unit vector; its first non-zero component, in the order x, y, z, is positive. */
42
+ readonly cartesian: Vec3;
43
+ }
44
+
45
+ /** One operation of any list described geometrically (`describeOperationsOf`). */
46
+ export interface CartesianOperationDescription {
47
+ /** What the operation is, without time reversal. */
48
+ readonly kind: OperationKind;
49
+ /**
50
+ * The n of the symbol n or n̄: 1 for the identity and the inversion, 2 for a mirror (m = 2̄),
51
+ * otherwise the order of the rotation part.
52
+ */
53
+ readonly order: number;
54
+ /** Rotation axis, rotoinversion axis or mirror normal; absent for the identity and the inversion. */
55
+ readonly axis?: CartesianAxis;
56
+ /**
57
+ * For n ≥ 3: `'+'` if the rotation part turns by +360°/n about `axis` (counter-clockwise seen
58
+ * from the tip of `axis` looking towards the origin), `'-'` if by −360°/n.
59
+ */
60
+ readonly sense?: '+' | '-';
61
+ /** True if the operation is combined with time reversal (a primed operation). */
62
+ readonly timeReversal: boolean;
63
+ }
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
+ /** No point group has more than 96 operations (m-3m1'). */
82
+ const MAX_ORDER = 96;
83
+
84
+ function toleranceOf(options?: PointGroupOfOptions): number {
85
+ const t = options?.tolerance ?? EPSILON;
86
+ if (!(typeof t === 'number' && t > 0 && t < 0.1)) throw new RangeError(`Invalid tolerance: ${String(t)}`);
87
+ return t;
88
+ }
89
+
90
+ /**
91
+ * How far the trace of a matrix with entries within `tolerance` may lie from an integer: three
92
+ * diagonal entries, so three times the tolerance (at least that of `EPSILON`).
93
+ */
94
+ const traceTolerance = (tolerance: number): number => 3 * Math.max(tolerance, EPSILON);
95
+
96
+ const same = (a: Operation, b: Operation, tolerance: number): boolean =>
97
+ a.timeReversal === b.timeReversal &&
98
+ a.matrix.every((row, i) => row.every((v, j) => Math.abs(v - b.matrix[i][j]) < tolerance));
99
+
100
+ /** The kind of an operation (rounded trace, sign of the determinant, time reversal): equal operations have the same. */
101
+ const kindOf = (op: Operation): string =>
102
+ `${Math.round(trace(op.matrix))}${det(op.matrix) > 0 ? '+' : '-'}${op.timeReversal ? "'" : ''}`;
103
+
104
+ /**
105
+ * The group the operations generate, or undefined if it is larger than any point group. The
106
+ * operations of the list that are not yet in the group are taken as generators, and the group is
107
+ * grown by multiplying each element by each generator until nothing new appears; a new operation
108
+ * is compared only with the operations of its kind.
109
+ */
110
+ function close(ops: readonly Operation[], tolerance: number): Operation[] | undefined {
111
+ const identity: Operation = {
112
+ matrix: [
113
+ [1, 0, 0],
114
+ [0, 1, 0],
115
+ [0, 0, 1],
116
+ ],
117
+ timeReversal: false,
118
+ };
119
+ const group: Operation[] = [];
120
+ const byKind = new Map<string, Operation[]>();
121
+ const has = (op: Operation): boolean => (byKind.get(kindOf(op)) ?? []).some((g) => same(g, op, tolerance));
122
+ const push = (op: Operation): void => {
123
+ group.push(op);
124
+ const k = kindOf(op);
125
+ const list = byKind.get(k);
126
+ if (list) list.push(op);
127
+ else byKind.set(k, [op]);
128
+ };
129
+ push(identity);
130
+ const generators: Operation[] = [];
131
+ for (const s of ops) {
132
+ if (has(s)) continue;
133
+ generators.push(s);
134
+ for (let i = 0; i < group.length; i++) {
135
+ for (const t of generators) {
136
+ const product: Operation = {
137
+ matrix: multiply(group[i].matrix, t.matrix),
138
+ timeReversal: group[i].timeReversal !== t.timeReversal,
139
+ };
140
+ if (has(product)) continue;
141
+ if (group.length >= MAX_ORDER) return undefined;
142
+ push(product);
143
+ }
144
+ }
145
+ }
146
+ return group;
147
+ }
148
+
149
+ /**
150
+ * How many operations of each kind a group has: determinant, trace and time reversal of each. For
151
+ * the 122 point groups these counts are all different (a test checks it), and since the 122 are
152
+ * all point groups up to orientation, the counts identify the point group of any finite group of
153
+ * crystallographic operations.
154
+ */
155
+ const signature = (ops: readonly Operation[], tolerance = EPSILON): string =>
156
+ ops
157
+ .map((op) => {
158
+ const t = trace(op.matrix);
159
+ const rounded = Math.round(t);
160
+ if (Math.abs(t - rounded) > traceTolerance(tolerance)) return 'x'; // not a crystallographic operation
161
+ return `${Math.round(det(op.matrix))}:${rounded}${op.timeReversal ? "'" : ''}`;
162
+ })
163
+ .sort()
164
+ .join(' ');
165
+
166
+ let bySignature: Map<string, MagneticPointGroupKey> | undefined;
167
+
168
+ function keyOfSignature(s: string): MagneticPointGroupKey | undefined {
169
+ if (!bySignature) {
170
+ bySignature = new Map();
171
+ for (const key of MAGNETIC_POINT_GROUP_KEYS) bySignature.set(signature(groupOperations(key)), key);
172
+ }
173
+ return bySignature.get(s);
174
+ }
175
+
176
+ /**
177
+ * The point group generated by a list of Cartesian operations, for instance those left after
178
+ * distorting a crystal: its key, and the setting whose operations it equals in the frame of symcrys
179
+ * (absent if the group is the point group in another orientation). The list is closed into a group
180
+ * first, two matrices being equal when no entry differs by `tolerance` (default `EPSILON`) or more.
181
+ * Time reversal counts: a list with time reversal gives a magnetic point group. Returns undefined
182
+ * if the operations generate no point group (an operation of order 5, a group larger than 96).
183
+ * 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
185
+ * setting 1.
186
+ */
187
+ export function pointGroupOf(
188
+ operations: readonly Operation[],
189
+ options?: PointGroupOfOptions,
190
+ ): IdentifiedPointGroup | undefined {
191
+ const tolerance = toleranceOf(options);
192
+ checkTimeReversal(operations);
193
+ operations.forEach((op, i) => checkOrthogonalWithin(op.matrix, `Operation ${i}`, tolerance));
194
+ const group = close(operations, tolerance);
195
+ if (!group) return undefined;
196
+ const key = keyOfSignature(signature(group, tolerance));
197
+ if (!key) return undefined;
198
+ // The operations passed in generate the group; if each is an operation of a setting of the same
199
+ // order, the group is that setting. Products are not compared, since their errors add up.
200
+ const setting = settings(key, 'itc').find((s) => {
201
+ const ops = groupOperations(key, { convention: 'itc', setting: s.index });
202
+ return ops.length === group.length && operations.every((g) => ops.some((op) => same(g, op, tolerance)));
203
+ });
204
+ return Object.freeze(setting ? { key, setting: setting.index } : { key });
205
+ }
206
+
207
+ /**
208
+ * The axis signed so that its first non-zero component, in the order x, y, z, is positive; a
209
+ * component smaller than the tolerance counts as zero.
210
+ */
211
+ function signed(v: Vec3, tolerance: number): { axis: Vec3; flip: boolean } {
212
+ const first = v.find((x) => Math.abs(x) >= Math.max(tolerance, EPSILON)) ?? 0;
213
+ return first < 0 ? { axis: [-v[0] + 0, -v[1] + 0, -v[2] + 0], flip: true } : { axis: v, flip: false };
214
+ }
215
+
216
+ const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
217
+
218
+ function describe(op: Operation, i: number, tolerance: number): CartesianOperationDescription {
219
+ checkOrthogonalWithin(op.matrix, `Operation ${i}`, tolerance);
220
+ const notCrystallographic = `Operation ${i} is not a crystallographic point operation`;
221
+ // The trace of the rotation part is an integer exactly for the angles 360°/n, n = 1, 2, 3, 4, 6.
222
+ const t = det(op.matrix) > 0 ? trace(op.matrix) : -trace(op.matrix);
223
+ if (Math.abs(t - Math.round(t)) > traceTolerance(tolerance)) throw new RangeError(notCrystallographic);
224
+ // The order from the trace of the rotation part, 1 + 2 cos(360°/n): 3, −1, 0, 1, 2 for n = 1, 2, 3, 4, 6.
225
+ const n = ({ 3: 1, [-1]: 2, 0: 3, 1: 4, 2: 6 } as Record<number, number>)[Math.round(t)];
226
+ if (n === undefined) throw new RangeError(notCrystallographic);
227
+ const r = (det(op.matrix) > 0 ? op.matrix : op.matrix.map((row) => row.map((v) => -v))) as Mat3;
228
+ const proper = det(op.matrix) > 0;
229
+ const timeReversal = op.timeReversal;
230
+ if (n === 1) return Object.freeze({ kind: proper ? 'identity' : 'inversion', order: 1, timeReversal });
231
+ const { axis } = signed(rotationAxis(r, n), tolerance);
232
+ const frozenAxis = Object.freeze({ cartesian: Object.freeze(axis) as unknown as Vec3 });
233
+ const kind: OperationKind = proper ? 'rotation' : n === 2 ? 'mirror' : 'rotoinversion';
234
+ if (n === 2) return Object.freeze({ kind, order: 2, axis: frozenAxis, timeReversal });
235
+ const sense = dot(axialVector(r), axis) > 0 ? '+' : '-';
236
+ return Object.freeze({ kind, order: n, axis: frozenAxis, sense, timeReversal });
237
+ }
238
+
239
+ /**
240
+ * Each operation of a list described geometrically, in the order of the list: kind, n, the
241
+ * Cartesian axis (rotation or rotoinversion axis, mirror normal) with its first non-zero component,
242
+ * in the order x, y, z, positive, and for n ≥ 3 the sense about that axis. The axes are not named
243
+ * by lattice directions, since the list need not belong to a setting; for a point group given by its
244
+ * key, `describeOperations` names them. Throws a RangeError for a matrix that is not orthogonal or
245
+ * 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`).
247
+ */
248
+ export function describeOperationsOf(
249
+ operations: readonly Operation[],
250
+ options?: PointGroupOfOptions,
251
+ ): readonly CartesianOperationDescription[] {
252
+ const tolerance = toleranceOf(options);
253
+ checkTimeReversal(operations);
254
+ return Object.freeze(operations.map((op, i) => describe(op, i, tolerance)));
255
+ }
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Operations in the lattice basis and orbits of faces and directions (docs/conventions.md,
3
+ * "Lattice basis and orbits"). Shared by both entry points.
4
+ */
5
+
6
+ import { crystalFamily, latticeBasis } from '../lattice.js';
7
+ import { apply, inverse, multiply, type Mat3, type Vec3 } from '../linalg.js';
8
+ import { checkOrthogonal, type Operation } from '../operations.js';
9
+ import { siteTolerance } from '../siteSymmetry.js';
10
+ import type { Uvw } from '../symmetryDirections.js';
11
+ import {
12
+ operations as groupOperations,
13
+ pointGroup,
14
+ type MagneticPointGroupKey,
15
+ type SettingOptions,
16
+ } from './pointGroups.js';
17
+ import type { Hkl } from './wyckoff.js';
18
+
19
+ const IDENTITY: Mat3 = [
20
+ [1, 0, 0],
21
+ [0, 1, 0],
22
+ [0, 0, 1],
23
+ ];
24
+
25
+ /**
26
+ * The conventional basis a, b, c (columns) in the Cartesian frame of a point group: that of
27
+ * `latticeBasis`, and for the monoclinic and triclinic families a, b, c along x, y, z, as for the
28
+ * Wyckoff positions (the integer matrices do not depend on the cell angles).
29
+ */
30
+ function conventionalBasis(key: MagneticPointGroupKey): Mat3 {
31
+ const family = crystalFamily(pointGroup(key).crystalSystem);
32
+ return family === 'monoclinic' || family === 'triclinic' ? IDENTITY : latticeBasis(family);
33
+ }
34
+
35
+ /** An integer matrix from one that should be one; throws if it is not (a data error). */
36
+ function integer(m: Mat3, what: string): Mat3 {
37
+ const r = m.map((row) => row.map((v) => Math.round(v) + 0)) as unknown as Mat3;
38
+ if (!m.every((row, i) => row.every((v, j) => Math.abs(v - r[i][j]) < 1e-9))) {
39
+ throw new Error(`${what} is not an integer matrix in the lattice basis: ${JSON.stringify(m)}`);
40
+ }
41
+ return r;
42
+ }
43
+
44
+ const deepFreeze = (m: Mat3): Mat3 => Object.freeze(m.map((row) => Object.freeze([...row]))) as unknown as Mat3;
45
+
46
+ const latticeCache = new WeakMap<readonly Operation[], readonly Operation[]>();
47
+
48
+ /**
49
+ * The operations of a point group in the conventional lattice basis (a, b, c; for the trigonal
50
+ * classes the hexagonal axes), in the order and with the time reversal of `operations` for the same
51
+ * setting and convention: integer matrices W acting on the coordinates of a lattice vector [uvw],
52
+ * W = B⁻¹·R·B with the basis B of `latticeBasis` and the Cartesian matrix R. They do not depend on
53
+ * the cell angles, so they exist for every family; for the monoclinic and triclinic families a, b,
54
+ * c are taken along x, y, z, as for the Wyckoff positions. In the ITC convention they are the
55
+ * matrices of ITA's general position (6th ed., Table 3.2.3.2). Not orthogonal in general: pass
56
+ * them to no function that takes Cartesian operations (docs/conventions.md, "Lattice basis and
57
+ * orbits").
58
+ */
59
+ export function latticeOperations(key: MagneticPointGroupKey, options?: SettingOptions): readonly Operation[] {
60
+ const ops = groupOperations(key, options);
61
+ let result = latticeCache.get(ops);
62
+ if (!result) {
63
+ const b = conventionalBasis(key);
64
+ const bInv = inverse(b);
65
+ result = Object.freeze(
66
+ ops.map((op, i) =>
67
+ Object.freeze({
68
+ matrix: deepFreeze(integer(multiply(multiply(bInv, op.matrix), b), `Operation ${i} of ${key}`)),
69
+ timeReversal: op.timeReversal,
70
+ }),
71
+ ),
72
+ );
73
+ latticeCache.set(ops, result);
74
+ }
75
+ return result;
76
+ }
77
+
78
+ /** The inverse of an integer matrix of determinant ±1, exactly (the adjugate). */
79
+ function integerInverse(w: Mat3): Mat3 {
80
+ return integer(inverse(w), 'The inverse of a lattice operation');
81
+ }
82
+
83
+ /** Indices of a face or a lattice direction, checked: three integers, not all zero. */
84
+ function indicesOf(value: unknown, name: string): readonly [number, number, number] {
85
+ if (
86
+ !Array.isArray(value) ||
87
+ value.length !== 3 ||
88
+ !value.every((x) => typeof x === 'number' && Number.isSafeInteger(x)) ||
89
+ value.every((x) => x === 0)
90
+ ) {
91
+ throw new RangeError(`${name} must be three (safe) integers, not all zero: ${JSON.stringify(value)}`);
92
+ }
93
+ return [value[0] + 0, value[1] + 0, value[2] + 0];
94
+ }
95
+
96
+ /** One face of the orbit of a face: its Miller indices and the operations that map the given face onto it. */
97
+ export interface FaceOrbitEntry {
98
+ /** Miller indices (hkl) of the face, in the conventional basis (hexagonal axes: without i). */
99
+ readonly hkl: Hkl;
100
+ /** Indices into `operations` (same setting and convention) of the operations that map the given face onto this one, ascending. */
101
+ readonly operations: readonly number[];
102
+ }
103
+
104
+ /** One direction of the orbit of a lattice direction: its indices and the operations that map the given direction onto it. */
105
+ export interface DirectionOrbitEntry {
106
+ /** The lattice direction [uvw] in the conventional basis. */
107
+ readonly uvw: Uvw;
108
+ /** Indices into `operations` (same setting and convention) of the operations that map the given direction onto this one, ascending. */
109
+ readonly operations: readonly number[];
110
+ }
111
+
112
+ /**
113
+ * The orbit of a face (hkl) or of a lattice direction [uvw] under a point group, exactly, in the
114
+ * lattice basis: the distinct faces (directions), in the order in which the operations reach them
115
+ * (so in the ITC convention the given face first), each with the indices of the operations that map
116
+ * the given one onto it. A face transforms with the inverse transpose of a lattice operation,
117
+ * h' = W⁻ᵀ·h, a direction with the operation itself, u' = W·u. The number of entries is the
118
+ * multiplicity of the face (direction), and the operations of the first entry, if it is the given
119
+ * one, are its site symmetry. Time reversal plays no part. Throws a RangeError unless exactly one of
120
+ * `hkl` and `uvw` is given, as three integers not all zero (hexagonal axes: three indices, without
121
+ * i).
122
+ */
123
+ export function orbit(
124
+ key: MagneticPointGroupKey,
125
+ indices: { readonly hkl: Hkl },
126
+ options?: SettingOptions,
127
+ ): readonly FaceOrbitEntry[];
128
+ export function orbit(
129
+ key: MagneticPointGroupKey,
130
+ indices: { readonly uvw: Uvw },
131
+ options?: SettingOptions,
132
+ ): readonly DirectionOrbitEntry[];
133
+ export function orbit(
134
+ key: MagneticPointGroupKey,
135
+ indices: { readonly hkl: Hkl } | { readonly uvw: Uvw },
136
+ options?: SettingOptions,
137
+ ): readonly FaceOrbitEntry[] | readonly DirectionOrbitEntry[];
138
+ export function orbit(
139
+ key: MagneticPointGroupKey,
140
+ indices: { readonly hkl: Hkl } | { readonly uvw: Uvw },
141
+ options?: SettingOptions,
142
+ ): readonly FaceOrbitEntry[] | readonly DirectionOrbitEntry[] {
143
+ const given = (indices ?? {}) as { readonly hkl?: unknown; readonly uvw?: unknown };
144
+ const hasHkl = given.hkl !== undefined;
145
+ const hasUvw = given.uvw !== undefined;
146
+ if (hasHkl === hasUvw) throw new RangeError('orbit: give either hkl (a face) or uvw (a lattice direction)');
147
+ const field = hasHkl ? 'hkl' : 'uvw';
148
+ const v = indicesOf(hasHkl ? given.hkl : given.uvw, field);
149
+ const ws = latticeOperations(key, options).map((op) => (hasHkl ? integerInverseTranspose(op.matrix) : op.matrix));
150
+ const images: { key: string; value: [number, number, number]; operations: number[] }[] = [];
151
+ ws.forEach((w, i) => {
152
+ const image = apply(w, v as unknown as Vec3).map((x) => x + 0) as [number, number, number];
153
+ const k = image.join(',');
154
+ const entry = images.find((e) => e.key === k);
155
+ if (entry) entry.operations.push(i);
156
+ else images.push({ key: k, value: image, operations: [i] });
157
+ });
158
+ return Object.freeze(
159
+ images.map((e) => Object.freeze({ [field]: Object.freeze(e.value), operations: Object.freeze(e.operations) })),
160
+ ) as unknown as readonly FaceOrbitEntry[] | readonly DirectionOrbitEntry[];
161
+ }
162
+
163
+ const inverseTransposeCache = new WeakMap<Mat3, Mat3>();
164
+
165
+ function integerInverseTranspose(w: Mat3): Mat3 {
166
+ let r = inverseTransposeCache.get(w);
167
+ if (!r) {
168
+ const inv = integerInverse(w);
169
+ r = deepFreeze([0, 1, 2].map((i) => [0, 1, 2].map((j) => inv[j][i])) as unknown as Mat3);
170
+ inverseTransposeCache.set(w, r);
171
+ }
172
+ return r;
173
+ }
174
+
175
+ /** Options of `orbitOf`. */
176
+ export interface OrbitOptions {
177
+ /**
178
+ * Two images count as one pole if their unit vectors are closer than this (Euclidean distance).
179
+ * Default 10⁻⁶; a caller whose directions carry rounding errors passes a larger value.
180
+ */
181
+ readonly tolerance?: number;
182
+ }
183
+
184
+ /** One pole of the orbit of a direction under a list of operations. */
185
+ export interface OrbitPole {
186
+ /** The image of the given direction as a Cartesian unit vector (the first operation's image where several coincide). */
187
+ readonly direction: Vec3;
188
+ /** Indices into the given operations of those that map the direction here, ascending. */
189
+ readonly operations: readonly number[];
190
+ }
191
+
192
+ /**
193
+ * The orbit of a direction (any non-zero vector, Cartesian, e.g. a face normal) under a list of
194
+ * operations, for instance those of a distorted crystal: the images of its unit vector under each
195
+ * operation, coinciding images merged (closer than `tolerance`, default `EPSILON`, as for
196
+ * `siteSymmetry`), in the order in which the operations reach them, each with the indices of the
197
+ * operations that map the direction there. The list is taken as it is, not closed into a group.
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`).
200
+ */
201
+ export function orbitOf(
202
+ operations: readonly { readonly matrix: Mat3 }[],
203
+ direction: Vec3,
204
+ options?: OrbitOptions,
205
+ ): readonly OrbitPole[] {
206
+ const tolerance = siteTolerance(options);
207
+ operations.forEach((op, i) => checkOrthogonal(op.matrix, `Operation ${i}`));
208
+ const n = Math.hypot(direction[0], direction[1], direction[2]);
209
+ if (!(n > 0) || !Number.isFinite(n)) throw new RangeError(`Not a direction: ${JSON.stringify(direction)}`);
210
+ const u: Vec3 = [direction[0] / n, direction[1] / n, direction[2] / n];
211
+ const poles: { direction: Vec3; operations: number[] }[] = [];
212
+ operations.forEach((op, i) => {
213
+ const w = apply(op.matrix, u);
214
+ const pole = poles.find(
215
+ (p) => Math.hypot(p.direction[0] - w[0], p.direction[1] - w[1], p.direction[2] - w[2]) < tolerance,
216
+ );
217
+ if (pole) pole.operations.push(i);
218
+ else poles.push({ direction: w, operations: [i] });
219
+ });
220
+ return Object.freeze(
221
+ poles.map((p) =>
222
+ Object.freeze({
223
+ direction: Object.freeze(p.direction) as unknown as Vec3,
224
+ operations: Object.freeze(p.operations),
225
+ }),
226
+ ),
227
+ );
228
+ }
@@ -54,35 +54,35 @@ export interface WyckoffPosition {
54
54
  export type WyckoffOptions = SettingOptions & SiteSymmetryOptions;
55
55
 
56
56
  /** The values substituted into ITA's Miller indices for the numeric representative. */
57
- const VALUES: Readonly<Record<string, number>> = { h: 3, k: 2, l: 1 };
57
+ export const REPRESENTATIVE_VALUES: Readonly<Record<'h' | 'k' | 'l', number>> = { h: 3, k: 2, l: 1 };
58
58
 
59
59
  /** One printed index (`h`, `-2h`, `0`, `1`) as a number. */
60
- function index(component: string): number {
60
+ function index(component: string, values: Readonly<Record<'h' | 'k' | 'l', number>>): number {
61
61
  const m = /^(-?)(\d*)([hkil]?)$/.exec(component);
62
62
  if (!m || (m[2] === '' && m[3] === '')) throw new Error(`Unreadable Miller index: ${component}`);
63
63
  const sign = m[1] ? -1 : 1;
64
64
  const factor = m[2] === '' ? 1 : Number(m[2]);
65
65
  if (m[3] === '') return sign * factor;
66
- if (m[3] === 'i') return sign * factor * -(VALUES.h + VALUES.k);
67
- return sign * factor * VALUES[m[3]];
66
+ if (m[3] === 'i') return sign * factor * -(values.h + values.k);
67
+ return sign * factor * values[m[3] as 'h' | 'k' | 'l'];
68
68
  }
69
69
 
70
- /** Printed Miller indices (three, or four for hexagonal axes) as three numbers. */
71
- function numericHkl(miller: string): Hkl {
72
- const parts = miller.split(',').map(index);
70
+ /** Printed Miller indices (three, or four for hexagonal axes) as three numbers, with the given values of h, k, l. */
71
+ export function numericHkl(miller: string, values = REPRESENTATIVE_VALUES): Hkl {
72
+ const parts = miller.split(',').map((c) => index(c, values));
73
73
  if (parts.length === 3) return [parts[0], parts[1], parts[2]];
74
74
  if (parts.length === 4 && parts[2] === -(parts[0] + parts[1])) return [parts[0], parts[1], parts[3]];
75
75
  throw new Error(`Unreadable Miller indices: ${miller}`);
76
76
  }
77
77
 
78
- const IDENTITY: Mat3 = [
78
+ export const IDENTITY: Mat3 = [
79
79
  [1, 0, 0],
80
80
  [0, 1, 0],
81
81
  [0, 0, 1],
82
82
  ];
83
83
 
84
84
  /** The face normal of (hkl) as a Cartesian unit vector: h a* + k b* + l c* with the reciprocal basis B⁻ᵀ. */
85
- function normal(basis: Mat3, hkl: Hkl): Vec3 {
85
+ export function normal(basis: Mat3, hkl: Hkl): Vec3 {
86
86
  const v = apply(transpose(inverse(basis)), hkl);
87
87
  const n = Math.hypot(v[0], v[1], v[2]);
88
88
  return [v[0] / n, v[1] / n, v[2] / n];
@@ -96,7 +96,7 @@ const HKL = 'hkl';
96
96
  * Only for components that are `0`, a number, or a plain letter with an optional `-` (as in `mm2`); a
97
97
  * letter is renamed after its new position. A factor such as `2x` throws.
98
98
  */
99
- function permutePattern(pattern: string, r: Mat3, letters: string): string {
99
+ export function permutePattern(pattern: string, r: Mat3, letters: string): string {
100
100
  const old = pattern.split(',');
101
101
  if (old.length !== 3) throw new Error(`Cannot carry ${pattern} into another setting`);
102
102
  return [0, 1, 2]
@@ -127,14 +127,12 @@ function isSignedPermutation(r: Mat3): boolean {
127
127
  );
128
128
  }
129
129
 
130
- /** The printed rows of a setting; for a setting ITA does not print, those of setting 1 carried into its frame. */
131
- function printedRows(key: PointGroupKey, setting: number): readonly WyckoffRow[] {
132
- const s = settings(key, 'itc')[setting - 1];
133
- const entry = ITA_WYCKOFF.find(
134
- (e) => e.symbol === s.symbol && (e.uniqueAxis === undefined || e.uniqueAxis === s.uniqueAxis),
135
- );
136
- if (entry) return entry.rows;
137
- if (setting === 1) throw new Error(`Point group ${key}: no printed Wyckoff positions for setting 1`);
130
+ /**
131
+ * The signed permutation r that carries setting 1 of a class into `setting` (new axis i = r[i][j] ×
132
+ * old axis j), for the settings ITA does not print (`mm2` settings 2 and 3). Throws if the frame of
133
+ * the setting is not a permutation of that of setting 1.
134
+ */
135
+ export function permutationFromSetting1(key: PointGroupKey, setting: number): Mat3 {
138
136
  const d = POINT_GROUP_DATA.find((x) => x.key === key);
139
137
  if (!d) throw new RangeError(`Unknown point group key: ${JSON.stringify(key)}`);
140
138
  const f1 = d.settings[0].frame;
@@ -147,6 +145,29 @@ function printedRows(key: PointGroupKey, setting: number): readonly WyckoffRow[]
147
145
  ) {
148
146
  throw new Error(`Point group ${key}, setting ${setting}: frame is not a permutation of setting 1`);
149
147
  }
148
+ return r;
149
+ }
150
+
151
+ /**
152
+ * The entry of a table printed per setting (Wyckoff positions, face forms) for a setting of a class:
153
+ * the one with the ITC short symbol (and unique axis) of the setting, or undefined if ITA does not
154
+ * print the setting.
155
+ */
156
+ export function printedEntry<E extends { readonly symbol: string; readonly uniqueAxis?: 'b' | 'c' }>(
157
+ table: readonly E[],
158
+ key: PointGroupKey,
159
+ setting: number,
160
+ ): E | undefined {
161
+ const s = settings(key, 'itc')[setting - 1];
162
+ return table.find((e) => e.symbol === s.symbol && (e.uniqueAxis === undefined || e.uniqueAxis === s.uniqueAxis));
163
+ }
164
+
165
+ /** The printed rows of a setting; for a setting ITA does not print, those of setting 1 carried into its frame. */
166
+ function printedRows(key: PointGroupKey, setting: number): readonly WyckoffRow[] {
167
+ const entry = printedEntry(ITA_WYCKOFF, key, setting);
168
+ if (entry) return entry.rows;
169
+ if (setting === 1) throw new Error(`Point group ${key}: no printed Wyckoff positions for setting 1`);
170
+ const r = permutationFromSetting1(key, setting);
150
171
  return printedRows(key, 1).map(([letter, mult, site, coords, miller]) => [
151
172
  letter,
152
173
  mult,
@@ -156,16 +177,32 @@ function printedRows(key: PointGroupKey, setting: number): readonly WyckoffRow[]
156
177
  ]);
157
178
  }
158
179
 
180
+ /**
181
+ * The lattice basis in which the Cartesian normals of the representatives are computed; monoclinic
182
+ * and triclinic: a, b, c along x, y, z (docs/conventions.md, "Site symmetry and Wyckoff positions").
183
+ */
184
+ export function faceBasis(key: PointGroupKey): Mat3 {
185
+ const d = POINT_GROUP_DATA.find((x) => x.key === key);
186
+ if (!d) throw new RangeError(`Unknown point group key: ${JSON.stringify(key)}`);
187
+ const family = crystalFamily(d.crystalSystem);
188
+ return family === 'monoclinic' || family === 'triclinic' ? IDENTITY : latticeBasis(family);
189
+ }
190
+
159
191
  const cache = new Map<string, readonly WyckoffPosition[]>();
160
192
 
161
- function itcSetting(key: PointGroupKey, options?: SettingOptions): number {
193
+ /**
194
+ * The setting index for a table that exists for the crystal classes in the ITC convention only
195
+ * (`what`: 'Wyckoff positions', 'Crystal forms'); throws a RangeError for a magnetic point group
196
+ * with time reversal and for another convention.
197
+ */
198
+ export function itcSetting(key: PointGroupKey, options?: SettingOptions, what = 'Wyckoff positions'): number {
162
199
  if (isMagneticPointGroupKey(key) && !isPointGroupKey(key)) {
163
200
  throw new RangeError(
164
- `Wyckoff positions are given for the 32 crystal classes only; ${JSON.stringify(key)} is a magnetic point group`,
201
+ `${what} are given for the 32 crystal classes only; ${JSON.stringify(key)} is a magnetic point group`,
165
202
  );
166
203
  }
167
204
  if ((options?.convention ?? 'itc') !== 'itc') {
168
- throw new RangeError("Wyckoff positions exist in the ITC convention only (convention 'itc')");
205
+ throw new RangeError(`${what} exist in the ITC convention only (convention 'itc')`);
169
206
  }
170
207
  const list = settings(key, 'itc');
171
208
  const index = options?.setting ?? list.find((s) => s.isDefault)?.index ?? 1;
@@ -186,11 +223,7 @@ export function wyckoffPositions(key: PointGroupKey, options?: SettingOptions):
186
223
  let result = cache.get(cacheKey);
187
224
  if (!result) {
188
225
  const ops = operations(key, { convention: 'itc', setting });
189
- const d = POINT_GROUP_DATA.find((x) => x.key === key);
190
- if (!d) throw new RangeError(`Unknown point group key: ${JSON.stringify(key)}`);
191
- const family = crystalFamily(d.crystalSystem);
192
- // Monoclinic and triclinic: a, b, c along x, y, z (docs/conventions.md, "Site symmetry and Wyckoff positions").
193
- const basis = family === 'monoclinic' || family === 'triclinic' ? IDENTITY : latticeBasis(family);
226
+ const basis = faceBasis(key);
194
227
  result = Object.freeze(
195
228
  printedRows(key, setting)
196
229
  .filter(([letter]) => letter !== 'o')
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.6.1';
6
+ export const VERSION = '0.7.0';