Skip to main content

qualia_core_db/solvers/calculus/
analysis.rs

1//! Finite-dimensional analysis foundations used by native calculus.
2
3#[derive(Debug, Clone, Copy, PartialEq)]
4pub enum AnalysisError {
5    NonFinite,
6    Degenerate,
7    Singular,
8    InvalidDomain,
9    NotCertified,
10    IterationLimit { residual: f64 },
11    OutputBufferFull,
12}
13
14#[repr(C)]
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct Vector<const N: usize> {
17    pub data: [f64; N],
18}
19
20impl<const N: usize> Vector<N> {
21    /// Wrap a raw array (unvalidated — call `validate` before use).
22    pub const fn new(data: [f64; N]) -> Self {
23        Self { data }
24    }
25
26    /// The zero vector.
27    pub const fn zero() -> Self {
28        Self { data: [0.0; N] }
29    }
30
31    /// Reject non-finite components.
32    pub fn validate(&self) -> Result<(), AnalysisError> {
33        if self.data.iter().all(|value| value.is_finite()) {
34            Ok(())
35        } else {
36            Err(AnalysisError::NonFinite)
37        }
38    }
39
40    /// Inner product; errors on non-finite inputs.
41    pub fn dot(self, other: Self) -> Result<f64, AnalysisError> {
42        self.validate()?;
43        other.validate()?;
44        Ok(self
45            .data
46            .iter()
47            .zip(other.data)
48            .map(|(left, right)| left * right)
49            .sum())
50    }
51
52    /// Euclidean norm ‖v‖₂.
53    pub fn norm(self) -> Result<f64, AnalysisError> {
54        Ok(self.dot(self)?.sqrt())
55    }
56
57    /// Euclidean distance ‖self − other‖.
58    pub fn distance(self, other: Self) -> Result<f64, AnalysisError> {
59        self.sub(other).norm()
60    }
61
62    /// Component-wise addition.
63    pub fn add(self, other: Self) -> Self {
64        let mut result = [0.0; N];
65        for (index, value) in result.iter_mut().enumerate() {
66            *value = self.data[index] + other.data[index];
67        }
68        Self::new(result)
69    }
70
71    /// Component-wise subtraction.
72    pub fn sub(self, other: Self) -> Self {
73        let mut result = [0.0; N];
74        for (index, value) in result.iter_mut().enumerate() {
75            *value = self.data[index] - other.data[index];
76        }
77        Self::new(result)
78    }
79
80    /// Scalar multiplication; errors on non-finite scalar.
81    pub fn scale(self, scalar: f64) -> Result<Self, AnalysisError> {
82        if !scalar.is_finite() {
83            return Err(AnalysisError::NonFinite);
84        }
85        let mut result = self;
86        for value in &mut result.data {
87            *value *= scalar;
88        }
89        result.validate()?;
90        Ok(result)
91    }
92
93    /// Orthogonal projection onto `direction`; errors on a zero
94    /// direction vector.
95    pub fn project_onto(self, direction: Self) -> Result<Self, AnalysisError> {
96        let denominator = direction.dot(direction)?;
97        if denominator <= f64::MIN_POSITIVE {
98            return Err(AnalysisError::Degenerate);
99        }
100        direction.scale(self.dot(direction)? / denominator)
101    }
102}
103
104#[repr(C)]
105#[derive(Debug, Clone, Copy, PartialEq)]
106pub struct LinearMap<const R: usize, const C: usize> {
107    pub coefficients: [[f64; C]; R],
108}
109
110impl<const R: usize, const C: usize> LinearMap<R, C> {
111    /// Wrap a row-major coefficient array (unvalidated).
112    pub const fn new(coefficients: [[f64; C]; R]) -> Self {
113        Self { coefficients }
114    }
115
116    /// Reject non-finite coefficients.
117    pub fn validate(&self) -> Result<(), AnalysisError> {
118        if self
119            .coefficients
120            .iter()
121            .flatten()
122            .all(|value| value.is_finite())
123        {
124            Ok(())
125        } else {
126            Err(AnalysisError::NonFinite)
127        }
128    }
129
130    /// Matrix-vector product `A·x` (validates both sides).
131    pub fn apply(&self, input: Vector<C>) -> Result<Vector<R>, AnalysisError> {
132        self.validate()?;
133        input.validate()?;
134        let mut output = [0.0; R];
135        for (row, value) in output.iter_mut().enumerate() {
136            *value = self.coefficients[row]
137                .iter()
138                .zip(input.data)
139                .map(|(coefficient, component)| coefficient * component)
140                .sum();
141        }
142        Ok(Vector::new(output))
143    }
144
145    /// The transposed map `Aᵀ : R → C`.
146    pub fn transpose(&self) -> LinearMap<C, R> {
147        let mut result = [[0.0; R]; C];
148        for (row, coefficients) in self.coefficients.iter().enumerate() {
149            for (column, coefficient) in coefficients.iter().enumerate() {
150                result[column][row] = *coefficient;
151            }
152        }
153        LinearMap::new(result)
154    }
155}
156
157impl<const N: usize> LinearMap<N, N> {
158    /// The N×N identity map.
159    pub const fn identity() -> Self {
160        let mut coefficients = [[0.0; N]; N];
161        let mut index = 0;
162        while index < N {
163            coefficients[index][index] = 1.0;
164            index += 1;
165        }
166        Self::new(coefficients)
167    }
168
169    /// Sum of diagonal entries.
170    pub fn trace(&self) -> Result<f64, AnalysisError> {
171        self.validate()?;
172        Ok((0..N).map(|index| self.coefficients[index][index]).sum())
173    }
174
175    /// Determinant via LU decomposition with partial pivoting.
176    pub fn determinant(&self) -> Result<f64, AnalysisError> {
177        self.validate()?;
178        let mut matrix = self.coefficients;
179        let mut determinant = 1.0;
180        let mut sign = 1.0;
181        for column in 0..N {
182            let mut pivot = column;
183            for row in column + 1..N {
184                if matrix[row][column].abs() > matrix[pivot][column].abs() {
185                    pivot = row;
186                }
187            }
188            if matrix[pivot][column].abs() <= f64::EPSILON {
189                return Ok(0.0);
190            }
191            if pivot != column {
192                matrix.swap(pivot, column);
193                sign = -sign;
194            }
195            let diagonal = matrix[column][column];
196            determinant *= diagonal;
197            for row in column + 1..N {
198                let factor = matrix[row][column] / diagonal;
199                for trailing in column + 1..N {
200                    matrix[row][trailing] -= factor * matrix[column][trailing];
201                }
202            }
203        }
204        Ok(sign * determinant)
205    }
206
207    /// Solve `A·x = rhs` by Gaussian elimination with partial
208    /// pivoting; errors on a singular matrix.
209    pub fn solve(&self, rhs: Vector<N>) -> Result<Vector<N>, AnalysisError> {
210        self.validate()?;
211        rhs.validate()?;
212        let mut matrix = self.coefficients;
213        let mut values = rhs.data;
214        for column in 0..N {
215            let mut pivot = column;
216            for row in column + 1..N {
217                if matrix[row][column].abs() > matrix[pivot][column].abs() {
218                    pivot = row;
219                }
220            }
221            if matrix[pivot][column].abs() <= 64.0 * f64::EPSILON {
222                return Err(AnalysisError::Singular);
223            }
224            matrix.swap(pivot, column);
225            values.swap(pivot, column);
226            for row in column + 1..N {
227                let factor = matrix[row][column] / matrix[column][column];
228                matrix[row][column] = 0.0;
229                for trailing in column + 1..N {
230                    matrix[row][trailing] -= factor * matrix[column][trailing];
231                }
232                values[row] -= factor * values[column];
233            }
234        }
235        let mut solution = [0.0; N];
236        for row in (0..N).rev() {
237            let mut value = values[row];
238            for column in row + 1..N {
239                value -= matrix[row][column] * solution[column];
240            }
241            solution[row] = value / matrix[row][row];
242        }
243        let result = Vector::new(solution);
244        result.validate()?;
245        Ok(result)
246    }
247}
248
249#[repr(C)]
250#[derive(Debug, Clone, Copy, PartialEq)]
251pub struct Basis<const N: usize> {
252    /// Basis vectors are stored as columns.
253    pub matrix: LinearMap<N, N>,
254}
255
256impl<const N: usize> Basis<N> {
257    /// Basis from a change-of-basis matrix — requires invertibility
258    /// (nonzero determinant).
259    pub fn new(matrix: LinearMap<N, N>) -> Result<Self, AnalysisError> {
260        if matrix.determinant()?.abs() <= 64.0 * f64::EPSILON {
261            return Err(AnalysisError::Singular);
262        }
263        Ok(Self { matrix })
264    }
265
266    /// Map basis coordinates to ambient-space vectors (`B·c`).
267    pub fn from_coordinates(&self, coordinates: Vector<N>) -> Result<Vector<N>, AnalysisError> {
268        self.matrix.apply(coordinates)
269    }
270
271    /// Solve for `v`'s coordinates in this basis (`B⁻¹·v`).
272    pub fn to_coordinates(&self, vector: Vector<N>) -> Result<Vector<N>, AnalysisError> {
273        self.matrix.solve(vector)
274    }
275}
276
277#[repr(C)]
278#[derive(Debug, Clone, Copy, PartialEq)]
279pub struct Interval {
280    pub lower: f64,
281    pub upper: f64,
282}
283
284impl Interval {
285    /// Closed interval `[lower, upper]`; errors on non-finite or
286    /// inverted bounds.
287    pub fn new(lower: f64, upper: f64) -> Result<Self, AnalysisError> {
288        if !lower.is_finite() || !upper.is_finite() || lower > upper {
289            return Err(AnalysisError::InvalidDomain);
290        }
291        Ok(Self { lower, upper })
292    }
293
294    /// `lower ≤ value ≤ upper`.
295    pub fn contains(self, value: f64) -> bool {
296        value.is_finite() && value >= self.lower && value <= self.upper
297    }
298
299    /// Partition the interval into `parts` equal sub-intervals
300    /// (caller-buffered).
301    pub fn uniform_cover(
302        self,
303        radius: f64,
304        out_centers: &mut [f64],
305    ) -> Result<usize, AnalysisError> {
306        if !radius.is_finite() || radius <= 0.0 {
307            return Err(AnalysisError::InvalidDomain);
308        }
309        let required = (((self.upper - self.lower) / (2.0 * radius)).ceil() as usize).max(1);
310        if out_centers.len() < required {
311            return Err(AnalysisError::OutputBufferFull);
312        }
313        let width = (self.upper - self.lower) / required as f64;
314        for (index, center) in out_centers[..required].iter_mut().enumerate() {
315            *center = self.lower + (index as f64 + 0.5) * width;
316        }
317        Ok(required)
318    }
319}
320
321#[repr(C)]
322#[derive(Debug, Clone, Copy, PartialEq)]
323pub struct FixedPointCertificate<const N: usize> {
324    pub point: Vector<N>,
325    pub contraction_factor: f64,
326    pub iterations: u32,
327    pub residual: f64,
328    pub a_posteriori_error_bound: f64,
329}
330
331/// Banach fixed-point iteration on ℝⁿ — iterates `f` from `x0`
332/// until step norm < tolerance or `max_iterations`; errors when
333/// `f`'s Lipschitz constant ≥ 1 or convergence fails.
334pub fn contraction_fixed_point<const N: usize, F>(
335    map: F,
336    initial: Vector<N>,
337    contraction_factor: f64,
338    tolerance: f64,
339    max_iterations: u32,
340) -> Result<FixedPointCertificate<N>, AnalysisError>
341where
342    F: Fn(Vector<N>) -> Vector<N>,
343{
344    if !contraction_factor.is_finite()
345        || !(0.0..1.0).contains(&contraction_factor)
346        || !tolerance.is_finite()
347        || tolerance <= 0.0
348    {
349        return Err(AnalysisError::NotCertified);
350    }
351    initial.validate()?;
352    let mut current = initial;
353    for iteration in 1..=max_iterations {
354        let next = map(current);
355        next.validate()?;
356        let residual = next.distance(current)?;
357        let error_bound = contraction_factor * residual / (1.0 - contraction_factor);
358        if error_bound <= tolerance {
359            return Ok(FixedPointCertificate {
360                point: next,
361                contraction_factor,
362                iterations: iteration,
363                residual,
364                a_posteriori_error_bound: error_bound,
365            });
366        }
367        current = next;
368    }
369    let residual = map(current).distance(current)?;
370    Err(AnalysisError::IterationLimit { residual })
371}
372
373#[repr(C)]
374#[derive(Debug, Clone, Copy, PartialEq)]
375pub struct Complex64 {
376    pub re: f64,
377    pub im: f64,
378}
379
380impl Complex64 {
381    pub const I: Self = Self { re: 0.0, im: 1.0 };
382
383    /// Complex number `re + im·i`.
384    pub const fn new(re: f64, im: f64) -> Self {
385        Self { re, im }
386    }
387
388    /// Complex modulus |z|.
389    pub fn norm(self) -> f64 {
390        self.re.hypot(self.im)
391    }
392
393    /// Component-wise complex addition.
394    pub fn add(self, other: Self) -> Self {
395        Self::new(self.re + other.re, self.im + other.im)
396    }
397
398    /// Complex multiplication.
399    pub fn mul(self, other: Self) -> Self {
400        Self::new(
401            self.re * other.re - self.im * other.im,
402            self.re * other.im + self.im * other.re,
403        )
404    }
405
406    /// Complex exponential `e^z = e^re·(cos im + i·sin im)`.
407    pub fn exp(self) -> Self {
408        let magnitude = self.re.exp();
409        Self::new(magnitude * self.im.cos(), magnitude * self.im.sin())
410    }
411
412    /// Principal logarithm with argument in `(-pi, pi]`.
413    pub fn principal_log(self) -> Result<Self, AnalysisError> {
414        let norm = self.norm();
415        if !norm.is_finite() || norm == 0.0 {
416            return Err(AnalysisError::InvalidDomain);
417        }
418        Ok(Self::new(norm.ln(), self.im.atan2(self.re)))
419    }
420
421    /// Principal square root with non-negative real part.
422    pub fn principal_sqrt(self) -> Result<Self, AnalysisError> {
423        if !self.re.is_finite() || !self.im.is_finite() {
424            return Err(AnalysisError::NonFinite);
425        }
426        let magnitude = self.norm();
427        let re = ((magnitude + self.re) * 0.5).max(0.0).sqrt();
428        let im_magnitude = ((magnitude - self.re) * 0.5).max(0.0).sqrt();
429        let im = if self.im < 0.0 {
430            -im_magnitude
431        } else {
432            im_magnitude
433        };
434        Ok(Self::new(re, im))
435    }
436}
437
438#[cfg(test)]
439mod tests {
440    use super::*;
441
442    #[test]
443    fn basis_coordinate_round_trip_and_singular_rejection() {
444        let basis = Basis::new(LinearMap::new([[1.0, 1.0], [0.0, 2.0]])).unwrap();
445        let coordinates = Vector::new([3.0, -1.0]);
446        let vector = basis.from_coordinates(coordinates).unwrap();
447        let recovered = basis.to_coordinates(vector).unwrap();
448        assert_eq!(recovered, coordinates);
449        assert_eq!(
450            Basis::new(LinearMap::new([[1.0, 2.0], [2.0, 4.0]])),
451            Err(AnalysisError::Singular)
452        );
453    }
454
455    #[test]
456    fn projection_is_idempotent_and_residual_is_orthogonal() {
457        let vector = Vector::new([2.0, 3.0, 4.0]);
458        let direction = Vector::new([1.0, -1.0, 0.0]);
459        let projection = vector.project_onto(direction).unwrap();
460        let second = projection.project_onto(direction).unwrap();
461        assert!(projection.distance(second).unwrap() < 1e-14);
462        assert!(vector.sub(projection).dot(direction).unwrap().abs() < 1e-14);
463    }
464
465    #[test]
466    fn contraction_certificate_contains_analytic_fixed_point() {
467        let certificate = contraction_fixed_point(
468            |x: Vector<1>| Vector::new([0.5 * x.data[0] + 1.0]),
469            Vector::new([0.0]),
470            0.5,
471            1e-10,
472            128,
473        )
474        .unwrap();
475        assert!((certificate.point.data[0] - 2.0).abs() <= 1e-10);
476        assert!(certificate.a_posteriori_error_bound <= 1e-10);
477    }
478
479    #[test]
480    fn complex_principal_branches_are_explicit_and_consistent() {
481        let z = Complex64::new(-3.0, 4.0);
482        let root = z.principal_sqrt().unwrap();
483        let squared = root.mul(root);
484        assert!((squared.re - z.re).abs() < 1e-14);
485        assert!((squared.im - z.im).abs() < 1e-14);
486
487        let value = Complex64::new(0.3, -0.7);
488        let round_trip = value.exp().principal_log().unwrap();
489        assert!((round_trip.re - value.re).abs() < 1e-14);
490        assert!((round_trip.im - value.im).abs() < 1e-14);
491    }
492
493    #[test]
494    fn interval_cover_reports_capacity() {
495        let interval = Interval::new(0.0, 1.0).unwrap();
496        let mut too_small = [0.0; 2];
497        assert_eq!(
498            interval.uniform_cover(0.1, &mut too_small),
499            Err(AnalysisError::OutputBufferFull)
500        );
501        let mut centers = [0.0; 5];
502        assert_eq!(interval.uniform_cover(0.1, &mut centers), Ok(5));
503    }
504}