1use crate::encode::errors::{EncodeError, Result};
11use crate::encode::registry::Conversion;
12use crate::encode::variables::STANDARD_GRAVITY;
13
14pub fn compact_unit(unit: &str) -> String {
17 unit.trim()
18 .to_lowercase()
19 .replace('²', "^2")
20 .chars()
21 .filter(|character| !character.is_whitespace() && !"*()[]".contains(*character))
22 .collect()
23}
24
25fn compact_for(rule: &Conversion, unit: &str) -> String {
29 let compact = compact_unit(unit);
30 match rule {
31 Conversion::Celsius | Conversion::SoilTemperature => compact
32 .replace('°', "")
33 .replace("degrees", "")
34 .replace("degree", ""),
35 Conversion::GeopotentialToMetres => compact.replace('^', ""),
36 Conversion::CodeTable { .. } => compact.replace("codetable", ""),
37 _ => compact,
38 }
39}
40
41const TEMPERATURE_SPELLINGS: [(&str, &str); 8] = [
44 ("k", "K"),
45 ("kelvin", "K"),
46 ("c", "C"),
47 ("celsius", "C"),
48 ("degc", "C"),
49 ("f", "F"),
50 ("fahrenheit", "F"),
51 ("degf", "F"),
52];
53
54pub fn temperature_unit(unit: &str) -> Result<&'static str> {
57 let compact = compact_for(&Conversion::Celsius, unit);
58 TEMPERATURE_SPELLINGS
59 .iter()
60 .find(|(spelling, _)| *spelling == compact)
61 .map(|(_, letter)| *letter)
62 .ok_or_else(|| unsupported("temperature", unit))
63}
64
65fn unsupported(what: &str, unit: &str) -> EncodeError {
66 EncodeError::conversion(format!(
67 "unsupported {what} unit: {}",
68 if unit.is_empty() { "<missing>" } else { unit }
69 ))
70}
71
72pub const SOIL_KELVIN_THRESHOLD: f64 = 150.0;
76
77fn soil_temperature_unit(unit: &'static str, values: &[f64]) -> &'static str {
85 if unit == "C" && values.iter().any(|value| *value > SOIL_KELVIN_THRESHOLD) {
86 "K"
87 } else {
88 unit
89 }
90}
91
92const MM_PER_HOUR: [&str; 2] = ["mm/h", "mm/hr"];
95const KG_PER_M2_S: [&str; 4] = ["kg/m^2s", "kg/m2s", "kgm^-2s^-1", "kgm-2s-1"];
96const METRES_ACCUMULATION: [&str; 3] = ["-", "m", ""];
99const MM_ACCUMULATION: [&str; 9] = [
103 "kg/m^2", "kg/m2", "kgm^-2", "kgm-2", "mm", "kg/m^2s", "kg/m^2*s", "kg/m2s", "kg/m2*s",
104];
105const PASCALS: [&str; 1] = ["pa"];
106const METRES: [&str; 5] = ["m", "metre", "meter", "metres", "meters"];
107const MASS_RATIO: [&str; 1] = ["kg/kg"];
108const PROPORTION: [&str; 5] = ["proportion", "fraction", "1", "-", ""];
109const CLOUD_FRACTION: [&str; 5] = ["-", "1", "fraction", "proportion", "0-1"];
110const DEGREES_TRUE: [&str; 6] = [
111 "degreetrue",
112 "degtrue",
113 "degrees",
114 "degree",
115 "deg",
116 "degreestrue",
117];
118const GEOPOTENTIAL_METRES: [&str; 2] = ["gpm", "m"];
124const GEOPOTENTIAL: [&str; 2] = ["m2/s2", "m2s-2"];
125const MASS_DENSITY: [&str; 4] = ["kg/m^3", "kg/m3", "kgm^-3", "kgm-3"];
126const PER_SECOND: [&str; 4] = ["1/s", "/s", "s-1", "s^-1"];
129
130fn noun(rule: &Conversion) -> Option<&'static str> {
132 Some(match rule {
133 Conversion::Identity { .. } => return None,
134 Conversion::Celsius => "temperature",
135 Conversion::SoilTemperature => "soil temperature",
136 Conversion::PrecipitationRate => "precipitation rate",
137 Conversion::PrecipitationAccumulation => "precipitation accumulation",
138 Conversion::PascalToHectopascal => "pressure",
139 Conversion::MetreToKilometre => "distance",
140 Conversion::MassRatioToGPerKg => "specific humidity",
141 Conversion::ProportionToPercent => "proportion",
142 Conversion::CloudCover => "cloud cover",
143 Conversion::DegreesTrue => "direction",
144 Conversion::GeopotentialToMetres => "geopotential height",
145 Conversion::MassDensityToMicrograms => "mass density",
146 Conversion::PerSecondTo1e5 => "per-second",
147 Conversion::CodeTable { .. } => "code table",
148 })
149}
150
151impl Conversion {
152 pub fn accepted_units(&self) -> Option<Vec<&str>> {
157 Some(match self {
158 Self::Identity {
159 accepted_units: None,
160 } => return None,
161 Self::Identity {
162 accepted_units: Some(units),
163 } => units.iter().map(String::as_str).collect(),
164 Self::CodeTable { table } => vec!["1", "-", "", table.as_str()],
165 Self::Celsius | Self::SoilTemperature => TEMPERATURE_SPELLINGS
166 .iter()
167 .map(|(spelling, _)| *spelling)
168 .collect(),
169 Self::PrecipitationRate => KG_PER_M2_S.iter().chain(&MM_PER_HOUR).copied().collect(),
170 Self::PrecipitationAccumulation => METRES_ACCUMULATION
171 .iter()
172 .chain(&MM_ACCUMULATION)
173 .copied()
174 .collect(),
175 Self::PascalToHectopascal => PASCALS.to_vec(),
176 Self::MetreToKilometre => METRES.to_vec(),
177 Self::MassRatioToGPerKg => MASS_RATIO.to_vec(),
178 Self::ProportionToPercent => PROPORTION.to_vec(),
179 Self::CloudCover => std::iter::once("%").chain(CLOUD_FRACTION).collect(),
180 Self::DegreesTrue => DEGREES_TRUE.to_vec(),
181 Self::GeopotentialToMetres => GEOPOTENTIAL_METRES
182 .iter()
183 .chain(&GEOPOTENTIAL)
184 .copied()
185 .collect(),
186 Self::MassDensityToMicrograms => MASS_DENSITY.to_vec(),
187 Self::PerSecondTo1e5 => PER_SECOND.to_vec(),
188 })
189 }
190
191 pub fn accepts(&self, unit: &str) -> bool {
194 let Some(accepted) = self.accepted_units() else {
195 return true;
196 };
197 let compact = compact_for(self, unit);
198 if accepted.contains(&compact.as_str()) {
199 return true;
200 }
201 match self {
202 Self::CodeTable { table } => {
203 compact.contains(table.as_str()) || compact.contains("0=no")
204 }
205 _ => false,
206 }
207 }
208
209 fn refuse(&self, unit: &str) -> EncodeError {
210 match noun(self) {
211 Some(noun) => unsupported(noun, unit),
212 None => EncodeError::conversion(format!(
213 "unsupported unit: {} (expected one of {})",
214 if unit.is_empty() { "<missing>" } else { unit },
215 self.accepted_units().unwrap_or_default().join(", ")
216 )),
217 }
218 }
219
220 fn scaled(&self, unit: &str) -> bool {
224 let compact = compact_for(self, unit);
225 let within = |list: &[&str]| list.contains(&compact.as_str());
226 match self {
227 Self::PrecipitationRate => !within(&MM_PER_HOUR),
228 Self::PrecipitationAccumulation => within(&METRES_ACCUMULATION),
229 Self::PascalToHectopascal => within(&PASCALS),
230 Self::MetreToKilometre => within(&METRES),
231 Self::MassRatioToGPerKg => within(&MASS_RATIO),
232 Self::ProportionToPercent => within(&PROPORTION),
233 Self::CloudCover => within(&CLOUD_FRACTION),
234 Self::GeopotentialToMetres => within(&GEOPOTENTIAL),
235 Self::MassDensityToMicrograms => within(&MASS_DENSITY),
236 Self::PerSecondTo1e5 => within(&PER_SECOND),
237 _ => false,
238 }
239 }
240
241 pub fn expression(&self, unit: &str) -> Result<String> {
247 if !self.accepts(unit) {
248 return Err(self.refuse(unit));
249 }
250 if matches!(self, Self::Celsius | Self::SoilTemperature) {
251 return Ok(match temperature_unit(unit)? {
252 "K" => "A-273.15",
253 "F" => "(A-32)*5/9",
254 _ => "A",
255 }
256 .to_string());
257 }
258 if !self.scaled(unit) {
259 return Ok("A".to_string());
260 }
261 Ok(match self {
262 Self::PrecipitationRate => "A*3600".to_string(),
263 Self::PrecipitationAccumulation | Self::MassRatioToGPerKg => "A*1000".to_string(),
264 Self::PascalToHectopascal => "A/100".to_string(),
265 Self::MetreToKilometre => "A/1000".to_string(),
266 Self::ProportionToPercent | Self::CloudCover => "A*100".to_string(),
267 Self::GeopotentialToMetres => format!("A/{STANDARD_GRAVITY}"),
268 Self::MassDensityToMicrograms => "A*1000000000".to_string(),
269 Self::PerSecondTo1e5 => "A*100000".to_string(),
270 _ => unreachable!("a rule that scales is one of the above"),
271 })
272 }
273
274 pub fn convert(&self, unit: &str, values: &mut [f64]) -> Result<()> {
284 match self {
285 Self::Celsius | Self::SoilTemperature => {
286 let mut normalized = temperature_unit(unit)?;
287 if matches!(self, Self::SoilTemperature) {
288 normalized = soil_temperature_unit(normalized, values);
289 }
290 match normalized {
291 "K" => values.iter_mut().for_each(|value| *value -= 273.15),
292 "F" => values
293 .iter_mut()
294 .for_each(|value| *value = (*value - 32.0) * 5.0 / 9.0),
295 _ => {}
296 }
297 return Ok(());
298 }
299 Self::DegreesTrue => {
300 values
301 .iter_mut()
302 .for_each(|value| *value = value.rem_euclid(360.0));
303 return Ok(());
304 }
305 _ => {}
306 }
307 if !self.scaled(unit) {
308 return Ok(());
309 }
310 match self {
311 Self::PrecipitationRate => values.iter_mut().for_each(|value| *value *= 3600.0),
313 Self::PrecipitationAccumulation | Self::MassRatioToGPerKg => {
316 values.iter_mut().for_each(|value| *value *= 1000.0)
317 }
318 Self::PascalToHectopascal => values.iter_mut().for_each(|value| *value /= 100.0),
319 Self::MetreToKilometre => values.iter_mut().for_each(|value| *value /= 1000.0),
320 Self::ProportionToPercent | Self::CloudCover => {
321 values.iter_mut().for_each(|value| *value *= 100.0)
322 }
323 Self::GeopotentialToMetres => values
324 .iter_mut()
325 .for_each(|value| *value /= STANDARD_GRAVITY),
326 Self::MassDensityToMicrograms => values.iter_mut().for_each(|value| *value *= 1e9),
327 Self::PerSecondTo1e5 => values.iter_mut().for_each(|value| *value *= 1e5),
328 _ => unreachable!("a rule that scales is one of the above"),
329 }
330 Ok(())
331 }
332}
333
334#[cfg(test)]
335mod tests {
336 use super::{compact_unit, temperature_unit, Conversion};
337
338 fn expression(rule: &Conversion, unit: &str) -> String {
339 rule.expression(unit)
340 .unwrap_or_else(|error| panic!("{unit:?}: {error}"))
341 }
342
343 fn refused(rule: &Conversion, unit: &str) {
344 assert!(!rule.accepts(unit), "{rule:?} accepted {unit:?}");
345 assert!(rule.expression(unit).is_err());
346 }
347
348 fn converted(rule: &Conversion, unit: &str, values: &[f64]) -> Vec<f64> {
349 let mut values = values.to_vec();
350 rule.convert(unit, &mut values)
351 .unwrap_or_else(|error| panic!("{unit:?}: {error}"));
352 values
353 }
354
355 #[test]
356 fn spellings_are_compared_after_compaction() {
357 assert_eq!(compact_unit(" Kg/(m^2 s) "), "kg/m^2s");
358 assert_eq!(compact_unit("[W/m²]"), "w/m^2");
359 assert_eq!(compact_unit("m s-1"), "ms-1");
360 assert_eq!(temperature_unit("[C]").unwrap(), "C");
361 assert_eq!(temperature_unit("degrees Kelvin").unwrap(), "K");
362 assert_eq!(temperature_unit("°F").unwrap(), "F");
363 assert_eq!(temperature_unit("deg C").unwrap(), "C");
364 assert!(temperature_unit("hPa").is_err());
365 }
366
367 #[test]
368 fn every_rule_accepts_its_spellings_and_refuses_others() {
369 let any = Conversion::Identity {
370 accepted_units: None,
371 };
372 assert_eq!(expression(&any, "whatever"), "A");
373 assert_eq!(any.accepted_units(), None);
374 let wind = Conversion::Identity {
375 accepted_units: Some(
376 ["m/s", "m/sec", "ms-1", "ms^-1", "mps"]
377 .map(String::from)
378 .to_vec(),
379 ),
380 };
381 assert_eq!(expression(&wind, "[m/s]"), "A");
382 assert_eq!(expression(&wind, "m s-1"), "A");
383 refused(&wind, "knots");
384 assert!(wind
385 .expression("knots")
386 .unwrap_err()
387 .to_string()
388 .contains("m/sec"));
389
390 assert_eq!(expression(&Conversion::Celsius, "[C]"), "A");
391 assert_eq!(expression(&Conversion::Celsius, "K"), "A-273.15");
392 assert_eq!(expression(&Conversion::Celsius, "degF"), "(A-32)*5/9");
393 refused(&Conversion::Celsius, "Pa");
394 assert_eq!(Conversion::Celsius.accepted_units().unwrap().len(), 8);
395 let soil = Conversion::SoilTemperature;
397 assert_eq!(
398 converted(&soil, "C", &[280.0, 290.0]),
399 [6.850000000000023, 16.850000000000023]
400 );
401 assert_eq!(converted(&soil, "C", &[10.0, 20.0]), [10.0, 20.0]);
402 assert_eq!(expression(&soil, "C"), "A");
403
404 let rate = Conversion::PrecipitationRate;
405 assert_eq!(expression(&rate, "kg/(m^2 s)"), "A*3600");
406 assert_eq!(expression(&rate, "mm/hr"), "A");
407 refused(&rate, "in/h");
408 assert_eq!(converted(&rate, "kg/m^2 s", &[1.0]), [3600.0]);
409 assert_eq!(converted(&rate, "mm/h", &[1.0]), [1.0]);
410
411 let accumulation = Conversion::PrecipitationAccumulation;
412 assert_eq!(expression(&accumulation, "-"), "A*1000");
413 assert_eq!(expression(&accumulation, "m"), "A*1000");
414 assert_eq!(expression(&accumulation, ""), "A*1000");
415 assert_eq!(expression(&accumulation, "kg/(m^2*s)"), "A");
416 assert_eq!(expression(&accumulation, "mm"), "A");
417 refused(&accumulation, "in");
418
419 assert_eq!(
420 expression(&Conversion::MassDensityToMicrograms, "[kg/(m^3)]"),
421 "A*1000000000"
422 );
423 refused(&Conversion::MassDensityToMicrograms, "10^-6g/m^3");
424 assert_eq!(
425 converted(&Conversion::MassDensityToMicrograms, "kg/(m^3)", &[2.5e-8]),
426 [2.5e-8 * 1e9]
427 );
428 let vorticity = Conversion::PerSecondTo1e5;
430 assert_eq!(expression(&vorticity, "[1/s]"), "A*100000");
431 assert_eq!(expression(&vorticity, "s**-1"), "A*100000");
432 refused(&vorticity, "1/h");
433 assert_eq!(converted(&vorticity, "1/s", &[-3.2e-4]), [-3.2e-4 * 1e5]);
434 assert_eq!(
435 expression(&Conversion::PascalToHectopascal, "[Pa]"),
436 "A/100"
437 );
438 refused(&Conversion::PascalToHectopascal, "hPa");
439 assert_eq!(
441 converted(&Conversion::PascalToHectopascal, "hPa", &[1013.0]),
442 [1013.0]
443 );
444 assert_eq!(
445 converted(&Conversion::PascalToHectopascal, "Pa", &[101300.0]),
446 [1013.0]
447 );
448 assert_eq!(
449 expression(&Conversion::MetreToKilometre, "metres"),
450 "A/1000"
451 );
452 refused(&Conversion::MetreToKilometre, "km");
453 assert_eq!(
454 converted(&Conversion::MetreToKilometre, "km", &[2.0]),
455 [2.0]
456 );
457 assert_eq!(
458 expression(&Conversion::MassRatioToGPerKg, "kg/kg"),
459 "A*1000"
460 );
461 refused(&Conversion::MassRatioToGPerKg, "g/kg");
462 assert_eq!(
463 converted(&Conversion::MassRatioToGPerKg, "g/kg", &[5.0]),
464 [5.0]
465 );
466 assert_eq!(
467 expression(&Conversion::ProportionToPercent, "Proportion"),
468 "A*100"
469 );
470 refused(&Conversion::ProportionToPercent, "%");
471 assert_eq!(
472 converted(&Conversion::ProportionToPercent, "%", &[50.0]),
473 [50.0]
474 );
475 assert_eq!(expression(&Conversion::CloudCover, "%"), "A");
476 assert_eq!(expression(&Conversion::CloudCover, "-"), "A*100");
477 assert_eq!(expression(&Conversion::CloudCover, "(0 - 1)"), "A*100");
478 refused(&Conversion::CloudCover, "okta");
479 assert_eq!(expression(&Conversion::DegreesTrue, "Degree true"), "A");
480 refused(&Conversion::DegreesTrue, "rad");
481 assert_eq!(
482 converted(
483 &Conversion::DegreesTrue,
484 "Degree true",
485 &[360.0, 370.0, 90.0]
486 ),
487 [0.0, 10.0, 90.0]
488 );
489 let orography = Conversion::GeopotentialToMetres;
490 assert_eq!(expression(&orography, "gpm"), "A");
491 assert_eq!(expression(&orography, "(m^2)/(s^2)"), "A/9.80665");
492 assert_eq!(expression(&orography, "m**2 s**-2"), "A/9.80665");
493 refused(&orography, "ft");
494 assert_eq!(converted(&orography, "m**2 s**-2", &[9.80665]), [1.0]);
495 let flags = Conversion::CodeTable {
496 table: "4.222".into(),
497 };
498 assert_eq!(expression(&flags, "0=no; 1=yes"), "A");
499 assert_eq!(expression(&flags, "(Code table 4.222)"), "A");
500 assert_eq!(expression(&flags, ""), "A");
501 refused(&flags, "4.201");
502 assert_eq!(flags.accepted_units().unwrap(), ["1", "-", "", "4.222"]);
503 }
504
505 #[test]
506 fn the_arithmetic_is_one_operation_per_value() {
507 assert_eq!(
508 converted(&Conversion::Celsius, "K", &[273.15, 283.15]),
509 [0.0, 10.0]
510 );
511 assert_eq!(
512 converted(&Conversion::Celsius, "F", &[32.0, 212.0]),
513 [0.0, 100.0]
514 );
515 assert_eq!(
516 converted(&Conversion::PrecipitationAccumulation, "m", &[0.001]),
517 [1.0]
518 );
519 assert_eq!(converted(&Conversion::CloudCover, "-", &[0.5]), [50.0]);
520 assert_eq!(converted(&Conversion::CloudCover, "%", &[50.0]), [50.0]);
521 assert!(Conversion::Celsius.convert("Pa", &mut [1.0]).is_err());
522 }
523}