Debian Codegraph @

node/colorjs.io/src/util.js

raw
1 /**
2 * Various utility functions
3 */
4
5 export { default as multiplyMatrices, multiply_v3_m3x3 } from "./multiply-matrices.js";
6
7 /**
8 * Check if a value is a string (including a String object)
9 * @param {any} str - Value to check
10 * @returns {str is string}
11 */
12 export function isString (str) {
13 return type(str) === "string";
14 }
15
16 /**
17 * Determine the internal JavaScript [[Class]] of an object.
18 * @param {any} o - Value to check
19 * @returns {string}
20 */
21 export function type (o) {
22 let str = Object.prototype.toString.call(o);
23
24 return (str.match(/^\[object\s+(.*?)\]$/)[1] || "").toLowerCase();
25 }
26
27 /**
28 * @param {number} n
29 * @param {{ precision?: number | undefined, unit?: string | undefined }} options
30 * @returns {string}
31 */
32 export function serializeNumber (n, { precision = 16, unit }) {
33 if (isNone(n)) {
34 return "none";
35 }
36
37 n = +toPrecision(n, precision);
38
39 return n + (unit ?? "");
40 }
41
42 /**
43 * Check if a value corresponds to a none argument
44 * @param {any} n - Value to check
45 * @returns {n is null}
46 */
47 export function isNone (n) {
48 return n === null;
49 }
50
51 /**
52 * Replace none values with 0
53 * @param {number | null} n
54 * @returns {number}
55 */
56 export function skipNone (n) {
57 return isNone(n) ? 0 : n;
58 }
59
60 /**
61 * Round a number to a certain number of significant digits
62 * @param {number} n - The number to round
63 * @param {number} precision - Number of significant digits
64 */
65 export function toPrecision (n, precision) {
66 if (n === 0) {
67 return 0;
68 }
69 let integer = ~~n;
70 let digits = 0;
71 if (integer && precision) {
72 digits = ~~Math.log10(Math.abs(integer)) + 1;
73 }
74 const multiplier = 10.0 ** (precision - digits);
75 return Math.floor(n * multiplier + 0.5) / multiplier;
76 }
77
78 /**
79 * Interpolate between two values, either of which may be a `none` value.
80 * A `none` endpoint is treated as having the other endpoint's value;
81 * if both are `none`, the result is `none` as well.
82 * @param {number | null} start
83 * @param {number | null} end
84 * @param {number} p
85 * @returns {number | null}
86 */
87 export function interpolate (start, end, p) {
88 if (isNone(start) || isNaN(start)) {
89 return end;
90 }
91
92 if (isNone(end) || isNaN(end)) {
93 return start;
94 }
95
96 return start + (end - start) * p;
97 }
98
99 /**
100 * @param {number} start
101 * @param {number} end
102 * @param {number} value
103 */
104 export function interpolateInv (start, end, value) {
105 return (value - start) / (end - start);
106 }
107
108 /**
109 * @param {[number, number]} from
110 * @param {[number, number]} to
111 * @param {number} value
112 */
113 export function mapRange (from, to, value) {
114 if (
115 !from ||
116 !to ||
117 from === to ||
118 (from[0] === to[0] && from[1] === to[1]) ||
119 isNaN(value) ||
120 value === null
121 ) {
122 // Ranges missing or the same
123 return value;
124 }
125
126 return interpolate(to[0], to[1], interpolateInv(from[0], from[1], value));
127 }
128
129 /**
130 * Clamp value between the minimum and maximum
131 * @param {number} min minimum value to return
132 * @param {number} val the value to return if it is between min and max
133 * @param {number} max maximum value to return
134 */
135 export function clamp (min, val, max) {
136 return Math.max(Math.min(max, val), min);
137 }
138
139 /**
140 * Copy sign of one value to another.
141 * @param {number} to - Number to copy sign to
142 * @param {number} from - Number to copy sign from
143 */
144 export function copySign (to, from) {
145 return Math.sign(to) === Math.sign(from) ? to : -to;
146 }
147
148 /**
149 * Perform pow on a signed number and copy sign to result
150 * @param {number} base The base number
151 * @param {number} exp The exponent
152 */
153 export function spow (base, exp) {
154 return copySign(Math.abs(base) ** exp, base);
155 }
156
157 /**
158 * Perform a divide, but return zero if the denominator is zero
159 * @param {number} n The numerator
160 * @param {number} d The denominator
161 */
162 export function zdiv (n, d) {
163 return d === 0 ? 0 : n / d;
164 }
165
166 /**
167 * Perform a bisect on a sorted list and locate the insertion point for
168 * a value in arr to maintain sorted order.
169 * @param {number[]} arr - array of sorted numbers
170 * @param {number} value - value to find insertion point for
171 * @param {number} lo - used to specify a the low end of a subset of the list
172 * @param {number} hi - used to specify a the high end of a subset of the list
173 */
174 export function bisectLeft (arr, value, lo = 0, hi = arr.length) {
175 while (lo < hi) {
176 const mid = (lo + hi) >> 1;
177 if (arr[mid] < value) {
178 lo = mid + 1;
179 }
180 else {
181 hi = mid;
182 }
183 }
184 return lo;
185 }
186
187 /**
188 * Determines whether an argument is an instance of a constructor, including subclasses.
189 * This is done by first just checking `instanceof`,
190 * and then comparing the string names of the constructors if that fails.
191 * @param {any} arg
192 * @param {C} constructor
193 * @template {new (...args: any) => any} C
194 * @returns {arg is InstanceType<C>}
195 */
196 export function isInstance (arg, constructor) {
197 if (arg instanceof constructor) {
198 return true;
199 }
200
201 const targetName = constructor.name;
202
203 while (arg) {
204 const proto = Object.getPrototypeOf(arg);
205 const constructorName = proto?.constructor?.name;
206 if (constructorName === targetName) {
207 return true;
208 }
209 if (!constructorName || constructorName === "Object") {
210 return false;
211 }
212 arg = proto;
213 }
214
215 return false;
216 }
217
218 /**
219 * Generate a matrix of size NxN with the given diagonal values of length N.
220 *
221 * @param {number[]} values
222 * @returns {number[][]}
223 */
224 export function diag (values) {
225 const n = values.length;
226 const matrix = [];
227 for (let i = 0; i < n; i++) {
228 matrix[i] = [];
229 for (let j = 0; j < n; j++) {
230 matrix[i][j] = i === j ? values[i] : 0;
231 }
232 }
233 return matrix;
234 }
235
236 /**
237 * Calculate the LU decomposition of an NxN matrix.
238 *
239 * P is returned as PA = UL or A = P'UL which follows Matlab and Octave opposed to Scipy which returns P as
240 * A = PUL or P'A = UL. For matrix inverse, we need P such that PA = UL and it is faster not having to invert
241 * P, even if we can invert it fairly fast as it is just a shuffled identity matrix.
242 *
243 * P is returned as a permutation matrix unless pIndices is true, in which case P would be returned as
244 * a vector containing the indexes such that A[P,:] = L*U.
245 *
246 * Reference:
247 * - https://www.statlect.com/matrix-algebra/Gaussian-elimination
248 * - https://www.sciencedirect.com/topics/mathematics/partial-pivoting
249 *
250 * @overload
251 * @param {number[][]} matrix
252 * @param {{ pIndices?: false | undefined }} [options]
253 * @returns {[number[][], number[][], number[][]]}
254 */
255 /**
256 * @overload
257 * @param {number[][]} matrix
258 * @param {{ pIndices?: true }} [options]
259 * @returns {[number[], number[][], number[][]]}
260 */
261 /**
262 * @param {number[][]} matrix
263 * @param {{ pIndices?: boolean | undefined }} [options]
264 * @returns {[number[] | number[][], number[][], number[][]]}
265 */
266 export function lu (matrix, { pIndices = false } = {}) {
267 let p1, p2, l, u;
268
269 const n = matrix.length;
270
271 // Initialize the triangle matrices along with the permutation matrix.
272 if (pIndices) {
273 p1 = Array.from({ length: n }, (_, index) => index);
274 l = diag(new Array(n).fill(1));
275 }
276 else {
277 p2 = diag(new Array(n).fill(1));
278 l = structuredClone(p2);
279 }
280 u = structuredClone(matrix);
281
282 // Create upper and lower triangle in 'u' and 'l'. 'p' tracks the permutation (relative position of rows)
283 for (let i = 0; i < n - 1; i++) {
284 // Partial pivoting: identify the row with the maximal value in the column
285 let j = i;
286 let maximum = Math.abs(u[i][i]);
287 for (let k = i + 1; k < n; k++) {
288 const a = Math.abs(u[k][i]);
289 if (a > maximum) {
290 j = k;
291 maximum = a;
292 }
293 }
294
295 // Partial pivoting: Swap rows
296 if (j != i) {
297 // Exchange current upper triangle row with row with maximal value at pivot
298 // Update permutation matrix as well
299 [u[i], u[j]] = [u[j], u[i]];
300 if (pIndices) {
301 [p1[i], p1[j]] = [p1[j], p1[i]];
302 }
303 else {
304 [p2[i], p2[j]] = [p2[j], p2[i]];
305 }
306
307 // Only swap columns up to the pivot for the lower triangle,
308 // if on first row, there is nothing to swap
309 if (i) {
310 for (let k = 0; k < i; k++) {
311 [l[i][k], l[j][k]] = [l[j][k], l[i][k]];
312 }
313 }
314 }
315
316 // Zero at pivot point, nothing to do
317 else if (!maximum) {
318 continue;
319 }
320
321 // We have a pivot point, let's zero out everything above and below
322 // the 'l' and 'u' diagonal respectively
323 for (let j = i + 1; j < n; j++) {
324 const scalar = u[j][i] / u[i][i];
325 for (let k = i; k < n; k++) {
326 u[j][k] += -u[i][k] * scalar;
327 l[j][k] += l[i][k] * scalar;
328 }
329 }
330 }
331
332 if (pIndices) {
333 return [p1, l, u];
334 }
335 return [p2, l, u];
336 }
337
338 /**
339 * Forward substitution for solution of ax = b where a and b are matricies.
340 *
341 * @param {number[][]} a
342 * @param {number[][]} b
343 * @param {number} n
344 * @returns {number[][]}
345 */
346 function forwardSubMatrix (a, b, n) {
347 for (let i = 0; i < n; i++) {
348 const v = b[i];
349 for (let j = 0; j < i; j++) {
350 for (let k = 0; k < n; k++) {
351 v[k] -= a[i][j] * b[j][k];
352 }
353 }
354 for (let j = 0; j < n; j++) {
355 v[j] /= a[i][i];
356 }
357 }
358 return b;
359 }
360
361 /**
362 * Back substitution for solution of ax = b where a and b are matricies.
363 *
364 * @param {number[][]} a
365 * @param {number[][]} b
366 * @param {number} n
367 * @returns {number[][]}
368 */
369 function backSubMatrix (a, b, n) {
370 for (let i = n - 1; i > -1; i--) {
371 const v = b[i];
372 for (let j = i + 1; j < n; j++) {
373 for (var k = 0; k < n; k++) {
374 v[k] -= a[i][j] * b[j][k];
375 }
376 }
377 for (let j = 0; j < n; j++) {
378 b[i][j] /= a[i][i];
379 }
380 }
381 return b;
382 }
383
384 /**
385 * Forward substitution for solution of ax = b where a is a matrix and b is a vector.
386 *
387 * @param {number[][]} a
388 * @param {number[]} b
389 * @param {number} n
390 * @returns {number[]}
391 */
392 function forwardSubVector (a, b, n) {
393 for (let i = 0; i < n; i++) {
394 let v = b[i];
395 for (let j = 0; j < i; j++) {
396 v -= a[i][j] * b[j];
397 }
398 b[i] = v / a[i][i];
399 }
400 return b;
401 }
402
403 /**
404 * Back substitution for solution of ax = b where a is a matrix and b is a vector.
405 *
406 * @param {number[][]} a
407 * @param {number[]} b
408 * @param {number} n
409 * @returns {number[]}
410 */
411 function backSubVector (a, b, n) {
412 for (let i = n - 1; i > -1; i--) {
413 let v = b[i];
414 for (let j = i + 1; j < n; j++) {
415 v -= a[i][j] * b[j];
416 }
417 b[i] = v / a[i][i];
418 }
419 return b;
420 }
421
422 /**
423 * Invert a NxN matrix.
424 *
425 * @param {number[][]} matrix
426 * @returns {number[][]}
427 */
428 export function inv (matrix) {
429 // Calculate the LU decomposition.
430 const [p, l, u] = lu(matrix);
431 const n = l.length;
432
433 // Floating point math can produce very small, non-zero determinants for singular matrices.
434 // This seems to happen in Numpy as well.
435 // Don't bother calculating sign as we only care about how close to zero we are.
436 if (l.map((row, i) => row[i] * u[i][i]).reduce((acc, val) => acc * val, 1) === 0.0) {
437 throw new Error("Matrix is singular");
438 }
439
440 // Solve for the identity matrix (will give us inverse)
441 // Permutation matrix is the identity matrix, even if shuffled.
442 return backSubMatrix(u, forwardSubMatrix(l, p, n), n);
443 }
444
445 /**
446 * Solve a NxN matrix representing a system of equations.
447 *
448 * @param {number[][]} matrix
449 * @param {number[]} vector
450 * @returns {number[]}
451 */
452 export function solve (matrix, vector) {
453 // Calculate the LU decomposition.
454 const [p, l, u] = lu(matrix, { pIndices: true });
455 const n = l.length;
456
457 // If determinant is zero, we can't solve.
458 if (l.map((row, i) => row[i] * u[i][i]).reduce((acc, val) => acc * val, 1) === 0.0) {
459 throw new Error("Matrix is singular");
460 }
461
462 return backSubVector(
463 u,
464 forwardSubVector(
465 l,
466 p.map(i => vector[i]),
467 n,
468 ),
469 n,
470 );
471 }