qualia_core_db/solvers/calculus/
manifold.rs1use super::analysis::{AnalysisError, Interval, LinearMap, Vector};
4
5#[repr(C)]
6#[derive(Debug, Clone, Copy, PartialEq)]
7pub struct Chart<const N: usize> {
8 pub chart_id: u64,
9 pub coordinate_domain: [Interval; N],
10}
11
12impl<const N: usize> Chart<N> {
13 pub fn contains(&self, point: Vector<N>) -> bool {
15 self.coordinate_domain
16 .iter()
17 .zip(point.data)
18 .all(|(interval, value)| interval.contains(value))
19 }
20}
21
22#[repr(C)]
23#[derive(Debug, Clone, Copy, PartialEq)]
24pub struct TransitionEvidence {
25 pub samples_checked: usize,
26 pub maximum_round_trip_error: f64,
27 pub tolerance: f64,
28}
29
30pub fn verify_transition<const N: usize, F, G>(
32 source: &Chart<N>,
33 target: &Chart<N>,
34 samples: &[Vector<N>],
35 forward: F,
36 inverse: G,
37 tolerance: f64,
38) -> Result<TransitionEvidence, AnalysisError>
39where
40 F: Fn(Vector<N>) -> Vector<N>,
41 G: Fn(Vector<N>) -> Vector<N>,
42{
43 if samples.is_empty() || !tolerance.is_finite() || tolerance <= 0.0 {
44 return Err(AnalysisError::InvalidDomain);
45 }
46 let mut maximum_error = 0.0_f64;
47 for sample in samples {
48 if !source.contains(*sample) {
49 return Err(AnalysisError::InvalidDomain);
50 }
51 let mapped = forward(*sample);
52 mapped.validate()?;
53 if !target.contains(mapped) {
54 return Err(AnalysisError::InvalidDomain);
55 }
56 let recovered = inverse(mapped);
57 let error = recovered.distance(*sample)?;
58 maximum_error = maximum_error.max(error);
59 }
60 if maximum_error > tolerance {
61 return Err(AnalysisError::NotCertified);
62 }
63 Ok(TransitionEvidence {
64 samples_checked: samples.len(),
65 maximum_round_trip_error: maximum_error,
66 tolerance,
67 })
68}
69
70#[repr(C)]
71#[derive(Debug, Clone, Copy, PartialEq)]
72pub struct RiemannMetric<const N: usize> {
73 pub coefficients: LinearMap<N, N>,
74}
75
76impl<const N: usize> RiemannMetric<N> {
77 pub fn new(coefficients: LinearMap<N, N>) -> Result<Self, AnalysisError> {
79 coefficients.validate()?;
80 for row in 0..N {
81 for column in 0..N {
82 let scale = coefficients.coefficients[row][column]
83 .abs()
84 .max(coefficients.coefficients[column][row].abs())
85 .max(1.0);
86 if (coefficients.coefficients[row][column] - coefficients.coefficients[column][row])
87 .abs()
88 > 32.0 * f64::EPSILON * scale
89 {
90 return Err(AnalysisError::InvalidDomain);
91 }
92 }
93 }
94 for order in 1..=N {
96 let mut block = [[0.0; N]; N];
97 for row in 0..order {
98 for column in 0..order {
99 block[row][column] = coefficients.coefficients[row][column];
100 }
101 }
102 for index in order..N {
105 block[index][index] = 1.0;
106 }
107 if LinearMap::new(block).determinant()? <= 0.0 {
108 return Err(AnalysisError::InvalidDomain);
109 }
110 }
111 Ok(Self { coefficients })
112 }
113
114 pub fn lower(&self, tangent: Vector<N>) -> Result<Vector<N>, AnalysisError> {
116 self.coefficients.apply(tangent)
117 }
118
119 pub fn raise(&self, covector: Vector<N>) -> Result<Vector<N>, AnalysisError> {
121 self.coefficients.solve(covector)
122 }
123
124 pub fn inner(&self, left: Vector<N>, right: Vector<N>) -> Result<f64, AnalysisError> {
126 left.dot(self.lower(right)?)
127 }
128
129 pub fn volume_density(&self) -> Result<f64, AnalysisError> {
131 Ok(self.coefficients.determinant()?.sqrt())
132 }
133}
134
135pub fn orientation_sign<const N: usize>(
137 transition_derivative: &LinearMap<N, N>,
138) -> Result<i8, AnalysisError> {
139 let determinant = transition_derivative.determinant()?;
140 if determinant > 0.0 {
141 Ok(1)
142 } else if determinant < 0.0 {
143 Ok(-1)
144 } else {
145 Err(AnalysisError::Singular)
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152
153 #[test]
154 fn chart_transition_round_trip_is_certified() {
155 let domain = [
156 Interval::new(-10.0, 10.0).unwrap(),
157 Interval::new(-10.0, 10.0).unwrap(),
158 ];
159 let source = Chart {
160 chart_id: 1,
161 coordinate_domain: domain,
162 };
163 let target = Chart {
164 chart_id: 2,
165 coordinate_domain: domain,
166 };
167 let samples = [
168 Vector::new([0.0, 0.0]),
169 Vector::new([1.0, -2.0]),
170 Vector::new([-3.0, 4.0]),
171 ];
172 let evidence = verify_transition(
173 &source,
174 &target,
175 &samples,
176 |x| Vector::new([x.data[0] + x.data[1], x.data[0] - x.data[1]]),
177 |y| Vector::new([0.5 * (y.data[0] + y.data[1]), 0.5 * (y.data[0] - y.data[1])]),
178 1e-14,
179 )
180 .unwrap();
181 assert_eq!(evidence.samples_checked, 3);
182 }
183
184 #[test]
185 fn musical_maps_and_volume_density_are_consistent() {
186 let metric = RiemannMetric::new(LinearMap::new([[4.0, 1.0], [1.0, 3.0]])).unwrap();
187 let vector = Vector::new([2.0, -1.0]);
188 let covector = metric.lower(vector).unwrap();
189 let recovered = metric.raise(covector).unwrap();
190 assert!(recovered.distance(vector).unwrap() < 1e-14);
191 assert!((metric.volume_density().unwrap() - 11.0_f64.sqrt()).abs() < 1e-14);
192 assert_eq!(
193 orientation_sign(&LinearMap::new([[0.0, 1.0], [1.0, 0.0]])),
194 Ok(-1)
195 );
196 }
197}