symcrys 0.3.0 → 0.4.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.
@@ -0,0 +1,222 @@
1
+ /**
2
+ * Symmetry-reduced forms of property tensors: which Cartesian components of a tensor of rank 0 to 4
3
+ * a point group allows, and how they depend on each other. Results are plain numbers (coefficient
4
+ * matrices and index lists); formulas, LaTeX and diagrams stay in the applications (CLAUDE.md,
5
+ * "Tensors").
6
+ *
7
+ * Components are numbered by their flat index: for indices (i₁, …, iₙ) with x, y, z = 0, 1, 2 the
8
+ * flat index is i₁·3ⁿ⁻¹ + … + iₙ, so the first index varies slowest (row-major, the order of a
9
+ * NumPy array of shape (3,)*n in C order). Moved from birss-app (`tensorForms.ts`,
10
+ * `tensorProjection.ts`, `linalg.ts`, revision 2be5fe3).
11
+ */
12
+ import { det } from '../linalg.js';
13
+ import { closeGroup } from '../operations.js';
14
+ import { operations, settings } from '../pointGroups/pointGroups.js';
15
+ import { EPSILON, SNAP_EPSILON } from '../tolerances.js';
16
+ import { reducedRowEchelon } from './rowEchelon.js';
17
+ const RANKS = [0, 1, 2, 3, 4];
18
+ /** Checks a specification and returns the index permutations that generate its intrinsic symmetry. */
19
+ function checkSpec(spec) {
20
+ const { rank, parity, timeParity, intrinsic } = spec;
21
+ if (!RANKS.includes(rank))
22
+ throw new RangeError(`Tensor rank must be 0 to 4, not ${JSON.stringify(rank)}`);
23
+ if (parity !== 'polar' && parity !== 'axial')
24
+ throw new RangeError(`Unknown tensor parity: ${JSON.stringify(parity)}`);
25
+ if (timeParity !== 'i' && timeParity !== 'c')
26
+ throw new RangeError(`Unknown time parity: ${JSON.stringify(timeParity)}`);
27
+ const swap = (a, b) => {
28
+ const p = Array.from({ length: rank }, (_, k) => k);
29
+ [p[a], p[b]] = [p[b], p[a]];
30
+ return p;
31
+ };
32
+ switch (intrinsic) {
33
+ case 'none':
34
+ return [];
35
+ case 'ij':
36
+ case 'jk':
37
+ if (rank < 2)
38
+ throw new RangeError(`Intrinsic symmetry '${intrinsic}' needs rank 2 or more, not ${rank}`);
39
+ return [intrinsic === 'ij' ? swap(0, 1) : swap(rank - 2, rank - 1)];
40
+ case 'ij_kl':
41
+ case 'voigt':
42
+ if (rank !== 4)
43
+ throw new RangeError(`Intrinsic symmetry '${intrinsic}' needs rank 4, not ${rank}`);
44
+ return intrinsic === 'ij_kl' ? [swap(0, 1), swap(2, 3)] : [swap(0, 1), swap(2, 3), [2, 3, 0, 1]];
45
+ default:
46
+ throw new RangeError(`Unknown intrinsic symmetry: ${JSON.stringify(intrinsic)}`);
47
+ }
48
+ }
49
+ /** Throws unless `m` is orthogonal (mᵀm = 1 within `EPSILON`): the code assumes Cartesian matrices. */
50
+ function checkOrthogonal(m, what) {
51
+ for (let i = 0; i < 3; i++) {
52
+ for (let j = 0; j < 3; j++) {
53
+ const dot = m[0][i] * m[0][j] + m[1][i] * m[1][j] + m[2][i] * m[2][j];
54
+ if (Math.abs(dot - (i === j ? 1 : 0)) > EPSILON) {
55
+ throw new RangeError(`${what} is not an orthogonal (Cartesian) matrix: ${JSON.stringify(m)}`);
56
+ }
57
+ }
58
+ }
59
+ }
60
+ /** The indices (x, y, z = 0, 1, 2) of every flat index at a rank, first index first. */
61
+ const digitTables = new Map();
62
+ function digits(rank) {
63
+ let table = digitTables.get(rank);
64
+ if (!table) {
65
+ table = Array.from({ length: 3 ** rank }, (_, flat) => Array.from({ length: rank }, (_, k) => Math.floor(flat / 3 ** (rank - 1 - k)) % 3));
66
+ digitTables.set(rank, table);
67
+ }
68
+ return table;
69
+ }
70
+ /** The flat indices reached from `flat` by the index permutations (`out[k] = in[perm[k]]`). */
71
+ function orbit(flat, rank, perms) {
72
+ const d = digits(rank);
73
+ const seen = new Set([flat]);
74
+ const stack = [flat];
75
+ while (stack.length > 0) {
76
+ const cur = stack.pop();
77
+ for (const p of perms) {
78
+ let next = 0;
79
+ for (let k = 0; k < rank; k++)
80
+ next = next * 3 + d[cur][p[k]];
81
+ if (!seen.has(next)) {
82
+ seen.add(next);
83
+ stack.push(next);
84
+ }
85
+ }
86
+ }
87
+ return [...seen];
88
+ }
89
+ function freezeRows(rows) {
90
+ return Object.freeze(rows.map((r) => Object.freeze([...r])));
91
+ }
92
+ /**
93
+ * The form for a group given as its full list of operations. The group average of each seed
94
+ * (a unit tensor on one orbit of the intrinsic symmetry) projects it onto the invariant subspace;
95
+ * the projections span it, and the reduced row echelon form makes the basis minimal and canonical.
96
+ */
97
+ function project(group, spec, perms) {
98
+ const { rank } = spec;
99
+ const dim = 3 ** rank;
100
+ const d = digits(rank);
101
+ const ops = group.map((op) => ({
102
+ m: op.matrix.flat(),
103
+ sign: (spec.parity === 'axial' ? Math.sign(det(op.matrix)) : 1) * (spec.timeParity === 'c' && op.timeReversal ? -1 : 1),
104
+ }));
105
+ const spanning = [];
106
+ for (let seed = 0; seed < dim; seed++) {
107
+ const members = orbit(seed, rank, perms);
108
+ if (seed !== Math.min(...members))
109
+ continue;
110
+ const averaged = new Array(dim).fill(0);
111
+ for (const { m, sign } of ops) {
112
+ for (let out = 0; out < dim; out++) {
113
+ const o = d[out];
114
+ let acc = 0;
115
+ for (const s of members) {
116
+ const i = d[s];
117
+ let p = 1;
118
+ for (let r = 0; r < rank; r++)
119
+ p *= m[o[r] * 3 + i[r]];
120
+ acc += p;
121
+ }
122
+ averaged[out] += sign * acc;
123
+ }
124
+ }
125
+ for (let k = 0; k < dim; k++)
126
+ averaged[k] /= ops.length;
127
+ if (averaged.some((x) => Math.abs(x) >= EPSILON))
128
+ spanning.push(averaged);
129
+ }
130
+ const basis = reducedRowEchelon(spanning, dim).map((row) => row.map(snapEntry));
131
+ const pivots = basis.map((row) => row.findIndex((x) => x !== 0));
132
+ const relations = [];
133
+ for (let c = 0; c < dim; c++) {
134
+ if (pivots.includes(c))
135
+ continue;
136
+ const row = new Array(dim).fill(0);
137
+ row[c] = 1;
138
+ basis.forEach((b, k) => {
139
+ if (b[c] !== 0)
140
+ row[pivots[k]] = -b[c];
141
+ });
142
+ relations.push(row);
143
+ }
144
+ return Object.freeze({
145
+ rank,
146
+ basis: freezeRows(basis),
147
+ parameters: freezeRows(pivots.map((p) => d[p])),
148
+ relations: freezeRows(relations),
149
+ });
150
+ }
151
+ /**
152
+ * An entry within 10⁻⁹ of a multiple of 1/12 is set to it, so that the exact values of the
153
+ * crystallographic forms (0, ±1/2, ±1, ±2 for the 32 classes in all settings) come out exact instead
154
+ * of with rounding errors of the order of 10⁻¹⁵; other values (e.g. for a rotated frame) are kept.
155
+ */
156
+ function snapEntry(x) {
157
+ const r = Math.round(x * 12) / 12;
158
+ return Math.abs(x - r) < SNAP_EPSILON ? r + 0 : x;
159
+ }
160
+ function specKey(spec) {
161
+ return `${spec.rank}:${spec.parity}:${spec.timeParity}:${spec.intrinsic}`;
162
+ }
163
+ const formCache = new Map();
164
+ /**
165
+ * The form of a tensor under a point group in the requested setting (default: the default setting
166
+ * of the convention, `'itc'` unless given). The convention matters only through the setting: the
167
+ * same setting index gives the same form in both conventions (docs/conventions.md, "Tensors").
168
+ */
169
+ export function tensorForm(key, spec, options) {
170
+ const perms = checkSpec(spec);
171
+ const ops = operations(key, options); // checks key, convention and setting
172
+ const index = options?.setting ?? settings(key, options?.convention).find((s) => s.isDefault).index;
173
+ const cacheKey = `${key}#${index}#${specKey(spec)}`;
174
+ let form = formCache.get(cacheKey);
175
+ if (!form) {
176
+ form = project(ops, spec, perms);
177
+ formCache.set(cacheKey, form);
178
+ }
179
+ return form;
180
+ }
181
+ /**
182
+ * The form of a tensor under the group generated by `operations`, e.g. the site symmetry of a
183
+ * surface normal (`siteSymmetry`) or the operations of a distorted crystal. The operations are
184
+ * Cartesian and orthogonal; a list that is not closed is closed first.
185
+ */
186
+ export function tensorFormOf(operations, spec) {
187
+ const perms = checkSpec(spec);
188
+ operations.forEach((op, i) => checkOrthogonal(op.matrix, `Operation ${i}`));
189
+ return project(closeGroup(operations), spec, perms);
190
+ }
191
+ /**
192
+ * The components of `tensor` (length 3^rank, flat index) in a frame rotated by the orthogonal
193
+ * matrix `rotation`: t′_{i…} = f·Σ R_{ia}…R_{…}·t_{a…}, with f = det(R) for an axial tensor and 1
194
+ * for a polar one. To express a tensor in the frame of a surface, pass the matrix whose rows are
195
+ * the new axes in the old frame. Time parity plays no part.
196
+ */
197
+ export function rotateTensor(tensor, rotation, spec) {
198
+ checkSpec(spec);
199
+ checkOrthogonal(rotation, 'The rotation');
200
+ const { rank } = spec;
201
+ const dim = 3 ** rank;
202
+ if (tensor.length !== dim)
203
+ throw new RangeError(`A tensor of rank ${rank} has ${dim} components, not ${tensor.length}`);
204
+ const d = digits(rank);
205
+ const m = rotation.flat();
206
+ const f = spec.parity === 'axial' ? Math.sign(det(rotation)) : 1;
207
+ const out = new Array(dim).fill(0);
208
+ for (let o = 0; o < dim; o++) {
209
+ let acc = 0;
210
+ for (let s = 0; s < dim; s++) {
211
+ if (tensor[s] === 0)
212
+ continue;
213
+ let p = tensor[s];
214
+ for (let r = 0; r < rank; r++)
215
+ p *= m[d[o][r] * 3 + d[s][r]];
216
+ acc += p;
217
+ }
218
+ out[o] = f * acc;
219
+ }
220
+ return out;
221
+ }
222
+ //# sourceMappingURL=tensorForm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tensorForm.js","sourceRoot":"","sources":["../../src/tensors/tensorForm.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,GAAG,EAAa,MAAM,cAAc,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAkB,MAAM,kBAAkB,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,QAAQ,EAA2C,MAAM,+BAA+B,CAAC;AAC9G,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAwDpD,MAAM,KAAK,GAAsB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CA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package.json (checked by version.test.ts). */
2
- export declare const VERSION = "0.3.0";
2
+ export declare const VERSION = "0.4.0";
3
3
  //# sourceMappingURL=version.d.ts.map
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  /** Version of symcrys. Kept equal to `version` in package.json (checked by version.test.ts). */
2
- export const VERSION = '0.3.0';
2
+ export const VERSION = '0.4.0';
3
3
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "symcrys",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Crystallographic symmetry calculations: point groups (crystallographic and magnetic), their settings, symbols and properties, and property tensors. TypeScript library without dependencies.",
5
5
  "keywords": [
6
6
  "crystallography",
@@ -32,6 +32,7 @@
32
32
  "src",
33
33
  "!src/**/*.test.ts",
34
34
  "!src/**/*.fixtures.ts",
35
+ "!src/**/*.pins.json",
35
36
  "!src/**/testUtils/**"
36
37
  ],
