symcrys 0.10.1 → 0.11.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 (218) hide show
  1. package/README.md +6 -6
  2. package/dist/cell.d.ts +19 -16
  3. package/dist/cell.d.ts.map +1 -1
  4. package/dist/cell.js +63 -35
  5. package/dist/cell.js.map +1 -1
  6. package/dist/checks.d.ts +29 -0
  7. package/dist/checks.d.ts.map +1 -0
  8. package/dist/checks.js +79 -0
  9. package/dist/checks.js.map +1 -0
  10. package/dist/closure.d.ts +43 -0
  11. package/dist/closure.d.ts.map +1 -0
  12. package/dist/closure.js +201 -0
  13. package/dist/closure.js.map +1 -0
  14. package/dist/crystalClasses.d.ts +145 -117
  15. package/dist/crystalClasses.d.ts.map +1 -1
  16. package/dist/crystalClasses.js +161 -121
  17. package/dist/crystalClasses.js.map +1 -1
  18. package/dist/freeze.d.ts +7 -0
  19. package/dist/freeze.d.ts.map +1 -0
  20. package/dist/freeze.js +15 -0
  21. package/dist/freeze.js.map +1 -0
  22. package/dist/index.d.ts +11 -10
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +4 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/indices.d.ts +31 -5
  27. package/dist/indices.d.ts.map +1 -1
  28. package/dist/indices.js +104 -13
  29. package/dist/indices.js.map +1 -1
  30. package/dist/lattice.d.ts +15 -1
  31. package/dist/lattice.d.ts.map +1 -1
  32. package/dist/lattice.js +30 -1
  33. package/dist/lattice.js.map +1 -1
  34. package/dist/linalg.d.ts +2 -2
  35. package/dist/linalg.d.ts.map +1 -1
  36. package/dist/linalg.js +3 -3
  37. package/dist/linalg.js.map +1 -1
  38. package/dist/magnetic.d.ts +12 -10
  39. package/dist/magnetic.d.ts.map +1 -1
  40. package/dist/magnetic.js +8 -6
  41. package/dist/magnetic.js.map +1 -1
  42. package/dist/notation.d.ts +16 -0
  43. package/dist/notation.d.ts.map +1 -0
  44. package/dist/notation.js +66 -0
  45. package/dist/notation.js.map +1 -0
  46. package/dist/operations.d.ts +40 -26
  47. package/dist/operations.d.ts.map +1 -1
  48. package/dist/operations.js +48 -60
  49. package/dist/operations.js.map +1 -1
  50. package/dist/plane.d.ts +141 -79
  51. package/dist/plane.d.ts.map +1 -1
  52. package/dist/plane.js +147 -77
  53. package/dist/plane.js.map +1 -1
  54. package/dist/pointGroups/crystalForms.d.ts +6 -21
  55. package/dist/pointGroups/crystalForms.d.ts.map +1 -1
  56. package/dist/pointGroups/crystalForms.js +9 -16
  57. package/dist/pointGroups/crystalForms.js.map +1 -1
  58. package/dist/pointGroups/crystalFormsData.d.ts +4 -1
  59. package/dist/pointGroups/crystalFormsData.d.ts.map +1 -1
  60. package/dist/pointGroups/crystalFormsData.js +64 -1
  61. package/dist/pointGroups/crystalFormsData.js.map +1 -1
  62. package/dist/pointGroups/elements.d.ts +19 -17
  63. package/dist/pointGroups/elements.d.ts.map +1 -1
  64. package/dist/pointGroups/elements.js +65 -83
  65. package/dist/pointGroups/elements.js.map +1 -1
  66. package/dist/pointGroups/identify.d.ts +10 -18
  67. package/dist/pointGroups/identify.d.ts.map +1 -1
  68. package/dist/pointGroups/identify.js +27 -79
  69. package/dist/pointGroups/identify.js.map +1 -1
  70. package/dist/pointGroups/itaOrder.d.ts +15 -14
  71. package/dist/pointGroups/itaOrder.d.ts.map +1 -1
  72. package/dist/pointGroups/itaOrder.js +116 -94
  73. package/dist/pointGroups/itaOrder.js.map +1 -1
  74. package/dist/pointGroups/itcData.d.ts +96 -0
  75. package/dist/pointGroups/itcData.d.ts.map +1 -0
  76. package/dist/pointGroups/itcData.js +336 -0
  77. package/dist/pointGroups/itcData.js.map +1 -0
  78. package/dist/pointGroups/itcMagneticData.d.ts +55 -0
  79. package/dist/pointGroups/itcMagneticData.d.ts.map +1 -0
  80. package/dist/pointGroups/itcMagneticData.js +172 -0
  81. package/dist/pointGroups/itcMagneticData.js.map +1 -0
  82. package/dist/pointGroups/keys.d.ts +32 -0
  83. package/dist/pointGroups/keys.d.ts.map +1 -0
  84. package/dist/pointGroups/keys.js +120 -0
  85. package/dist/pointGroups/keys.js.map +1 -0
  86. package/dist/pointGroups/magneticSymbols.d.ts +6 -5
  87. package/dist/pointGroups/magneticSymbols.d.ts.map +1 -1
  88. package/dist/pointGroups/magneticSymbols.js +15 -12
  89. package/dist/pointGroups/magneticSymbols.js.map +1 -1
  90. package/dist/pointGroups/orbits.d.ts +23 -42
  91. package/dist/pointGroups/orbits.d.ts.map +1 -1
  92. package/dist/pointGroups/orbits.js +20 -62
  93. package/dist/pointGroups/orbits.js.map +1 -1
  94. package/dist/pointGroups/pointGroups.d.ts +135 -67
  95. package/dist/pointGroups/pointGroups.d.ts.map +1 -1
  96. package/dist/pointGroups/pointGroups.js +409 -244
  97. package/dist/pointGroups/pointGroups.js.map +1 -1
  98. package/dist/pointGroups/properties.d.ts +21 -22
  99. package/dist/pointGroups/properties.d.ts.map +1 -1
  100. package/dist/pointGroups/properties.js +40 -37
  101. package/dist/pointGroups/properties.js.map +1 -1
  102. package/dist/pointGroups/seitzData.d.ts +26 -0
  103. package/dist/pointGroups/seitzData.d.ts.map +1 -0
  104. package/dist/pointGroups/seitzData.js +130 -0
  105. package/dist/pointGroups/seitzData.js.map +1 -0
  106. package/dist/pointGroups/wyckoff.d.ts +70 -40
  107. package/dist/pointGroups/wyckoff.d.ts.map +1 -1
  108. package/dist/pointGroups/wyckoff.js +98 -91
  109. package/dist/pointGroups/wyckoff.js.map +1 -1
  110. package/dist/pointGroups/wyckoffData.d.ts +7 -4
  111. package/dist/pointGroups/wyckoffData.d.ts.map +1 -1
  112. package/dist/pointGroups/wyckoffData.js +789 -168
  113. package/dist/pointGroups/wyckoffData.js.map +1 -1
  114. package/dist/siteSymmetry.d.ts +8 -16
  115. package/dist/siteSymmetry.d.ts.map +1 -1
  116. package/dist/siteSymmetry.js +34 -24
  117. package/dist/siteSymmetry.js.map +1 -1
  118. package/dist/spaceGroups/affine.d.ts.map +1 -1
  119. package/dist/spaceGroups/affine.js +3 -2
  120. package/dist/spaceGroups/affine.js.map +1 -1
  121. package/dist/spaceGroups/cell.d.ts +43 -31
  122. package/dist/spaceGroups/cell.d.ts.map +1 -1
  123. package/dist/spaceGroups/cell.js +173 -85
  124. package/dist/spaceGroups/cell.js.map +1 -1
  125. package/dist/spaceGroups/describe.d.ts +12 -10
  126. package/dist/spaceGroups/describe.d.ts.map +1 -1
  127. package/dist/spaceGroups/describe.js +11 -10
  128. package/dist/spaceGroups/describe.js.map +1 -1
  129. package/dist/spaceGroups/planeGroupData.d.ts +1 -1
  130. package/dist/spaceGroups/planeGroupData.d.ts.map +1 -1
  131. package/dist/spaceGroups/planeGroupData.js +8 -8
  132. package/dist/spaceGroups/planeGroupData.js.map +1 -1
  133. package/dist/spaceGroups/planeGroups.d.ts.map +1 -1
  134. package/dist/spaceGroups/planeGroups.js +2 -1
  135. package/dist/spaceGroups/planeGroups.js.map +1 -1
  136. package/dist/spaceGroups/positions.d.ts +48 -19
  137. package/dist/spaceGroups/positions.d.ts.map +1 -1
  138. package/dist/spaceGroups/positions.js +166 -67
  139. package/dist/spaceGroups/positions.js.map +1 -1
  140. package/dist/tensors/propertyTable.d.ts +3 -1
  141. package/dist/tensors/propertyTable.d.ts.map +1 -1
  142. package/dist/tensors/propertyTable.js +17 -10
  143. package/dist/tensors/propertyTable.js.map +1 -1
  144. package/dist/tensors/rowEchelon.d.ts +3 -3
  145. package/dist/tensors/rowEchelon.d.ts.map +1 -1
  146. package/dist/tensors/rowEchelon.js +4 -4
  147. package/dist/tensors/rowEchelon.js.map +1 -1
  148. package/dist/tensors/tensorForm.d.ts +75 -34
  149. package/dist/tensors/tensorForm.d.ts.map +1 -1
  150. package/dist/tensors/tensorForm.js +171 -67
  151. package/dist/tensors/tensorForm.js.map +1 -1
  152. package/dist/tensors/tensorProperties.d.ts +10 -9
  153. package/dist/tensors/tensorProperties.d.ts.map +1 -1
  154. package/dist/tensors/tensorProperties.js +22 -12
  155. package/dist/tensors/tensorProperties.js.map +1 -1
  156. package/dist/tolerances.d.ts +56 -1
  157. package/dist/tolerances.d.ts.map +1 -1
  158. package/dist/tolerances.js +51 -1
  159. package/dist/tolerances.js.map +1 -1
  160. package/dist/version.d.ts +1 -1
  161. package/dist/version.js +1 -1
  162. package/package.json +1 -1
  163. package/src/cell.ts +78 -51
  164. package/src/checks.ts +84 -0
  165. package/src/closure.ts +214 -0
  166. package/src/crystalClasses.ts +232 -157
  167. package/src/freeze.ts +14 -0
  168. package/src/index.ts +21 -10
  169. package/src/indices.ts +108 -18
  170. package/src/lattice.ts +41 -1
  171. package/src/linalg.ts +3 -3
  172. package/src/magnetic.ts +14 -9
  173. package/src/notation.ts +73 -0
  174. package/src/operations.ts +78 -71
  175. package/src/plane.ts +253 -127
  176. package/src/pointGroups/crystalForms.ts +11 -44
  177. package/src/pointGroups/crystalFormsData.ts +66 -1
  178. package/src/pointGroups/elements.ts +82 -92
  179. package/src/pointGroups/identify.ts +38 -97
  180. package/src/pointGroups/itaOrder.ts +117 -101
  181. package/src/pointGroups/itcData.ts +404 -0
  182. package/src/pointGroups/itcMagneticData.ts +206 -0
  183. package/src/pointGroups/keys.ts +144 -0
  184. package/src/pointGroups/magneticSymbols.ts +18 -17
  185. package/src/pointGroups/orbits.ts +41 -89
  186. package/src/pointGroups/pointGroups.ts +540 -297
  187. package/src/pointGroups/properties.ts +44 -40
  188. package/src/pointGroups/seitzData.ts +147 -0
  189. package/src/pointGroups/wyckoff.ts +137 -112
  190. package/src/pointGroups/wyckoffData.ts +793 -170
  191. package/src/siteSymmetry.ts +43 -40
  192. package/src/spaceGroups/affine.ts +3 -2
  193. package/src/spaceGroups/cell.ts +227 -116
  194. package/src/spaceGroups/describe.ts +22 -19
  195. package/src/spaceGroups/planeGroupData.ts +9 -9
  196. package/src/spaceGroups/planeGroups.ts +2 -1
  197. package/src/spaceGroups/positions.ts +202 -78
  198. package/src/tensors/propertyTable.ts +26 -14
  199. package/src/tensors/rowEchelon.ts +4 -3
  200. package/src/tensors/tensorForm.ts +258 -88
  201. package/src/tensors/tensorProperties.ts +34 -14
  202. package/src/tolerances.ts +66 -1
  203. package/src/version.ts +1 -1
  204. package/dist/pointGroups/data.d.ts +0 -75
  205. package/dist/pointGroups/data.d.ts.map +0 -1
  206. package/dist/pointGroups/data.js +0 -212
  207. package/dist/pointGroups/data.js.map +0 -1
  208. package/dist/pointGroups/magneticData.d.ts +0 -66
  209. package/dist/pointGroups/magneticData.d.ts.map +0 -1
  210. package/dist/pointGroups/magneticData.js +0 -184
  211. package/dist/pointGroups/magneticData.js.map +0 -1
  212. package/dist/spaceGroups/snap.d.ts +0 -20
  213. package/dist/spaceGroups/snap.d.ts.map +0 -1
  214. package/dist/spaceGroups/snap.js +0 -103
  215. package/dist/spaceGroups/snap.js.map +0 -1
  216. package/src/pointGroups/data.ts +0 -305
  217. package/src/pointGroups/magneticData.ts +0 -328
  218. package/src/spaceGroups/snap.ts +0 -121
