1use core::cmp::Ordering;
6use core::f64::consts::TAU;
7
8use crate::sensing::acquisition::{Clock, ComplexConvention};
9use crate::sensing::authority::certificates::{CalibrationValidityWindow, RationalInstant};
10use crate::sensing::SemanticId;
11
12pub const LEAP_SECOND_TABLE_DOMAIN: &[u8] = b"QUALIA-LEAP-SECOND-TABLE-v1\0";
14
15pub const MAX_LEAP_SECOND_ENTRIES: usize = 64;
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20#[repr(u32)]
21pub enum ClockScale {
22 Tai = 0,
24 Utc = 1,
26 MonotonicRelative = 2,
28}
29
30impl ClockScale {
31 pub const fn from_code(code: u32) -> Result<Self, ClockDisciplineError> {
32 match code {
33 0 => Ok(Self::Tai),
34 1 => Ok(Self::Utc),
35 2 => Ok(Self::MonotonicRelative),
36 _ => Err(ClockDisciplineError::InvalidClockScale),
37 }
38 }
39}
40
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub struct LeapSecondStep {
44 pub effective_utc_second: i64,
46 pub tai_minus_utc_seconds: i32,
48}
49
50#[derive(Clone, Copy, Debug, PartialEq)]
54pub struct LeapSecondTable {
55 table_id: SemanticId,
56 steps: [LeapSecondStep; MAX_LEAP_SECOND_ENTRIES],
57 step_count: usize,
58 valid_from_utc_sec: i64,
59 valid_until_utc_sec: i64,
60 table_uncertainty_seconds: f64,
61 table_digest: [u8; 32],
62}
63
64impl LeapSecondTable {
65 pub fn new(
66 table_id: SemanticId,
67 steps_slice: &[LeapSecondStep],
68 valid_from_utc_sec: i64,
69 valid_until_utc_sec: i64,
70 table_uncertainty_seconds: f64,
71 ) -> Result<Self, ClockDisciplineError> {
72 if table_id.value().is_none() {
73 return Err(ClockDisciplineError::InvalidIdentifier);
74 }
75 if steps_slice.is_empty() || steps_slice.len() > MAX_LEAP_SECOND_ENTRIES {
76 return Err(ClockDisciplineError::InvalidLeapSecondTable);
77 }
78 if valid_from_utc_sec >= valid_until_utc_sec
79 || !table_uncertainty_seconds.is_finite()
80 || table_uncertainty_seconds < 0.0
81 {
82 return Err(ClockDisciplineError::InvalidLeapSecondTable);
83 }
84 let mut steps = [LeapSecondStep {
85 effective_utc_second: 0,
86 tai_minus_utc_seconds: 0,
87 }; MAX_LEAP_SECOND_ENTRIES];
88 let mut prev_effective: Option<i64> = None;
89 for (idx, step) in steps_slice.iter().copied().enumerate() {
90 if let Some(prev) = prev_effective {
91 if step.effective_utc_second <= prev {
92 return Err(ClockDisciplineError::InvalidLeapSecondTable);
93 }
94 }
95 prev_effective = Some(step.effective_utc_second);
96 steps[idx] = step;
97 }
98 if steps[0].effective_utc_second > valid_from_utc_sec {
99 return Err(ClockDisciplineError::InvalidLeapSecondTable);
100 }
101
102 let mut hasher = blake3::Hasher::new();
103 hasher.update(LEAP_SECOND_TABLE_DOMAIN);
104 hasher.update(&table_id.value().unwrap_or(0).to_le_bytes());
105 hasher.update(&valid_from_utc_sec.to_le_bytes());
106 hasher.update(&valid_until_utc_sec.to_le_bytes());
107 hasher.update(&table_uncertainty_seconds.to_bits().to_le_bytes());
108 hasher.update(&(steps_slice.len() as u32).to_le_bytes());
109 for step in steps_slice {
110 hasher.update(&step.effective_utc_second.to_le_bytes());
111 hasher.update(&step.tai_minus_utc_seconds.to_le_bytes());
112 }
113 let table_digest = *hasher.finalize().as_bytes();
114
115 Ok(Self {
116 table_id,
117 steps,
118 step_count: steps_slice.len(),
119 valid_from_utc_sec,
120 valid_until_utc_sec,
121 table_uncertainty_seconds,
122 table_digest,
123 })
124 }
125
126 pub const fn table_id(&self) -> SemanticId {
127 self.table_id
128 }
129
130 pub const fn table_digest(&self) -> &[u8; 32] {
131 &self.table_digest
132 }
133
134 pub const fn table_uncertainty_seconds(&self) -> f64 {
135 self.table_uncertainty_seconds
136 }
137
138 pub fn tai_minus_utc_at(&self, utc_second: i64) -> Result<i32, ClockDisciplineError> {
140 if utc_second < self.valid_from_utc_sec || utc_second >= self.valid_until_utc_sec {
141 return Err(ClockDisciplineError::LeapTableExpiredOrOutOfRange);
142 }
143 let mut active = self.steps[0].tai_minus_utc_seconds;
144 for step in self.steps.iter().take(self.step_count) {
145 if utc_second >= step.effective_utc_second {
146 active = step.tai_minus_utc_seconds;
147 } else {
148 break;
149 }
150 }
151 Ok(active)
152 }
153
154 pub fn convert_utc_instant_to_tai(
157 &self,
158 utc_instant: RationalInstant,
159 tai_origin: SemanticId,
160 source_time_uncertainty_seconds: Option<f64>,
161 ) -> Result<(RationalInstant, f64), ClockDisciplineError> {
162 if ClockScale::from_code(utc_instant.scale())? != ClockScale::Utc {
163 return Err(ClockDisciplineError::InvalidClockScale);
164 }
165 let u_src = validate_known_time_uncertainty(source_time_uncertainty_seconds)?;
166 let floor_utc_sec = rational_floor_seconds(utc_instant);
167 let floor_i64 = i64::try_from(floor_utc_sec)
168 .map_err(|_| ClockDisciplineError::LeapTableExpiredOrOutOfRange)?;
169 let delta_tai = self.tai_minus_utc_at(floor_i64)?;
170 let shifted = utc_instant
171 .add_rational_seconds(i128::from(delta_tai), 1)
172 .map_err(|_| ClockDisciplineError::RationalOverflow)?;
173 let tai_instant = RationalInstant::new(
174 tai_origin,
175 utc_instant.restart_epoch(),
176 ClockScale::Tai as u32,
177 shifted.numerator(),
178 shifted.denominator(),
179 )
180 .map_err(|_| ClockDisciplineError::InvalidIdentifier)?;
181 let total_u_t = u_src + self.table_uncertainty_seconds;
182 if !total_u_t.is_finite() {
183 return Err(ClockDisciplineError::UnknownOrInvalidTimeUncertainty);
184 }
185 Ok((tai_instant, total_u_t))
186 }
187}
188
189#[derive(Clone, Copy, Debug, PartialEq)]
192pub struct CrossClockMapping {
193 pub mapping_id: SemanticId,
194 pub source_origin: SemanticId,
195 pub source_restart: u64,
196 pub source_scale: u32,
197 pub target_origin: SemanticId,
198 pub target_restart: u64,
199 pub target_scale: u32,
200 pub source_validity: CalibrationValidityWindow,
201 pub offset_seconds_num: i128,
202 pub offset_seconds_den: i128,
203 pub mapping_time_uncertainty_seconds: f64,
204}
205
206impl CrossClockMapping {
207 pub fn validate(&self) -> Result<(), ClockDisciplineError> {
208 if self.mapping_id.value().is_none()
209 || self.source_origin.value().is_none()
210 || self.target_origin.value().is_none()
211 {
212 return Err(ClockDisciplineError::InvalidIdentifier);
213 }
214 ClockScale::from_code(self.source_scale)?;
215 ClockScale::from_code(self.target_scale)?;
216 if self.offset_seconds_den <= 0 {
217 return Err(ClockDisciplineError::RationalOverflow);
218 }
219 if !self.mapping_time_uncertainty_seconds.is_finite()
220 || self.mapping_time_uncertainty_seconds < 0.0
221 {
222 return Err(ClockDisciplineError::UnknownOrInvalidTimeUncertainty);
223 }
224 if self.source_validity.valid_from().clock_origin() != self.source_origin
225 || self.source_validity.valid_from().restart_epoch() != self.source_restart
226 || self.source_validity.valid_from().scale() != self.source_scale
227 {
228 return Err(ClockDisciplineError::CrossClockOriginRejected);
229 }
230 Ok(())
231 }
232
233 pub fn map_instant(
236 &self,
237 source_instant: RationalInstant,
238 source_time_uncertainty_seconds: Option<f64>,
239 ) -> Result<(RationalInstant, f64), ClockDisciplineError> {
240 self.validate()?;
241 let u_src = validate_known_time_uncertainty(source_time_uncertainty_seconds)?;
242 self.source_validity
243 .verify_contains(source_instant)
244 .map_err(|_| ClockDisciplineError::MappingOutsideValidityWindow)?;
245 let shifted = source_instant
246 .add_rational_seconds(self.offset_seconds_num, self.offset_seconds_den)
247 .map_err(|_| ClockDisciplineError::RationalOverflow)?;
248 let mapped = RationalInstant::new(
249 self.target_origin,
250 self.target_restart,
251 self.target_scale,
252 shifted.numerator(),
253 shifted.denominator(),
254 )
255 .map_err(|_| ClockDisciplineError::InvalidIdentifier)?;
256 let total_u = u_src + self.mapping_time_uncertainty_seconds;
257 if !total_u.is_finite() {
258 return Err(ClockDisciplineError::UnknownOrInvalidTimeUncertainty);
259 }
260 Ok((mapped, total_u))
261 }
262}
263
264pub fn verify_same_clock_join(clock_a: Clock, clock_b: Clock) -> Result<(), ClockDisciplineError> {
270 if clock_a.origin() != clock_b.origin() || clock_a.restart() != clock_b.restart() {
271 return Err(ClockDisciplineError::CrossClockOriginRejected);
272 }
273 clock_a
274 .require_same_domain(clock_b)
275 .map_err(|_| ClockDisciplineError::ClockParametersMismatch)
276}
277
278pub fn compute_phase_uncertainty_rad(
283 frequency_hz: f64,
284 time_uncertainty_seconds: Option<f64>,
285) -> Result<f64, ClockDisciplineError> {
286 if !frequency_hz.is_finite() || frequency_hz <= 0.0 {
287 return Err(ClockDisciplineError::InvalidCarrierFrequency);
288 }
289 let u_t = validate_known_time_uncertainty(time_uncertainty_seconds)?;
290 let delta_phi = TAU * frequency_hz * u_t;
291 if !delta_phi.is_finite() {
292 return Err(ClockDisciplineError::PhaseUncertaintyOverflow);
293 }
294 Ok(delta_phi)
295}
296
297pub fn verify_phase_coherent_join(
301 instant_a: RationalInstant,
302 instant_b: RationalInstant,
303 frequency_hz: f64,
304 time_uncertainty_seconds: Option<f64>,
305 max_allowed_phase_uncertainty_rad: f64,
306) -> Result<f64, ClockDisciplineError> {
307 if !instant_a.same_clock_domain(instant_b) {
308 return Err(ClockDisciplineError::CrossClockOriginRejected);
309 }
310 if instant_a
311 .checked_cmp(instant_b)
312 .map_err(|_| ClockDisciplineError::CrossClockOriginRejected)?
313 != Ordering::Equal
314 {
315 return Err(ClockDisciplineError::InstantNotSimultaneous);
316 }
317 if !max_allowed_phase_uncertainty_rad.is_finite() || max_allowed_phase_uncertainty_rad < 0.0 {
318 return Err(ClockDisciplineError::InvalidPhaseCoherenceBudget);
319 }
320 let delta_phi = compute_phase_uncertainty_rad(frequency_hz, time_uncertainty_seconds)?;
321 if delta_phi > max_allowed_phase_uncertainty_rad {
322 return Err(ClockDisciplineError::PhaseUncertaintyExceedsBudget);
323 }
324 Ok(delta_phi)
325}
326
327#[derive(Clone, Copy, Debug, PartialEq, Eq)]
329pub enum IqCarrierConvention {
330 EmfNegativeCarrier,
334 QacPositiveCarrier,
338}
339
340impl IqCarrierConvention {
341 pub fn from_wire_str(s: &str) -> Result<Self, ClockDisciplineError> {
342 match s {
343 "I_plus_iQ_exp_minus_iwt" => Ok(Self::EmfNegativeCarrier),
344 "I_plus_iQ_exp_plus_iwt" => Ok(Self::QacPositiveCarrier),
345 _ => Err(ClockDisciplineError::UnknownIqCarrierConvention),
346 }
347 }
348
349 pub const fn as_wire_str(self) -> &'static str {
350 match self {
351 Self::EmfNegativeCarrier => "I_plus_iQ_exp_minus_iwt",
352 Self::QacPositiveCarrier => "I_plus_iQ_exp_plus_iwt",
353 }
354 }
355
356 pub const fn from_acquisition_convention(conv: ComplexConvention) -> Self {
357 match conv {
358 ComplexConvention::RealPlusIImagNegativeExponent => Self::EmfNegativeCarrier,
359 ComplexConvention::RealPlusIImagPositiveExponent => Self::QacPositiveCarrier,
360 }
361 }
362}
363
364#[derive(Clone, Copy, Debug, PartialEq)]
367pub struct QualifiedIqSample {
368 pub i: f64,
369 pub q: f64,
370 pub convention: IqCarrierConvention,
371 pub carrier_hz: f64,
372 pub reference_phase_rad: f64,
373 pub signed_baseband_offset_hz: f64,
374}
375
376impl QualifiedIqSample {
377 pub fn validate(&self) -> Result<(), ClockDisciplineError> {
378 if !self.i.is_finite()
379 || !self.q.is_finite()
380 || !self.carrier_hz.is_finite()
381 || self.carrier_hz <= 0.0
382 || !self.reference_phase_rad.is_finite()
383 || !self.signed_baseband_offset_hz.is_finite()
384 {
385 return Err(ClockDisciplineError::NonFiniteIqParameter);
386 }
387 Ok(())
388 }
389
390 pub fn reconstruct_real_at(&self, dt_seconds: f64) -> Result<f64, ClockDisciplineError> {
395 self.validate()?;
396 if !dt_seconds.is_finite() {
397 return Err(ClockDisciplineError::NonFiniteIqParameter);
398 }
399 let theta = TAU * self.carrier_hz * dt_seconds + self.reference_phase_rad;
400 let (sin_t, cos_t) = theta.sin_cos();
401 let real = match self.convention {
402 IqCarrierConvention::EmfNegativeCarrier => self.i * cos_t + self.q * sin_t,
403 IqCarrierConvention::QacPositiveCarrier => self.i * cos_t - self.q * sin_t,
404 };
405 Ok(real)
406 }
407}
408
409pub fn reject_unconjugated_iq_memcpy(
414 source_convention: IqCarrierConvention,
415 target_convention: IqCarrierConvention,
416) -> Result<(), ClockDisciplineError> {
417 if source_convention != target_convention {
418 return Err(ClockDisciplineError::UnconjugatedCarrierMemcpyRejected);
419 }
420 Ok(())
421}
422
423pub fn convert_iq_sample_between_conventions(
436 source: QualifiedIqSample,
437 target_convention: IqCarrierConvention,
438 target_phase_origin_shift_seconds: f64,
439) -> Result<QualifiedIqSample, ClockDisciplineError> {
440 source.validate()?;
441 if !target_phase_origin_shift_seconds.is_finite() {
442 return Err(ClockDisciplineError::NonFiniteIqParameter);
443 }
444
445 let (mut i_out, mut q_out, mut offset_out) = if source.convention == target_convention {
446 (source.i, source.q, source.signed_baseband_offset_hz)
447 } else {
448 (source.i, -source.q, -source.signed_baseband_offset_hz)
449 };
450
451 let origin_delta_theta = TAU * source.carrier_hz * target_phase_origin_shift_seconds;
455 if origin_delta_theta != 0.0 || (source.convention != target_convention && source.reference_phase_rad != 0.0) {
456 let total_phase = match target_convention {
459 IqCarrierConvention::EmfNegativeCarrier => {
460 let phi_eff = if source.convention == target_convention {
463 source.reference_phase_rad
464 } else {
465 -source.reference_phase_rad
466 };
467 -(origin_delta_theta + phi_eff)
468 }
469 IqCarrierConvention::QacPositiveCarrier => {
470 let phi_eff = if source.convention == target_convention {
473 source.reference_phase_rad
474 } else {
475 source.reference_phase_rad
476 };
477 origin_delta_theta + phi_eff
478 }
479 };
480 let (sin_p, cos_p) = total_phase.sin_cos();
481 let i_rot = i_out * cos_p - q_out * sin_p;
482 let q_rot = i_out * sin_p + q_out * cos_p;
483 i_out = i_rot;
484 q_out = q_rot;
485 if offset_out == -0.0 {
486 offset_out = 0.0;
487 }
488 return Ok(QualifiedIqSample {
489 i: i_out,
490 q: q_out,
491 convention: target_convention,
492 carrier_hz: source.carrier_hz,
493 reference_phase_rad: 0.0,
494 signed_baseband_offset_hz: offset_out,
495 });
496 }
497
498 Ok(QualifiedIqSample {
499 i: i_out,
500 q: q_out,
501 convention: target_convention,
502 carrier_hz: source.carrier_hz,
503 reference_phase_rad: source.reference_phase_rad,
504 signed_baseband_offset_hz: offset_out,
505 })
506}
507
508fn validate_known_time_uncertainty(u_t: Option<f64>) -> Result<f64, ClockDisciplineError> {
509 match u_t {
510 Some(v) if v.is_finite() && v >= 0.0 => Ok(v),
511 _ => Err(ClockDisciplineError::UnknownOrInvalidTimeUncertainty),
512 }
513}
514
515fn rational_floor_seconds(instant: RationalInstant) -> i128 {
516 let n = instant.numerator();
517 let d = instant.denominator();
518 if n >= 0 {
519 n / d
520 } else {
521 (n - d + 1) / d
522 }
523}
524
525#[derive(Clone, Copy, Debug, PartialEq, Eq)]
526pub enum ClockDisciplineError {
527 InvalidIdentifier,
528 InvalidClockScale,
529 InvalidLeapSecondTable,
530 LeapTableExpiredOrOutOfRange,
531 RationalOverflow,
532 UnknownOrInvalidTimeUncertainty,
533 CrossClockOriginRejected,
534 ClockParametersMismatch,
535 MappingOutsideValidityWindow,
536 InstantNotSimultaneous,
537 InvalidCarrierFrequency,
538 InvalidPhaseCoherenceBudget,
539 PhaseUncertaintyOverflow,
540 PhaseUncertaintyExceedsBudget,
541 UnknownIqCarrierConvention,
542 NonFiniteIqParameter,
543 UnconjugatedCarrierMemcpyRejected,
544}