@automovie/recovery 0.0.0 → 0.2.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 (105) hide show
  1. package/lib/compilation/index.d.ts +2 -2
  2. package/lib/compilation/index.js +16 -5
  3. package/lib/compilation/index.js.map +1 -1
  4. package/lib/curves/AutoMovieRecoveryCompactApproximation.d.ts +125 -0
  5. package/lib/curves/AutoMovieRecoveryCompactApproximation.js +62 -0
  6. package/lib/curves/AutoMovieRecoveryCompactApproximation.js.map +1 -0
  7. package/lib/curves/AutoMovieRecoveryConicApproximation.d.ts +218 -0
  8. package/lib/curves/AutoMovieRecoveryConicApproximation.js +113 -0
  9. package/lib/curves/AutoMovieRecoveryConicApproximation.js.map +1 -0
  10. package/lib/curves/approximateAutoMovieRecoveryCompactCurves.d.ts +30 -0
  11. package/lib/curves/approximateAutoMovieRecoveryCompactCurves.js +303 -0
  12. package/lib/curves/approximateAutoMovieRecoveryCompactCurves.js.map +1 -0
  13. package/lib/curves/approximateAutoMovieRecoveryConicsAhn.d.ts +39 -0
  14. package/lib/curves/approximateAutoMovieRecoveryConicsAhn.js +289 -0
  15. package/lib/curves/approximateAutoMovieRecoveryConicsAhn.js.map +1 -0
  16. package/lib/curves/approximateAutoMovieRecoveryConicsGhosh.d.ts +32 -0
  17. package/lib/curves/approximateAutoMovieRecoveryConicsGhosh.js +350 -0
  18. package/lib/curves/approximateAutoMovieRecoveryConicsGhosh.js.map +1 -0
  19. package/lib/curves/findAutoMovieRecoveryCubicCriticalParameters.d.ts +29 -0
  20. package/lib/curves/findAutoMovieRecoveryCubicCriticalParameters.js +77 -0
  21. package/lib/curves/findAutoMovieRecoveryCubicCriticalParameters.js.map +1 -0
  22. package/lib/curves/index.d.ts +6 -1
  23. package/lib/curves/index.js +20 -3
  24. package/lib/curves/index.js.map +1 -1
  25. package/lib/fitting/index.d.ts +2 -2
  26. package/lib/fitting/index.js +16 -5
  27. package/lib/fitting/index.js.map +1 -1
  28. package/lib/index.d.ts +6 -57
  29. package/lib/index.js +6 -57
  30. package/lib/index.js.map +1 -1
  31. package/lib/internal/GhoshConicApproximationBalance.d.ts +25 -0
  32. package/lib/internal/GhoshConicApproximationBalance.js +177 -0
  33. package/lib/internal/GhoshConicApproximationBalance.js.map +1 -0
  34. package/lib/internal/GhoshConicApproximationDisplacement.d.ts +23 -0
  35. package/lib/internal/GhoshConicApproximationDisplacement.js +77 -0
  36. package/lib/internal/GhoshConicApproximationDisplacement.js.map +1 -0
  37. package/lib/internal/index.d.ts +183 -0
  38. package/lib/internal/index.js +200 -0
  39. package/lib/internal/index.js.map +1 -0
  40. package/lib/internal/mesh-observations/index.d.ts +1 -2
  41. package/lib/internal/mesh-observations/index.js +1 -2
  42. package/lib/internal/mesh-observations/index.js.map +1 -1
  43. package/lib/observation/index.d.ts +15 -15
  44. package/lib/observation/index.js +29 -31
  45. package/lib/observation/index.js.map +1 -1
  46. package/lib/reconstruction/index.d.ts +10 -10
  47. package/lib/reconstruction/index.js +24 -21
  48. package/lib/reconstruction/index.js.map +1 -1
  49. package/lib/structures/curve/index.d.ts +15 -15
  50. package/lib/structures/curve/index.js +29 -0
  51. package/lib/structures/curve/index.js.map +1 -1
  52. package/lib/structures/domain/index.d.ts +45 -45
  53. package/lib/structures/domain/index.js +59 -0
  54. package/lib/structures/domain/index.js.map +1 -1
  55. package/lib/structures/image/index.d.ts +45 -45
  56. package/lib/structures/image/index.js +59 -0
  57. package/lib/structures/image/index.js.map +1 -1
  58. package/lib/structures/index.d.ts +1 -0
  59. package/lib/structures/index.js +1 -0
  60. package/lib/structures/index.js.map +1 -1
  61. package/lib/structures/internal/index.d.ts +58 -0
  62. package/lib/structures/internal/index.js +75 -0
  63. package/lib/structures/internal/index.js.map +1 -0
  64. package/lib/structures/mesh/index.d.ts +19 -19
  65. package/lib/structures/mesh/index.js +33 -0
  66. package/lib/structures/mesh/index.js.map +1 -1
  67. package/lib/structures/node/index.d.ts +23 -23
  68. package/lib/structures/node/index.js +37 -0
  69. package/lib/structures/node/index.js.map +1 -1
  70. package/lib/structures/observation/index.d.ts +15 -15
  71. package/lib/structures/observation/index.js +29 -0
  72. package/lib/structures/observation/index.js.map +1 -1
  73. package/lib/structures/operation/index.d.ts +10 -10
  74. package/lib/structures/operation/index.js +24 -0
  75. package/lib/structures/operation/index.js.map +1 -1
  76. package/lib/typings/index.d.ts +6 -6
  77. package/lib/typings/index.js +20 -0
  78. package/lib/typings/index.js.map +1 -1
  79. package/package.json +6 -6
  80. package/src/compilation/index.ts +2 -2
  81. package/src/curves/AutoMovieRecoveryCompactApproximation.ts +149 -0
  82. package/src/curves/AutoMovieRecoveryConicApproximation.ts +282 -0
  83. package/src/curves/approximateAutoMovieRecoveryCompactCurves.ts +285 -0
  84. package/src/curves/approximateAutoMovieRecoveryConicsAhn.ts +315 -0
  85. package/src/curves/approximateAutoMovieRecoveryConicsGhosh.ts +444 -0
  86. package/src/curves/findAutoMovieRecoveryCubicCriticalParameters.ts +76 -0
  87. package/src/curves/index.ts +6 -1
  88. package/src/fitting/index.ts +2 -2
  89. package/src/index.ts +6 -57
  90. package/src/internal/GhoshConicApproximationBalance.ts +184 -0
  91. package/src/internal/GhoshConicApproximationDisplacement.ts +83 -0
  92. package/src/internal/index.ts +183 -0
  93. package/src/internal/mesh-observations/index.ts +1 -2
  94. package/src/observation/index.ts +15 -15
  95. package/src/reconstruction/index.ts +10 -10
  96. package/src/structures/curve/index.ts +15 -15
  97. package/src/structures/domain/index.ts +45 -45
  98. package/src/structures/image/index.ts +45 -45
  99. package/src/structures/index.ts +1 -0
  100. package/src/structures/internal/index.ts +58 -0
  101. package/src/structures/mesh/index.ts +19 -19
  102. package/src/structures/node/index.ts +23 -23
  103. package/src/structures/observation/index.ts +15 -15
  104. package/src/structures/operation/index.ts +10 -10
  105. package/src/typings/index.ts +6 -6
