1use std::borrow::Cow;
13use std::fmt;
14
15use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
16use serde::{Deserialize, Serialize};
17
18#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
20#[serde(transparent)]
21pub struct Type(pub String);
22
23impl Type {
24 pub const ANY: &'static str = "any";
26
27 pub fn new(name: impl AsRef<str>) -> Self {
29 Type(name.as_ref().trim().to_lowercase())
30 }
31
32 pub fn parse(name: &str) -> Result<Self, String> {
35 let ok = |part: &str| {
36 !part.is_empty() && part.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
37 };
38 let valid = match name.split_once(':') {
39 Some((ns, n)) => ok(ns) && ok(n),
40 None => ok(name),
41 };
42 if valid {
43 Ok(Type(name.to_string()))
44 } else {
45 Err(format!("type {name:?}: lowercase letters, digits and '-', as `name` or `namespace:name`"))
46 }
47 }
48
49 pub fn as_str(&self) -> &str {
51 &self.0
52 }
53
54 pub fn namespace(&self) -> Option<&str> {
56 self.0.split_once(':').map(|(ns, _)| ns)
57 }
58
59 pub fn feeds(&self, input: &Type) -> bool {
61 self == input || input.0 == Self::ANY || self.0 == Self::ANY
62 }
63}
64
65impl fmt::Display for Type {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 f.write_str(&self.0)
68 }
69}
70
71impl JsonSchema for Type {
72 fn schema_name() -> Cow<'static, str> {
73 "Type".into()
74 }
75
76 fn json_schema(_: &mut SchemaGenerator) -> Schema {
77 json_schema!({
78 "type": "string",
79 "description": "A type's name: a shared type (`image`) or an app's (`dspk:sorting`).",
80 "pattern": "^([a-z0-9-]+:)?[a-z0-9-]+$"
81 })
82 }
83}
84
85#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
87#[serde(transparent)]
88pub struct Format(pub String);
89
90impl Format {
91 pub fn parse(name: &str) -> Result<Self, String> {
93 let ok = !name.is_empty()
94 && name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '-' | '_' | '.'));
95 if ok {
96 Ok(Format(name.to_string()))
97 } else {
98 Err(format!("format {name:?}: lowercase letters, digits, '-', '_' or '.'"))
99 }
100 }
101
102 pub fn as_str(&self) -> &str {
104 &self.0
105 }
106}
107
108impl fmt::Display for Format {
109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110 f.write_str(&self.0)
111 }
112}
113
114impl JsonSchema for Format {
115 fn schema_name() -> Cow<'static, str> {
116 "Format".into()
117 }
118
119 fn json_schema(_: &mut SchemaGenerator) -> Schema {
120 json_schema!({
121 "type": "string",
122 "description": "How a stored result is encoded (`ome-zarr`, `parquet`, `svg`).",
123 "pattern": "^[a-z0-9._-]+$"
124 })
125 }
126}
127
128#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
131pub struct Axis {
132 pub name: String,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub unit: Option<String>,
137}
138
139#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
142pub struct TypeDescription {
143 pub name: Type,
145 pub summary: String,
147 #[serde(default, skip_serializing_if = "Vec::is_empty")]
149 pub formats: Vec<Format>,
150 #[serde(default, skip_serializing_if = "Vec::is_empty")]
152 pub axes: Vec<Axis>,
153}
154
155fn describe(name: &str, summary: &str, formats: &[&str], axes: &[(&str, Option<&str>)]) -> TypeDescription {
156 TypeDescription {
157 name: Type(name.into()),
158 summary: summary.into(),
159 formats: formats.iter().map(|f| Format((*f).into())).collect(),
160 axes: axes.iter().map(|(n, u)| Axis { name: (*n).into(), unit: u.map(String::from) }).collect(),
161 }
162}
163
164pub fn shared() -> Vec<TypeDescription> {
166 vec![
167 describe(
168 "signal",
169 "Samples over time on channels, with a rate.",
170 &["raw", "nwb-zarr", "zarr", "nwb"],
171 &[("channels", None), ("samples", Some("time"))],
172 ),
173 describe("events", "Points in time with labels: spikes, stimuli, TTLs.", &["parquet", "csv", "nwb"], &[]),
174 describe(
175 "image",
176 "Pixels: a plane, a stack, a pyramid; channels.",
177 &["ome-zarr", "ome-tiff", "png"],
178 &[("channels", None), ("z", Some("length")), ("y", Some("length")), ("x", Some("length"))],
179 ),
180 describe("mask", "Yes or no per pixel or sample.", &["ome-zarr", "png"], &[]),
181 describe("labels", "An integer per pixel or sample: objects.", &["ome-zarr"], &[]),
182 describe(
183 "region",
184 "Shapes in an image's or a recording's coordinates: polygons, intervals.",
185 &["geojson", "geoparquet", "json"],
186 &[],
187 ),
188 describe("table", "Rows and named columns.", &["parquet", "csv"], &[]),
189 describe(
190 "figure",
191 "Something to look at: static, or a description an app draws (decision 0013).",
192 &["svg", "png", "pdf", "plot-json"],
193 &[],
194 ),
195 describe(
196 "video",
197 "Frames with exact times.",
198 &["mp4", "image-sequence"],
199 &[("frames", Some("time")), ("y", Some("length")), ("x", Some("length"))],
200 ),
201 describe("file", "Anything else, opaque.", &[], &[]),
202 describe("any", "Accepts every type (inputs only).", &[], &[]),
203 ]
204}
205
206pub fn from_kind(kind: &str) -> Option<(Type, Format)> {
221 let (family, format) = kind.split_once('/')?;
222 let pair = |t: &str, f: &str| Some((Type(t.into()), Format(f.into())));
223 match (family, format) {
224 ("raw", _) => pair("signal", "raw"),
225 ("zarr", "nwb") => pair("signal", "nwb-zarr"),
226 ("zarr", "ome") => pair("image", "ome-zarr"),
227 ("zarr", "labels") => pair("labels", "ome-zarr"),
228 ("zarr", "sorting") => pair("dspk:sorting", "zarr"),
229 ("table", "parquet") => pair("table", "parquet"),
230 ("table", "csv") => pair("table", "csv"),
231 ("table", "geoparquet") => pair("region", "geoparquet"),
232 ("file", f) if !f.is_empty() => pair("file", f),
233 _ => None,
234 }
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240
241 #[test]
242 fn types_feed_their_own_and_any() {
243 let (image, mask, any) = (Type::new("Image"), Type::new("mask"), Type::new("any"));
244 assert_eq!(image.as_str(), "image");
245 assert!(image.feeds(&image));
246 assert!(!image.feeds(&mask));
247 assert!(image.feeds(&any));
248 assert!(any.feeds(&mask));
249 }
250
251 #[test]
252 fn names_are_checked_and_namespaced() {
253 assert!(Type::parse("signal").is_ok());
254 assert_eq!(Type::parse("dspk:sorting").unwrap().namespace(), Some("dspk"));
255 assert_eq!(Type::parse("table").unwrap().namespace(), None);
256 for bad in ["Image", "a:b:c", ":x", "x:", "two words", ""] {
257 assert!(Type::parse(bad).is_err(), "{bad:?}");
258 }
259 assert!(Format::parse("ome-zarr").is_ok());
260 assert!(Format::parse("OME").is_err());
261 }
262
263 #[test]
264 fn every_shared_type_is_described_once() {
265 let all = shared();
266 let mut names: Vec<&str> = all.iter().map(|t| t.name.as_str()).collect();
267 names.sort();
268 names.dedup();
269 assert_eq!(names.len(), all.len());
270 for t in &all {
271 Type::parse(t.name.as_str()).unwrap();
272 assert!(!t.summary.is_empty());
273 }
274 let signal = all.iter().find(|t| t.name.as_str() == "signal").unwrap();
275 assert_eq!(signal.axes[1].unit.as_deref(), Some("time"), "units are kinds; the rate is the data's");
276 }
277
278 #[test]
279 fn old_kinds_read_as_type_and_format() {
280 assert_eq!(from_kind("zarr/ome"), Some((Type::new("image"), Format("ome-zarr".into()))));
281 assert_eq!(from_kind("raw/spikeglx").unwrap().0, Type::new("signal"));
282 assert_eq!(from_kind("zarr/sorting").unwrap().0.namespace(), Some("dspk"));
283 assert_eq!(from_kind("table/geoparquet").unwrap().0, Type::new("region"));
284 assert_eq!(from_kind("file/png"), Some((Type::new("file"), Format("png".into()))));
285 assert_eq!(from_kind("zarr/unknown"), None);
286 assert_eq!(from_kind("nonsense"), None);
287 }
288}