1use crate::value::Value;
44use std::collections::BTreeMap;
45
46#[derive(Debug, Clone, PartialEq)]
54pub struct MeasurementContext {
55 pub observer: String,
57 pub instrument: String,
59 pub instant_secs: i64,
61 pub instant_nanos: u32,
63 pub frame: Option<String>,
65 pub uncertainty: Option<f64>,
67 pub stalk_id: Option<u64>,
69}
70
71impl MeasurementContext {
72 pub fn new(observer: &str, instrument: &str, instant_secs: i64) -> Self {
74 Self {
75 observer: observer.into(),
76 instrument: instrument.into(),
77 instant_secs,
78 instant_nanos: 0,
79 frame: None,
80 uncertainty: None,
81 stalk_id: None,
82 }
83 }
84
85 pub fn with_frame(mut self, frame: &str) -> Self {
87 self.frame = Some(frame.into());
88 self
89 }
90
91 pub fn with_uncertainty(mut self, u: f64) -> Self {
93 self.uncertainty = Some(u);
94 self
95 }
96
97 pub fn with_stalk(mut self, stalk_id: u64) -> Self {
99 self.stalk_id = Some(stalk_id);
100 self
101 }
102
103 pub fn to_value(&self) -> Value {
105 let mut rec = BTreeMap::new();
106 rec.insert("observer".into(), Value::String(self.observer.clone()));
107 rec.insert("instrument".into(), Value::String(self.instrument.clone()));
108 rec.insert("instant_secs".into(), Value::I64(self.instant_secs));
109 rec.insert(
110 "instant_nanos".into(),
111 Value::U64(self.instant_nanos as u64),
112 );
113 if let Some(ref f) = self.frame {
114 rec.insert("frame".into(), Value::String(f.clone()));
115 }
116 if let Some(u) = self.uncertainty {
117 rec.insert("uncertainty".into(), Value::F64(u));
118 }
119 if let Some(s) = self.stalk_id {
120 rec.insert("stalk_id".into(), Value::U64(s));
121 }
122 Value::Record(rec)
123 }
124
125 pub fn from_value(val: &Value) -> Option<Self> {
127 let rec = match val {
128 Value::Record(r) => r,
129 _ => return None,
130 };
131 let observer = match rec.get("observer") {
132 Some(Value::String(s)) => s.clone(),
133 _ => return None,
134 };
135 let instrument = match rec.get("instrument") {
136 Some(Value::String(s)) => s.clone(),
137 _ => return None,
138 };
139 let instant_secs = match rec.get("instant_secs") {
140 Some(Value::I64(n)) => *n,
141 _ => return None,
142 };
143 let instant_nanos = match rec.get("instant_nanos") {
144 Some(Value::U64(n)) => *n as u32,
145 _ => 0,
146 };
147 let frame = match rec.get("frame") {
148 Some(Value::String(s)) => Some(s.clone()),
149 _ => None,
150 };
151 let uncertainty = match rec.get("uncertainty") {
152 Some(Value::F64(n)) => Some(*n),
153 _ => None,
154 };
155 let stalk_id = match rec.get("stalk_id") {
156 Some(Value::U64(n)) => Some(*n),
157 _ => None,
158 };
159 Some(Self {
160 observer,
161 instrument,
162 instant_secs,
163 instant_nanos,
164 frame,
165 uncertainty,
166 stalk_id,
167 })
168 }
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
175pub enum IdentifierModality {
176 Visual,
178 Oral,
180 Heraldic,
182 Tactile,
184}
185
186impl IdentifierModality {
187 pub fn as_str(&self) -> &'static str {
189 match self {
190 Self::Visual => "visual",
191 Self::Oral => "oral",
192 Self::Heraldic => "heraldic",
193 Self::Tactile => "tactile",
194 }
195 }
196
197 pub fn from_str(s: &str) -> Option<Self> {
199 match s {
200 "visual" => Some(Self::Visual),
201 "oral" => Some(Self::Oral),
202 "heraldic" => Some(Self::Heraldic),
203 "tactile" => Some(Self::Tactile),
204 _ => None,
205 }
206 }
207}
208
209#[derive(Debug, Clone, PartialEq)]
211pub struct IdentifierView {
212 pub iri: String,
214 pub modality: IdentifierModality,
216 pub content: String,
218 pub locale: Option<String>,
220}
221
222impl IdentifierView {
223 pub fn new(iri: &str, modality: IdentifierModality, content: &str) -> Self {
225 Self {
226 iri: iri.into(),
227 modality,
228 content: content.into(),
229 locale: None,
230 }
231 }
232
233 pub fn with_locale(mut self, locale: &str) -> Self {
235 self.locale = Some(locale.into());
236 self
237 }
238
239 pub fn to_value(&self) -> Value {
241 let mut rec = BTreeMap::new();
242 rec.insert("iri".into(), Value::String(self.iri.clone()));
243 rec.insert(
244 "modality".into(),
245 Value::String(self.modality.as_str().into()),
246 );
247 rec.insert("content".into(), Value::String(self.content.clone()));
248 if let Some(ref l) = self.locale {
249 rec.insert("locale".into(), Value::String(l.clone()));
250 }
251 Value::Record(rec)
252 }
253}
254
255#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
262pub enum LevelOfDetail {
263 Continuum,
265 Mesoscopic,
267 Molecular,
269 Atomic,
271 Subatomic,
273}
274
275impl LevelOfDetail {
276 pub fn as_str(&self) -> &'static str {
278 match self {
279 Self::Continuum => "continuum",
280 Self::Mesoscopic => "mesoscopic",
281 Self::Molecular => "molecular",
282 Self::Atomic => "atomic",
283 Self::Subatomic => "subatomic",
284 }
285 }
286
287 pub fn from_str(s: &str) -> Option<Self> {
289 match s {
290 "continuum" => Some(Self::Continuum),
291 "mesoscopic" => Some(Self::Mesoscopic),
292 "molecular" => Some(Self::Molecular),
293 "atomic" => Some(Self::Atomic),
294 "subatomic" => Some(Self::Subatomic),
295 _ => None,
296 }
297 }
298
299 pub fn is_coarser_than(&self, other: &Self) -> bool {
301 self < other
302 }
303}
304
305#[derive(Debug, Clone, PartialEq)]
307pub struct MultiScaleSheaf {
308 pub sheaf_id: String,
310 pub lod: LevelOfDetail,
312 pub scale: f64,
314 pub is_finest: bool,
316}
317
318impl MultiScaleSheaf {
319 pub fn new(sheaf_id: &str, lod: LevelOfDetail, scale: f64) -> Self {
321 Self {
322 sheaf_id: sheaf_id.into(),
323 lod,
324 scale,
325 is_finest: false,
326 }
327 }
328
329 pub fn finest(sheaf_id: &str, lod: LevelOfDetail, scale: f64) -> Self {
331 Self {
332 sheaf_id: sheaf_id.into(),
333 lod,
334 scale,
335 is_finest: true,
336 }
337 }
338
339 pub fn to_value(&self) -> Value {
341 let mut rec = BTreeMap::new();
342 rec.insert("sheaf_id".into(), Value::String(self.sheaf_id.clone()));
343 rec.insert("lod".into(), Value::String(self.lod.as_str().into()));
344 rec.insert("scale".into(), Value::F64(self.scale));
345 rec.insert("is_finest".into(), Value::Bool(self.is_finest));
346 Value::Record(rec)
347 }
348}
349
350#[derive(Debug, Clone, PartialEq)]
359pub struct CivicInstant {
360 pub secs: i64,
362 pub nanos: u32,
364 pub authority: String,
367 pub uncertainty_nanos: Option<u64>,
369}
370
371impl CivicInstant {
372 pub fn new(secs: i64, nanos: u32, authority: &str) -> Self {
374 Self {
375 secs,
376 nanos,
377 authority: authority.into(),
378 uncertainty_nanos: None,
379 }
380 }
381
382 pub fn with_uncertainty(mut self, uncertainty_nanos: u64) -> Self {
384 self.uncertainty_nanos = Some(uncertainty_nanos);
385 self
386 }
387
388 pub fn to_value(&self) -> Value {
390 let mut rec = BTreeMap::new();
391 rec.insert("secs".into(), Value::I64(self.secs));
392 rec.insert("nanos".into(), Value::U64(self.nanos as u64));
393 rec.insert("authority".into(), Value::String(self.authority.clone()));
394 if let Some(u) = self.uncertainty_nanos {
395 rec.insert("uncertainty_nanos".into(), Value::U64(u));
396 }
397 Value::Record(rec)
398 }
399}
400
401#[derive(Debug, Clone, PartialEq)]
405pub struct AgentCharacteristic {
406 pub agent_id: String,
408 pub name: String,
410 pub value: f64,
412 pub observed_at: i64,
414 pub sample_count: u64,
416}
417
418impl AgentCharacteristic {
419 pub fn new(agent_id: &str, name: &str, value: f64, observed_at: i64) -> Self {
421 Self {
422 agent_id: agent_id.into(),
423 name: name.into(),
424 value,
425 observed_at,
426 sample_count: 1,
427 }
428 }
429
430 pub fn with_sample_count(mut self, count: u64) -> Self {
432 self.sample_count = count;
433 self
434 }
435
436 pub fn to_value(&self) -> Value {
438 let mut rec = BTreeMap::new();
439 rec.insert("agent_id".into(), Value::String(self.agent_id.clone()));
440 rec.insert("name".into(), Value::String(self.name.clone()));
441 rec.insert("value".into(), Value::F64(self.value));
442 rec.insert("observed_at".into(), Value::I64(self.observed_at));
443 rec.insert("sample_count".into(), Value::U64(self.sample_count));
444 Value::Record(rec)
445 }
446}
447
448#[derive(Debug, Clone, Default)]
451pub struct AgentCharacteristicsKb {
452 entries: Vec<AgentCharacteristic>,
453}
454
455impl AgentCharacteristicsKb {
456 pub fn new() -> Self {
458 Self::default()
459 }
460
461 pub fn log(&mut self, entry: AgentCharacteristic) -> &mut Self {
463 self.entries.push(entry);
464 self
465 }
466
467 pub fn for_agent(&self, agent_id: &str) -> Vec<&AgentCharacteristic> {
469 self.entries
470 .iter()
471 .filter(|e| e.agent_id == agent_id)
472 .collect()
473 }
474
475 pub fn latest(&self, agent_id: &str, name: &str) -> Option<&AgentCharacteristic> {
477 self.entries
478 .iter()
479 .filter(|e| e.agent_id == agent_id && e.name == name)
480 .max_by_key(|e| e.observed_at)
481 }
482
483 pub fn mean(&self, agent_id: &str, name: &str) -> Option<f64> {
485 let matches: Vec<&AgentCharacteristic> = self
486 .entries
487 .iter()
488 .filter(|e| e.agent_id == agent_id && e.name == name)
489 .collect();
490 if matches.is_empty() {
491 return None;
492 }
493 let total: f64 = matches.iter().map(|e| e.value).sum();
494 Some(total / matches.len() as f64)
495 }
496
497 pub fn len(&self) -> usize {
499 self.entries.len()
500 }
501
502 pub fn is_empty(&self) -> bool {
504 self.entries.is_empty()
505 }
506
507 pub fn to_value_list(&self) -> Value {
509 Value::List(self.entries.iter().map(|e| e.to_value()).collect())
510 }
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516
517 #[test]
520 fn w7_measurement_context_basic() {
521 let mc = MeasurementContext::new("did:alice", "sensor:therm-0", 1000);
522 assert_eq!(mc.observer, "did:alice");
523 assert_eq!(mc.instrument, "sensor:therm-0");
524 assert_eq!(mc.instant_secs, 1000);
525 assert_eq!(mc.instant_nanos, 0);
526 assert!(mc.frame.is_none());
527 assert!(mc.uncertainty.is_none());
528 }
529
530 #[test]
531 fn w7_measurement_context_with_options() {
532 let mc = MeasurementContext::new("did:bob", "sensor:accel-1", 2000)
533 .with_frame("frame:lab")
534 .with_uncertainty(0.01)
535 .with_stalk(42);
536 assert_eq!(mc.frame, Some("frame:lab".into()));
537 assert_eq!(mc.uncertainty, Some(0.01));
538 assert_eq!(mc.stalk_id, Some(42));
539 }
540
541 #[test]
542 fn w7_measurement_context_round_trip() {
543 let mc = MeasurementContext::new("did:alice", "sensor:therm-0", 1000)
544 .with_uncertainty(0.5)
545 .with_stalk(7);
546 let v = mc.to_value();
547 let restored = MeasurementContext::from_value(&v).unwrap();
548 assert_eq!(restored.observer, "did:alice");
549 assert_eq!(restored.instrument, "sensor:therm-0");
550 assert_eq!(restored.instant_secs, 1000);
551 assert_eq!(restored.uncertainty, Some(0.5));
552 assert_eq!(restored.stalk_id, Some(7));
553 }
554
555 #[test]
556 fn w7_measurement_context_from_non_record() {
557 let v = Value::I64(42);
558 assert!(MeasurementContext::from_value(&v).is_none());
559 }
560
561 #[test]
564 fn w9_identifier_modality_round_trip() {
565 for m in &[
566 IdentifierModality::Visual,
567 IdentifierModality::Oral,
568 IdentifierModality::Heraldic,
569 IdentifierModality::Tactile,
570 ] {
571 let s = m.as_str();
572 assert_eq!(IdentifierModality::from_str(s), Some(*m));
573 }
574 assert_eq!(IdentifierModality::from_str("unknown"), None);
575 }
576
577 #[test]
578 fn w9_identifier_view_basic() {
579 let v = IdentifierView::new("did:alice", IdentifierModality::Oral, "Alice");
580 assert_eq!(v.iri, "did:alice");
581 assert_eq!(v.modality, IdentifierModality::Oral);
582 assert_eq!(v.content, "Alice");
583 assert!(v.locale.is_none());
584 }
585
586 #[test]
587 fn w9_identifier_view_with_locale() {
588 let v =
589 IdentifierView::new("did:alice", IdentifierModality::Oral, "爱丽丝").with_locale("zh");
590 assert_eq!(v.locale, Some("zh".into()));
591 }
592
593 #[test]
594 fn w9_identifier_view_to_value() {
595 let v = IdentifierView::new("did:alice", IdentifierModality::Heraldic, "rose sigil")
596 .with_locale("en");
597 let val = v.to_value();
598 match &val {
599 Value::Record(r) => {
600 assert_eq!(r.len(), 4);
601 assert!(r.contains_key("iri"));
602 assert!(r.contains_key("modality"));
603 assert!(r.contains_key("content"));
604 assert!(r.contains_key("locale"));
605 }
606 _ => panic!("expected Record"),
607 }
608 }
609
610 #[test]
613 fn w14_lod_round_trip() {
614 for l in &[
615 LevelOfDetail::Continuum,
616 LevelOfDetail::Mesoscopic,
617 LevelOfDetail::Molecular,
618 LevelOfDetail::Atomic,
619 LevelOfDetail::Subatomic,
620 ] {
621 let s = l.as_str();
622 assert_eq!(LevelOfDetail::from_str(s), Some(*l));
623 }
624 }
625
626 #[test]
627 fn w14_lod_ordering() {
628 assert!(LevelOfDetail::Continuum.is_coarser_than(&LevelOfDetail::Molecular));
629 assert!(LevelOfDetail::Molecular.is_coarser_than(&LevelOfDetail::Atomic));
630 assert!(!LevelOfDetail::Atomic.is_coarser_than(&LevelOfDetail::Continuum));
631 }
632
633 #[test]
634 fn w14_multi_scale_sheaf_basic() {
635 let s = MultiScaleSheaf::new("sheaf:fluid", LevelOfDetail::Continuum, 1.0);
636 assert_eq!(s.sheaf_id, "sheaf:fluid");
637 assert_eq!(s.lod, LevelOfDetail::Continuum);
638 assert_eq!(s.scale, 1.0);
639 assert!(!s.is_finest);
640 }
641
642 #[test]
643 fn w14_multi_scale_sheaf_finest() {
644 let s = MultiScaleSheaf::finest("sheaf:fluid", LevelOfDetail::Atomic, 1e-10);
645 assert!(s.is_finest);
646 }
647
648 #[test]
649 fn w14_multi_scale_sheaf_to_value() {
650 let s = MultiScaleSheaf::new("sheaf:fluid", LevelOfDetail::Molecular, 1e-9);
651 let v = s.to_value();
652 match &v {
653 Value::Record(r) => {
654 assert_eq!(r.len(), 4);
655 assert!(r.contains_key("sheaf_id"));
656 assert!(r.contains_key("lod"));
657 assert!(r.contains_key("scale"));
658 assert!(r.contains_key("is_finest"));
659 }
660 _ => panic!("expected Record"),
661 }
662 }
663
664 #[test]
667 fn w15_civic_instant_basic() {
668 let ci = CivicInstant::new(1000, 500_000_000, "did:civic:nist");
669 assert_eq!(ci.secs, 1000);
670 assert_eq!(ci.nanos, 500_000_000);
671 assert_eq!(ci.authority, "did:civic:nist");
672 assert!(ci.uncertainty_nanos.is_none());
673 }
674
675 #[test]
676 fn w15_civic_instant_with_uncertainty() {
677 let ci = CivicInstant::new(1000, 0, "did:civic:gps").with_uncertainty(100);
678 assert_eq!(ci.uncertainty_nanos, Some(100));
679 }
680
681 #[test]
682 fn w15_civic_instant_to_value() {
683 let ci = CivicInstant::new(2000, 0, "did:civic:nist").with_uncertainty(50);
684 let v = ci.to_value();
685 match &v {
686 Value::Record(r) => {
687 assert_eq!(r.len(), 4);
688 assert!(r.contains_key("secs"));
689 assert!(r.contains_key("nanos"));
690 assert!(r.contains_key("authority"));
691 assert!(r.contains_key("uncertainty_nanos"));
692 }
693 _ => panic!("expected Record"),
694 }
695 }
696
697 #[test]
700 fn t59_agent_characteristic_basic() {
701 let c = AgentCharacteristic::new("did:agent-1", "latency_p50_ms", 42.5, 1000);
702 assert_eq!(c.agent_id, "did:agent-1");
703 assert_eq!(c.name, "latency_p50_ms");
704 assert_eq!(c.value, 42.5);
705 assert_eq!(c.sample_count, 1);
706 }
707
708 #[test]
709 fn t59_agent_characteristic_with_sample_count() {
710 let c = AgentCharacteristic::new("did:agent-1", "success_rate", 0.95, 1000)
711 .with_sample_count(100);
712 assert_eq!(c.sample_count, 100);
713 }
714
715 #[test]
716 fn t59_kb_log_and_query() {
717 let mut kb = AgentCharacteristicsKb::new();
718 kb.log(AgentCharacteristic::new(
719 "did:agent-1",
720 "latency_ms",
721 42.0,
722 1000,
723 ));
724 kb.log(AgentCharacteristic::new(
725 "did:agent-1",
726 "latency_ms",
727 38.0,
728 2000,
729 ));
730 kb.log(AgentCharacteristic::new(
731 "did:agent-2",
732 "latency_ms",
733 55.0,
734 1000,
735 ));
736 assert_eq!(kb.len(), 3);
737 let a1 = kb.for_agent("did:agent-1");
738 assert_eq!(a1.len(), 2);
739 let a2 = kb.for_agent("did:agent-2");
740 assert_eq!(a2.len(), 1);
741 }
742
743 #[test]
744 fn t59_kb_latest() {
745 let mut kb = AgentCharacteristicsKb::new();
746 kb.log(AgentCharacteristic::new(
747 "did:agent-1",
748 "latency_ms",
749 42.0,
750 1000,
751 ));
752 kb.log(AgentCharacteristic::new(
753 "did:agent-1",
754 "latency_ms",
755 38.0,
756 2000,
757 ));
758 kb.log(AgentCharacteristic::new(
759 "did:agent-1",
760 "latency_ms",
761 40.0,
762 1500,
763 ));
764 let latest = kb.latest("did:agent-1", "latency_ms").unwrap();
765 assert_eq!(latest.value, 38.0);
766 assert_eq!(latest.observed_at, 2000);
767 }
768
769 #[test]
770 fn t59_kb_mean() {
771 let mut kb = AgentCharacteristicsKb::new();
772 kb.log(AgentCharacteristic::new(
773 "did:agent-1",
774 "latency_ms",
775 40.0,
776 1000,
777 ));
778 kb.log(AgentCharacteristic::new(
779 "did:agent-1",
780 "latency_ms",
781 60.0,
782 2000,
783 ));
784 let mean = kb.mean("did:agent-1", "latency_ms").unwrap();
785 assert!((mean - 50.0).abs() < 1e-9);
786 }
787
788 #[test]
789 fn t59_kb_latest_missing() {
790 let kb = AgentCharacteristicsKb::new();
791 assert!(kb.latest("did:unknown", "anything").is_none());
792 }
793
794 #[test]
795 fn t59_kb_mean_missing() {
796 let kb = AgentCharacteristicsKb::new();
797 assert!(kb.mean("did:unknown", "anything").is_none());
798 }
799
800 #[test]
801 fn t59_kb_empty() {
802 let kb = AgentCharacteristicsKb::new();
803 assert!(kb.is_empty());
804 assert_eq!(kb.len(), 0);
805 }
806
807 #[test]
808 fn t59_kb_to_value_list() {
809 let mut kb = AgentCharacteristicsKb::new();
810 kb.log(AgentCharacteristic::new(
811 "did:agent-1",
812 "latency_ms",
813 42.0,
814 1000,
815 ));
816 let v = kb.to_value_list();
817 match &v {
818 Value::List(xs) => assert_eq!(xs.len(), 1),
819 _ => panic!("expected List"),
820 }
821 }
822}