@@ -0,0 +1,282 @@
1
+ import { findAutoMovieRecoveryCubicCriticalParameters } from "./findAutoMovieRecoveryCubicCriticalParameters";
2
+
3
+ /**
4
+ * Shared planar, millimetre-valued contract for experimental conic recovery.
5
+ * Rational quadratics use endpoint weights one and a positive middle weight;
6
+ * a collinear control triple with weight one is the admitted line primitive.
7
+ * The contract does not imply a Hausdorff certificate or a globally minimal net.
8
+ *
9
+ * @evidence contracts/development/common.md#meaningful-documentation States units, coefficient normalization, line representation and the limits of reported evidence.
10
+ * @evidence contracts/development/design.md#principled-representation Readonly planar tuples and explicit domains represent source charts and conic coefficients; finite values, positive weights and ordered domains require runtime admission.
11
+ * @evidence contracts/development/design.md#minimal-and-owned-surface Recovery owns the shared contract consumed by the two paper experiments and their reconstruction caller.
12
+ * @evidence contracts/development/design.md#prohibited-design-shortcuts No specimen, source artifact, rendering option or optional algorithm-specific state enters this planar contract.
13
+ */
14
+ export namespace AutoMovieRecoveryConicApproximation {
15
+ /**
16
+ * A point or derivative in the caller's fixed planar millimetre frame.
17
+ *
18
+ * @evidence contracts/development/common.md#meaningful-documentation States the fixed frame and physical unit; derivative orders inherit the source parameter.
19
+ * @evidence contracts/development/design.md#principled-representation A readonly two-tuple excludes changing dimension; finite arithmetic remains a runtime condition.
20
+ * @evidence contracts/development/design.md#minimal-and-owned-surface Both algorithms and their caller share this single point owner.
21
+ * @evidence contracts/development/design.md#prohibited-design-shortcuts No fixture-specific axes or numeric wrapper is introduced.
22
+ */
23
+ export type Point = readonly [number, number];
24
+
25
+ /**
26
+ * Borrowed parametric planar source, with source-span and singularity breaks.
27
+ * Derivatives are with respect to the original parameter, not normalized arc
28
+ * length. At a declared break the derivative callback must supply the exact
29
+ * requested one-sided limit; no epsilon displacement approximates a corner.
30
+ * Smooth callbacks may ignore side. Callbacks must be deterministic and leave
31
+ * their input unchanged; algorithms snapshot returned coordinate tuples.
32
+ *
33
+ * @evidence contracts/development/common.md#meaningful-documentation Documents callback parameterization, exact one-sided derivatives at breaks, domain, breaks and coordinate snapshot ownership.
34
+ * @evidence contracts/development/design.md#principled-representation The ordered domain and derivatives through order five support both papers; regularity is checked numerically by the selected algorithm.
35
+ * @evidence contracts/development/design.md#minimal-and-owned-surface Recovery accepts a pure evaluator so source basis and artifact I/O remain with existing owners.
36
+ * @evidence contracts/development/design.md#prohibited-design-shortcuts The interface accepts arbitrary planar source charts without a Human or polynomial-degree dependency.
37
+ */
38
+ export interface ICurve {
39
+ /** Inclusive source parameter interval, strictly increasing. */
40
+ domain: readonly [number, number];
41
+
42
+ /** Ordered or unordered interior parameter boundaries that may not be crossed. */
43
+ breaks: readonly number[];
44
+
45
+ /** Whether the source identifies its two domain endpoints. */
46
+ closed: boolean;
47
+
48
+ /**
49
+ * Evaluate in millimetres; nonfinite coordinates refuse the affected arc.
50
+ *
51
+ * @evidence contracts/development/common.md#meaningful-documentation States the unit of the returned point and what a nonfinite coordinate does to the arc that reads it; the interface comment states determinism and input ownership.
52
+ * @evidenceExclude contracts/development/implementation.md#principled-implementation The point evaluator is a callback the caller supplies: this declaration has no body whose method could be judged.
53
+ * @evidenceExclude contracts/development/implementation.md#clear-and-simple-structure The point evaluator is a callback the caller supplies: no structure is implemented here.
54
+ * @evidenceExclude contracts/development/implementation.md#prohibited-implementation-shortcuts The point evaluator is a callback the caller supplies: no implementation exists here to take a shortcut.
55
+ * @evidenceExclude contracts/development/implementation.md#efficient-algorithms The point evaluator is a callback the caller supplies: its cost belongs to the supplied source.
56
+ * @evidenceExclude contracts/development/implementation.md#reuse-equivalent-work The point evaluator is a callback the caller supplies: the algorithms that call it own their caching.
57
+ * @evidenceExclude contracts/development/implementation.md#bound-retention-and-release-resources The point evaluator is a callback the caller supplies: it declares no state or resource.
58
+ */
59
+ evaluate(t: number): Point;
60
+
61
+ /**
62
+ * Evaluate mm/parameter^order. At a nonsmooth break, left/right requests
63
+ * select the exact incident chart's endpoint derivative; omission selects
64
+ * the caller's ordinary point value and makes no one-sided promise.
65
+ *
66
+ * @evidence contracts/development/common.md#meaningful-documentation States the derivative's unit per order, the one-sided selection at a break and what omitting the side promises.
67
+ * @evidenceExclude contracts/development/implementation.md#principled-implementation The derivative evaluator is a callback the caller supplies: no method is implemented under this signature.
68
+ * @evidenceExclude contracts/development/implementation.md#clear-and-simple-structure The derivative evaluator is a callback the caller supplies: its structure is the source chart's own.
69
+ * @evidenceExclude contracts/development/implementation.md#prohibited-implementation-shortcuts The derivative evaluator is a callback the caller supplies: exactness at breaks is demanded of it, not implemented here.
70
+ * @evidenceExclude contracts/development/implementation.md#efficient-algorithms The derivative evaluator is a callback the caller supplies: the cost of each order is the source chart's.
71
+ * @evidenceExclude contracts/development/implementation.md#reuse-equivalent-work The derivative evaluator is a callback the caller supplies: Ahn and Ghosh cache its jets themselves.
72
+ * @evidenceExclude contracts/development/implementation.md#bound-retention-and-release-resources The derivative evaluator is a callback the caller supplies: the signature holds no state between orders or sides.
73
+ */
74
+ derivative(
75
+ t: number,
76
+ order: 1 | 2 | 3 | 4 | 5,
77
+ side?: "left" | "right",
78
+ ): Point;
79
+ }
80
+
81
+ /**
82
+ * Physical fit tolerance and explicit work limits, with no implicit defaults.
83
+ *
84
+ * @evidence contracts/development/common.md#meaningful-documentation Distinguishes physical tolerance from arc and subdivision budgets.
85
+ * @evidence contracts/development/design.md#principled-representation Positive finite tolerance and positive integer budgets require admission; reaching a budget returns partial evidence.
86
+ * @evidence contracts/development/design.md#minimal-and-owned-surface The caller supplies the three controls needed to bound adaptive approximation.
87
+ * @evidence contracts/development/design.md#prohibited-design-shortcuts No specimen-dependent preset or hidden quality option is exposed.
88
+ */
89
+ export interface IOptions {
90
+ /** Requested sampled geometric tolerance, in millimetres. */
91
+ toleranceMm: number;
92
+
93
+ /** Maximum accepted and unresolved leaf intervals in the resulting net. */
94
+ maximumArcs: number;
95
+
96
+ /** Maximum bisection depth per supplied source interval. */
97
+ maximumDepth: number;
98
+ }
99
+
100
+ /**
101
+ * One positive-weight rational quadratic over an original source interval.
102
+ * Its parameter runs independently from zero to one; domain only registers
103
+ * the source interval, since a fitted conic need not retain source speed.
104
+ *
105
+ * @evidence contracts/development/common.md#meaningful-documentation States normalized conic parameter, source registration and sampled error meaning.
106
+ * @evidence contracts/development/design.md#principled-representation Three planar controls and one positive middle weight encode exactly a rational quadratic, including explicitly admitted straight lines.
107
+ * @evidence contracts/development/design.md#minimal-and-owned-surface Reconstruction consumes these coefficients without source geometry or a parallel curve representation.
108
+ * @evidence contracts/development/design.md#prohibited-design-shortcuts No dense source samples or original topology is retained in the result.
109
+ */
110
+ export interface IArc {
111
+ /** Source interval represented by this coefficient record. */
112
+ domain: readonly [number, number];
113
+
114
+ /** Endpoint, tangent intersection, endpoint in the same millimetre frame. */
115
+ controls: readonly [Point, Point, Point];
116
+
117
+ /** Positive finite middle weight; endpoint weights are exactly one. */
118
+ weight: number;
119
+
120
+ /** Largest sampled geometric discrepancy, not a certified supremum. */
121
+ maximumSampleErrorMm: number;
122
+ }
123
+
124
+ /**
125
+ * Fitted coefficients and explicit limits of the supporting evidence.
126
+ * Partial results may omit unresolved intervals and must not be mistaken for
127
+ * a complete reconstruction; refused results have no admitted coefficients.
128
+ *
129
+ * @evidence contracts/development/common.md#meaningful-documentation Defines status, omission, certification and query accounting.
130
+ * @evidence contracts/development/design.md#principled-representation The closed status union separates complete, limited and refused operations; runtime logic owns consistency with coefficients.
131
+ * @evidence contracts/development/design.md#minimal-and-owned-surface Both experiments report their coefficients and limitations through one recovery result owner.
132
+ * @evidence contracts/development/design.md#prohibited-design-shortcuts Diagnostics preserve unsupported premises rather than hiding them behind an empty successful fit.
133
+ */
134
+ export interface IResult {
135
+ /** Honest algorithm/provenance label, including adaptation where applicable. */
136
+ method: string;
137
+
138
+ /** Completeness of admitted source coverage. */
139
+ status: "complete" | "partial" | "refused";
140
+
141
+ /** Ordered coefficients; no source samples are retained. */
142
+ arcs: readonly IArc[];
143
+
144
+ /** Admission failures, approximation limits and provenance qualifications. */
145
+ diagnostics: readonly string[];
146
+
147
+ /** Maximum of accepted arcs' sampled error; zero for an empty result. */
148
+ maximumSampleErrorMm: number;
149
+
150
+ /** True only with a proven continuous error bound, never mere sampling. */
151
+ certified: boolean;
152
+
153
+ /** Number of source evaluate/derivative callback invocations. */
154
+ queries: number;
155
+ }
156
+
157
+ /**
158
+ * Isolated numerical source-cubic critical candidates on normalized (0,1).
159
+ * D=0 includes inflections and stationary points; categories may overlap.
160
+ * No endpoint or unresolved continuum is fabricated as an isolated root.
161
+ *
162
+ * @evidence contracts/development/common.md#meaningful-documentation Defines normalized parameters, overlapping categories, degeneracy and numerical limitations.
163
+ * @evidence contracts/development/design.md#principled-representation Readonly parameter arrays separate zero curvature numerator, affine extrema and velocity zeros; finite interior admission belongs to the polynomial-root owner.
164
+ * @evidence contracts/development/design.md#minimal-and-owned-surface Both conic algorithms and the cubic source adapter share Recovery's critical-event result, with no reference-artifact dependency.
165
+ * @evidence contracts/development/design.md#prohibited-design-shortcuts No sampled data, specimen option or presumed future critical-event vocabulary is exposed.
166
+ */
167
+ export interface ICubicCriticalParameters {
168
+ /** Sorted exact-value union of the three numerical candidate arrays. */
169
+ breaks: readonly number[];
170
+
171
+ /** Interior roots of cross(p',p''); not necessarily regular inflections. */
172
+ zeroCurvature: readonly number[];
173
+
174
+ /** Interior roots of the affine-curvature critical equations where defined. */
175
+ affineCritical: readonly number[];
176
+
177
+ /** Interior velocity common-root candidates, checked in both coordinates. */
178
+ stationary: readonly number[];
179
+
180
+ /** Computed curvature-numerator polynomial is identically zero. */
181
+ collinear: boolean;
182
+
183
+ /** Degenerate continua and finite arithmetic/root-observation limitations. */
184
+ diagnostics: readonly string[];
185
+ }
186
+
187
+ /**
188
+ * Observe cubic critical parameters without changing its points or jets.
189
+ * The four planar Bernstein controls define normalized t in [0,1]; the caller
190
+ * maps interior candidates to its source chart and reports unrepresentable
191
+ * mapped intervals. Close distinct roots are not merged by an epsilon.
192
+ *
193
+ * @evidence contracts/development/common.md#meaningful-documentation States coefficient basis, normalized parameter, caller mapping responsibility and unaltered source semantics.
194
+ * @evidence contracts/development/implementation.md#principled-implementation The coefficient helper differentiates the source cubic and delegates D=0, affine critical and stationary candidates to the existing engine polynomial-root owner.
195
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure This namespace entry exposes one shared numerical owner to the two algorithms and their actual input adapter.
196
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts No finite-difference endpoint movement, source samples or epsilon root merging is introduced.
197
+ * @evidence contracts/development/implementation.md#efficient-algorithms Fixed degree-two equations give bounded work independent of any mesh or source curve count.
198
+ * @evidence contracts/development/implementation.md#reuse-equivalent-work The returned classification is reusable by both methods for the same admitted coefficients.
199
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources The pure wrapper retains no controls, callbacks or external resources.
200
+ */
201
+ export function cubicCriticalParameters(
202
+ controls: readonly [Point, Point, Point, Point],
203
+ ): ICubicCriticalParameters {
204
+ return findAutoMovieRecoveryCubicCriticalParameters(controls);
205
+ }
206
+
207
+ /**
208
+ * Evaluate positive-weight rational Bernstein coefficients on [0,1].
209
+ *
210
+ * @evidence contracts/development/common.md#meaningful-documentation Gives parameter range and assumes an admitted finite coefficient record.
211
+ * @evidence contracts/development/implementation.md#principled-implementation The quadratic Bernstein quotient is the standard rational conic representation with endpoint weights one.
212
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure One shared evaluation prevents basis differences between fitting and reconstruction.
213
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts No source samples, weight correction or specimen branch changes the coefficients.
214
+ * @evidence contracts/development/implementation.md#efficient-algorithms Constant arithmetic and one output tuple are independent of source complexity.
215
+ * @evidence contracts/development/implementation.md#reuse-equivalent-work Bernstein factors and denominator are calculated once per evaluation.
216
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources The pure call retains no input or resources after return.
217
+ */
218
+ export function evaluate(arc: IArc, u: number): Point {
219
+ const a: number = (1 - u) ** 2;
220
+ const b: number = 2 * arc.weight * u * (1 - u);
221
+ const c: number = u * u;
222
+ const denominator: number = a + b + c;
223
+ return [
224
+ (a * arc.controls[0][0] + b * arc.controls[1][0] + c * arc.controls[2][0]) / denominator,
225
+ (a * arc.controls[0][1] + b * arc.controls[1][1] + c * arc.controls[2][1]) / denominator,
226
+ ];
227
+ }
228
+
229
+ /**
230
+ * Euclidean separation in millimetres between two same-frame points.
231
+ *
232
+ * @evidence contracts/development/common.md#meaningful-documentation States the returned physical unit and same-frame premise.
233
+ * @evidence contracts/development/implementation.md#principled-implementation Math.hypot computes the Euclidean norm of the coordinate difference.
234
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Shared scalar geometry has no fitting or I/O responsibility.
235
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts No rounding, clamping or specimen constants alter the distance.
236
+ * @evidence contracts/development/implementation.md#efficient-algorithms Constant arithmetic requires no retained storage.
237
+ * @evidence contracts/development/implementation.md#reuse-equivalent-work Each coordinate difference is evaluated once.
238
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources No resources or state survive the call.
239
+ */
240
+ export function distance(a: Point, b: Point): number {
241
+ return Math.hypot(a[0] - b[0], a[1] - b[1]);
242
+ }
243
+
244
+ /**
245
+ * Signed planar determinant, used for orientation and tangent intersection.
246
+ *
247
+ * @evidence contracts/development/common.md#meaningful-documentation States the signed determinant and its geometric consumers.
248
+ * @evidence contracts/development/implementation.md#principled-implementation The 2-by-2 determinant measures oriented parallelogram area.
249
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Both algorithms share the primitive without a solver dependency.
250
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts No tolerance or absolute value erases orientation.
251
+ * @evidence contracts/development/implementation.md#efficient-algorithms Two products and one subtraction have constant cost.
252
+ * @evidence contracts/development/implementation.md#reuse-equivalent-work No repeated source work is performed by this arithmetic helper.
253
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources The call owns no retained state or external handle.
254
+ */
255
+ export function cross(a: Point, b: Point): number {
256
+ return a[0] * b[1] - a[1] * b[0];
257
+ }
258
+
259
+ /**
260
+ * Admit a finite source chart and positive explicit numerical budgets.
261
+ *
262
+ * @evidence contracts/development/common.md#meaningful-documentation Lists invalid-domain, boundary and budget effects; callbacks are checked when queried.
263
+ * @evidence contracts/development/implementation.md#principled-implementation Finite interval and budget checks establish the adaptive subdivision preconditions.
264
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Common admission owns structural checks; each paper owns differential premises.
265
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts Invalid options produce diagnostics without defaults, clamping or callback invocation.
266
+ * @evidence contracts/development/implementation.md#efficient-algorithms Admission scans B source breaks once, using O(B) diagnostic storage only on failure.
267
+ * @evidence contracts/development/implementation.md#reuse-equivalent-work Callers validate once before fitting their intervals.
268
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources No callbacks, source arrays or process resources are retained.
269
+ */
270
+ export function validate(curve: ICurve, options: IOptions): string[] {
271
+ const errors: string[] = [];
272
+ if (!Number.isFinite(curve.domain[0]) || !Number.isFinite(curve.domain[1]) || curve.domain[0] >= curve.domain[1])
273
+ errors.push("Source domain must be finite and strictly increasing.");
274
+ if (curve.breaks.some((t: number): boolean => !Number.isFinite(t) || t <= curve.domain[0] || t >= curve.domain[1]))
275
+ errors.push("Every supplied break must be finite and strictly inside the source domain.");
276
+ if (!Number.isFinite(options.toleranceMm) || options.toleranceMm <= 0)
277
+ errors.push("toleranceMm must be finite and positive.");
278
+ if (!Number.isSafeInteger(options.maximumArcs) || options.maximumArcs < 1 || !Number.isSafeInteger(options.maximumDepth) || options.maximumDepth < 1 || options.maximumDepth > 52)
279
+ errors.push("Budgets must be positive safe integers; maximumDepth must not exceed binary64's 52-bit subdivision precision.");
280
+ return errors;
281
+ }
282
+ }
@@ -0,0 +1,285 @@
1
+ import {
2
+ AutoMovieBernstein64 as B,
3
+ decomposeAutoMovieSingularMatrix,
4
+ type IAutoMovieSingularDecomposition,
5
+ } from "@automovie/engine";
6
+
7
+ import { AutoMovieRecoveryCompactApproximation as C } from "./AutoMovieRecoveryCompactApproximation";
8
+ import { AutoMovieRecoveryConicApproximation as Q } from "./AutoMovieRecoveryConicApproximation";
9
+ import { approximateAutoMovieRecoveryConicsAhn } from "./approximateAutoMovieRecoveryConicsAhn";
10
+
11
+ /**
12
+ * Refit whole smooth charts with storage-selected degree-three to degree-five
13
+ * Bernstein pieces and optional positive bitangent conics. Old source knots
14
+ * inform observation coverage but do not force output pieces.
15
+ *
16
+ * This is a degree-bounded adaptation of Schneider's endpoint-tangent fitting
17
+ * and adaptive subdivision (Graphics Gems, 1990), not a reproduction of a
18
+ * global minimum-control theorem. The existing engine's original-design Jacobi
19
+ * SVD replaces two-handle normal equations and extends the interior controls:
20
+ * https://github.com/erich666/GraphicsGems/blob/master/gems/FitCurves.c
21
+ * https://www.netlib.org/lapack/lapack_routine/dgesvj.f
22
+ *
23
+ * Every polynomial fixes endpoint positions and forward tangent directions.
24
+ * Trapezoid-weighted fitting nodes and distinct held-out quarter nodes inspect
25
+ * every supplied source knot interval. Polynomial paired-point distances give
26
+ * bidirectional geometric witnesses at those nodes, not a continuous bound.
27
+ * Conics additionally use independent source-apex radial correspondences in
28
+ * both directions. Finite samples cannot certify missed features, embedding,
29
+ * Hausdorff error or likeness. No source observation is retained in the result.
30
+ *
31
+ * @evidence contracts/development/common.md#meaningful-documentation States papers, adaptation, units, charts, hard corners, observation-only knots, sampling and incomplete-budget semantics.
32
+ * @evidence contracts/development/implementation.md#principled-implementation Endpoint-tangent least squares extends Schneider's construction to bounded degrees; original-design engine SVD avoids squared conditioning. Adaptive subdivision and independent-node distances admit candidates under explicit sampled premises.
33
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Call-local observation, candidate fit, verification and subdivision own separate steps; existing engine algebra and Ahn conic fitting retain their numerical responsibilities.
34
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts No degree elevation, source mesh, specimen table, tolerance relaxation, numerical ridge or fabricated missing interval supplies output. Negative handles and unresolved numerical rank refuse their candidate.
35
+ * @evidence contracts/development/implementation.md#efficient-algorithms With N supplied source supports, L visited leaves and Q permitted callbacks, fixed degree at most five bounds each design width by six. Balanced subdivision observes O(N log L) nodes; binary searches restrict each support scan to its interval. Callback, leaf and depth budgets bound retained work; no global optimality or unmeasured speedup is claimed.
36
+ * @evidence contracts/development/implementation.md#reuse-equivalent-work Exact-parameter source points are snapshotted once and reused across degrees, fitting and verification; one candidate SVD solves every unknown on its original weighted design.
37
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources At most maximumQueries cached observations and maximumPieces leaves survive within the synchronous call. Only compact coefficients and scalar evidence escape; no callback or process is retained.
38
+ */
39
+ export function approximateAutoMovieRecoveryCompactCurves(
40
+ curve: C.ICurve,
41
+ options: C.IOptions,
42
+ ): C.IResult {
43
+ const diagnostics: string[] = Q.validate(curve, {
44
+ toleranceMm: options.toleranceMm,
45
+ maximumArcs: options.maximumPieces,
46
+ maximumDepth: options.maximumDepth,
47
+ });
48
+ if (![3, 4, 5, "mixed"].includes(options.degree)
49
+ || !Number.isSafeInteger(options.maximumQueries) || options.maximumQueries < 1)
50
+ diagnostics.push("A supported degree and positive safe-integer query budget are required.");
51
+ if (curve.knots.some((t: number): boolean => !Number.isFinite(t) || t <= curve.domain[0] || t >= curve.domain[1]))
52
+ diagnostics.push("Source observation knots must lie strictly inside the finite domain.");
53
+ const pieces: C.IPiece[] = [];
54
+ let queries: number = 0;
55
+ let omitted: number = 0;
56
+
57
+ /** Report sampled coverage; source failure can explicitly clear prior pieces. */
58
+ function result(refused: boolean = false): C.IResult {
59
+ const retained: readonly C.IPiece[] = refused ? [] : pieces;
60
+ return {
61
+ status: refused || retained.length === 0 ? "refused" : omitted === 0 ? "complete" : "partial",
62
+ pieces: retained,
63
+ maximumSampleErrorMm: retained.reduce((n: number, p: C.IPiece): number => Math.max(n, p.maximumSampleErrorMm), 0),
64
+ storedScalars: C.storedScalars(retained), queries, diagnostics, certified: false,
65
+ };
66
+ }
67
+ if (diagnostics.length !== 0) return result(true);
68
+ diagnostics.push("Sampled degree-bounded refitting; no continuous Hausdorff, topology or global minimum-storage certificate.");
69
+ if (options.degree === "mixed")
70
+ diagnostics.push("Mixed candidates include bitangent conics and polynomial degrees 3/4/5; a whole analytic-oval fitter is not implemented.");
71
+ const observations: Map<number, Q.Point> = new Map();
72
+ const queryLimit: Error = new Error("Source query budget exhausted; unprocessed domains remain omitted.");
73
+
74
+ /** Snapshot borrowed coordinates and bound all source callback work. */
75
+ function observe(t: number, order?: 1 | 2 | 3 | 4 | 5, side?: "left" | "right"): Q.Point {
76
+ const cached: Q.Point | undefined = order === undefined ? observations.get(t) : undefined;
77
+ if (cached !== undefined) return cached;
78
+ if (queries >= options.maximumQueries) throw queryLimit;
79
+ ++queries;
80
+ const borrowed: Q.Point = order === undefined ? curve.evaluate(t) : curve.derivative(t, order, side);
81
+ if (!borrowed.every(Number.isFinite)) throw new Error("Source returned nonfinite compact-fit coordinates or jets.");
82
+ const p: Q.Point = [borrowed[0], borrowed[1]];
83
+ if (order === undefined) observations.set(t, p);
84
+ return p;
85
+ }
86
+ const support: number[] = [...new Set([curve.domain[0], ...curve.knots, ...curve.breaks, curve.domain[1]])].sort((a: number, b: number): number => a - b);
87
+
88
+ /** Find the first source support greater than a, without scanning old knots. */
89
+ function upper(a: number): number {
90
+ let lo: number = 0;
91
+ let hi: number = support.length;
92
+ while (lo < hi) {
93
+ const middle: number = (lo + hi) >>> 1;
94
+ if (support[middle]! <= a) lo = middle + 1;
95
+ else hi = middle;
96
+ }
97
+ return lo;
98
+ }
99
+
100
+ /** Fitting midpoints and held-out quarters cover every original source piece. */
101
+ function nodes(a: number, b: number): { fitting: number[]; validation: number[] } {
102
+ const partition: number[] = [a];
103
+ for (let i: number = upper(a); i < support.length && support[i]! < b; ++i) partition.push(support[i]!);
104
+ partition.push(b);
105
+ const fitting: Set<number> = new Set(partition);
106
+ const validation: Set<number> = new Set();
107
+ for (let i: number = 1; i < partition.length; ++i) {
108
+ const left: number = partition[i - 1]!;
109
+ const width: number = partition[i]! - left;
110
+ fitting.add(left + width / 2);
111
+ validation.add(left + width / 4);
112
+ validation.add(left + 3 * width / 4);
113
+ }
114
+ for (let i: number = 0; i <= 16; ++i) fitting.add(a + (b - a) * i / 16);
115
+ for (let i: number = 0; i < 33; ++i) validation.add(a + (b - a) * (i + 0.5) / 33);
116
+ return {
117
+ fitting: [...fitting].sort((x: number, y: number): number => x - y),
118
+ validation: [...validation].filter((t: number): boolean => !fitting.has(t)).sort((x: number, y: number): number => x - y),
119
+ };
120
+ }
121
+
122
+ /** Weighted original-design solve with fixed endpoints and forward tangents. */
123
+ function polynomial(a: number, b: number, degree: 3 | 4 | 5, at: readonly number[]): C.IPiece | undefined {
124
+ const p: Q.Point = observe(a);
125
+ const q: Q.Point = observe(b);
126
+ const left: Q.Point = observe(a, 1, "right");
127
+ const right: Q.Point = observe(b, 1, "left");
128
+ const ln: number = Math.hypot(...left);
129
+ const rn: number = Math.hypot(...right);
130
+ if (ln === 0 || rn === 0) return undefined;
131
+ const u: Q.Point = [left[0] / ln, left[1] / ln];
132
+ const v: Q.Point = [right[0] / rn, right[1] / rn];
133
+ const width: number = 2 + 2 * (degree - 3);
134
+ const rows: number[][] = [];
135
+ const values: number[] = [];
136
+ for (let i: number = 1; i < at.length - 1; ++i) {
137
+ const t: number = at[i]!;
138
+ const local: number = (t - a) / (b - a);
139
+ const basis: number[] = Array.from({ length: degree + 1 }, (_x: unknown, k: number): number => B.choose(degree, k) * local ** k * (1 - local) ** (degree - k));
140
+ const scale: number = Math.sqrt((at[i + 1]! - at[i - 1]!) / (2 * (b - a)));
141
+ const point: Q.Point = observe(t);
142
+ for (let axis: number = 0; axis < 2; ++axis) {
143
+ const row: number[] = new Array<number>(width).fill(0);
144
+ row[0] = basis[1]! * u[axis]! * scale;
145
+ row[1] = -basis[degree - 1]! * v[axis]! * scale;
146
+ for (let j: number = 2; j <= degree - 2; ++j) row[2 + 2 * (j - 2) + axis] = basis[j]! * scale;
147
+ rows.push(row);
148
+ values.push((point[axis]! - p[axis]! - (basis[degree - 1]! + basis[degree]!) * (q[axis]! - p[axis]!)) * scale);
149
+ }
150
+ }
151
+ let decomposition: IAutoMovieSingularDecomposition;
152
+ try {
153
+ decomposition = decomposeAutoMovieSingularMatrix(rows, {
154
+ maxEntries: Math.max(rows.length * width, width * width),
155
+ maxSweeps: 40, orthogonalityTolerance: 128 * Number.EPSILON,
156
+ });
157
+ } catch {
158
+ return undefined;
159
+ }
160
+ if (decomposition.numericalRank !== width) return undefined;
161
+ const solution: number[] = new Array<number>(width).fill(0);
162
+ for (let k: number = 0; k < width; ++k) {
163
+ const projection: number = decomposition.leftColumns[k]!.reduce((s: number, value: number, i: number): number => s + value * values[i]!, 0) / decomposition.singularValues[k]!;
164
+ for (let j: number = 0; j < width; ++j) solution[j] += projection * decomposition.rightColumns[k]![j]!;
165
+ }
166
+ if (!solution.every(Number.isFinite) || solution[0]! <= 0 || solution[1]! <= 0) return undefined;
167
+ const controls: Q.Point[] = [p, [p[0] + solution[0]! * u[0], p[1] + solution[0]! * u[1]]];
168
+ for (let j: number = 2; j <= degree - 2; ++j) controls.push([p[0] + solution[2 + 2 * (j - 2)]!, p[1] + solution[3 + 2 * (j - 2)]!]);
169
+ controls.push([q[0] - solution[1]! * v[0], q[1] - solution[1]! * v[1]], q);
170
+ return { kind: "polynomial", degree, domain: [a, b], controls, maximumSampleErrorMm: 0 };
171
+ }
172
+
173
+ /** Linear source registration supplies paired witnesses in both directions. */
174
+ function verifyPolynomial(piece: C.IPiece, at: readonly number[]): number {
175
+ let maximum: number = 0;
176
+ for (const t of at) {
177
+ const p: Q.Point = observe(t);
178
+ const q: Q.Point = C.evaluate(piece, (t - piece.domain[0]) / (piece.domain[1] - piece.domain[0]));
179
+ maximum = Math.max(maximum, Q.distance(p, q));
180
+ }
181
+ return maximum;
182
+ }
183
+
184
+ /** Independently check the conic's apex-ray chart, including reverse samples. */
185
+ function verifyConic(piece: C.IPiece & { kind: "conic" }, at: readonly number[]): number {
186
+ const p: Q.Point = piece.controls[0];
187
+ const x: Q.Point = [piece.controls[1][0] - p[0], piece.controls[1][1] - p[1]];
188
+ const y: Q.Point = [piece.controls[2][0] - p[0], piece.controls[2][1] - p[1]];
189
+ const area: number = Q.cross(x, y);
190
+
191
+ /** Recover rational u from source barycentric coordinates along an apex ray. */
192
+ function radial(t: number): number {
193
+ if (t === piece.domain[0]) return 0;
194
+ if (t === piece.domain[1]) return 1;
195
+ const q: Q.Point = observe(t);
196
+ const delta: Q.Point = [q[0] - p[0], q[1] - p[1]];
197
+ if (area === 0) return (delta[0] * y[0] + delta[1] * y[1]) / (y[0] ** 2 + y[1] ** 2);
198
+ const b1: number = Q.cross(delta, y) / area;
199
+ const b2: number = Q.cross(x, delta) / area;
200
+ const b0: number = 1 - b1 - b2;
201
+ return b0 < 0 || b2 < 0 ? NaN : Math.sqrt(b2) / (Math.sqrt(b0) + Math.sqrt(b2));
202
+ }
203
+ let maximum: number = 0;
204
+ let previous: number = -Infinity;
205
+ for (const t of at) {
206
+ const u: number = radial(t);
207
+ if (!Number.isFinite(u) || u < previous || u < 0 || u > 1) return Infinity;
208
+ previous = u;
209
+ maximum = Math.max(maximum, Q.distance(observe(t), C.evaluate(piece, u)));
210
+ }
211
+ for (let i: number = 0; i < 33; ++i) {
212
+ const u: number = (i + 0.5) / 33;
213
+ let low: number = piece.domain[0];
214
+ let high: number = piece.domain[1];
215
+ for (let j: number = 0; j < 28; ++j) {
216
+ const middle: number = (low + high) / 2;
217
+ const value: number = radial(middle);
218
+ if (!Number.isFinite(value)) return Infinity;
219
+ if (value < u) low = middle;
220
+ else high = middle;
221
+ }
222
+ maximum = Math.max(maximum, Q.distance(observe((low + high) / 2), C.evaluate(piece, u)));
223
+ }
224
+ return maximum;
225
+ }
226
+
227
+ /** A leaf carries no old source span ownership. */
228
+ interface Interval { a: number; b: number; depth: number }
229
+ const boundaries: Set<number> = new Set([curve.domain[0], ...curve.breaks, curve.domain[1]]);
230
+ if (curve.closed) for (let i: number = 1; i < 4; ++i) boundaries.add(curve.domain[0] + (curve.domain[1] - curve.domain[0]) * i / 4);
231
+ const ordered: number[] = [...boundaries].sort((a: number, b: number): number => a - b);
232
+ if (ordered.length - 1 > options.maximumPieces) {
233
+ diagnostics.push("Initial feature charts exceed the piece budget.");
234
+ return result(true);
235
+ }
236
+ const pending: Interval[] = [];
237
+ for (let i: number = ordered.length - 2; i >= 0; --i) pending.push({ a: ordered[i]!, b: ordered[i + 1]!, depth: 0 });
238
+ let leaves: number = pending.length;
239
+ try {
240
+ while (pending.length !== 0) {
241
+ const interval: Interval = pending.pop()!;
242
+ const { a, b, depth } = interval;
243
+ const sample: { fitting: number[]; validation: number[] } = nodes(a, b);
244
+ const validation: number[] = [...new Set([...sample.fitting, ...sample.validation])].sort((x: number, y: number): number => x - y);
245
+ let accepted: C.IPiece | undefined;
246
+ if (options.degree === "mixed") {
247
+ const conic: Q.IResult = approximateAutoMovieRecoveryConicsAhn({ domain: [a, b], breaks: [], closed: false, evaluate: (t: number): Q.Point => observe(t), derivative: (t: number, order: 1 | 2 | 3 | 4 | 5, side?: "left" | "right"): Q.Point => observe(t, order, side) }, { toleranceMm: options.toleranceMm, maximumArcs: 1, maximumDepth: 1 });
248
+ if (conic.status === "complete" && conic.arcs.length === 1) {
249
+ const candidate: C.IPiece & { kind: "conic" } = { ...conic.arcs[0]!, kind: "conic" };
250
+ candidate.maximumSampleErrorMm = Math.max(candidate.maximumSampleErrorMm, verifyConic(candidate, validation));
251
+ if (candidate.maximumSampleErrorMm <= options.toleranceMm) accepted = candidate;
252
+ }
253
+ }
254
+ const degrees: readonly (3 | 4 | 5)[] = options.degree === "mixed" ? [3, 4, 5] : [options.degree];
255
+ for (const degree of degrees) {
256
+ if (accepted !== undefined) break;
257
+ const candidate: C.IPiece | undefined = polynomial(a, b, degree, sample.fitting);
258
+ if (candidate === undefined) continue;
259
+ candidate.maximumSampleErrorMm = verifyPolynomial(candidate, validation);
260
+ if (candidate.maximumSampleErrorMm <= options.toleranceMm) accepted = candidate;
261
+ }
262
+ if (accepted !== undefined) {
263
+ pieces.push(accepted);
264
+ continue;
265
+ }
266
+ const middle: number = (a + b) / 2;
267
+ if (depth >= options.maximumDepth || leaves >= options.maximumPieces || middle === a || middle === b) {
268
+ ++omitted;
269
+ continue;
270
+ }
271
+ ++leaves;
272
+ pending.push({ a: middle, b, depth: depth + 1 }, { a, b: middle, depth: depth + 1 });
273
+ }
274
+ } catch (error) {
275
+ if (error === queryLimit) {
276
+ omitted += pending.length + 1;
277
+ diagnostics.push(queryLimit.message);
278
+ } else {
279
+ diagnostics.push(`Source failure: ${error instanceof Error ? error.message : String(error)}`);
280
+ return result(true);
281
+ }
282
+ }
283
+ if (omitted !== 0) diagnostics.push(`${omitted} source domain(s) omitted after piece, depth, query or numerical admission limits.`);
284
+ return result();
285
+ }