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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
//! Data type and methods to store an atmospheric sounding.

use ::chrono::NaiveDateTime;

use ::error::*;
use ::missing_value::OptionVal;

/// All the variables stored in the sounding.
///
/// The upper air profile variables are stored in parallel vectors. If a profile lacks a certain
/// variable, e.g. cloud fraction, that whole vector has length 0 instead of being full of missing
/// values.
///
#[derive(Default)]
pub struct Sounding {
    // Station info section
    /// station number, USAF number, eg 727730
    pub num: OptionVal<i32>,
    /// Valid time of sounding
    pub valid_time: Option<NaiveDateTime>,
    /// Difference in model initialization time and `valid_time` in hours.
    pub lead_time: OptionVal<i32>,
    /// Latitude of grid point used to make sounding.
    pub lat: OptionVal<f32>,
    /// Longitude of grid point used to make sounding.
    pub lon: OptionVal<f32>,
    /// Elevation of grid point in meters, this is in model terrain, not necessarily the same as
    /// the real world.
    pub elevation: OptionVal<f32>,

    // Sounding Indexes
    /// Showalter index
    pub show: OptionVal<f32>,
    /// Lifted index
    pub li: OptionVal<f32>,
    /// Severe Weather Threat Index
    pub swet: OptionVal<f32>,
    /// K-index
    pub kinx: OptionVal<f32>,
    /// Lifting Condensation Level, or LCL (hPa), pressure vertical coordinate.
    pub lclp: OptionVal<f32>,
    /// Precipitable Water (mm)
    pub pwat: OptionVal<f32>,
    /// Total-Totals
    pub totl: OptionVal<f32>,
    /// Convective Available Potential Energy, or CAPE. (J/kg)
    pub cape: OptionVal<f32>,
    /// Temperature at LCL (K)
    pub lclt: OptionVal<f32>,
    /// Convective Inhibitive Energy, or CIN (J/kg)
    pub cins: OptionVal<f32>,
    /// Equilibrium Level (hPa), pressure vertical coordinate
    pub eqlv: OptionVal<f32>,
    /// Level of Free Convection (hPa), pressure vertical coordinate
    pub lfc: OptionVal<f32>,
    /// Bulk Richardson Number
    pub brch: OptionVal<f32>,
    /// Haines Index
    pub hain: OptionVal<i32>,

    // Upper air profile
    /// Pressure (hPa) profile
    pub pressure: Vec<OptionVal<f32>>,
    /// Temperature (c) profile
    pub temperature: Vec<OptionVal<f32>>,
    /// Wet-bulb (c) profile
    pub wet_bulb: Vec<OptionVal<f32>>,
    /// Dew Point (C) profile
    pub dew_point: Vec<OptionVal<f32>>,
    /// Equivalent Potential Temperature (K) profile
    pub theta_e: Vec<OptionVal<f32>>,
    /// Wind direction (degrees) profile
    pub direction: Vec<OptionVal<f32>>,
    /// Wind speed (knots) profile
    pub speed: Vec<OptionVal<f32>>,
    /// Vertical velocity (Pa/sec), pressure vertical coordinate
    pub omega: Vec<OptionVal<f32>>,
    /// Geopotential Height (m) profile
    pub height: Vec<OptionVal<f32>>,
    /// Cloud coverage fraction in percent
    pub cloud_fraction: Vec<OptionVal<f32>>,

    // Surface data
    /// Surface pressure reduce to mean sea level (hPa)
    pub mslp: OptionVal<f32>,
    /// Surface pressure (hPa)
    pub station_pres: OptionVal<f32>,
    /// Low cloud fraction
    pub low_cloud: OptionVal<f32>,
    /// Mid cloud fraction
    pub mid_cloud: OptionVal<f32>,
    /// Hi cloud fraction
    pub hi_cloud: OptionVal<f32>,
    /// U - wind speed (m/s) (West -> East is positive)
    pub uwind: OptionVal<f32>,
    /// V - wind speed (m/s) (South -> North is positive)
    pub vwind: OptionVal<f32>,
}

