qualia_core_db/solvers/calculus/
exterior.rs1use super::analysis::{AnalysisError, LinearMap, Vector};
4
5pub const EXTERIOR3_COMPONENTS: usize = 8;
6
7#[repr(C)]
8#[derive(Debug, Clone, Copy, PartialEq)]
9pub struct Exterior3 {
10 pub coefficients: [f64; EXTERIOR3_COMPONENTS],
12}
13
14impl Exterior3 {
15 pub const fn zero() -> Self {
17 Self {
18 coefficients: [0.0; EXTERIOR3_COMPONENTS],
19 }
20 }
21
22 pub const fn scalar(value: f64) -> Self {
24 let mut coefficients = [0.0; EXTERIOR3_COMPONENTS];
25 coefficients[0] = value;
26 Self { coefficients }
27 }
28
29 pub const fn basis(mask: usize, value: f64) -> Self {
31 let mut coefficients = [0.0; EXTERIOR3_COMPONENTS];
32 if mask < EXTERIOR3_COMPONENTS {
33 coefficients[mask] = value;
34 }
35 Self { coefficients }
36 }
37
38 pub fn validate(&self) -> Result<(), AnalysisError> {
40 if self.coefficients.iter().all(|value| value.is_finite()) {
41 Ok(())
42 } else {
43 Err(AnalysisError::NonFinite)
44 }
45 }
46
47 pub fn grade(self, grade: u32) -> Self {
49 let mut result = Self::zero();
50 for mask in 0..EXTERIOR3_COMPONENTS {
51 if mask.count_ones() == grade {
52 result.coefficients[mask] = self.coefficients[mask];
53 }
54 }
55 result
56 }
57
58 pub fn add(self, other: Self) -> Self {
60 let mut result = Self::zero();
61 for mask in 0..EXTERIOR3_COMPONENTS {
62 result.coefficients[mask] = self.coefficients[mask] + other.coefficients[mask];
63 }
64 result
65 }
66
67 pub fn scale(self, scalar: f64) -> Result<Self, AnalysisError> {
69 if !scalar.is_finite() {
70 return Err(AnalysisError::NonFinite);
71 }
72 let mut result = self;
73 for value in &mut result.coefficients {
74 *value *= scalar;
75 }
76 Ok(result)
77 }
78
79 pub fn wedge(self, other: Self) -> Result<Self, AnalysisError> {
81 self.validate()?;
82 other.validate()?;
83 let mut result = Self::zero();
84 for left in 0..EXTERIOR3_COMPONENTS {
85 for right in 0..EXTERIOR3_COMPONENTS {
86 if left & right != 0 {
87 continue;
88 }
89 let (mask, sign) = wedge_basis(left, right);
90 result.coefficients[mask] +=
91 sign * self.coefficients[left] * other.coefficients[right];
92 }
93 }
94 Ok(result)
95 }
96
97 pub fn interior(self, vector: Vector<3>) -> Result<Self, AnalysisError> {
99 self.validate()?;
100 vector.validate()?;
101 let mut result = Self::zero();
102 for mask in 0..EXTERIOR3_COMPONENTS {
103 let coefficient = self.coefficients[mask];
104 for axis in 0..3 {
105 let bit = 1usize << axis;
106 if mask & bit == 0 {
107 continue;
108 }
109 let lower = (mask & (bit - 1)).count_ones();
110 let sign = if lower & 1 == 0 { 1.0 } else { -1.0 };
111 result.coefficients[mask ^ bit] += sign * vector.data[axis] * coefficient;
112 }
113 }
114 Ok(result)
115 }
116
117 pub fn hodge_star(self) -> Result<Self, AnalysisError> {
119 self.validate()?;
120 let mut result = Self::zero();
121 for mask in 0..EXTERIOR3_COMPONENTS {
122 let complement = 0b111 ^ mask;
123 let (_, sign) = wedge_basis(mask, complement);
124 result.coefficients[complement] += sign * self.coefficients[mask];
125 }
126 Ok(result)
127 }
128}
129
130fn wedge_basis(left: usize, right: usize) -> (usize, f64) {
131 let mut inversions = 0_u32;
132 for left_axis in 0..3 {
133 if left & (1 << left_axis) == 0 {
134 continue;
135 }
136 inversions += (right & ((1 << left_axis) - 1)).count_ones();
137 }
138 (left | right, if inversions & 1 == 0 { 1.0 } else { -1.0 })
139}
140
141pub fn permutation_parity(permutation: &[usize]) -> Result<i8, AnalysisError> {
143 for (index, value) in permutation.iter().enumerate() {
144 if *value >= permutation.len()
145 || permutation[index + 1..].iter().any(|other| other == value)
146 {
147 return Err(AnalysisError::InvalidDomain);
148 }
149 }
150 let mut inversions = 0usize;
151 for left in 0..permutation.len() {
152 for right in left + 1..permutation.len() {
153 inversions += usize::from(permutation[left] > permutation[right]);
154 }
155 }
156 Ok(if inversions & 1 == 0 { 1 } else { -1 })
157}
158
159pub fn determinant_from_wedge(columns: [Vector<3>; 3]) -> Result<f64, AnalysisError> {
161 let mut forms = [Exterior3::zero(); 3];
162 for column in 0..3 {
163 for row in 0..3 {
164 forms[column].coefficients[1 << row] = columns[column].data[row];
165 }
166 }
167 Ok(forms[0].wedge(forms[1])?.wedge(forms[2])?.coefficients[0b111])
168}
169
170pub fn pullback_one_form(
172 derivative: &LinearMap<3, 3>,
173 one_form: Vector<3>,
174) -> Result<Vector<3>, AnalysisError> {
175 derivative.transpose().apply(one_form)
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181
182 #[test]
183 fn wedge_is_graded_commutative_and_associative() {
184 let e1 = Exterior3::basis(0b001, 1.0);
185 let e2 = Exterior3::basis(0b010, 1.0);
186 let e3 = Exterior3::basis(0b100, 1.0);
187 assert_eq!(e1.wedge(e1).unwrap(), Exterior3::zero());
188 assert_eq!(
189 e1.wedge(e2).unwrap(),
190 e2.wedge(e1).unwrap().scale(-1.0).unwrap()
191 );
192 assert_eq!(
193 e1.wedge(e2).unwrap().wedge(e3).unwrap(),
194 e1.wedge(e2.wedge(e3).unwrap()).unwrap()
195 );
196 }
197
198 #[test]
199 fn determinant_and_hodge_identities_hold() {
200 let columns = [
201 Vector::new([2.0, 0.0, 0.0]),
202 Vector::new([1.0, 3.0, 0.0]),
203 Vector::new([0.0, 2.0, 4.0]),
204 ];
205 assert_eq!(determinant_from_wedge(columns).unwrap(), 24.0);
206
207 for mask in 0..8 {
208 let blade = Exterior3::basis(mask, 1.0);
209 let twice = blade.hodge_star().unwrap().hodge_star().unwrap();
210 let grade = mask.count_ones();
211 let sign = if (grade * (3 - grade)) & 1 == 0 {
212 1.0
213 } else {
214 -1.0
215 };
216 assert_eq!(twice, blade.scale(sign).unwrap());
217 }
218 }
219
220 #[test]
221 fn permutation_and_pullback_are_correct() {
222 assert_eq!(permutation_parity(&[2, 0, 1]), Ok(1));
223 assert_eq!(permutation_parity(&[1, 0, 2]), Ok(-1));
224 assert_eq!(
225 permutation_parity(&[0, 0, 1]),
226 Err(AnalysisError::InvalidDomain)
227 );
228
229 let derivative = LinearMap::new([[2.0, 0.0, 0.0], [1.0, 3.0, 0.0], [0.0, 0.0, 4.0]]);
230 let pulled = pullback_one_form(&derivative, Vector::new([1.0, 2.0, 3.0])).unwrap();
231 assert_eq!(pulled, Vector::new([4.0, 6.0, 12.0]));
232 }
233}