1use std::fs;
2use std::num::{ParseFloatError, ParseIntError};
3use std::path::Path;
4
5use nalgebra::Point2;
6use thiserror::Error;
7use visloc_vision::features::{FeatureSet, FeatureSetError};
8use visloc_vision::matching::DescriptorMatch;
9
10#[derive(Debug, Clone, PartialEq)]
11pub struct ExternalDeepFeature {
12 pub xy: Point2<f64>,
13 pub score: f32,
14 pub descriptor: Vec<f32>,
15}
16
17#[derive(Debug, Clone, Default, PartialEq)]
18pub struct ExternalDeepFeatureSet {
19 features: Vec<ExternalDeepFeature>,
20}
21
22impl ExternalDeepFeatureSet {
23 pub const fn new(features: Vec<ExternalDeepFeature>) -> Self {
24 Self { features }
25 }
26
27 pub fn features(&self) -> &[ExternalDeepFeature] {
28 &self.features
29 }
30
31 pub fn into_features(self) -> Vec<ExternalDeepFeature> {
32 self.features
33 }
34
35 pub fn len(&self) -> usize {
36 self.features.len()
37 }
38
39 pub fn is_empty(&self) -> bool {
40 self.features.is_empty()
41 }
42
43 pub fn keypoints(&self) -> Vec<Point2<f64>> {
44 self.features.iter().map(|feature| feature.xy).collect()
45 }
46
47 pub fn scores(&self) -> Vec<f32> {
48 self.features.iter().map(|feature| feature.score).collect()
49 }
50
51 pub fn descriptors(&self) -> Vec<Vec<f32>> {
52 self.features
53 .iter()
54 .map(|feature| feature.descriptor.clone())
55 .collect()
56 }
57
58 pub fn to_feature_set(&self) -> Result<FeatureSet, FeatureSetError> {
59 FeatureSet::new(self.keypoints(), self.descriptors())
60 }
61
62 pub fn into_feature_set(self) -> Result<FeatureSet, FeatureSetError> {
63 let mut keypoints = Vec::with_capacity(self.features.len());
64 let mut descriptors = Vec::with_capacity(self.features.len());
65 for feature in self.features {
66 keypoints.push(feature.xy);
67 descriptors.push(feature.descriptor);
68 }
69 FeatureSet::new(keypoints, descriptors)
70 }
71}
72
73#[derive(Debug, Clone, PartialEq)]
74pub struct ExternalDeepMatch {
75 pub query_index: usize,
76 pub train_index: usize,
77 pub confidence: f32,
78 pub distance: Option<f32>,
79}
80
81impl ExternalDeepMatch {
82 pub fn to_descriptor_match(&self) -> DescriptorMatch {
83 DescriptorMatch {
84 query_index: self.query_index,
85 train_index: self.train_index,
86 distance: self.distance.unwrap_or(1.0 - self.confidence),
87 second_best_distance: None,
88 ratio: None,
89 confidence: Some(self.confidence),
90 }
91 }
92}
93
94#[derive(Debug, Clone, Default, PartialEq)]
95pub struct ExternalDeepMatchSet {
96 matches: Vec<ExternalDeepMatch>,
97}
98
99impl ExternalDeepMatchSet {
100 pub const fn new(matches: Vec<ExternalDeepMatch>) -> Self {
101 Self { matches }
102 }
103
104 pub fn matches(&self) -> &[ExternalDeepMatch] {
105 &self.matches
106 }
107
108 pub fn into_matches(self) -> Vec<ExternalDeepMatch> {
109 self.matches
110 }
111
112 pub fn len(&self) -> usize {
113 self.matches.len()
114 }
115
116 pub fn is_empty(&self) -> bool {
117 self.matches.is_empty()
118 }
119
120 pub fn to_descriptor_matches(&self) -> Vec<DescriptorMatch> {
121 self.matches
122 .iter()
123 .map(ExternalDeepMatch::to_descriptor_match)
124 .collect()
125 }
126
127 pub fn into_descriptor_matches(self) -> Vec<DescriptorMatch> {
128 self.matches
129 .into_iter()
130 .map(|deep_match| deep_match.to_descriptor_match())
131 .collect()
132 }
133}
134
135#[derive(Debug, Error)]
136pub enum ExternalDeepError {
137 #[error("I/O error: {0}")]
138 Io(#[from] std::io::Error),
139 #[error("integer parse error: {0}")]
140 ParseInt(#[from] ParseIntError),
141 #[error("float parse error: {0}")]
142 ParseFloat(#[from] ParseFloatError),
143 #[error("feature set error: {0}")]
144 FeatureSet(#[from] FeatureSetError),
145 #[error("invalid external deep feature line: {line}")]
146 InvalidFeatureLine { line: String },
147 #[error("invalid external deep match line: {line}")]
148 InvalidMatchLine { line: String },
149}
150
151pub fn read_external_deep_features_txt(
152 path: impl AsRef<Path>,
153) -> Result<ExternalDeepFeatureSet, ExternalDeepError> {
154 parse_external_deep_features_txt(&fs::read_to_string(path)?)
155}
156
157pub fn parse_external_deep_features_txt(
158 contents: &str,
159) -> Result<ExternalDeepFeatureSet, ExternalDeepError> {
160 let mut features = Vec::new();
161
162 for line in contents.lines().map(str::trim) {
163 if line.is_empty() || line.starts_with('#') {
164 continue;
165 }
166
167 let tokens = line.split_whitespace().collect::<Vec<_>>();
168 if tokens.len() < 4 {
169 return Err(ExternalDeepError::InvalidFeatureLine {
170 line: line.to_owned(),
171 });
172 }
173
174 let xy = Point2::new(
175 parse_finite_f64(tokens[0], line, true)?,
176 parse_finite_f64(tokens[1], line, true)?,
177 );
178 let score = parse_unit_confidence(tokens[2], line, true)?;
179 let descriptor = tokens[3..]
180 .iter()
181 .map(|value| parse_finite_f32(value, line, true))
182 .collect::<Result<Vec<_>, _>>()?;
183
184 features.push(ExternalDeepFeature {
185 xy,
186 score,
187 descriptor,
188 });
189 }
190
191 let set = ExternalDeepFeatureSet::new(features);
192 set.to_feature_set()?;
193 Ok(set)
194}
195
196pub fn read_external_deep_matches_txt(
197 path: impl AsRef<Path>,
198) -> Result<ExternalDeepMatchSet, ExternalDeepError> {
199 parse_external_deep_matches_txt(&fs::read_to_string(path)?)
200}
201
202pub fn parse_external_deep_matches_txt(
203 contents: &str,
204) -> Result<ExternalDeepMatchSet, ExternalDeepError> {
205 let mut matches = Vec::new();
206
207 for line in contents.lines().map(str::trim) {
208 if line.is_empty() || line.starts_with('#') {
209 continue;
210 }
211
212 let tokens = line.split_whitespace().collect::<Vec<_>>();
213 if tokens.len() != 3 && tokens.len() != 4 {
214 return Err(ExternalDeepError::InvalidMatchLine {
215 line: line.to_owned(),
216 });
217 }
218
219 matches.push(ExternalDeepMatch {
220 query_index: tokens[0].parse()?,
221 train_index: tokens[1].parse()?,
222 confidence: parse_unit_confidence(tokens[2], line, false)?,
223 distance: tokens
224 .get(3)
225 .map(|value| parse_finite_f32(value, line, false))
226 .transpose()?,
227 });
228 }
229
230 Ok(ExternalDeepMatchSet::new(matches))
231}
232
233fn parse_unit_confidence(
234 value: &str,
235 line: &str,
236 feature_line: bool,
237) -> Result<f32, ExternalDeepError> {
238 let confidence = parse_finite_f32(value, line, feature_line)?;
239 if !(0.0..=1.0).contains(&confidence) {
240 return invalid_line(line, feature_line);
241 }
242 Ok(confidence)
243}
244
245fn parse_finite_f32(value: &str, line: &str, feature_line: bool) -> Result<f32, ExternalDeepError> {
246 let parsed = value.parse::<f32>()?;
247 if !parsed.is_finite() {
248 return invalid_line(line, feature_line);
249 }
250 Ok(parsed)
251}
252
253fn parse_finite_f64(value: &str, line: &str, feature_line: bool) -> Result<f64, ExternalDeepError> {
254 let parsed = value.parse::<f64>()?;
255 if !parsed.is_finite() {
256 return invalid_line(line, feature_line);
257 }
258 Ok(parsed)
259}
260
261fn invalid_line<T>(line: &str, feature_line: bool) -> Result<T, ExternalDeepError> {
262 if feature_line {
263 Err(ExternalDeepError::InvalidFeatureLine {
264 line: line.to_owned(),
265 })
266 } else {
267 Err(ExternalDeepError::InvalidMatchLine {
268 line: line.to_owned(),
269 })
270 }
271}