impl Sounding {
    /// Validates the sounding with some simple sanity checks. For instance, checks that pressure
    /// decreases with height.
    #[cfg_attr(feature = "cargo-clippy", allow(cyclomatic_complexity))]
    pub fn validate(&self) -> Result<()> {

        macro_rules! validate_f32_positive {
            ($var:ident, $err_msg:ident, $var_name:expr) => {
                let opt: Option<f32> = self.$var.into();
                if let Some(val) = opt {
                    if val < 0.0 {
                        $err_msg.push_str(&format!("\n{} < 0.0: {}", $var_name, val));
                    }
                }
            };
        }

        macro_rules! validate_vector_len {
            ($var:ident, $len:expr, $err_msg:ident, $var_name:expr) => {
                if !self.$var.is_empty() && self.$var.len() != $len {
                    $err_msg
                        .push_str(&format!("\n{} array has different length than pressure array.",
                                    $var_name));
                }
            };
        }

        let mut error_msg = String::from("");

        // Sounding checks
        if self.pressure.is_empty() {
            error_msg.push_str("\nPressure variable required, none given.");
        }

        let len = self.pressure.len();

        validate_vector_len!(temperature, len, error_msg, "Temperature");
        validate_vector_len!(wet_bulb, len, error_msg, "Wet bulb temperature");
        validate_vector_len!(dew_point, len, error_msg, "Dew point");
        validate_vector_len!(theta_e, len, error_msg, "Theta-e");
        validate_vector_len!(direction, len, error_msg, "Wind direction");
        validate_vector_len!(speed, len, error_msg, "wind speed");
        validate_vector_len!(omega, len, error_msg, "Omega (pressure vertical velocity)");
        validate_vector_len!(height, len, error_msg, "Height");
        validate_vector_len!(cloud_fraction, len, error_msg, "Cloud fraction");

        // Check that pressure always decreases with height and that the station pressure is more
        // than the lowest pressure level in sounding.
        let mut pressure_one_level_down = ::std::f32::MAX;
        if let Some(val) = self.station_pres.as_option() {
            pressure_one_level_down = val;
        }
        for pres in &self.pressure {
            if pres.as_option().is_none() {
                continue;
            }
            let pres_val = pres.unwrap();
            if pressure_one_level_down < pres_val {
                error_msg.push_str(&format!(
                    "\nPressure increasing with height: {} < {}",
                    pressure_one_level_down,
                    pres_val
                ));
            }
            pressure_one_level_down = pres_val;
        }

        // Check height always increases with height.
        let mut height_one_level_down = ::std::f32::MIN;
        for hght in &self.height {
            if hght.as_option().is_none() {
                continue;
            }
            let hght_val = hght.unwrap();
            if height_one_level_down > hght_val {
                error_msg.push_str(&format!(
                    "\nHeight values decreasing with height: {} < {}",
                    height_one_level_down,
                    hght_val
                ));
            }
            height_one_level_down = hght_val;
        }

        // Check that dew point <= wet bulb <= t
        for (t, wb) in self.temperature.iter().zip(self.wet_bulb.iter()) {
            if t.as_option().is_none() || wb.as_option().is_none() {
                continue;
            }
            if t.unwrap() < wb.unwrap() {
                error_msg.push_str(&format!(
                    "\nTemperature < Wet bulb: {} < {}",
                    t.unwrap(),
                    wb.unwrap()
                ));
            }
        }
        for (t, dp) in self.temperature.iter().zip(self.dew_point.iter()) {
            if t.as_option().is_none() || dp.as_option().is_none() {
                continue;
            }
            if t.unwrap() < dp.unwrap() {
                error_msg.push_str(&format!(
                    "\nTemperature < Dew Point: {} < {}",
                    t.unwrap(),
                    dp.unwrap()
                ));
            }
        }
        for (wb, dp) in self.wet_bulb.iter().zip(self.dew_point.iter()) {
            if wb.as_option().is_none() || dp.as_option().is_none() {
                continue;
            }
            if wb.unwrap() < dp.unwrap() {
                error_msg.push_str(&format!(
                    "\nWet bulb < Dew Point: {} < {}",
                    wb.unwrap(),
                    dp.unwrap()
                ));
            }
        }

        // Check that speed >= 0
        for spd in &self.speed {
            if spd.as_option().is_none() {
                continue;
            }
            if spd.unwrap() < 0.0 {
                error_msg.push_str(&format!("\nWind speed < 0: {} < 0.0", spd.unwrap()));
            }
        }

        // Check that cloud fraction >= 0
        for cld in &self.cloud_fraction {
            if cld.as_option().is_none() {
                continue;
            }
            if cld.unwrap() < 0.0 {
                error_msg.push_str(&format!("\nCloud fraction < 0: {} < 0.0", cld.unwrap()));
            }

        }

        // Index checks
        validate_f32_positive!(cape, error_msg, "CAPE");
        validate_f32_positive!(pwat, error_msg, "PWAT");

        // Check that cin <= 0
        let opt: Option<f32> = self.cins.into();
        if let Some(val) = opt {
            if val > 0.0 {
                error_msg.push_str(&format!("\nCINS > 0.0: {}", val));
            }
        }

        // Check Haines Index = 2, 3, 4, 5, or 6
        let opt: Option<i32> = self.hain.into();
        if let Some(val) = opt {

            match val {
                2...6 => {} // Good values, do nothing.
                _ => error_msg.push_str(&format!("\nInvalid Haines Index: {}", val)),
            }
        }

        // Surface checks
        // Check that hi, mid, and low cloud are all positive or zero
        validate_f32_positive!(low_cloud, error_msg, "low cloud");
        validate_f32_positive!(mid_cloud, error_msg, "mid cloud");
        validate_f32_positive!(hi_cloud, error_msg, "hi cloud");

        if error_msg == "" {
            Ok(())
        } else {
            error_msg.push('\n');
            Err(Error::from(ErrorKind::ValidationError(error_msg)))
        }
    }

