deep_causality_physics 0.6.2

Standard library of physics formulas and engineering primitives for DeepCausality.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/*
 * SPDX-License-Identifier: MIT
 * Copyright (c) 2023 - 2026. The DeepCausality Authors and Contributors. All Rights Reserved.
 */

// =============================================================================
// GrOps Implementation for GR (GaugeField<Lorentz, f64, f64>)
// =============================================================================

use crate::theories::general_relativity::gr_lie_mapping::expand_lie_to_riemann;
use crate::theories::general_relativity::gr_utils;
use crate::{
    GR, GeodesicState, GrOps, PhysicsError, geodesic_integrator_kernel, parallel_transport_kernel,
    proper_time_kernel,
};
use deep_causality_haft::RiemannMap;
use deep_causality_metric::{EastCoastMetric, LorentzianMetric};
use deep_causality_num::{Field, Float};
use deep_causality_tensor::CausalTensor;
use deep_causality_topology::GaugeFieldWitness;
use deep_causality_topology::{
    CurvatureSymmetry, CurvatureTensor, CurvatureTensorVector, CurvatureTensorWitness, TensorVector,
};

impl<S> GrOps<S> for GR<S>
where
    S: Field + Float + Clone + From<f64> + Into<f64> + Copy + deep_causality_num::RealField,
{
    fn ricci_tensor(&self) -> Result<CausalTensor<S>, PhysicsError> {
        let lie_fs = self.field_strength();
        let dim = 4;

        // Use East Coast metric type info (structure only)
        let metric_sig = EastCoastMetric::minkowski_4d().into_metric();

        // Expand Lie-algebra storage [points, 4, 4, 6] to geometric [4, 4, 4, 4]
        let riemann = expand_lie_to_riemann(lie_fs)?;

        let ct = CurvatureTensor::<S, (), (), (), ()>::new(
            riemann,
            metric_sig,
            CurvatureSymmetry::Riemann,
            dim,
        );

        let ricci_data = ct.ricci_tensor();
        Ok(CausalTensor::from_vec(ricci_data, &[dim, dim]))
    }

    fn ricci_scalar(&self) -> Result<S, PhysicsError> {
        // Use CurvatureTensor for the complex Riemann->Ricci contraction
        let ricci = self.ricci_tensor()?;
        let ricci_data = ricci.as_slice();

        // Use the metric from the field for the scalar contraction
        let metric = self.metric_tensor();
        let dim = 4;

        // Full 4x4 Matrix Inversion
        let inv_metric = gr_utils::invert_4x4(metric)?;

        let mut scalar = S::zero();
        // R = g^μν R_μν
        for mu in 0..dim {
            for nu in 0..dim {
                // Flattened index [mu, nu]
                let idx = mu * dim + nu;
                let g_upper = inv_metric[idx];
                let r_lower = ricci_data.get(idx).copied().unwrap_or(S::zero());
                scalar += g_upper * r_lower;
            }
        }

        Ok(scalar)
    }

    fn einstein_tensor(&self) -> Result<CausalTensor<S>, PhysicsError> {
        // Use CurvatureTensor from topology for the Einstein tensor calculation
        let lie_fs = self.field_strength();
        let dim = 4;
        let metric_sig = EastCoastMetric::minkowski_4d().into_metric();

        // Expand Lie-algebra storage [points, 4, 4, 6] to geometric [4, 4, 4, 4]
        let riemann = expand_lie_to_riemann(lie_fs)?;

        let ct = CurvatureTensor::<S, (), (), (), ()>::new(
            riemann,
            metric_sig,
            CurvatureSymmetry::Riemann,
            dim,
        );

        // Use topology's einstein_tensor method
        let einstein_data = ct.einstein_tensor();
        Ok(CausalTensor::from_vec(einstein_data, &[dim, dim]))
    }

    fn kretschmann_scalar(&self) -> Result<S, PhysicsError> {
        let lie_fs = self.field_strength();
        let dim = 4;
        let metric_sig = EastCoastMetric::minkowski_4d().into_metric();

        // Expand Lie-algebra storage [points, 4, 4, 6] to geometric [4, 4, 4, 4]
        let riemann = expand_lie_to_riemann(lie_fs)?;

        // Get Inverse Metric for index raising
        let metric = self.metric_tensor();
        let inv_g = gr_utils::invert_4x4(metric)?;

        // Create CurvatureTensor and use topology's kretschmann_scalar_with_metric
        let ct = CurvatureTensor::<S, (), (), (), ()>::new(
            riemann,
            metric_sig,
            CurvatureSymmetry::Riemann,
            dim,
        );

        // Use topology method with the precomputed inverse metric
        Ok(ct.kretschmann_scalar_with_metric(&inv_g))
    }

    fn geodesic_deviation(&self, velocity: &[S], separation: &[S]) -> Result<Vec<S>, PhysicsError> {
        let lie_fs = self.field_strength();
        let dim = 4;
        let metric_sig = EastCoastMetric::minkowski_4d().into_metric();

        // Expand Lie storage to geometric for CurvatureTensor
        let riemann = expand_lie_to_riemann(lie_fs)?;

        // Use TensorVector for HKT safety contract
        let u = TensorVector::new(velocity);
        let v = TensorVector::new(separation);
        let u_w = u.clone();

        // Construct CurvatureTensorVector for HKT witness with geometric Riemann
        let ct =
            CurvatureTensorVector::<S>::new(riemann, metric_sig, CurvatureSymmetry::Riemann, dim);

        // Use RiemannMap HKT trait via witness type
        // D^2 ξ / dτ^2 = R(u, ξ)u
        let result_vector = CurvatureTensorWitness::curvature(ct, u, v, u_w);
        Ok(result_vector.into())
    }

    fn solve_geodesic(
        &self,
        initial_position: &[S],
        initial_velocity: &[S],
        proper_time_step: S,
        num_steps: usize,
    ) -> Result<Vec<GeodesicState<S>>, PhysicsError> {
        geodesic_integrator_kernel(
            initial_position,
            initial_velocity,
            self.connection(),
            proper_time_step,
            num_steps,
        )
    }

    fn proper_time(&self, path: &[Vec<S>]) -> Result<S, PhysicsError> {
        proper_time_kernel(path, self.metric_tensor())
    }

    fn parallel_transport(
        &self,
        initial_vector: &[S],
        path: &[Vec<S>],
    ) -> Result<Vec<S>, PhysicsError> {
        parallel_transport_kernel(initial_vector, path, self.connection())
    }

    fn metric_tensor(&self) -> &CausalTensor<S> {
        self.connection()
    }

    fn compute_riemann_from_christoffel(&self) -> CausalTensor<S> {
        // The coupling constant for GR is effectively 1.0
        // (structure constants encode the non-abelian part)
        GaugeFieldWitness::compute_field_strength_non_abelian(self, S::one())
    }

    fn momentum_constraint_field(
        &self,
        extrinsic_curvature: &CausalTensor<S>,
        matter_momentum: Option<&CausalTensor<S>>,
    ) -> Result<CausalTensor<S>, PhysicsError> {
        // =========================================================================
        // ADM Momentum Constraint: M_i = D_j(K^j_i - δ^j_i K) - 8πj_i
        // =========================================================================

        // -------------------------------------------------------------------------
        // 1. INPUT VALIDATION
        // -------------------------------------------------------------------------
        let k_shape = extrinsic_curvature.shape();

        // Validate K_ij tensor shape: [N, 3, 3] or [3, 3]
        let (num_points, is_batched) = match k_shape.len() {
            2 => {
                if k_shape[0] != 3 || k_shape[1] != 3 {
                    return Err(PhysicsError::DimensionMismatch(format!(
                        "Expected K_ij shape [3, 3], got {:?}",
                        k_shape
                    )));
                }
                (1, false)
            }
            3 => {
                if k_shape[1] != 3 || k_shape[2] != 3 {
                    return Err(PhysicsError::DimensionMismatch(format!(
                        "Expected K_ij shape [N, 3, 3], got {:?}",
                        k_shape
                    )));
                }
                (k_shape[0], true)
            }
            _ => {
                return Err(PhysicsError::DimensionMismatch(format!(
                    "K_ij must be 2D [3,3] or 3D [N,3,3], got {:?}",
                    k_shape
                )));
            }
        };

        // Validate matter momentum if provided
        if let Some(j) = matter_momentum {
            let expected_size = num_points * 3;
            if j.as_slice().len() != expected_size {
                return Err(PhysicsError::DimensionMismatch(format!(
                    "Matter momentum j_i size mismatch: expected {}, got {}",
                    expected_size,
                    j.as_slice().len()
                )));
            }
        }

        let k_data = extrinsic_curvature.as_slice();

        // -------------------------------------------------------------------------
        // 2. EXTRACT SPATIAL 3-METRIC FROM 4D METRIC
        // -------------------------------------------------------------------------
        // The 4D metric g_μν is stored in self.connection() (semantic overload).
        // In ADM form: ds² = -α²dt² + γ_ij(dx^i + β^i dt)(dx^j + β^j dt)
        // For the spatial slice: γ_ij = g_ij (i,j ∈ {1,2,3} → indices 1,2,3 of 4D metric)

        let metric_4d = self.connection().as_slice();
        let metric_shape = self.connection().shape();

        // Determine metric stride based on storage format
        let metric_stride = if metric_shape.len() >= 2 {
            metric_shape[metric_shape.len() - 2] * metric_shape[metric_shape.len() - 1]
        } else {
            16 // Fallback: 4x4 metric
        };

        // Helper: Extract γ_ij (3x3 spatial metric) from g_μν
        let extract_spatial_metric = |p: usize| -> [[S; 3]; 3] {
            let base = p * metric_stride;

            // If metric is 4x4 (stride=16), extract spatial components g_{i+1,j+1}
            if metric_stride >= 16 {
                let mut gamma = [[S::zero(); 3]; 3];
                for (i, row) in gamma.iter_mut().enumerate() {
                    for (j, val) in row.iter_mut().enumerate() {
                        let idx = base + (i + 1) * 4 + (j + 1);
                        *val = metric_4d.get(idx).copied().unwrap_or(if i == j {
                            S::one()
                        } else {
                            S::zero()
                        });
                    }
                }
                gamma
            } else {
                // Fallback: identity metric (flat space)
                [
                    [S::one(), S::zero(), S::zero()],
                    [S::zero(), S::one(), S::zero()],
                    [S::zero(), S::zero(), S::one()],
                ]
            }
        };

        // -------------------------------------------------------------------------
        // 3. COMPUTE COVARIANT DIVERGENCE USING MANIFOLD TOPOLOGY
        // -------------------------------------------------------------------------
        // D_j T^j_i = ∂_j T^j_i + Γ^j_jk T^k_i - Γ^k_ji T^j_k

        let base_manifold = self.base();
        let complex = base_manifold.complex();

        // Allocate result: M_i for each point
        let mut result = vec![S::zero(); num_points * 3];

        for p in 0..num_points {
            let k_offset = if is_batched { p * 9 } else { 0 };

            // Extract spatial metric and its inverse at this point
            let gamma = extract_spatial_metric(p);
            let gamma_inv = gr_utils::invert_3x3(gamma)?;

            // Compute trace K = γ^ij K_ij
            let mut k_trace = S::zero();
            for (i, row) in gamma_inv.iter().enumerate() {
                for (j, &g_inv_ij) in row.iter().enumerate() {
                    let k_ij = k_data
                        .get(k_offset + i * 3 + j)
                        .copied()
                        .unwrap_or(S::zero());
                    k_trace += g_inv_ij * k_ij;
                }
            }

            // Compute mixed tensor K^j_i = γ^jk K_ki
            let mut k_mixed = [[S::zero(); 3]; 3];
            for (j, row) in k_mixed.iter_mut().enumerate() {
                for (i, val) in row.iter_mut().enumerate() {
                    for (k, &g_inv_jk) in gamma_inv[j].iter().enumerate() {
                        let k_ki = k_data
                            .get(k_offset + k * 3 + i)
                            .copied()
                            .unwrap_or(S::zero());
                        *val += g_inv_jk * k_ki;
                    }
                }
            }

            // Compute T^j_i = K^j_i - δ^j_i K
            let mut t_tensor = [[S::zero(); 3]; 3];
            for j in 0..3 {
                for i in 0..3 {
                    let delta = if i == j { S::one() } else { S::zero() };
                    t_tensor[j][i] = k_mixed[j][i] - delta * k_trace;
                }
            }

            // Get neighbor indices from manifold topology
            let neighbors: Vec<usize> = complex.skeletons()[0]
                .simplices()
                .iter()
                .enumerate()
                .filter(|(idx, _)| *idx != p && *idx < num_points)
                .take(6)
                .map(|(idx, _)| idx)
                .collect();

            // Compute spatial Christoffel symbols Γ^k_ij from metric derivatives
            let mut christoffel = [[[S::zero(); 3]; 3]; 3];

            if !neighbors.is_empty() {
                for n_idx in &neighbors {
                    let gamma_n = extract_spatial_metric(*n_idx);
                    let weight = S::one() / <S as From<f64>>::from(neighbors.len() as f64);
                    let half = <S as From<f64>>::from(0.5);

                    for k in 0..3 {
                        for i in 0..3 {
                            for j in 0..3 {
                                for l in 0..3 {
                                    let d_gamma_jl = (gamma_n[j][l] - gamma[j][l]) * weight;
                                    let d_gamma_il = (gamma_n[i][l] - gamma[i][l]) * weight;
                                    let d_gamma_ij = (gamma_n[i][j] - gamma[i][j]) * weight;

                                    christoffel[k][i][j] += half
                                        * gamma_inv[k][l]
                                        * (d_gamma_jl + d_gamma_il - d_gamma_ij);
                                }
                            }
                        }
                    }
                }
            }

            // Compute ∂_j T^j_i using finite differences with neighbors
            let mut partial_div = [S::zero(); 3];

            if !neighbors.is_empty() {
                for n_idx in &neighbors {
                    let n_k_offset = if is_batched { n_idx * 9 } else { 0 };
                    let gamma_n = extract_spatial_metric(*n_idx);
                    let gamma_n_inv = gr_utils::invert_3x3(gamma_n)?;

                    // Compute T^j_i at neighbor
                    let mut k_trace_n = S::zero();
                    for (i, row) in gamma_n_inv.iter().enumerate() {
                        for (j, &g_n_inv_ij) in row.iter().enumerate() {
                            let k_ij = k_data
                                .get(n_k_offset + i * 3 + j)
                                .copied()
                                .unwrap_or(S::zero());
                            k_trace_n += g_n_inv_ij * k_ij;
                        }
                    }

                    let mut k_mixed_n = [[S::zero(); 3]; 3];
                    for (j, row) in k_mixed_n.iter_mut().enumerate() {
                        for (i, val) in row.iter_mut().enumerate() {
                            for (k, &g_n_inv_jk) in gamma_n_inv[j].iter().enumerate() {
                                let k_ki = k_data
                                    .get(n_k_offset + k * 3 + i)
                                    .copied()
                                    .unwrap_or(S::zero());
                                *val += g_n_inv_jk * k_ki;
                            }
                        }
                    }

                    let mut t_n = [[S::zero(); 3]; 3];
                    for j in 0..3 {
                        for i in 0..3 {
                            let delta = if i == j { S::one() } else { S::zero() };
                            t_n[j][i] = k_mixed_n[j][i] - delta * k_trace_n;
                        }
                    }

                    let weight = S::one() / <S as From<f64>>::from(neighbors.len() as f64);
                    for i in 0..3 {
                        for j in 0..3 {
                            partial_div[i] += (t_n[j][i] - t_tensor[j][i]) * weight;
                        }
                    }
                }
            }

            // Compute connection terms: Γ^j_jk T^k_i - Γ^k_ji T^j_k
            let mut connection_term = [S::zero(); 3];
            for i in 0..3 {
                for j in 0..3 {
                    for k in 0..3 {
                        connection_term[i] += christoffel[j][j][k] * t_tensor[k][i];
                        connection_term[i] -= christoffel[k][j][i] * t_tensor[j][k];
                    }
                }
            }

            // -------------------------------------------------------------------------
            // 4. ASSEMBLE MOMENTUM CONSTRAINT
            // -------------------------------------------------------------------------
            let eight_pi = <S as From<f64>>::from(8.0 * std::f64::consts::PI);

            for i in 0..3 {
                let j_i = match matter_momentum {
                    Some(j) => j.as_slice().get(p * 3 + i).copied().unwrap_or(S::zero()),
                    None => S::zero(),
                };

                result[p * 3 + i] = partial_div[i] + connection_term[i] - eight_pi * j_i;
            }
        }

        let output_shape = if is_batched {
            vec![num_points, 3]
        } else {
            vec![3]
        };
        Ok(CausalTensor::from_vec(result, &output_shape))
    }
}