-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmachine_learning.rs
More file actions
179 lines (155 loc) · 5.59 KB
/
machine_learning.rs
File metadata and controls
179 lines (155 loc) · 5.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
use crate::{
dataset::{is_invalid_name_char, SYSTEM_NAMESPACE},
raster::RasterDataType,
};
use serde::{de::Visitor, Deserialize, Serialize};
use snafu::Snafu;
use std::path::PathBuf;
use std::str::FromStr;
use strum::IntoStaticStr;
const NAME_DELIMITER: char = ':';
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct MlModelName {
pub namespace: Option<String>,
pub name: String,
}
#[derive(Snafu, IntoStaticStr, Debug)]
#[snafu(visibility(pub(crate)))]
#[snafu(context(suffix(false)))] // disables default `Snafu` suffix
pub enum MlModelNameError {
#[snafu(display("MlModelName is empty"))]
IsEmpty,
#[snafu(display("invalid character '{invalid_char}' in named model"))]
InvalidCharacter { invalid_char: String },
#[snafu(display("ml model name must consist of at most two parts"))]
TooManyParts,
}
impl MlModelName {
/// Canonicalize a name that reflects the system namespace and model.
fn canonicalize<S: Into<String> + PartialEq<&'static str>>(
name: S,
system_name: &'static str,
) -> Option<String> {
if name == system_name {
None
} else {
Some(name.into())
}
}
pub fn new<S: Into<String>>(namespace: Option<String>, name: S) -> Self {
Self {
namespace,
name: name.into(),
}
}
}
impl Serialize for MlModelName {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let d = NAME_DELIMITER;
let serialized = match (&self.namespace, &self.name) {
(None, name) => name.to_string(),
(Some(namespace), name) => {
format!("{namespace}{d}{name}")
}
};
serializer.serialize_str(&serialized)
}
}
impl<'de> Deserialize<'de> for MlModelName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_str(MlModelNameDeserializeVisitor)
}
}
impl FromStr for MlModelName {
type Err = MlModelNameError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut strings = [None, None];
let mut split = s.split(NAME_DELIMITER);
for (buffer, part) in strings.iter_mut().zip(&mut split) {
if part.is_empty() {
return Err(MlModelNameError::IsEmpty);
}
if let Some(c) = part.matches(is_invalid_name_char).next() {
return Err(MlModelNameError::InvalidCharacter {
invalid_char: c.to_string(),
});
}
*buffer = Some(part.to_string());
}
if split.next().is_some() {
return Err(MlModelNameError::TooManyParts);
}
match strings {
[Some(namespace), Some(name)] => Ok(MlModelName {
namespace: MlModelName::canonicalize(namespace, SYSTEM_NAMESPACE),
name,
}),
[Some(name), None] => Ok(MlModelName {
namespace: None,
name,
}),
_ => Err(MlModelNameError::IsEmpty),
}
}
}
struct MlModelNameDeserializeVisitor;
impl Visitor<'_> for MlModelNameDeserializeVisitor {
type Value = MlModelName;
/// always keep in sync with [`is_allowed_name_char`]
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
formatter,
"a string consisting of a namespace and name name, separated by a colon, only using alphanumeric characters, underscores & dashes"
)
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
MlModelName::from_str(s).map_err(|e| E::custom(e.to_string()))
}
}
// For now we assume all models are pixel-wise, i.e., they take a single pixel with multiple bands as input and produce a single output value.
// To support different inputs, we would need a more sophisticated logic to produce the inputs for the model.
#[derive(Debug, Clone, Hash, Eq, PartialEq, Deserialize, Serialize)]
pub struct MlModelMetadata {
pub file_path: PathBuf,
pub input_type: RasterDataType,
pub num_input_bands: u32, // number of features per sample (bands per pixel)
pub output_type: RasterDataType, // TODO: support multiple outputs, e.g. one band for the probability of prediction
// TODO: output measurement, e.g. classification or regression, label names for classification. This would have to be provided by the model creator along the model file as it cannot be extracted from the model file(?)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ml_model_name_from_str() {
const ML_MODEL_NAME: &str = "myModelName";
let mln = MlModelName::from_str(ML_MODEL_NAME).unwrap();
assert_eq!(mln.name, ML_MODEL_NAME);
assert!(mln.namespace.is_none());
}
#[test]
fn ml_model_name_from_str_prefixed() {
const ML_MODEL_NAME: &str = "d5328854-6190-4af9-ad69-4e74b0961ac9:myModelName";
let mln = MlModelName::from_str(ML_MODEL_NAME).unwrap();
assert_eq!(mln.name, "myModelName".to_string());
assert_eq!(
mln.namespace,
Some("d5328854-6190-4af9-ad69-4e74b0961ac9".to_string())
);
}
#[test]
fn ml_model_name_from_str_system() {
const ML_MODEL_NAME: &str = "_:myModelName";
let mln = MlModelName::from_str(ML_MODEL_NAME).unwrap();
assert_eq!(mln.name, "myModelName".to_string());
assert!(mln.namespace.is_none());
}
}