    /// Returns the maximum and minimum extents.
    /// `(max_pressure, min_pressure, (t_min_ext, p_min_ext),(t_max_ext, p_max_ext))`
    pub fn get_pressure_extents(&self) -> (f32, f32, (f32, f32),(f32, f32)) {
        let mut max_pressure = ::std::f32::MIN;
        let mut min_pressure = ::std::f32::MAX;
        let mut minx = ::std::f32::MAX;
        let mut maxx = ::std::f32::MIN;
        let mut minx_extents = (::std::f32::NAN, ::std::f32::NAN);
        let mut maxx_extents = (::std::f32::NAN, ::std::f32::NAN);

        if let Some(pres) = self.station_pres.as_option() {
            if pres > max_pressure {
                max_pressure = pres;
            }
        }

       let long_list = self.pressure.iter()
            .zip(self.temperature.iter())
            .chain(self.pressure.iter()
                .zip(self.dew_point.iter())
            )
            .filter_map(|v| {
                let (pres, temp) = v;
                if pres.as_option().is_some() && temp.as_option().is_some() {
                    Some((pres.unwrap(), temp.unwrap()))
                } else {
                    None
                }
            });

        for (pres, tmp) in long_list {
            if pres > max_pressure {
                max_pressure = pres;
            }
            if pres < min_pressure {
                min_pressure = pres;
            }

            let x = tmp + pres;
            if x > maxx {
                maxx = x;
                maxx_extents = (pres, tmp);
            }
            if x < minx {
                minx = x;
                minx_extents = (pres, tmp);
            }
        }

        (max_pressure, min_pressure, minx_extents, maxx_extents)
    }

}