@@ -1,11 +1,61 @@
1
1
  /**
2
2
  * Numeric tolerances, in one place. The values differ on purpose: each gates a different quantity.
3
+ * The tolerance a caller passes is one contract for every function (docs/conventions.md,
4
+ * "Tolerances"): one option, one metric per kind of object, one check.
5
+ */
6
+ import { shown } from './checks.js';
7
+ /**
8
+ * The default tolerance of every function that compares numbers a caller passes in (operations,
9
+ * directions, points): two numbers closer than this count as equal, in the metric of their kind
10
+ * (docs/conventions.md, "Tolerances").
3
11
  */
4
- /** Two matrix entries (or vector components) closer than this are equal. */
5
12
  export const EPSILON = 1e-6;
6
13
  /**
7
14
  * During group closure, an entry closer than this to one of the exact values in `SNAP_VALUES`
8
15
  * (linalg.ts) is replaced by it, so rounding errors cannot accumulate over repeated products.
9
16
  */
10
17
  export const SNAP_EPSILON = 1e-9;
18
+ /**
19
+ * The upper bound of the tolerance per kind of object, above which it says nothing: two distinct
20
+ * operations A, B of a crystallographic point group differ in some entry by at least √2/3 ≈ 0.47 in
21
+ * any orthonormal frame (‖A − B‖ = ‖1 − A⁻¹B‖ ≥ √2 in the Frobenius norm, the least for a sixfold
22
+ * rotation), so 0.1 keeps them apart; two unit vectors are at most 2 apart; two points modulo the
23
+ * lattice at most 1/2 per coordinate; a relative deviation of the metric tensor is at most of the
24
+ * order of 1.
25
+ */
26
+ export const TOLERANCE_BOUND = Object.freeze({ operations: 0.1, directions: 1, points: 0.5, metric: 1 });
27
+ /**
28
+ * The tolerance of the options, checked: a finite number above 0 and below the bound of the kind
29
+ * of object it measures; the default `EPSILON`.
30
+ */
31
+ export function toleranceOf(options, kind) {
32
+ // Only a missing tolerance takes the default; null is a wrong value, not a missing one.
33
+ const t = options?.tolerance === undefined ? EPSILON : options.tolerance;
34
+ const bound = TOLERANCE_BOUND[kind];
35
+ if (!(typeof t === 'number' && t > 0 && t < bound)) {
36
+ throw new RangeError(`The tolerance must be a number above 0 and below ${bound}, not ${shown(t)}`);
37
+ }
38
+ return t;
39
+ }
40
+ /**
41
+ * Making a group of a caller exact (`idealGroup`, closure.ts): a product is matched to the nearest
42
+ * element of the group, which must lie closer than `PRODUCT_MATCH` per entry (distinct operations
43
+ * of a point group differ by at least √2/3 ≈ 0.47 in some entry, so a nearer one is the product);
44
+ * the averaging has settled when no entry changes by `IDEAL_SETTLED` or more in a pass, and fails
45
+ * if after `IDEAL_PASSES` passes an entry still changes by `IDEAL_UNSETTLED` (it settles in one to
46
+ * six passes for every point group, exact or rounded); entries within `IDEAL_SNAP` of an exact value
47
+ * are set to it, which catches the rounding of the last bits but not a group turned by a small
48
+ * angle.
49
+ */
50
+ export const PRODUCT_MATCH = 0.25;
51
+ export const IDEAL_SETTLED = 1e-15;
52
+ export const IDEAL_UNSETTLED = 1e-12;
53
+ export const IDEAL_PASSES = 50;
54
+ export const IDEAL_SNAP = 1e-12;
55
+ /**
56
+ * The largest pivot threshold of a tensor form (tensorForm.ts, `reduce`): the threshold is raised
57
+ * up to this only in a general orientation, when components of the order of 10⁻⁷ would otherwise be
58
+ * taken for independent ones; a genuine pivot of a form of a point group is far larger.
59
+ */
60
+ export const MAX_PIVOT_THRESHOLD = 1e-2;
11
61
  //# sourceMappingURL=tolerances.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tolerances.js","sourceRoot":"","sources":["../src/tolerances.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,4EAA4E;AAC5E,MAAM,CAAC,MAAM,OAAO,GAAG,IAAI,CAAC;AAE5B;;;GAGG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,CAAC"}
