smath 1.15.1 → 2.0.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.
package/README.md CHANGED
@@ -23,3 +23,54 @@ npx smath normalize 4 0 10
23
23
  ```
24
24
 
25
25
  > Most `SMath` functions are available through `npx`, except for calculus functions which require a functional argument.
26
+
27
+ ## Data Fitting
28
+
29
+ SMath also exports the `DataFit` object which contains only 1 function, `fit()` which is used for curve fitting. All other exports are purely for defining types used within `fit()`. `fit()` uses a genetic-style algorithm to fit a curve.
30
+
31
+ ### How it works
32
+
33
+ It generates many sets of parameters to test, and keeps ones with smaller error than the previous iteration. Parameter sets with larger errors are discarded. Each subsequent iteration uses the sets of parameters with the least error and "mutates" them randomly.
34
+
35
+ > Because of these random mutations, running the same code multiple times may yield slightly different results. See [best practices](#best-practices) for mitigation tactics.
36
+
37
+ ### Complexity
38
+
39
+ The folling factors affect computation time and resources:
40
+
41
+ - Number of iterations
42
+ - Number of independent/unknown function parameters
43
+ - Number of data points
44
+
45
+ Each one alone has a linear effect on performance, but combined has an incremental effect.
46
+
47
+ `time = iterations * ( parameters + dataset )`
48
+
49
+ The dimensionality, or number of free `x` variables per data point, should not have an impact on computation time.
50
+
51
+ ### Best Practices
52
+
53
+ For production software that relies on a best curve fit for data, it's best to avoid critical operations using `fit()` for a few reasons.
54
+
55
+ 1. `fit()` uses an algorithm that generates random mutations in a set of parameters, which could yield slightly different results, even if run on the same dataset.
56
+ 1. If the number of iterations is very high (in the millions or higher), it could have a significant effect on software performance.
57
+ 1. Due to a limitation in JavaScript/TypeScript, the input function parameters cannot be optional or have default values. If they do have default values, assign them inside the function body.
58
+
59
+ To circumvent some of these issues, the following is recommended.
60
+
61
+ 1. Use `datafit` during the testing phase of application development, and use the best-fit parameters as constants in the final application.
62
+ 1. If that is not possible, `datafit` may be helpful for determining an initial guess of curve fit constants, which can be input to `fit()` during production. The number of iterations could be reduced if the initial guess is reasonably close to the desired result.
63
+ 1. Using `datafit` primarily for data visualization or rough estimation.
64
+ 1. For operations that *need* `datafit`, a suggestion would be to run multiple iterations of `fit()` itself, and using each output as the subsequent call's input. This will converge to a result more effectively but could take longer.
65
+
66
+ And here are some general good practices.
67
+
68
+ 1. Avoid overfitting your data. That means, you should never have more function unknowns than the number of data points. `fit()` allows this for the rare chance that it is needed. Typically, having more, accurate data, is better for curve fitting.
69
+ 1. Reject outliers. `fit()` does not do this. Any outliers existing in the dataset will be treated like normal data points and could negatively impact the best fit.
70
+
71
+ There are also some great arguments and use cases for this function, namely...
72
+
73
+ 1. Data analysis and visualization.
74
+ 1. Quickly iterating on different model functions for determining which best fits the data.
75
+ 1. Curve fitting for multivariate or nonlinear models.
76
+ 1. The ease of use of it all! It's just one function call with as little as 2 inputs!
package/dist/bin.js CHANGED
@@ -1,10 +1,7 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
3
- var _a, _b, _c, _d;
4
- Object.defineProperty(exports, "__esModule", { value: true });
5
- var SMath = require(".");
6
- var func = ((_a = process.argv[2]) !== null && _a !== void 0 ? _a : '').toLowerCase(), nums = process.argv.slice(3).map(function (arg, i) {
7
- var num = Number.parseFloat(arg);
2
+ import { SMath } from './index.js';
3
+ const func = (process.argv[2] ?? '').toLowerCase(), nums = process.argv.slice(3).map((arg, i) => {
4
+ const num = Number.parseFloat(arg);
8
5
  if (Number.isFinite(num)) {
9
6
  return num;
10
7
  }
@@ -53,7 +50,7 @@ if (func.includes('help')) {
53
50
  }
54
51
  switch (func) {
55
52
  case ('approx'): {
56
- console.log(SMath.approx(nums[0], nums[1], (_b = nums[2]) !== null && _b !== void 0 ? _b : 1e-6));
53
+ console.log(SMath.approx(nums[0], nums[1], nums[2] ?? 1e-6));
57
54
  break;
58
55
  }
59
56
  case ('clamp'): {
@@ -157,11 +154,11 @@ switch (func) {
157
154
  break;
158
155
  }
159
156
  case ('rat'): {
160
- console.log(SMath.rat(nums[0], (_c = nums[1]) !== null && _c !== void 0 ? _c : 1e-6));
157
+ console.log(SMath.rat(nums[0], nums[1] ?? 1e-6));
161
158
  break;
162
159
  }
163
160
  case ('mixed'): {
164
- console.log(SMath.mixed(nums[0], (_d = nums[1]) !== null && _d !== void 0 ? _d : 1e-6));
161
+ console.log(SMath.mixed(nums[0], nums[1] ?? 1e-6));
165
162
  break;
166
163
  }
167
164
  case (''): {
@@ -0,0 +1,2 @@
1
+ export * from './lib.js';
2
+ export * from './types.js';
@@ -0,0 +1,72 @@
1
+ import { SMath } from '../index.js';
2
+ /**
3
+ * Minimize the sum of squared errors to fit a set of data
4
+ * points to a curve with a set of unknown parameters.
5
+ * @param f The model function for curve fitting.
6
+ * @param data The entire dataset, as an array of points.
7
+ * @param params_initial The initial guess for function
8
+ * parameters, which defaults to an array filled with zeroes.
9
+ * @param iterations The number of parameter sets to generate.
10
+ * @param maxDeviation The relative standard parameter deviation.
11
+ * This is a number [0.0-1.0] and affects the standard deviation
12
+ * on the first iteration. Every subsequent iteration has a
13
+ * decayed standard deviation until the final iteration.
14
+ * @returns The set of parameters and error for the best fit.
15
+ * @example
16
+ * // Define model function
17
+ * function f(x: number, a2: number = -0.5, a1: number = 3.9, a0: number = -1.2): number {
18
+ * return a2 * x ** 2 + a1 * x + a0;
19
+ * }
20
+ * // Construct a data set
21
+ * const data: Datum<number>[] = [0, 2, 4].map(x => ({ x: x, y: f(x) }));
22
+ * // Compute best-fit summary
23
+ * const summary = fit(f, data);
24
+ */
25
+ export function fit(f, data, params_initial = [], iterations = 1e3, maxDeviation = 1) {
26
+ const N_params = f.length - 1;
27
+ if (params_initial.length === 0) {
28
+ params_initial.length = N_params;
29
+ params_initial.fill(0);
30
+ }
31
+ if (params_initial.length !== N_params) {
32
+ throw new Error('The initial guess should contain ' + N_params + ' parameters.');
33
+ }
34
+ if (maxDeviation <= 0) {
35
+ throw new Error('Standard deviation should be a positive value.');
36
+ }
37
+ let params = params_initial, error = err(f, params, data);
38
+ for (let i = 0; i < iterations; i++) {
39
+ const params_i = mutate(params, SMath.translate(i, 0, iterations, maxDeviation, 0)), error_i = err(f, params_i, data);
40
+ if (error_i < error) {
41
+ params = params_i;
42
+ error = error_i;
43
+ }
44
+ }
45
+ return {
46
+ f: (x) => f(x, ...params),
47
+ params: params,
48
+ error: error,
49
+ errorAvgAbs: Math.sqrt(error / data.length),
50
+ };
51
+ }
52
+ /**
53
+ * Calculate the sum of squared errors for a set of function parameters.
54
+ * @param f The model function for curve fitting.
55
+ * @param params The array of parameters to check.
56
+ * @param data The entire dataset, as an array of points.
57
+ * @returns The sum of squared errors.
58
+ */
59
+ function err(f, params, data) {
60
+ let sum = 0;
61
+ data.forEach(point => sum += (point.y - f(point.x, ...params)) ** 2);
62
+ return sum;
63
+ }
64
+ /**
65
+ * Randomly mutate the set of function parameters by some standard deviation.
66
+ * @param params The set of function parameters to mutate.
67
+ * @param deviation The standard relative amount to deviate in any direction.
68
+ * @returns A mutated set of parameters.
69
+ */
70
+ function mutate(params, deviation) {
71
+ return params.map(c => SMath.rnorm(c, deviation * Math.max(1, Math.abs(c))));
72
+ }
@@ -0,0 +1 @@
1
+ export {};