amari_relativistic/lib.rs
1//! # Amari Relativistic Physics Library
2//!
3//! A comprehensive Rust library for relativistic physics simulations using geometric algebra,
4//! designed for charged particle simulations and plasma physics applications involving
5//! particle trajectories through curved spacetime.
6//!
7//! ## Overview
8//!
9//! This crate leverages the geometric algebra (Clifford algebra) framework from `amari-core`
10//! to provide a mathematically rigorous foundation for relativistic physics calculations.
11//! It implements spacetime algebra (STA) for four-dimensional spacetime, geodesic integration
12//! for curved spacetime, and relativistic particle dynamics.
13//!
14//! ## Key Features
15//!
16//! - **Spacetime Algebra**: Four-vectors, Lorentz transformations using geometric algebra
17//! - **Geodesic Integration**: Numerical integration of Einstein's geodesic equation
18//! - **Schwarzschild Metric**: Spacetime around spherically symmetric masses
19//! - **Relativistic Particles**: Energy-momentum relations, proper time evolution
20//! - **Charged Particle Applications**: Ion beam trajectories, particle deflection
21//!
22//! ## Mathematical Foundation
23//!
24//! The library is built on spacetime algebra Cl(1,3) with signature (+---):
25//! - γ₀² = +1 (timelike basis vector)
26//! - γ₁², γ₂², γ₃² = -1 (spacelike basis vectors)
27//! - Four-vectors: X = ctγ₀ + xγ₁ + yγ₂ + zγ₃
28//! - Minkowski inner product: X·Y = X₀Y₀ - X₁Y₁ - X₂Y₂ - X₃Y₃
29//!
30//! ## Example Usage
31//!
32//! ### Basic Charged Particle Trajectory Simulation
33//!
34//! ```rust
35//! use amari_relativistic::*;
36//! use nalgebra::Vector3;
37//!
38//! // Create gravitational field from massive object
39//! let massive_object = schwarzschild::SchwarzschildMetric::sun();
40//! let mut integrator = geodesic::GeodesicIntegrator::with_metric(Box::new(massive_object));
41//!
42//! // Create 100 keV iron ion in strong gravitational field
43//! let position = Vector3::new(2e11, 0.0, 0.0); // Distance from center
44//! let direction = Vector3::new(-1.0, 0.0, 0.1); // Initial trajectory
45//! let mut ion = particle::RelativisticParticle::with_energy(
46//! position,
47//! direction,
48//! 100e3 * constants::E_CHARGE, // 100 keV
49//! 55.845 * constants::AMU, // Iron mass
50//! constants::E_CHARGE, // Singly ionized
51//! )?;
52//!
53//! // Propagate through gravitational field
54//! let trajectory = particle::propagate_relativistic(
55//! &mut ion,
56//! &mut integrator,
57//! 30.0 * 86400.0, // Integration time
58//! 100.0, // Time step size
59//! )?;
60//!
61//! println!("Final position: {:?}", ion.position_3d());
62//! println!("Deflection: {:.2e} m",
63//! trajectory.last().unwrap().1.magnitude() - position.magnitude());
64//! # Ok::<(), Box<dyn std::error::Error>>(())
65//! ```
66//!
67//! ### Light Deflection by Massive Objects
68//!
69//! ```rust
70//! use amari_relativistic::*;
71//!
72//! // Calculate light deflection for photon grazing massive object surface
73//! let object_radius = 6.957e8; // meters
74//! let deflection_angle = particle::light_deflection_angle(
75//! object_radius,
76//! constants::SOLAR_MASS
77//! );
78//!
79//! // Convert to arcseconds
80//! let arcseconds = deflection_angle * 180.0 * 3600.0 / std::f64::consts::PI;
81//! println!("Light deflection: {:.2} arcseconds", arcseconds);
82//! // Expected: ~1.75 arcseconds (Einstein's prediction)
83//! ```
84//!
85//! ### Four-Velocity and Spacetime Intervals
86//!
87//! ```rust
88//! use amari_relativistic::spacetime::*;
89//! use amari_relativistic::constants;
90//! use nalgebra::Vector3;
91//!
92//! // Create relativistic four-velocity
93//! let velocity = Vector3::new(0.8 * constants::C, 0.0, 0.0); // 0.8c
94//! let four_vel = FourVelocity::from_velocity(velocity);
95//!
96//! println!("Lorentz factor γ = {:.3}", four_vel.gamma());
97//! println!("Rapidity φ = {:.3}", four_vel.rapidity());
98//!
99//! // Spacetime interval between events
100//! let event1 = SpacetimeVector::new(0.0, 0.0, 0.0, 0.0);
101//! let event2 = SpacetimeVector::new(1.0, 0.5 * constants::C, 0.0, 0.0);
102//! let interval = event1.minkowski_dot(&event2);
103//!
104//! if interval > 0.0 {
105//! println!("Timelike separation: Δτ = {:.6} s",
106//! interval.sqrt() / constants::C);
107//! }
108//! ```
109//!
110//! ### High-Precision Arithmetic for Spacecraft Orbital Mechanics
111//!
112//! When precision is critical for spacecraft missions, use high-precision arithmetic:
113//!
114//! ```rust
115//! use amari_relativistic::prelude::*;
116//! use amari_relativistic::precision::*;
117//! use amari_relativistic::precision_geodesic::*;
118//! use amari_relativistic::constants;
119//! use num_traits::float::FloatConst;
120//!
121//! // High-precision orbital parameter calculation
122//! let semi_major_axis = StandardFloat::from_f64(7000e3); // 7000 km
123//! let eccentricity = StandardFloat::from_f64(0.01);
124//! let mu = constants::precision::g::<StandardFloat>() * constants::precision::earth_mass::<StandardFloat>();
125//!
126//! // Orbital period with high precision
127//! let period = StandardFloat::from_f64(2.0) * <StandardFloat as PrecisionFloat>::PI() *
128//! (semi_major_axis.powf_precise(StandardFloat::from_f64(3.0)) / mu).sqrt_precise();
129//!
130//! // Precision spacetime vector for spacecraft position
131//! let spacecraft_pos = PrecisionSpacetimeVector::<StandardFloat>::new(
132//! StandardFloat::from_f64(0.0),
133//! StandardFloat::from_f64(7000e3),
134//! StandardFloat::from_f64(0.0),
135//! StandardFloat::from_f64(0.0)
136//! );
137//!
138//! println!("Orbital period: {:.12} s", period.to_f64());
139//! println!("Spacecraft tolerance: {:.2e}", StandardFloat::orbital_tolerance().to_f64());
140//! ```
141//!
142//! ### Compile-Time Verification with Phantom Types
143//!
144//! When the `phantom-types` feature is enabled (default), you get compile-time guarantees:
145//!
146//! ```rust
147//! # #[cfg(feature = "phantom-types")] {
148//! use amari_relativistic::prelude::*;
149//!
150//! // Verified spacetime vector with compile-time signature guarantees
151//! let position = VerifiedSpacetimeVector::new(0.0, Vector3::zeros());
152//! let velocity = Vector3::new(0.6 * C, 0.0, 0.0);
153//!
154//! // Four-velocity is automatically normalized and verified at creation
155//! let four_vel = VerifiedFourVelocity::from_velocity(velocity)?;
156//! assert!(four_vel.is_normalized()); // Guaranteed by phantom types
157//!
158//! // Particles must satisfy energy-momentum relation E² = (pc)² + (mc²)²
159//! let particle = VerifiedRelativisticParticle::new(
160//! position, four_vel, 9.109e-31, -1.602e-19
161//! )?;
162//! assert!(particle.satisfies_energy_momentum_relation()); // Type-guaranteed
163//! # }
164//! # Ok::<(), Box<dyn std::error::Error>>(())
165//! ```
166//!
167//! ### Formal Verification with Creusot Contracts
168//!
169//! With the `formal-verification` feature on nightly Rust:
170//!
171//! ```rust,ignore
172//! use amari_relativistic::prelude::*;
173//!
174//! // Functions with mathematical guarantees proven at compile time
175//! let boosted = verified_lorentz_boost(&vector, boost_velocity);
176//! // Guaranteed: Minkowski norm preserved by Lorentz transformation
177//!
178//! let collision_valid = verified_collision(&p1, &p2, &p3, &p4);
179//! // Guaranteed: Energy and momentum conservation in particle collisions
180//! ```
181//!
182//! ## Application Domains
183//!
184//! ### Charged Particle Simulations
185//! - Ion beam focusing and deflection
186//! - Particle accelerator beam dynamics
187//! - Plasma physics particle trajectories
188//! - Industrial ion implantation processes
189//!
190//! ### Astrophysics
191//! - Planetary motion around compact objects
192//! - Photon trajectories near black holes
193//! - Gravitational lensing calculations
194//! - Tidal effects and frame dragging
195//!
196//! ### Fundamental Physics
197//! - Tests of general relativity
198//! - Precision orbit determination
199//! - Relativistic corrections to classical mechanics
200//! - Coordinate transformation verification
201//!
202//! ## Performance Considerations
203//!
204//! - Uses `#[inline]` for hot path functions
205//! - Leverages SIMD through `amari-core` geometric algebra
206//! - Symplectic integrators preserve energy conservation
207//! - Adaptive step sizing for numerical stability
208//!
209//! ## Integration with Amari Ecosystem
210//!
211//! This crate builds upon:
212//! - [`amari-core`]: Geometric algebra operations and multivectors
213//! - [`amari-gpu`]: GPU acceleration for large-scale simulations
214//! - [`amari-dual`]: Automatic differentiation for optimization
215//! - [`amari-info-geom`]: Information geometry for parameter estimation
216//!
217//! ## References
218//!
219//! - Misner, Thorne & Wheeler, "Gravitation" (1973)
220//! - Doran & Lasenby, "Geometric Algebra for Physicists" (2003)
221//! - Jackson, "Classical Electrodynamics" (1999)
222//! - Weinberg, "Gravitation and Cosmology" (1972)
223
224#![cfg_attr(not(feature = "std"), no_std)]
225#![warn(missing_docs)]
226#![warn(clippy::missing_docs_in_private_items)]
227#![doc(
228 html_logo_url = "https://raw.githubusercontent.com/justinelliottcobb/Amari/main/logo.png",
229 html_favicon_url = "https://raw.githubusercontent.com/justinelliottcobb/Amari/main/favicon.ico"
230)]
231
232// Re-export key types for convenience
233pub use constants::*;
234pub use geodesic::{GeodesicIntegrator, GeodesicResult, IntegrationConfig, Metric};
235pub use particle::light_deflection_angle;
236pub use particle::{
237 propagate_relativistic, ParticleError, ParticleResult, RelativisticParticle, TrajectoryPoint,
238 TrajectoryResult,
239};
240pub use schwarzschild::{effective_potential, SchwarzschildMetric};
241pub use spacetime::{FourVelocity, LorentzRotor, SpacetimeVector};
242
243// Re-export phantom types and verified constructs when features are enabled
244#[cfg(feature = "phantom-types")]
245pub use verified::{
246 EnergyMomentumInvariant, FourVelocityNorm, MinkowskiMetric, SpacetimeSignature, ValidSpacetime,
247 VerifiedFourVelocity, VerifiedRelativisticParticle, VerifiedSpacetimeVector,
248};
249
250#[cfg(feature = "formal-verification")]
251pub use verified_contracts::{
252 verified_collision, verified_four_velocity_addition, verified_geodesic_step,
253 verified_invariant_mass, verified_lorentz_boost, verified_lorentz_force,
254};
255
256/// Physical constants for relativistic physics
257pub mod constants;
258
259/// Spacetime algebra implementation using geometric algebra
260pub mod spacetime;
261
262/// Geodesic integration for curved spacetime
263pub mod geodesic;
264
265/// Schwarzschild metric for spherically symmetric gravitational fields
266pub mod schwarzschild;
267
268/// Relativistic charged particle dynamics
269pub mod particle;
270
271/// High-precision arithmetic for spacecraft orbital mechanics
272pub mod precision;
273
274/// High-precision geodesic integration for orbital mechanics
275pub mod precision_geodesic;
276
277#[cfg(feature = "phantom-types")]
278/// Formally verified relativistic physics with phantom types
279pub mod verified;
280
281#[cfg(feature = "formal-verification")]
282/// Creusot contracts for formal verification
283pub mod verified_contracts;
284
285/// Common error types used throughout the library
286pub mod error {
287 pub use crate::geodesic::GeodesicError;
288 pub use crate::particle::ParticleError;
289}
290
291/// Common result types used throughout the library
292pub mod result {
293 pub use crate::geodesic::GeodesicResult;
294 pub use crate::particle::ParticleResult;
295}
296
297/// Prelude module for common imports
298///
299/// Common imports for relativistic physics calculations
300///
301/// This prelude module re-exports the most commonly used types and functions
302/// for convenient importing with `use amari_relativistic::prelude::*;`
303pub mod prelude {
304
305 // Core constants
306 pub use crate::constants::{AMU, C, E_CHARGE, G, SOLAR_MASS};
307
308 // Core spacetime types
309 pub use crate::spacetime::{FourVelocity, LorentzRotor, SpacetimeVector};
310
311 // Particle physics
312 pub use crate::particle::{
313 light_deflection_angle, propagate_relativistic, ParticleError, ParticleResult,
314 RelativisticParticle, TrajectoryPoint, TrajectoryResult,
315 };
316
317 // Geodesic integration
318 pub use crate::geodesic::{GeodesicIntegrator, GeodesicResult, IntegrationConfig, Metric};
319
320 // Schwarzschild geometry
321 pub use crate::schwarzschild::{effective_potential, SchwarzschildMetric};
322
323 // External dependencies commonly used
324 pub use nalgebra::Vector3;
325
326 // High-precision arithmetic
327 pub use crate::precision::{OrbitalFloat, PrecisionFloat, StandardFloat};
328
329 // Phantom types for compile-time verification (stable Rust)
330 #[cfg(feature = "phantom-types")]
331 pub use crate::verified::{
332 EnergyMomentumInvariant, FourVelocityNorm, MinkowskiMetric, SpacetimeSignature,
333 ValidSpacetime, VerifiedFourVelocity, VerifiedRelativisticParticle,
334 VerifiedSpacetimeVector,
335 };
336
337 // Formal verification contracts (nightly Rust)
338 #[cfg(feature = "formal-verification")]
339 pub use crate::verified_contracts::{
340 verified_collision, verified_four_velocity_addition, verified_geodesic_step,
341 verified_invariant_mass, verified_lorentz_boost, verified_lorentz_force,
342 };
343}
344
345// Version information
346/// Current version of the amari-relativistic crate
347pub const VERSION: &str = env!("CARGO_PKG_VERSION");
348
349/// Library information
350pub const INFO: &str = concat!(
351 "Amari Relativistic Physics v",
352 env!("CARGO_PKG_VERSION"),
353 " - Relativistic physics using geometric algebra"
354);
355
356#[cfg(test)]
357mod integration_tests {
358 //! Integration tests demonstrating complete workflows
359 use super::prelude::*;
360 use approx::assert_relative_eq;
361
362 #[test]
363 fn test_complete_ion_simulation() {
364 // Complete simulation: 100 keV iron ion near Sun
365 let sun = SchwarzschildMetric::sun();
366 let mut integrator = GeodesicIntegrator::with_metric(Box::new(sun));
367
368 // Ion starting at 2 AU, aimed toward Sun with small impact parameter
369 let position = Vector3::new(2.0 * 1.496e11, 0.0, 0.0);
370 let direction = Vector3::new(-1.0, 0.0, 0.1);
371 let mut ion = RelativisticParticle::with_energy(
372 position,
373 direction,
374 100e3 * E_CHARGE, // 100 keV
375 55.845 * AMU, // Iron-56
376 E_CHARGE, // Singly ionized
377 )
378 .expect("Ion creation should succeed");
379
380 // Verify initial conditions
381 assert_relative_eq!(ion.kinetic_energy(), 100e3 * E_CHARGE, epsilon = 1e-6);
382 assert!(ion.position_3d().magnitude() > 2.9e11); // > 1.9 AU
383
384 // Short propagation to test integration
385 let trajectory = propagate_relativistic(
386 &mut ion,
387 &mut integrator,
388 86400.0, // 1 day
389 3600.0, // 1 hour steps
390 )
391 .expect("Propagation should succeed");
392
393 // Verify trajectory properties
394 assert!(trajectory.len() > 10);
395 assert!(trajectory.last().unwrap().0 > 80000.0); // Time advanced
396
397 // Ion should have moved closer to Sun
398 let final_distance = ion.position_3d().magnitude();
399 let initial_distance = position.magnitude();
400 assert!(final_distance < initial_distance);
401 }
402
403 #[test]
404 fn test_light_deflection_calculation() {
405 // Test Einstein's light deflection prediction
406 let solar_radius = 6.957e8;
407 let deflection = crate::particle::light_deflection_angle(solar_radius, SOLAR_MASS);
408
409 // Convert to arcseconds
410 let arcseconds = deflection * 180.0 * 3600.0 / std::f64::consts::PI;
411
412 // Should be approximately 1.75 arcseconds
413 assert_relative_eq!(arcseconds, 1.75, epsilon = 0.1);
414 }
415
416 #[test]
417 fn test_four_velocity_consistency() {
418 // Test four-velocity normalization and consistency
419 let velocity = Vector3::new(0.6 * C, 0.8 * C, 0.0);
420
421 // This should be true because |v| = sqrt(0.36 + 0.64) * C = C
422 assert_eq!(velocity.magnitude(), C);
423
424 // Test with valid velocity
425 let valid_velocity = Vector3::new(0.36 * C, 0.48 * C, 0.0); // |v| = 0.6c
426 let four_vel = FourVelocity::from_velocity(valid_velocity);
427
428 // Check normalization: u·u = c²
429 let norm_sq = four_vel.as_spacetime_vector().minkowski_norm_squared();
430 assert_relative_eq!(norm_sq, C * C, epsilon = 1e-10);
431
432 // Check Lorentz factor
433 let expected_gamma = 1.0 / (1.0 - 0.6_f64.powi(2)).sqrt();
434 assert_relative_eq!(four_vel.gamma(), expected_gamma, epsilon = 1e-12);
435 }
436
437 #[test]
438 fn test_energy_conservation_in_flat_spacetime() {
439 // Test energy conservation in flat spacetime (should be exact)
440 use crate::geodesic::{GeodesicIntegrator, Metric};
441
442 #[derive(Debug)]
443 struct FlatSpacetime;
444
445 impl<T: crate::precision::PrecisionFloat> crate::geodesic::GenericMetric<T> for FlatSpacetime {
446 fn metric_tensor(
447 &self,
448 _: &crate::spacetime::GenericSpacetimeVector<T>,
449 ) -> [[T; 4]; 4] {
450 let one = T::one();
451 let neg_one = -T::one();
452 [
453 [one, T::zero(), T::zero(), T::zero()],
454 [T::zero(), neg_one.clone(), T::zero(), T::zero()],
455 [T::zero(), T::zero(), neg_one.clone(), T::zero()],
456 [T::zero(), T::zero(), T::zero(), neg_one],
457 ]
458 }
459
460 fn christoffel(
461 &self,
462 _: &crate::spacetime::GenericSpacetimeVector<T>,
463 ) -> [[[T; 4]; 4]; 4] {
464 T::zero_tensor_4x4x4() // All zeros for flat spacetime
465 }
466
467 fn name(&self) -> &str {
468 "Flat Spacetime"
469 }
470 }
471
472 impl Metric for FlatSpacetime {
473 fn metric_tensor(&self, _: &SpacetimeVector) -> [[f64; 4]; 4] {
474 [
475 [1.0, 0.0, 0.0, 0.0],
476 [0.0, -1.0, 0.0, 0.0],
477 [0.0, 0.0, -1.0, 0.0],
478 [0.0, 0.0, 0.0, -1.0],
479 ]
480 }
481
482 fn christoffel(&self, _: &SpacetimeVector) -> [[[f64; 4]; 4]; 4] {
483 [[[0.0; 4]; 4]; 4] // All zeros for flat spacetime
484 }
485
486 fn name(&self) -> &str {
487 "Flat Spacetime"
488 }
489 }
490
491 let flat = Box::new(FlatSpacetime);
492 let mut integrator = GeodesicIntegrator::with_metric(flat);
493
494 let position = Vector3::new(1e6, 0.0, 0.0);
495 let velocity = Vector3::new(1e5, 0.0, 0.0); // 100 km/s
496 let mut particle = RelativisticParticle::new(
497 position,
498 velocity,
499 0.0,
500 crate::constants::atomic_masses::HYDROGEN,
501 E_CHARGE,
502 )
503 .expect("Particle creation should succeed");
504
505 let initial_energy = particle.total_energy();
506
507 // Propagate in flat spacetime
508 let _trajectory = propagate_relativistic(
509 &mut particle,
510 &mut integrator,
511 3600.0, // 1 hour
512 60.0, // 1 minute steps
513 )
514 .expect("Flat spacetime propagation should succeed");
515
516 let final_energy = particle.total_energy();
517
518 // Energy should be conserved in flat spacetime
519 assert_relative_eq!(final_energy, initial_energy, epsilon = 1e-12);
520 }
521
522 #[test]
523 fn test_schwarzschild_coordinate_singularity() {
524 // Test behavior near Schwarzschild radius
525 let sun = SchwarzschildMetric::sun();
526
527 // Position just outside Schwarzschild radius
528 let rs = sun.schwarzschild_radius;
529 let position = SpacetimeVector::new(0.0, rs * 1.1, 0.0, 0.0);
530
531 // Should not be singular
532 assert!(!sun.has_singularity(&position));
533
534 // Position at Schwarzschild radius should be singular
535 let horizon = SpacetimeVector::new(0.0, rs, 0.0, 0.0);
536 assert!(sun.has_singularity(&horizon));
537
538 // Test metric behavior
539 let g = sun.metric_tensor(&position);
540 assert!(g[0][0].is_finite()); // Should not be infinite
541 assert!(g[0][0] < 0.0); // Should be negative (timelike)
542 }
543}
544
545#[cfg(doctest)]
546mod doctests {
547 //! Additional documentation tests to ensure examples compile and run correctly
548
549 /// Test that the main example in the crate documentation works
550 ///
551 /// ```rust
552 /// use amari_relativistic::prelude::*;
553 /// use amari_relativistic::constants::{atomic_masses, E_CHARGE};
554 ///
555 /// // This should compile without errors
556 /// let sun = SchwarzschildMetric::sun();
557 /// assert!(sun.schwarzschild_radius > 1000.0); // > 1 km
558 ///
559 /// let position = Vector3::new(1e6, 0.0, 0.0);
560 /// let velocity = Vector3::new(1e5, 0.0, 0.0);
561 /// let particle = RelativisticParticle::new(
562 /// position, velocity, 0.0,
563 /// atomic_masses::HYDROGEN,
564 /// E_CHARGE
565 /// );
566 /// assert!(particle.is_ok());
567 /// ```
568 fn _doctest_main_example() {}
569}