37
38
  "sideEffects": false,
@@ -48,7 +49,7 @@
48
49
  "check:dist": "node scripts/check-dist.mjs",
49
50
  "prepack": "npm run build",
50
51
  "audit:point-groups": "vitest run --config audit/point-groups/vitest.config.ts",
51
- "audit:birss-app": "vitest run --config audit/birss-app/vitest.config.ts && prettier --write src/pointGroups/birssApp.pins.fixtures.ts",
52
+ "audit:birss-app": "vitest run --config audit/birss-app/vitest.config.ts",
52
53
  "audit:wyckoff-2006": "vitest run --config audit/wyckoff-2006/vitest.config.ts"
53
54
  },
54
55
  "devDependencies": {
package/src/index.ts CHANGED
@@ -33,7 +33,7 @@ export {
33
33
  type SettingOptions,
34
34
  type SymbolOptions,
35
35
  } from './pointGroups/pointGroups.js';
36
- export { isCentrosymmetric, isChiral, isPolar, laueClass } from './pointGroups/properties.js';
36
+ export { isCentrosymmetric, isChiral, isPiezoelectric, isPolar, laueClass } from './pointGroups/properties.js';
37
37
  export { LATTICE_SYMMETRY_DIRECTIONS, type Uvw } from './symmetryDirections.js';
38
38
  export {
39
39
  describeOperations,
@@ -52,3 +52,14 @@ export {
52
52
  type WyckoffOptions,
53
53
  type WyckoffPosition,
54
54
  } from './pointGroups/wyckoff.js';
55
+ export {
56
+ rotateTensor,
57
+ tensorForm,
58
+ tensorFormOf,
59
+ type IntrinsicSymmetry,
60
+ type TensorForm,
61
+ type TensorParity,
62
+ type TensorRank,
63
+ type TensorSpec,
64
+ type TimeParity,
65
+ } from './tensors/tensorForm.js';
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Properties of a point group that follow from its operations alone. They do not depend on the
3
- * setting or the convention. Properties that need tensors (piezoelectric, …) come with the tensor
4
- * module (CLAUDE.md, decision of 2026-11-08 on #13).
2
+ * Properties of a point group that follow from its operations, directly or through the form of a
3
+ * tensor (piezoelectric). They do not depend on the setting or the convention. Piezomagnetic,
4
+ * magnetoelectric and ferromagnetic follow with the magnetic point groups (#13).
5
5
  */
6
6
 
7
7
  import { INVERSION, det, matricesEqual } from '../linalg.js';
@@ -9,6 +9,7 @@ import { EPSILON } from '../tolerances.js';
9
9
  import { compose, operation, operationsEqual, type Operation } from '../operations.js';
10
10
  import { POINT_GROUP_KEYS, type PointGroupKey } from './data.js';
11
11
  import { operations } from './pointGroups.js';
12
+ import { tensorForm } from '../tensors/tensorForm.js';
12
13
 
13
14
  /** Operations in setting 1, the frame all stored data share. */
14
15
  const stored = (key: PointGroupKey): readonly Operation[] => operations(key, { setting: 1 });
@@ -60,3 +61,13 @@ export function laueClass(key: PointGroupKey): PointGroupKey {
60
61
  laueCache.set(key, laue);
61
62
  return laue;
62
63
  }
64
+
65
+ /**
66
+ * Piezoelectric: the polarization can depend linearly on stress, i.e. a polar time-even tensor of
67
+ * rank 3, symmetric in its last two indices, is allowed (ITA Table 3.2.2.1).
68
+ */
69
+ export function isPiezoelectric(key: PointGroupKey): boolean {
70
+ return (
71
+ tensorForm(key, { rank: 3, parity: 'polar', timeParity: 'i', intrinsic: 'jk' }, { setting: 1 }).basis.length > 0
72
+ );
73
+ }
@@ -3,7 +3,7 @@
3
3
  * fixed (docs/conventions.md, "Site symmetry and Wyckoff positions").
4
4
  */
5
5
 
6
- import { apply, type Vec3 } from './linalg.js';
6
+ import { apply, matricesEqual, multiply, type Vec3 } from './linalg.js';
7
7
  import type { Operation } from './operations.js';
8
8
  import { EPSILON } from './tolerances.js';
9
9
 
@@ -18,7 +18,10 @@ export interface SiteSymmetryOptions {
18
18
 
19
19
  /** The site symmetry of a direction. */
20
20
  export interface SiteSymmetry {
21
- /** Indices into the given operations of those that leave the direction fixed, ascending. */
21
+ /**
22
+ * Indices into the given operations of those that leave the direction fixed, ascending: for a group,
23
+ * a subgroup (the operations fixing within the tolerance, closed under products, see `siteSymmetry`).
24
+ */
22
25
  readonly operations: readonly number[];
23
26
  /**
24
27
  * The unit vector of the direction, set onto the fixed space of its site symmetry (the mean of
@@ -47,6 +50,60 @@ function isIdentity(op: Operation): boolean {
47
50
  return op.matrix.every((row, i) => row.every((v, j) => Math.abs(v - (i === j ? 1 : 0)) < EPSILON));
48
51
  }
49
52
 
53
+ /** Products already looked up, per list of operations: `i * n + j` → index of op[i]·op[j] in the list, or -1. */
54
+ const productTables = new WeakMap<readonly Operation[], Map<number, number>>();
55
+
56
+ function productIndex(operations: readonly Operation[], i: number, j: number): number {
57
+ let table = productTables.get(operations);
58
+ if (!table) {
59
+ table = new Map();
60
+ productTables.set(operations, table);
61
+ }
62
+ const key = i * operations.length + j;
63
+ let k = table.get(key);
64
+ if (k === undefined) {
65
+ const product = multiply(operations[i].matrix, operations[j].matrix);
66
+ k = operations.findIndex((op) => matricesEqual(op.matrix, product));
67
+ table.set(key, k);
68
+ }
69
+ return k;
70
+ }
71
+
72
+ /** The indices plus those of every product of two of them that is itself in the list, until closed. */
73
+ function closeWithin(operations: readonly Operation[], indices: readonly number[]): number[] {
74
+ const set = [...indices];
75
+ const inSet = new Set(set);
76
+ // Each element is multiplied with every element before it once, in both orders, as it is added.
77
+ for (let i = 0; i < set.length; i++) {
78
+ for (let j = 0; j <= i; j++) {
79
+ for (const k of [productIndex(operations, set[i], set[j]), productIndex(operations, set[j], set[i])]) {
80
+ if (k >= 0 && !inSet.has(k)) {
81
+ inSet.add(k);
82
+ set.push(k);
83
+ }
84
+ }
85
+ }
86
+ }
87
+ return set.sort((x, y) => x - y);
88
+ }
89
+
90
+ /** The normalised mean of the images of v under the operations at `indices`; undefined if it vanishes. */
91
+ function meanImage(operations: readonly Operation[], indices: readonly number[], v: Vec3): Vec3 | undefined {
92
+ if (indices.length === 0) return v;
93
+ const sum: [number, number, number] = [0, 0, 0];
94
+ for (const i of indices) {
95
+ const w = apply(operations[i].matrix, v);
96
+ sum[0] += w[0];
97
+ sum[1] += w[1];
98
+ sum[2] += w[2];
99
+ }
100
+ const n = Math.hypot(sum[0], sum[1], sum[2]);
101
+ return n > 1e-9 * indices.length ? [sum[0] / n, sum[1] / n, sum[2] / n] : undefined;
102
+ }
103
+
104
+ const sameIndices = (a: readonly number[], b: readonly number[]): boolean =>
105
+ a.length === b.length && a.every((x, i) => x === b[i]);
106
+
50
107
  /** The tolerance of the options, checked. */
51
108
  export function siteTolerance(options?: SiteSymmetryOptions): number {
52
109
  const t = options?.tolerance ?? EPSILON;
@@ -57,9 +114,12 @@ export function siteTolerance(options?: SiteSymmetryOptions): number {
57
114
  /**
58
115
  * The site symmetry of `direction` (any non-zero vector, Cartesian) under `operations`, which may
59
116
  * be any list of point operations (for instance those of a distorted crystal). Time reversal is
60
- * ignored: a direction or a face normal is not changed by it. `direction` and `multiplicity` are
61
- * meaningful when the operations form a group (then the fixing ones do too); for another list
62
- * `multiplicity` may not be an integer. Throws a RangeError for a zero vector.
117
+ * ignored: a direction or a face normal is not changed by it. The operations fixing the direction
118
+ * within the tolerance are closed under the products found in the list and the direction is set onto
119
+ * their fixed space, repeated until stable, so that for a group the result is a subgroup and the
120
+ * set direction lies exactly on its elements. For a list that is not a group, `multiplicity` may
121
+ * not be an integer. Throws a RangeError for a zero vector, and if the closed operations fix no
122
+ * common direction (a tolerance far too large, e.g. 0.5).
63
123
  */
64
124
  export function siteSymmetry(
65
125
  operations: readonly Operation[],
@@ -68,18 +128,35 @@ export function siteSymmetry(
68
128
  ): SiteSymmetry {
69
129
  const tolerance = siteTolerance(options);
70
130
  const v = unit(direction);
71
- const indices: number[] = [];
72
- operations.forEach((op, i) => {
73
- if (fixes(op, v, tolerance)) indices.push(i);
74
- });
75
- const sum: [number, number, number] = [0, 0, 0];
76
- for (const i of indices) {
77
- const w = apply(operations[i].matrix, v);
78
- sum[0] += w[0];
79
- sum[1] += w[1];
80
- sum[2] += w[2];
131
+ const fixing = (w: Vec3): number[] => {
132
+ const out: number[] = [];
133
+ operations.forEach((op, i) => {
134
+ if (fixes(op, w, tolerance)) out.push(i);
135
+ });
136
+ return out;
137
+ };
138
+ // Within the tolerance the operations fixing v need not form a group (near an axis a rotation can count
139
+ // as fixing while its square does not). Close them under products found in the list, set v onto the
140
+ // fixed space of the closure (the mean of its images, the projector for a group), and repeat on the
141
+ // projected direction until the set is stable.
142
+ let indices = fixing(v);
143
+ let projected = v;
144
+ let set = closeWithin(operations, indices);
145
+ for (let pass = 0; pass < 8; pass++) {
146
+ const mean = meanImage(operations, set, v);
147
+ if (mean === undefined) {
148
+ throw new RangeError(
149
+ `No common fixed direction for the operations fixing ${JSON.stringify(direction)} within ${tolerance} (tolerance too large?)`,
150
+ );
151
+ }
152
+ const next = closeWithin(operations, fixing(mean));
153
+ if (sameIndices(next, set)) {
154
+ indices = set;
155
+ projected = mean;
156
+ break;
157
+ }
158
+ set = next;
81
159
  }
82
- const projected = indices.length > 0 ? unit(sum) : v;
83
160
  return Object.freeze({
84
161
  operations: Object.freeze(indices),
85
162
  direction: Object.freeze(projected) as Vec3,
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Row reduction of real vectors (any length): the reduced row echelon form of a spanning set, and
3
+ * the rank. The tolerances are those of birss-app's `linalg.ts`, where the tensor code comes from.
4
+ */
5
+
6
+ /** An entry below this (absolute) does not serve as a pivot: float noise is never a new direction. */
7
+ export const PIVOT_EPSILON = 1e-7;
8
+
9
+ /** An entry below this (absolute) is not eliminated, and is set to zero in the result. */
10
+ export const ELIMINATION_EPSILON = 1e-12;
11
+
12
+ /**
13
+ * The reduced row echelon form of the span of `vectors` (all of length `dim`): one row per
14
+ * independent direction, each with a 1 at its pivot and 0 at every other row's pivot, pivots
15
+ * ascending. The rows are unique for a given span, so the pivots name the free parameters
16
+ * unambiguously: each is the lowest-index component that is independent of the ones before it.
17
+ */
18
+ export function reducedRowEchelon(vectors: readonly (readonly number[])[], dim: number): number[][] {
19
+ const m = vectors.map((v) => Array.from(v));
20
+ let row = 0;
21
+ for (let c = 0; c < dim && row < m.length; c++) {
22
+ let pivot = row;
23
+ for (let r = row + 1; r < m.length; r++) if (Math.abs(m[r][c]) > Math.abs(m[pivot][c])) pivot = r;
24
+ if (Math.abs(m[pivot][c]) < PIVOT_EPSILON) continue;
25
+ [m[row], m[pivot]] = [m[pivot], m[row]];
26
+ const p = m[row][c];
27
+ for (let j = 0; j < dim; j++) m[row][j] /= p;
28
+ for (let r = 0; r < m.length; r++) {
29
+ if (r === row || Math.abs(m[r][c]) <= ELIMINATION_EPSILON) continue;
30
+ const f = m[r][c];
31
+ for (let j = 0; j < dim; j++) m[r][j] -= f * m[row][j];
32
+ }
33
+ row++;
34
+ }
35
+ const out = m.slice(0, row);
36
+ for (const r of out) for (let j = 0; j < dim; j++) if (Math.abs(r[j]) < ELIMINATION_EPSILON) r[j] = 0;
37
+ return out;
38
+ }
39
+
40
+ /** The number of independent vectors among `vectors` (all of length `dim`). */
41
+ export function rank(vectors: readonly (readonly number[])[], dim: number): number {
42
+ return reducedRowEchelon(vectors, dim).length;
43
+ }