1
+ {"version":3,"file":"tolerances.js","sourceRoot":"","sources":["../src/tolerances.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAEpC;;;;GAIG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,IAAI,CAAC;AAE5B;;;GAGG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,CAAC;AAYjC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;AAEzG;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,OAAqC,EAAE,IAAkC;IACnG,wFAAwF;IACxF,MAAM,CAAC,GAAY,OAAO,EAAE,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC;IAClF,MAAM,KAAK,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IACpC,IAAI,CAAC,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC;QACnD,MAAM,IAAI,UAAU,CAAC,oDAAoD,KAAK,SAAS,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACrG,CAAC;IACD,OAAO,CAAC,CAAC;AACX,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,IAAI,CAAC;AAClC,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,CAAC;AACnC,MAAM,CAAC,MAAM,eAAe,GAAG,KAAK,CAAC;AACrC,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,CAAC;AAC/B,MAAM,CAAC,MAAM,UAAU,GAAG,KAAK,CAAC;AAEhC;;;;GAIG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,IAAI,CAAC"}
package/dist/version.d.ts CHANGED
@@ -3,5 +3,5 @@
3
3
  *
4
4
  * @remarks Kept equal to `version` in package.json (checked by version.test.ts).
5
5
  */
6
- export declare const VERSION = "0.10.1";
6
+ export declare const VERSION = "0.11.0";
7
7
  //# sourceMappingURL=version.d.ts.map
package/dist/version.js CHANGED
@@ -3,5 +3,5 @@
3
3
  *
4
4
  * @remarks Kept equal to `version` in package.json (checked by version.test.ts).
5
5
  */
6
- export const VERSION = '0.10.1';
6
+ export const VERSION = '0.11.0';
7
7
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "symcrys",
3
- "version": "0.10.1",
3
+ "version": "0.11.0",
4
4
  "description": "Crystallographic symmetry calculations: point groups (crystallographic and magnetic) and plane groups, their settings, symbols and properties, and property tensors. TypeScript library without dependencies.",
5
5
  "keywords": [
6
6
  "crystallography",
package/src/cell.ts CHANGED
@@ -4,9 +4,11 @@
4
4
  * coordinates, as `latticeBasis` gives it; lengths in any unit, angles in degrees.
5
5
  */
6
6
 
7
+ import { checkObject, checkOptions, shown, TOLERANCE_KEYS } from './checks.js';
7
8
  import { apply, inverse, isSingular, multiply, transpose, type Mat3, type Vec3 } from './linalg.js';
8
- import { checkTimeReversal, type Operation as MagneticOperation } from './operations.js';
9
- import { EPSILON } from './tolerances.js';
9
+ import { checkTimeReversal, type CartesianOperation as MagneticOperation } from './operations.js';
10
+ import { toleranceOf, type ToleranceOptions } from './tolerances.js';
11
+ import { deepFreeze } from './freeze.js';
10
12
 
11
13
  /** The lattice parameters of a cell: edge lengths and angles in degrees (α between b and c, β between a and c, γ between a and b). */
12
14
  export interface LatticeParameters {
@@ -34,9 +36,9 @@ export interface CellAngles {
34
36
  readonly gamma: number;
35
37
  }
36
38
 
37
- /** An operation of a list given to `residualOperations`: at least its matrix; other fields are kept. */
39
+ /** An operation of a list given to `residualOperations`: at least its matrix W; other fields are kept. */
38
40
  export interface CellOperation {
39
- /** The 3×3 matrix W acting on lattice coordinates. */
41
+ /** The integer 3×3 matrix W acting on lattice coordinates (the `matrix` of an operation). */
40
42
  readonly matrix: Mat3;
41
43
  }
42
44
 
@@ -50,12 +52,6 @@ export interface IsValidCellOptions {
50
52
  readonly minVolumeRatio?: number;
51
53
  }
52
54
 
53
- /** Options of `residualOperations`. */
54
- export interface ResidualOperationsOptions {
55
- /** The largest accepted deviation of WᵀGW from G, relative to the largest entry of G; default `EPSILON`. */
56
- readonly tolerance?: number;
57
- }
58
-
59
55
  const DEG = Math.PI / 180;
60
56
 
61
57
  /** Cosine of an angle in degrees, exact at the multiples of 30° that cells use (90°, 60°, 120°, 180°). */
@@ -85,6 +81,15 @@ function anglesOk({ alpha, beta, gamma }: CellAngles): boolean {
85
81
  * number from 0 to 1.
86
82
  */
87
83
  export function isValidCell(angles: CellAngles, options?: IsValidCellOptions): boolean {
84
+ checkOptions(options, ['minVolumeRatio'], 'isValidCell');
85
+ checkObject(angles, 'isValidCell takes the angles { alpha, beta, gamma }');
86
+ // Numbers out of range are no cell (false); anything else is wrong input.
87
+ for (const name of ['alpha', 'beta', 'gamma'] as const) {
88
+ const x = (angles as Partial<CellAngles>)[name];
89
+ if (!(typeof x === 'number' && Number.isFinite(x))) {
90
+ throw new RangeError(`The angle ${name} must be a finite number of degrees, not ${shown(x)}`);
91
+ }
92
+ }
88
93
  if (!anglesOk(angles)) return false;
89
94
  const min = options?.minVolumeRatio ?? 0;
90
95
  if (!(typeof min === 'number' && min >= 0 && min <= 1))
@@ -94,14 +99,16 @@ export function isValidCell(angles: CellAngles, options?: IsValidCellOptions): b
94
99
  return Math.sqrt(r) >= min;
95
100
  }
96
101
 
97
- function checkEdges({ a, b, c }: LatticeParameters): void {
102
+ function checkEdges(p: LatticeParameters): void {
103
+ checkObject(p, 'latticeFromParameters takes the parameters { a, b, c, alpha, beta, gamma }');
104
+ const { a, b, c } = p;
98
105
  for (const [name, x] of [
99
106
  ['a', a],
100
107
  ['b', b],
101
108
  ['c', c],
102
109
  ] as const) {
103
110
  if (typeof x !== 'number' || !Number.isFinite(x) || x <= 0) {
104
- throw new RangeError(`latticeFromParameters: edge ${name} must be a positive number, not ${JSON.stringify(x)}`);
111
+ throw new RangeError(`latticeFromParameters: edge ${name} must be a positive number, not ${shown(x)}`);
105
112
  }
106
113
  }
107
114
  }
@@ -114,24 +121,26 @@ function checkEdges({ a, b, c }: LatticeParameters): void {
114
121
  * axis b, b lies along y (docs/conventions.md, "Cell, metric and indices"). The basis is
115
122
  * right-handed. Throws a RangeError for an edge that is not positive and for angles that give no cell.
116
123
  */
117
- export function latticeFromParameters(p: LatticeParameters): Mat3 {
118
- checkEdges(p);
119
- if (!isValidCell(p)) {
120
- throw new RangeError(`latticeFromParameters: angles ${p.alpha}°, ${p.beta}°, ${p.gamma}° give no cell`);
124
+ export function latticeFromParameters(parameters: LatticeParameters): Mat3 {
125
+ checkEdges(parameters);
126
+ if (!isValidCell(parameters)) {
127
+ throw new RangeError(
128
+ `latticeFromParameters: angles ${parameters.alpha}°, ${parameters.beta}°, ${parameters.gamma}° give no cell`,
129
+ );
121
130
  }
122
- const ca = cosDeg(p.alpha);
123
- const cb = cosDeg(p.beta);
124
- const cg = cosDeg(p.gamma);
131
+ const ca = cosDeg(parameters.alpha);
132
+ const cb = cosDeg(parameters.beta);
133
+ const cg = cosDeg(parameters.gamma);
125
134
  const sg = Math.sqrt(1 - cg * cg);
126
- const volumeRatio = Math.sqrt(radicand(p));
135
+ const volumeRatio = Math.sqrt(radicand(parameters));
127
136
  // columns: a = (a, 0, 0), b = (b cos γ, b sin γ, 0), c = (c cos β, c (cos α − cos β cos γ)/sin γ, c V/(abc sin γ))
128
- const cy = (p.c * (ca - cb * cg)) / sg;
129
- const cz = (p.c * volumeRatio) / sg;
130
- return [
131
- [p.a + 0, p.b * cg + 0, p.c * cb + 0],
132
- [0, p.b * sg + 0, cy + 0],
137
+ const cy = (parameters.c * (ca - cb * cg)) / sg;
138
+ const cz = (parameters.c * volumeRatio) / sg;
139
+ return deepFreeze([
140
+ [parameters.a + 0, parameters.b * cg + 0, parameters.c * cb + 0],
141
+ [0, parameters.b * sg + 0, cy + 0],
133
142
  [0, 0, cz + 0],
134
- ];
143
+ ]);
135
144
  }
136
145
 
137
146
  function columns(basis: Mat3): [Vec3, Vec3, Vec3] {
@@ -164,13 +173,13 @@ export function latticeParameters(basis: Mat3): LatticeParameters {
164
173
  const cross: Vec3 = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
165
174
  return Math.atan2(norm(cross), dot(u, v)) / DEG + 0;
166
175
  };
167
- return { a: norm(a), b: norm(b), c: norm(c), alpha: angle(b, c), beta: angle(a, c), gamma: angle(a, b) };
176
+ return deepFreeze({ a: norm(a), b: norm(b), c: norm(c), alpha: angle(b, c), beta: angle(a, c), gamma: angle(a, b) });
168
177
  }
169
178
 
170
179
  /** The metric tensor G = AᵀA of a basis A (columns a, b, c): g_ij = a_i · a_j, in the unit of the edge lengths squared. */
171
180
  export function metricTensor(basis: Mat3): Mat3 {
172
181
  checkBasis(basis, 'metricTensor');
173
- return multiply(transpose(basis), basis);
182
+ return deepFreeze(multiply(transpose(basis), basis));
174
183
  }
175
184
 
176
185
  /**
@@ -179,7 +188,7 @@ export function metricTensor(basis: Mat3): Mat3 {
179
188
  */
180
189
  export function reciprocalBasis(basis: Mat3): Mat3 {
181
190
  checkBasis(basis, 'reciprocalBasis');
182
- return transpose(inverse(basis));
191
+ return deepFreeze(transpose(inverse(basis)));
183
192
  }
184
193
 
185
194
  function vector(v: Vec3, name: string): Vec3 {
@@ -196,9 +205,9 @@ function angleOf(u: Vec3, v: Vec3): number {
196
205
  }
197
206
 
198
207
  /** The angle in degrees between two lattice directions [uvw] (coordinates in the basis, columns a, b, c), 0° to 180°. Throws a RangeError for a zero vector. */
199
- export function angleBetweenDirections(basis: Mat3, u: Vec3, v: Vec3): number {
208
+ export function angleBetweenDirections(basis: Mat3, direction1: Vec3, direction2: Vec3): number {
200
209
  checkBasis(basis, 'angleBetweenDirections');
201
- return angleOf(apply(basis, vector(u, 'u')), apply(basis, vector(v, 'v')));
210
+ return angleOf(apply(basis, vector(direction1, 'direction1')), apply(basis, vector(direction2, 'direction2')));
202
211
  }
203
212
 
204
213
  /**
@@ -206,15 +215,28 @@ export function angleBetweenDirections(basis: Mat3, u: Vec3, v: Vec3): number {
206
215
  * reciprocal vectors h·a* + k·b* + l·c*. For two faces this is 180° minus the interior dihedral
207
216
  * angle. Throws a RangeError for a zero vector.
208
217
  */
209
- export function angleBetweenPlanes(basis: Mat3, h: Vec3, k: Vec3): number {
218
+ export function angleBetweenPlanes(basis: Mat3, plane1: Vec3, plane2: Vec3): number {
210
219
  checkBasis(basis, 'angleBetweenPlanes');
211
220
  const b = reciprocalBasis(basis);
212
- return angleOf(apply(b, vector(h, 'h')), apply(b, vector(k, 'k')));
221
+ return angleOf(apply(b, vector(plane1, 'plane1')), apply(b, vector(plane2, 'plane2')));
213
222
  }
214
223
 
215
224
  /**
216
- * The operations that leave the metric of a cell unchanged: those W (integer matrices on the
217
- * coordinates of a lattice direction, as `latticeOperations` gives them) with WᵀGW = G, G the metric
225
+ * The unit normal of a plane (hkl) in a cell, a Cartesian vector: h·a* + k·b* + l·c* normalised, the
226
+ * pole of the face (#137 G4). With `latticeBasis(family)` for a family with fixed cell angles, or
227
+ * `latticeFromParameters` for a real cell; Miller indices of hexagonal axes are three, without i.
228
+ * Throws a RangeError for a basis that is not a regular 3 × 3 matrix and for a zero vector.
229
+ */
230
+ export function faceNormal(basis: Mat3, hkl: Vec3): Vec3 {
231
+ checkBasis(basis, 'faceNormal');
232
+ const v = apply(reciprocalBasis(basis), vector(hkl, 'hkl'));
233
+ const n = norm(v);
234
+ return Object.freeze(v.map((x) => x / n + 0)) as unknown as Vec3;
235
+ }
236
+
237
+ /**
238
+ * The operations that leave the metric of a cell unchanged: those W (`matrix`, the integer matrices
239
+ * on the coordinates of a lattice direction, as `operations` gives them) with WᵀGW = G, G the metric
218
240
  * tensor of `basis`. It is the point symmetry of a distorted lattice among the operations of a group;
219
241
  * the list is taken as it is, not closed into a group, and the kept operations are the ones of the
220
242
  * list, in its order. The deviation counts relative to the largest entry of G (`tolerance`, default
@@ -223,15 +245,11 @@ export function angleBetweenPlanes(basis: Mat3, h: Vec3, k: Vec3): number {
223
245
  export function residualOperations<T extends CellOperation>(
224
246
  operations: readonly T[],
225
247
  basis: Mat3,
226
- options?: ResidualOperationsOptions,
227
- ): T[] {
248
+ options?: ToleranceOptions,
249
+ ): readonly T[] {
250
+ checkOptions(options, TOLERANCE_KEYS, 'residualOperations');
228
251
  const g = metricTensor(basis);
229
- const tolerance = options?.tolerance ?? EPSILON;
230
- if (typeof tolerance !== 'number' || !Number.isFinite(tolerance) || tolerance < 0) {
231
- throw new RangeError(
232
- `residualOperations: tolerance must be a non-negative number, not ${JSON.stringify(tolerance)}`,
233
- );
234
- }
252
+ const tolerance = toleranceOf(options, 'metric');
235
253
  if (!Array.isArray(operations)) throw new RangeError('residualOperations: operations must be a list');
236
254
  operations.forEach((op, i) => {
237
255
  const m = (op as { readonly matrix?: unknown } | null)?.matrix;
@@ -240,12 +258,21 @@ export function residualOperations<T extends CellOperation>(
240
258
  m.length === 3 &&
241
259
  m.every((r) => Array.isArray(r) && r.length === 3 && r.every((x) => typeof x === 'number' && Number.isFinite(x)));
242
260
  if (!ok) throw new RangeError(`residualOperations: operation ${i} has no 3×3 matrix of finite numbers`);
261
+ // W is an integer matrix; a Cartesian matrix (±√3/2) passed as `matrix` would give a wrong answer.
262
+ if (!(m as number[][]).every((r) => r.every((x) => Math.abs(x - Math.round(x)) <= 1e-9))) {
263
+ throw new RangeError(
264
+ `residualOperations: the matrix of operation ${i} is not an integer matrix in the lattice basis (the field matrix of an operation, not cartesian): ${shown(m)}`,
265
+ );
266
+ }
243
267
  });
244
268
  const scale = Math.max(...g.flat().map(Math.abs));
245
- return operations.filter((op) => {
246
- const m = multiply(multiply(transpose(op.matrix), g), op.matrix);
247
- return m.every((row, i) => row.every((x, j) => Math.abs(x - g[i][j]) <= tolerance * scale));
248
- });
269
+ // The list is frozen, not the operations in it, which are the caller's.
270
+ return Object.freeze(
271
+ operations.filter((op) => {
272
+ const m = multiply(multiply(transpose(op.matrix), g), op.matrix);
273
+ return m.every((row, i) => row.every((x, j) => Math.abs(x - g[i][j]) < tolerance * scale));
274
+ }),
275
+ );
249
276
  }
250
277
 
251
278
  /** An operation of the magnetic API passed to `residualOperations`: its matrix and whether it is combined with time reversal. */
@@ -256,8 +283,8 @@ export interface MagneticCellOperation extends CellOperation {
256
283
 
257
284
  /**
258
285
  * The operations of a list that keep the metric of a cell: W with WᵀGW = G, G the metric tensor
259
- * of `basis`. The operations are integer matrices on lattice coordinates, as `latticeOperations`
260
- * gives them; the list is taken as it is and the kept operations are the ones of the list, in its
286
+ * of `basis`. The operations are read by `matrix`, the integer matrix W on lattice coordinates, as
287
+ * `operations` gives them; the list is taken as it is and the kept operations are the ones of the list, in its
261
288
  * order. The deviation counts relative to the largest entry of G (`tolerance`, default `EPSILON`).
262
289
  * Every operation must say whether it is combined with time reversal (`timeReversal`), which is
263
290
  * kept; one that does not (an operation of the crystallographic API) is a RangeError.
@@ -265,8 +292,8 @@ export interface MagneticCellOperation extends CellOperation {
265
292
  export function residualMagneticOperations<T extends MagneticCellOperation>(
266
293
  operations: readonly T[],
267
294
  basis: Mat3,
268
- options?: ResidualOperationsOptions,
269
- ): T[] {
295
+ options?: ToleranceOptions,
296
+ ): readonly T[] {
270
297
  if (Array.isArray(operations)) checkTimeReversal(operations as unknown as readonly MagneticOperation[]);
271
298
  return residualOperations(operations, basis, options);
272
299
  }
package/src/checks.ts ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Checks of what a caller passes in, shared by the entry points (#137 D2): wrong input is a
3
+ * RangeError that names what is wrong, never a TypeError from deep inside the library.
4
+ */
5
+
6
+ /**
7
+ * A value for an error message; never throws: numbers as written (NaN, Infinity), BigInt with its
8
+ * `n`, a function or symbol by its kind, and a value with a cycle as such.
9
+ */
10
+ export function shown(value: unknown): string {
11
+ if (typeof value === 'number') return String(value);
12
+ if (typeof value === 'bigint') return `${value}n`;
13
+ if (typeof value === 'function') return 'a function';
14
+ if (typeof value === 'symbol') return 'a symbol';
15
+ try {
16
+ return (
17
+ JSON.stringify(value, (_, v: unknown) =>
18
+ typeof v === 'bigint'
19
+ ? `${v}n`
20
+ : typeof v === 'symbol'
21
+ ? 'a symbol'
22
+ : typeof v === 'number' && !Number.isFinite(v)
23
+ ? String(v)
24
+ : v,
25
+ ) ?? String(value)
26
+ );
27
+ } catch {
28
+ return 'a value that contains itself';
29
+ }
30
+ }
31
+
32
+ /** The keys of the options of the functions that choose a setting of a point group. */
33
+ export const SETTING_KEYS = ['setting', 'axes', 'uniqueAxis'] as const;
34
+ /** The key of the options of the functions that compare numbers of a caller. */
35
+ export const TOLERANCE_KEYS = ['tolerance'] as const;
36
+
37
+ /**
38
+ * Throws unless `options` is undefined or a plain object whose keys are all among `keys`: an
39
+ * options argument of the wrong type and a key the function does not know (a misspelling such as
40
+ * `uniqueaxis`, which would otherwise be ignored) are RangeErrors. The option `convention`, removed
41
+ * in 0.11.0, gets a message of its own.
42
+ */
43
+ export function checkOptions(options: unknown, keys: readonly string[], what: string): void {
44
+ if (options === undefined) return;
45
+ if (!isPlainObject(options)) {
46
+ throw new RangeError(`${what} takes its options as an object { ${keys.join(', ')} }, not ${shown(options)}`);
47
+ }
48
+ const unknown = Object.keys(options).filter((k) => !keys.includes(k));
49
+ if (unknown.includes('convention')) {
50
+ throw new RangeError(
51
+ 'The option convention was removed in symcrys 0.11.0: symcrys follows ITC only (CHANGELOG.md, 0.11.0)',
52
+ );
53
+ }
54
+ if (unknown.length > 0) {
55
+ throw new RangeError(
56
+ `${what} takes the options ${keys.join(', ')}, not ${unknown.map((k) => JSON.stringify(k)).join(', ')}`,
57
+ );
58
+ }
59
+ }
60
+
61
+ /** The options restricted to `keys`, for a function that passes part of its options on. */
62
+ export function pick<T extends object>(options: T | undefined, keys: readonly string[]): Partial<T> | undefined {
63
+ if (options === undefined) return undefined;
64
+ return Object.fromEntries(Object.entries(options).filter(([k]) => keys.includes(k))) as Partial<T>;
65
+ }
66
+
67
+ /** Throws unless `v` is an array of `length` finite numbers. */
68
+ export function checkNumbers(v: unknown, length: number, what: string): asserts v is readonly number[] {
69
+ if (!Array.isArray(v) || v.length !== length || !v.every((x) => typeof x === 'number' && Number.isFinite(x))) {
70
+ throw new RangeError(`${what} must be ${length} finite numbers, not ${shown(v)}`);
71
+ }
72
+ }
73
+
74
+ /** True for a plain object: `{ … }` or one without a prototype, not an array, a Map or a Date. */
75
+ export function isPlainObject(v: unknown): v is Record<string, unknown> {
76
+ if (typeof v !== 'object' || v === null) return false;
77
+ const proto = Object.getPrototypeOf(v) as unknown;
78
+ return proto === Object.prototype || proto === null;
79
+ }
80
+
81
+ /** Throws unless `v` is a plain object. */
82
+ export function checkObject(v: unknown, what: string): asserts v is object {
83
+ if (!isPlainObject(v)) throw new RangeError(`${what}, not ${shown(v)}`);
84
+ }
package/src/closure.ts ADDED
@@ -0,0 +1,214 @@
1
+ /**
2
+ * The group generated by operations a caller passes in, within a tolerance, and that group made
3
+ * exact (docs/conventions.md, "Tolerances"). Operations read from a file or computed elsewhere carry
4
+ * rounding errors (√3/2 written as 0.866025); compared within the tolerance they still generate the
5
+ * right group, but its matrices are not exactly a group, and a tensor form computed from them has
6
+ * the wrong number of free parameters (#89). `idealGroup` therefore replaces them by the exact group
7
+ * nearest to them before anything is computed from them.
8
+ */
9
+
10
+ import { det, inverse, multiply, snap, trace, transpose, type Mat3 } from './linalg.js';
11
+ import type { CartesianOperation } from './operations.js';
12
+ import { IDEAL_PASSES, IDEAL_SETTLED, IDEAL_SNAP, IDEAL_UNSETTLED, PRODUCT_MATCH } from './tolerances.js';
13
+
14
+ const IDENTITY: CartesianOperation = {
15
+ cartesian: [
16
+ [1, 0, 0],
17
+ [0, 1, 0],
18
+ [0, 0, 1],
19
+ ],
20
+ timeReversal: false,
21
+ };
22
+
23
+ /** No finite group of Cartesian operations that symcrys computes with has more elements (m-3m1' has 96). */
24
+ export const MAX_GROUP_ORDER = 200;
25
+
26
+ /** True if the two operations agree in time reversal and in every matrix entry within `tolerance`. */
27
+ export function sameWithin(a: CartesianOperation, b: CartesianOperation, tolerance: number): boolean {
28
+ return (
29
+ a.timeReversal === b.timeReversal &&
30
+ a.cartesian.every((row, i) => row.every((v, j) => Math.abs(v - b.cartesian[i][j]) < tolerance))
31
+ );
32
+ }
33
+
34
+ /** The kind of an operation (rounded trace, sign of the determinant, time reversal): equal operations have the same. */
35
+ const kindOf = (op: CartesianOperation): string =>
36
+ `${Math.round(trace(op.cartesian))}${det(op.cartesian) > 0 ? '+' : '-'}${op.timeReversal ? "'" : ''}`;
37
+
38
+ /**
39
+ * The group the operations generate within `tolerance` (two operations equal when they agree in
40
+ * time reversal and in every matrix entry within it), the identity first, then the operations of
41
+ * the list that are new, then products in the order they are found; or undefined if it has more
42
+ * than `maxOrder` elements. A new operation is compared only with the operations of its kind.
43
+ */
44
+ export function closeWithin(
45
+ operations: readonly CartesianOperation[],
46
+ tolerance: number,
47
+ maxOrder = MAX_GROUP_ORDER,
48
+ ): CartesianOperation[] | undefined {
49
+ const group: CartesianOperation[] = [];
50
+ const byKind = new Map<string, CartesianOperation[]>();
51
+ const has = (op: CartesianOperation): boolean =>
52
+ (byKind.get(kindOf(op)) ?? []).some((g) => sameWithin(g, op, tolerance));
53
+ const push = (op: CartesianOperation): void => {
54
+ group.push(op);
55
+ const k = kindOf(op);
56
+ const list = byKind.get(k);
57
+ if (list) list.push(op);
58
+ else byKind.set(k, [op]);
59
+ };
60
+ push(IDENTITY);
61
+ const generators: CartesianOperation[] = [];
62
+ for (const s of operations) {
63
+ const op: CartesianOperation = { cartesian: s.cartesian, timeReversal: s.timeReversal };
64
+ if (has(op)) continue;
65
+ generators.push(op);
66
+ for (let i = 0; i < group.length; i++) {
67
+ for (const t of generators) {
68
+ const product: CartesianOperation = {
69
+ cartesian: multiply(group[i].cartesian, t.cartesian),
70
+ timeReversal: group[i].timeReversal !== t.timeReversal,
71
+ };
72
+ if (has(product)) continue;
73
+ if (group.length >= maxOrder) return undefined;
74
+ push(product);
75
+ }
76
+ }
77
+ }
78
+ return group;
79
+ }
80
+
81
+ /**
82
+ * The group the operations generate within `tolerance` (`closeWithin`); throws a RangeError if it
83
+ * has more than `MAX_GROUP_ORDER` elements.
84
+ */
85
+ export function closedGroup(operations: readonly CartesianOperation[], tolerance: number): CartesianOperation[] {
86
+ const group = closeWithin(operations, tolerance);
87
+ if (!group) {
88
+ throw new RangeError(
89
+ `The operations generate no finite point group within the tolerance ${tolerance} (more than ${MAX_GROUP_ORDER} elements): matrices with errors too large for the tolerance (pass a larger one, about ten times their rounding), or a rotation by an angle that is not 360°/n`,
90
+ );
91
+ }
92
+ return group;
93
+ }
94
+
95
+ /** The largest difference of two matrix entries. */
96
+ function distance(a: Mat3, b: Mat3): number {
97
+ let d = 0;
98
+ for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) d = Math.max(d, Math.abs(a[i][j] - b[i][j]));
99
+ return d;
100
+ }
101
+
102
+ const add = (a: Mat3, b: Mat3): Mat3 => a.map((row, i) => row.map((v, j) => v + b[i][j])) as unknown as Mat3;
103
+ const scale = (a: Mat3, s: number): Mat3 => a.map((row) => row.map((v) => v * s)) as unknown as Mat3;
104
+
105
+ /**
106
+ * The square root of a symmetric positive definite matrix and its inverse, by the iteration of
107
+ * Denman and Beavers (Y ← (Y + Z⁻¹)/2, Z ← (Z + Y⁻¹)/2 from Y = M, Z = 1), which converges
108
+ * quadratically; here M lies near the identity.
109
+ */
110
+ function squareRoots(m: Mat3): [Mat3, Mat3] {
111
+ let y = m;
112
+ let z = IDENTITY.cartesian;
113
+ for (let pass = 0; pass < IDEAL_PASSES; pass++) {
114
+ const nextY = scale(add(y, inverse(z)), 0.5);
115
+ const nextZ = scale(add(z, inverse(y)), 0.5);
116
+ const change = distance(nextY, y);
117
+ y = nextY;
118
+ z = nextZ;
119
+ if (change < IDEAL_SETTLED) break;
120
+ }
121
+ return [y, z];
122
+ }
123
+
124
+ /** A group made exact: its operations, and how far they lie from the operations it was made from. */
125
+ export interface IdealGroup {
126
+ readonly operations: readonly CartesianOperation[];
127
+ /** The largest difference of a matrix entry from the closed operations of the caller. */
128
+ readonly deviation: number;
129
+ }
130
+
131
+ /**
132
+ * The group generated by `operations` within `tolerance` (`closeWithin`, at most `MAX_GROUP_ORDER`
133
+ * elements), made exact: each matrix f(x) is replaced by the mean of f(xy)·f(y)⁻¹ over the group,
134
+ * repeated until nothing changes. For an exact group this is f(x) itself; for matrices that are a
135
+ * group only within a small error the passes settle on an exact representation nearby (tested in
136
+ * closure.test.ts and tensors/tolerance.test.ts), and the invariant metric of the result makes it
137
+ * orthogonal. Entries within 10⁻¹² of 0, ±1/2, ±√2/2, ±√3/2, ±1 are then set to them, so that exact
138
+ * input stays exact. Throws a RangeError if the operations generate more than `MAX_GROUP_ORDER`
139
+ * elements or do not settle into a group (a tolerance too large or too small for their errors).
140
+ */
141
+ export function idealGroup(operations: readonly CartesianOperation[], tolerance: number): IdealGroup {
142
+ const group = closedGroup(operations, tolerance);
143
+ const n = group.length;
144
+ // The product table: the element nearest to each product, of the same time reversal, sought
145
+ // among the elements of its kind first and among all if none of them is near enough.
146
+ const byKind = new Map<string, number[]>();
147
+ group.forEach((g, k) => {
148
+ const list = byKind.get(kindOf(g));
149
+ if (list) list.push(k);
150
+ else byKind.set(kindOf(g), [k]);
151
+ });
152
+ const all = group.map((_, k) => k);
153
+ const nearest = (product: CartesianOperation, candidates: readonly number[]) => {
154
+ let best = -1;
155
+ let bestDistance = Infinity;
156
+ for (const k of candidates) {
157
+ if (group[k].timeReversal !== product.timeReversal) continue;
158
+ const d = distance(group[k].cartesian, product.cartesian);
159
+ if (d < bestDistance) {
160
+ best = k;
161
+ bestDistance = d;
162
+ }
163
+ }
164
+ return bestDistance < PRODUCT_MATCH ? best : -1;
165
+ };
166
+ const table = group.map((a) =>
167
+ group.map((b) => {
168
+ const product: CartesianOperation = {
169
+ cartesian: multiply(a.cartesian, b.cartesian),
170
+ timeReversal: a.timeReversal !== b.timeReversal,
171
+ };
172
+ let k = nearest(product, byKind.get(kindOf(product)) ?? []);
173
+ if (k < 0) k = nearest(product, all);
174
+ if (k < 0) throw new RangeError(`The operations do not form a group within the tolerance ${tolerance}`);
175
+ return k;
176
+ }),
177
+ );
178
+ let f: Mat3[] = group.map((g) => g.cartesian);
179
+ for (let pass = 0; ; pass++) {
180
+ const inverses = f.map(inverse);
181
+ const next = f.map((_, x) => {
182
+ const sum = [
183
+ [0, 0, 0],
184
+ [0, 0, 0],
185
+ [0, 0, 0],
186
+ ];
187
+ for (let y = 0; y < n; y++) {
188
+ const p = multiply(f[table[x][y]], inverses[y]);
189
+ for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) sum[i][j] += p[i][j] / n;
190
+ }
191
+ return sum as unknown as Mat3;
192
+ });
193
+ const change = Math.max(...next.map((m, k) => distance(m, f[k])));
194
+ f = next;
195
+ if (change < IDEAL_SETTLED) break;
196
+ if (pass >= IDEAL_PASSES) {
197
+ if (change < IDEAL_UNSETTLED) break;
198
+ throw new RangeError(`The operations do not settle into a group within the tolerance ${tolerance}`);
199
+ }
200
+ }
201
+ // The representation is exact but need not be orthogonal: it may be an orthogonal one seen in a
202
+ // slightly oblique frame. Its invariant metric M = (1/n) Σ fᵀf gives that frame, and M^½ f M^-½
203
+ // is orthogonal.
204
+ const metric = f.reduce((sum, m) => add(sum, scale(multiply(transpose(m), m), 1 / n)), scale(IDENTITY.cartesian, 0));
205
+ const [root, inverseRoot] = squareRoots(metric);
206
+ f = f.map((m) => multiply(multiply(root, m), inverseRoot));
207
+ // Only rounding of the last bits is snapped: a group turned by a small angle has entries near the
208
+ // exact values that are not equal to them.
209
+ const exact = f.map((m, k) => ({ cartesian: snap(m, IDEAL_SNAP), timeReversal: group[k].timeReversal }));
210
+ return {
211
+ operations: exact,
212
+ deviation: Math.max(...exact.map((op, k) => distance(op.cartesian, group[k].cartesian))),
213
+ };
214
+ }