Skip to main content

vibe/cosmic/
microverse.rs

1//! Subatomic microverses and scaling lens (OCS §12.4).
2//!
3//! The OCS supports "microverse" realm classes — self-contained
4//! realities at subatomic scales, useful for quantum simulations,
5//! particle physics visualizations, and fictional narratives that
6//! operate at microscopic scales.
7//!
8//! Reference: OCS Specification v2.2.0 §12.4.
9
10use crate::cosmic::cb_usri::HierarchyLevel;
11use crate::cosmic::usri::RealmClass;
12use crate::value::Value;
13use std::collections::BTreeMap;
14
15/// Fundamental physical constants used for scaling (OCS §12.4).
16pub mod constants {
17    /// Planck length in meters
18    pub const PLANCK_LENGTH_M: f64 = 1.616255e-35;
19    /// Planck time in seconds
20    pub const PLANCK_TIME_S: f64 = 5.391247e-44;
21    /// Planck mass in kg
22    pub const PLANCK_MASS_KG: f64 = 2.176434e-8;
23    /// Planck energy in Joules
24    pub const PLANCK_ENERGY_J: f64 = 1.9561e9;
25    /// Planck temperature in Kelvin
26    pub const PLANCK_TEMP_K: f64 = 1.416784e32;
27    /// Reduced Planck constant ℏ in J·s
28    pub const HBAR_J_S: f64 = 1.054571817e-34;
29    /// Boltzmann constant in J/K
30    pub const BOLTZMANN_J_K: f64 = 1.380649e-23;
31    /// Speed of light in m/s
32    pub const C_M_S: f64 = 299_792_458.0;
33    /// Electron mass in kg
34    pub const ELECTRON_MASS_KG: f64 = 9.1093837015e-31;
35    /// Proton mass in kg
36    pub const PROTON_MASS_KG: f64 = 1.67262192369e-27;
37    /// Bohr radius in meters
38    pub const BOHR_RADIUS_M: f64 = 5.29177210903e-11;
39    /// Compton wavelength of electron in meters
40    pub const ELECTRON_COMPTON_M: f64 = 2.42631023867e-12;
41    /// Fine-structure constant (dimensionless)
42    pub const FINE_STRUCTURE: f64 = 7.2973525693e-3;
43}
44
45/// A scaling lens — maps between hierarchy levels (OCS §12.4).
46///
47/// The OCS spans 61 orders of magnitude. The scaling lens provides
48/// conversion factors between adjacent levels, enabling a "zoom"
49/// operation that preserves physical relationships.
50#[derive(Debug, Clone, Copy, PartialEq)]
51pub struct ScalingLens {
52    /// Source hierarchy level
53    pub from_level: HierarchyLevel,
54    /// Target hierarchy level
55    pub to_level: HierarchyLevel,
56    /// Linear scale factor (from → to)
57    pub scale_factor: f64,
58}
59
60impl ScalingLens {
61    /// Create a scaling lens between two hierarchy levels (OCS §12.4).
62    pub fn between(from: HierarchyLevel, to: HierarchyLevel) -> Self {
63        let scale = scale_factor_between(from, to);
64        Self {
65            from_level: from,
66            to_level: to,
67            scale_factor: scale,
68        }
69    }
70
71    /// Transform a length from the source level to the target level.
72    pub fn transform_length(&self, length: f64) -> f64 {
73        length * self.scale_factor
74    }
75
76    /// Transform a length back from target to source.
77    pub fn inverse_length(&self, length: f64) -> f64 {
78        length / self.scale_factor
79    }
80}
81
82/// Compute the scale factor between two hierarchy levels (OCS §12.4).
83///
84/// Returns the ratio: 1 unit at `from` level = X units at `to` level.
85/// Based on typical length scales at each level.
86pub fn scale_factor_between(from: HierarchyLevel, to: HierarchyLevel) -> f64 {
87    typical_length(from) / typical_length(to)
88}
89
90/// Typical length scale at each hierarchy level (in meters) (OCS §12.4).
91pub fn typical_length(level: HierarchyLevel) -> f64 {
92    match level {
93        HierarchyLevel::LNeg2 => constants::PLANCK_LENGTH_M, // ~1.6e-35 m
94        HierarchyLevel::LNeg1 => 1e-34,                      // String scale
95        HierarchyLevel::L0 => constants::ELECTRON_COMPTON_M, // ~2.4e-12 m
96        HierarchyLevel::L1 => 1e-15,                         // Femtometer (nuclear)
97        HierarchyLevel::L2 => constants::BOHR_RADIUS_M,      // ~5.3e-11 m (atomic)
98        HierarchyLevel::L3 => 1e-9,                          // Nanometer (macromolecular)
99        HierarchyLevel::L4 => 1e-5,                          // 10 μm (cellular)
100        HierarchyLevel::L5 => 1e3,                           // 1 km (geodetic)
101        HierarchyLevel::L6 => 1e3,                           // 1 km (local AR)
102        HierarchyLevel::L7 => 1e11,                          // 100 Gm (planetary system)
103        HierarchyLevel::L8 => 1e16,                          // 10 light-years (interstellar)
104        HierarchyLevel::L9 => 1e21,                          // 100 kpc (galactic)
105        HierarchyLevel::L10 => 1e23,                         // 10 Mpc (cluster)
106        HierarchyLevel::L11 => 1e24,                         // 100 Mpc (supercluster)
107        HierarchyLevel::L12 => 8.8e26,                       // ~93 Gly (cosmological horizon)
108    }
109}
110
111/// A subatomic particle classification for microverse realms (OCS §12.4).
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113pub enum ParticleClass {
114    Fermion,
115    Boson,
116    Quark,
117    Lepton,
118    Hadron,
119    Meson,
120    Baryon,
121    GaugeBoson,
122    Hypothetical,
123}
124
125impl ParticleClass {
126    /// `str` form.
127    pub fn as_str(&self) -> &'static str {
128        match self {
129            Self::Fermion => "fermion",
130            Self::Boson => "boson",
131            Self::Quark => "quark",
132            Self::Lepton => "lepton",
133            Self::Hadron => "hadron",
134            Self::Meson => "meson",
135            Self::Baryon => "baryon",
136            Self::GaugeBoson => "gauge_boson",
137            Self::Hypothetical => "hypothetical",
138        }
139    }
140}
141
142/// A particle profile for microverse simulations (OCS §12.4).
143#[derive(Debug, Clone, PartialEq)]
144pub struct ParticleProfile {
145    pub name: String,
146    pub class: ParticleClass,
147    pub mass_kg: f64,
148    pub charge_e: f64, // In units of elementary charge
149    pub spin: f64,     // In units of ℏ
150    pub lifetime_s: f64,
151    pub usri: String,
152}
153
154impl ParticleProfile {
155    /// Electron (OCS §12.4).
156    pub fn electron() -> Self {
157        Self {
158            name: "Electron".into(),
159            class: ParticleClass::Lepton,
160            mass_kg: constants::ELECTRON_MASS_KG,
161            charge_e: -1.0,
162            spin: 0.5,
163            lifetime_s: f64::INFINITY, // Stable
164            usri: "urn:omni:v1:physical:observable:standard:particle:electron".into(),
165        }
166    }
167
168    /// Proton (OCS §12.4).
169    pub fn proton() -> Self {
170        Self {
171            name: "Proton".into(),
172            class: ParticleClass::Baryon,
173            mass_kg: constants::PROTON_MASS_KG,
174            charge_e: 1.0,
175            spin: 0.5,
176            lifetime_s: f64::INFINITY, // Stable
177            usri: "urn:omni:v1:physical:observable:standard:particle:proton".into(),
178        }
179    }
180
181    /// Neutron (OCS §12.4).
182    pub fn neutron() -> Self {
183        Self {
184            name: "Neutron".into(),
185            class: ParticleClass::Baryon,
186            mass_kg: 1.67492749804e-27,
187            charge_e: 0.0,
188            spin: 0.5,
189            lifetime_s: 879.4, // Free neutron half-life
190            usri: "urn:omni:v1:physical:observable:standard:particle:neutron".into(),
191        }
192    }
193
194    /// Photon (OCS §12.4).
195    pub fn photon() -> Self {
196        Self {
197            name: "Photon".into(),
198            class: ParticleClass::GaugeBoson,
199            mass_kg: 0.0,
200            charge_e: 0.0,
201            spin: 1.0,
202            lifetime_s: f64::INFINITY,
203            usri: "urn:omni:v1:physical:observable:standard:particle:photon".into(),
204        }
205    }
206
207    /// Up quark (OCS §12.4).
208    pub fn up_quark() -> Self {
209        Self {
210            name: "Up Quark".into(),
211            class: ParticleClass::Quark,
212            mass_kg: 4.1e-30, // ~2.2 MeV/c²
213            charge_e: 2.0 / 3.0,
214            spin: 0.5,
215            lifetime_s: 0.0, // Confined, never free
216            usri: "urn:omni:v1:physical:observable:standard:particle:quark:up".into(),
217        }
218    }
219
220    /// Higgs boson (OCS §12.4).
221    pub fn higgs_boson() -> Self {
222        Self {
223            name: "Higgs Boson".into(),
224            class: ParticleClass::Boson,
225            mass_kg: 2.209e-25, // ~125 GeV/c²
226            charge_e: 0.0,
227            spin: 0.0,
228            lifetime_s: 1.56e-22, // Very short-lived
229            usri: "urn:omni:v1:physical:observable:standard:particle:higgs".into(),
230        }
231    }
232
233    /// Compute the Compton wavelength of a particle (OCS §12.4).
234    /// λ = h / (m * c)  where h = 2πℏ
235    pub fn compton_wavelength(&self) -> f64 {
236        if self.mass_kg == 0.0 {
237            return f64::INFINITY; // Massless particles
238        }
239        let h = 2.0 * std::f64::consts::PI * constants::HBAR_J_S;
240        h / (self.mass_kg * constants::C_M_S)
241    }
242
243    /// Compute the rest energy in Joules (OCS §12.4).
244    /// E = m * c²
245    pub fn rest_energy_j(&self) -> f64 {
246        self.mass_kg * constants::C_M_S * constants::C_M_S
247    }
248
249    /// Compute the de Broglie wavelength at a given velocity (OCS §12.4).
250    /// λ = ℏ / (m * v)
251    pub fn de_broglie_wavelength(&self, velocity_m_s: f64) -> f64 {
252        if velocity_m_s == 0.0 {
253            return f64::INFINITY;
254        }
255        constants::HBAR_J_S / (self.mass_kg * velocity_m_s)
256    }
257
258    /// Converts to value.
259    pub fn to_value(&self) -> Value {
260        let mut rec = BTreeMap::new();
261        rec.insert("name".into(), Value::String(self.name.clone()));
262        rec.insert("class".into(), Value::String(self.class.as_str().into()));
263        rec.insert("mass_kg".into(), Value::F64(self.mass_kg));
264        rec.insert("charge_e".into(), Value::F64(self.charge_e));
265        rec.insert("spin".into(), Value::F64(self.spin));
266        if self.lifetime_s.is_finite() {
267            rec.insert("lifetime_s".into(), Value::F64(self.lifetime_s));
268        } else {
269            rec.insert("lifetime_s".into(), Value::String("stable".into()));
270        }
271        rec.insert(
272            "compton_wavelength_m".into(),
273            Value::F64(self.compton_wavelength()),
274        );
275        rec.insert("rest_energy_j".into(), Value::F64(self.rest_energy_j()));
276        Value::Record(rec)
277    }
278}
279
280/// A microverse realm — a subatomic-scale reality (OCS §12.4).
281#[derive(Debug, Clone, PartialEq)]
282pub struct MicroverseRealm {
283    pub usri: String,
284    pub name: String,
285    pub realm_class: RealmClass,
286    pub level: HierarchyLevel,
287    /// The particle or system this microverse represents
288    pub focus_particle: String,
289}
290
291impl MicroverseRealm {
292    /// Create a quantum-scale microverse (OCS §12.4).
293    pub fn quantum(name: &str, focus: &str) -> Self {
294        Self {
295            usri: format!("urn:omni:v1:microverse:quantum:{}", focus),
296            name: name.into(),
297            realm_class: RealmClass::Microverse,
298            level: HierarchyLevel::L0,
299            focus_particle: focus.into(),
300        }
301    }
302
303    /// Create an atomic-scale microverse (OCS §12.4).
304    pub fn atomic(name: &str, focus: &str) -> Self {
305        Self {
306            usri: format!("urn:omni:v1:microverse:atomic:{}", focus),
307            name: name.into(),
308            realm_class: RealmClass::Microverse,
309            level: HierarchyLevel::L2,
310            focus_particle: focus.into(),
311        }
312    }
313
314    /// Converts to value.
315    pub fn to_value(&self) -> Value {
316        let mut rec = BTreeMap::new();
317        rec.insert("usri".into(), Value::String(self.usri.clone()));
318        rec.insert("name".into(), Value::String(self.name.clone()));
319        rec.insert(
320            "realm_class".into(),
321            Value::String(self.realm_class.as_str().into()),
322        );
323        rec.insert("level".into(), Value::F64(self.level.as_u8() as f64));
324        rec.insert(
325            "focus_particle".into(),
326            Value::String(self.focus_particle.clone()),
327        );
328        Value::Record(rec)
329    }
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335
336    #[test]
337    fn planck_length_is_tiny() {
338        assert!(constants::PLANCK_LENGTH_M < 1e-34);
339        assert!(constants::PLANCK_LENGTH_M > 1e-36);
340    }
341
342    #[test]
343    fn scale_factor_atomic_to_geodetic() {
344        let lens = ScalingLens::between(HierarchyLevel::L2, HierarchyLevel::L5);
345        // L2 (~5e-11 m) → L5 (~1e3 m): scale = 5e-11 / 1e3 ≈ 5e-14 (small)
346        assert!(lens.scale_factor < 1e-10);
347    }
348
349    #[test]
350    fn scale_factor_geodetic_to_atomic() {
351        let lens = ScalingLens::between(HierarchyLevel::L5, HierarchyLevel::L2);
352        // L5 (~1e3 m) → L2 (~5e-11 m): scale = 1e3 / 5e-11 ≈ 2e13 (large)
353        assert!(lens.scale_factor > 1e10);
354    }
355
356    #[test]
357    fn scaling_lens_round_trip() {
358        let lens = ScalingLens::between(HierarchyLevel::L2, HierarchyLevel::L5);
359        let original = 1e-10; // 1 Angstrom
360        let scaled = lens.transform_length(original);
361        let recovered = lens.inverse_length(scaled);
362        assert!((recovered - original).abs() < 1e-20);
363    }
364
365    #[test]
366    fn electron_compton_wavelength() {
367        let e = ParticleProfile::electron();
368        let lambda = e.compton_wavelength();
369        // Should be ~2.43e-12 m
370        assert!(
371            (lambda - 2.43e-12).abs() < 0.1e-12,
372            "got {} expected ~2.43e-12",
373            lambda
374        );
375    }
376
377    #[test]
378    fn proton_rest_energy() {
379        let p = ParticleProfile::proton();
380        let e = p.rest_energy_j();
381        // Should be ~1.503e-10 J (~938 MeV)
382        assert!(
383            (e - 1.503e-10).abs() < 0.01e-10,
384            "got {} expected ~1.503e-10",
385            e
386        );
387    }
388
389    #[test]
390    fn photon_massless() {
391        let ph = ParticleProfile::photon();
392        assert_eq!(ph.mass_kg, 0.0);
393        assert!(ph.compton_wavelength().is_infinite());
394    }
395
396    #[test]
397    fn electron_de_broglie() {
398        let e = ParticleProfile::electron();
399        // At 1 m/s
400        let lambda = e.de_broglie_wavelength(1.0);
401        assert!(lambda > 0.0);
402        // At higher velocity, wavelength is shorter
403        let lambda_fast = e.de_broglie_wavelength(1000.0);
404        assert!(lambda_fast < lambda);
405    }
406
407    #[test]
408    fn neutron_unstable() {
409        let n = ParticleProfile::neutron();
410        assert!(n.lifetime_s.is_finite());
411        assert!(n.lifetime_s > 800.0); // ~879 seconds
412    }
413
414    #[test]
415    fn higgs_boson_short_lived() {
416        let h = ParticleProfile::higgs_boson();
417        assert!(h.lifetime_s < 1e-20);
418    }
419
420    #[test]
421    fn microverse_quantum_realm() {
422        let m = MicroverseRealm::quantum("Electron Field", "electron");
423        assert_eq!(m.realm_class, RealmClass::Microverse);
424        assert_eq!(m.level, HierarchyLevel::L0);
425    }
426
427    #[test]
428    fn microverse_atomic_realm() {
429        let m = MicroverseRealm::atomic("Hydrogen Atom", "hydrogen");
430        assert_eq!(m.level, HierarchyLevel::L2);
431    }
432
433    #[test]
434    fn particle_to_value() {
435        let e = ParticleProfile::electron();
436        let v = e.to_value();
437        match v {
438            Value::Record(r) => {
439                assert!(r.contains_key("mass_kg"));
440                assert!(r.contains_key("compton_wavelength_m"));
441            }
442            _ => panic!("expected Record"),
443        }
444    }
445
446    #[test]
447    fn typical_length_monotonic() {
448        // Length should generally increase with level
449        let l0 = typical_length(HierarchyLevel::L0);
450        let l5 = typical_length(HierarchyLevel::L5);
451        let l12 = typical_length(HierarchyLevel::L12);
452        assert!(l0 < l5);
453        assert!(l5 < l12);
454    }
455
456    #[test]
457    fn up_quark_fractional_charge() {
458        let u = ParticleProfile::up_quark();
459        assert!((u.charge_e - 2.0 / 3.0).abs() < 1e-10);
460    }
461
462    #[test]
463    fn microverse_to_value() {
464        let m = MicroverseRealm::quantum("Test", "electron");
465        let v = m.to_value();
466        match v {
467            Value::Record(r) => {
468                assert_eq!(
469                    r.get("realm_class"),
470                    Some(&Value::String("microverse".into()))
471                );
472            }
473            _ => panic!("expected Record"),
474        }
475    }
476}