Skip to main content

faultscope_core/
labels.rs

1use std::collections::HashMap;
2
3use crate::{NoiseLocation, NoiseModel, TagValue};
4
5/// Dense identifier for a user-facing noise-location label.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
7#[repr(transparent)]
8pub struct LocationId(usize);
9
10impl LocationId {
11    pub(crate) const fn new(index: usize) -> Self {
12        Self(index)
13    }
14
15    pub const fn index(self) -> usize {
16        self.0
17    }
18}
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21#[repr(transparent)]
22pub(crate) struct TagValueId(pub(crate) usize);
23
24impl TagValueId {
25    pub(crate) const fn index(self) -> usize {
26        self.0
27    }
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub(crate) enum HotspotTagKind {
32    Round,
33    Gate,
34    Operation,
35}
36
37impl HotspotTagKind {
38    const ALL: [Self; 3] = [Self::Round, Self::Gate, Self::Operation];
39
40    const fn index(self) -> usize {
41        match self {
42            Self::Round => 0,
43            Self::Gate => 1,
44            Self::Operation => 2,
45        }
46    }
47
48    const fn label(self) -> &'static str {
49        match self {
50            Self::Round => "round",
51            Self::Gate => "gate",
52            Self::Operation => "operation",
53        }
54    }
55}
56
57#[derive(Debug, Clone, PartialEq)]
58struct LocationLabel {
59    label: String,
60    tags: HashMap<String, TagValue>,
61    hotspot_tags: [Option<TagValueId>; 3],
62    lexical_rank: usize,
63}
64
65/// Boundary catalog retaining user-facing labels outside computation-heavy data.
66#[derive(Debug, Clone, PartialEq, Default)]
67pub struct LocationCatalog {
68    locations: Vec<LocationLabel>,
69    tag_values: Vec<TagValue>,
70}
71
72impl LocationCatalog {
73    pub fn len(&self) -> usize {
74        self.locations.len()
75    }
76
77    pub fn is_empty(&self) -> bool {
78        self.locations.is_empty()
79    }
80
81    pub fn label(&self, location_id: LocationId) -> &str {
82        &self.locations[location_id.index()].label
83    }
84
85    pub fn tags(&self, location_id: LocationId) -> &HashMap<String, TagValue> {
86        &self.locations[location_id.index()].tags
87    }
88
89    pub fn find_label(&self, label: &str) -> Option<LocationId> {
90        self.locations
91            .iter()
92            .position(|location| location.label == label)
93            .map(LocationId::new)
94    }
95
96    pub(crate) fn hotspot_tag(
97        &self,
98        location_id: LocationId,
99        kind: HotspotTagKind,
100    ) -> Option<TagValueId> {
101        self.locations[location_id.index()].hotspot_tags[kind.index()]
102    }
103
104    pub(crate) fn tag_value(&self, tag_value_id: TagValueId) -> &TagValue {
105        &self.tag_values[tag_value_id.index()]
106    }
107
108    pub(crate) fn tag_value_count(&self) -> usize {
109        self.tag_values.len()
110    }
111
112    pub(crate) fn lexical_rank(&self, location_id: LocationId) -> usize {
113        self.locations[location_id.index()].lexical_rank
114    }
115
116    pub(crate) fn materialize_noise_location(
117        &self,
118        location: &IndexedNoiseLocation,
119    ) -> NoiseLocation {
120        NoiseLocation {
121            id: self.label(location.location_id).to_string(),
122            model: location.model.clone(),
123            rate: location.rate,
124            qubits: location.qubits.clone(),
125            tags: self.tags(location.location_id).clone(),
126        }
127    }
128}
129
130#[derive(Debug, Clone, PartialEq)]
131pub struct IndexedNoiseLocation {
132    pub location_id: LocationId,
133    pub model: NoiseModel,
134    pub rate: f64,
135    pub qubits: Vec<usize>,
136}
137
138impl IndexedNoiseLocation {
139    pub(crate) fn from_input(location_id: LocationId, location: NoiseLocation) -> Self {
140        Self {
141            location_id,
142            model: location.model,
143            rate: location.rate,
144            qubits: location.qubits,
145        }
146    }
147}
148
149pub(crate) struct LocationCatalogBuilder {
150    location_ids: HashMap<String, LocationId>,
151    locations: Vec<LocationLabel>,
152    tag_value_ids: HashMap<TagValue, TagValueId>,
153    tag_values: Vec<TagValue>,
154}
155
156impl LocationCatalogBuilder {
157    pub(crate) fn with_capacity(capacity: usize) -> Self {
158        Self {
159            location_ids: HashMap::with_capacity(capacity),
160            locations: Vec::with_capacity(capacity),
161            tag_value_ids: HashMap::new(),
162            tag_values: Vec::new(),
163        }
164    }
165
166    /// Intern a location label. The first tag set wins for repeated labels,
167    /// matching the historical DEM hotspot grouping behavior.
168    pub(crate) fn intern(&mut self, label: String, tags: HashMap<String, TagValue>) -> LocationId {
169        self.intern_with_status(label, tags).0
170    }
171
172    pub(crate) fn intern_with_status(
173        &mut self,
174        label: String,
175        tags: HashMap<String, TagValue>,
176    ) -> (LocationId, bool) {
177        if let Some(location_id) = self.location_ids.get(&label) {
178            return (*location_id, false);
179        }
180
181        let location_id = LocationId::new(self.locations.len());
182        let mut hotspot_tags = [None; 3];
183        for kind in HotspotTagKind::ALL {
184            if let Some(tag_value) = tags.get(kind.label()) {
185                hotspot_tags[kind.index()] = Some(self.intern_tag_value(tag_value.clone()));
186            }
187        }
188        self.location_ids.insert(label.clone(), location_id);
189        self.locations.push(LocationLabel {
190            label,
191            tags,
192            hotspot_tags,
193            lexical_rank: 0,
194        });
195        (location_id, true)
196    }
197
198    pub(crate) fn finish(mut self) -> LocationCatalog {
199        let mut lexical_order = (0..self.locations.len()).collect::<Vec<_>>();
200        lexical_order.sort_unstable_by(|left, right| {
201            self.locations[*left]
202                .label
203                .cmp(&self.locations[*right].label)
204        });
205        for (rank, location_index) in lexical_order.into_iter().enumerate() {
206            self.locations[location_index].lexical_rank = rank;
207        }
208        LocationCatalog {
209            locations: self.locations,
210            tag_values: self.tag_values,
211        }
212    }
213
214    fn intern_tag_value(&mut self, value: TagValue) -> TagValueId {
215        if let Some(tag_value_id) = self.tag_value_ids.get(&value) {
216            return *tag_value_id;
217        }
218        let tag_value_id = TagValueId(self.tag_values.len());
219        self.tag_value_ids.insert(value.clone(), tag_value_id);
220        self.tag_values.push(value);
221        tag_value_id
222    }
223}