compass_data 0.0.7

A library for working with Compass cave survey data
Documentation
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use std::fmt::Write;

use chrono::{Datelike, NaiveDate};

use crate::Error;

mod parser;

/// Bearing Units are used to represent heading measurements
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum BearingUnits {
    Degrees,
    Quads,
    Grads,
}

impl BearingUnits {
    fn as_char(&self) -> char {
        match self {
            Self::Degrees => 'D',
            Self::Quads => 'Q',
            Self::Grads => 'R',
        }
    }
}

/// Length Units are used to represent distance measurements
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum LengthUnits {
    DecimalFeet,
    FeetAndInches,
    Meters,
}

impl LengthUnits {
    fn as_char(&self) -> char {
        match self {
            Self::DecimalFeet => 'D',
            Self::FeetAndInches => 'I',
            Self::Meters => 'M',
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum InclinationUnits {
    Degrees,
    PercentGrade,
    DegreesAndMinutes,
    Grads,
    DepthGauge,
}

impl InclinationUnits {
    fn as_char(&self) -> char {
        match self {
            Self::Degrees => 'D',
            Self::PercentGrade => 'G',
            Self::DegreesAndMinutes => 'M',
            Self::Grads => 'R',
            Self::DepthGauge => 'W',
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum PassageDimension {
    Left,
    Right,
    Up,
    Down,
}

impl PassageDimension {
    fn as_char(&self) -> char {
        match self {
            Self::Left => 'L',
            Self::Right => 'R',
            Self::Up => 'U',
            Self::Down => 'D',
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum ShotItem {
    Length,
    Azimuth,
    Inclination,
    BackAzimuth,
    BackInclination,
}

impl ShotItem {
    fn as_char(&self) -> char {
        match self {
            Self::Length => 'L',
            Self::Azimuth => 'A',
            Self::Inclination => 'D',
            Self::BackAzimuth => 'a',
            Self::BackInclination => 'd',
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum RedundantBackSight {
    RedundantBacksight,
    NoRedundantBacksight,
}

impl RedundantBackSight {
    fn as_char(&self) -> char {
        match self {
            Self::RedundantBacksight => 'B',
            Self::NoRedundantBacksight => 'N',
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum LRUDAssociation {
    FromStation,
    ToStation,
}

impl LRUDAssociation {
    fn as_char(&self) -> char {
        match self {
            Self::FromStation => 'F',
            Self::ToStation => 'T',
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct SurveyFormat11 {
    bearing_units: BearingUnits,
    length_units: LengthUnits,
    passage_units: LengthUnits,
    inclination_units: InclinationUnits,
    passage_dimension_order: [PassageDimension; 4],
    shot_item_order: [ShotItem; 3],
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct SurveyFormat12 {
    bearing_units: BearingUnits,
    length_units: LengthUnits,
    passage_units: LengthUnits,
    inclination_units: InclinationUnits,
    passage_dimension_order: [PassageDimension; 4],
    shot_item_order: [ShotItem; 3],
    backsight: RedundantBackSight,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct SurveyFormat13 {
    bearing_units: BearingUnits,
    length_units: LengthUnits,
    passage_units: LengthUnits,
    inclination_units: InclinationUnits,
    passage_dimension_order: [PassageDimension; 4],
    shot_item_order: [ShotItem; 3],
    backsight: RedundantBackSight,
    lrud_association: LRUDAssociation,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct SurveyFormat15 {
    bearing_units: BearingUnits,
    length_units: LengthUnits,
    passage_units: LengthUnits,
    inclination_units: InclinationUnits,
    passage_dimension_order: [PassageDimension; 4],
    shot_item_order: [ShotItem; 5],
    backsight: RedundantBackSight,
    lrud_association: LRUDAssociation,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum SurveyFormat {
    None,
    Format11(SurveyFormat11),
    Format12(SurveyFormat12),
    Format13(SurveyFormat13),
    Format15(SurveyFormat15),
}

impl SurveyFormat11 {
    fn serialize(&self) -> String {
        let mut result = String::with_capacity(11);
        result.push(self.bearing_units.as_char());
        result.push(self.length_units.as_char());
        result.push(self.passage_units.as_char());
        result.push(self.inclination_units.as_char());
        for dim in &self.passage_dimension_order {
            result.push(dim.as_char());
        }
        for item in &self.shot_item_order {
            result.push(item.as_char());
        }
        result
    }
}

impl SurveyFormat12 {
    fn serialize(&self) -> String {
        let mut result = String::with_capacity(12);
        result.push(self.bearing_units.as_char());
        result.push(self.length_units.as_char());
        result.push(self.passage_units.as_char());
        result.push(self.inclination_units.as_char());
        for dim in &self.passage_dimension_order {
            result.push(dim.as_char());
        }
        for item in &self.shot_item_order {
            result.push(item.as_char());
        }
        result.push(self.backsight.as_char());
        result
    }
}

impl SurveyFormat13 {
    fn serialize(&self) -> String {
        let mut result = String::with_capacity(13);
        result.push(self.bearing_units.as_char());
        result.push(self.length_units.as_char());
        result.push(self.passage_units.as_char());
        result.push(self.inclination_units.as_char());
        for dim in &self.passage_dimension_order {
            result.push(dim.as_char());
        }
        for item in &self.shot_item_order {
            result.push(item.as_char());
        }
        result.push(self.backsight.as_char());
        result.push(self.lrud_association.as_char());
        result
    }
}

impl SurveyFormat15 {
    fn serialize(&self) -> String {
        let mut result = String::with_capacity(15);
        result.push(self.bearing_units.as_char());
        result.push(self.length_units.as_char());
        result.push(self.passage_units.as_char());
        result.push(self.inclination_units.as_char());
        for dim in &self.passage_dimension_order {
            result.push(dim.as_char());
        }
        for item in &self.shot_item_order {
            result.push(item.as_char());
        }
        result.push(self.backsight.as_char());
        result.push(self.lrud_association.as_char());
        result
    }
}

impl SurveyFormat {
    fn serialize(&self) -> Option<String> {
        match self {
            Self::None => None,
            Self::Format11(f) => Some(f.serialize()),
            Self::Format12(f) => Some(f.serialize()),
            Self::Format13(f) => Some(f.serialize()),
            Self::Format15(f) => Some(f.serialize()),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct CorrectionFactors {
    pub azimuth: f64,
    pub inclination: f64,
    pub length: f64,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct BackSightCorrectionFactors {
    pub azimuth: f64,
    pub inclination: f64,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct SurveyParameters {
    pub declination: f64,
    pub format_parameters: SurveyFormat,
    pub correction_factors: Option<CorrectionFactors>,
    pub backsight_correction_factors: Option<BackSightCorrectionFactors>,
}

impl SurveyParameters {
    fn serialize(&self) -> String {
        let mut result = String::new();
        let _ = write!(result, "DECLINATION:   {:>4.2}  ", self.declination);
        if let Some(format_str) = self.format_parameters.serialize() {
            let _ = write!(result, "FORMAT: {format_str}  ");
        }
        if let Some(cf) = &self.correction_factors {
            let _ = write!(
                result,
                "CORRECTIONS:  {:.2} {:.2} {:.2}  ",
                cf.azimuth, cf.inclination, cf.length
            );
        }
        if let Some(bcf) = &self.backsight_correction_factors {
            let _ = write!(
                result,
                "CORRECTIONS2: {:.1} {:.1}",
                bcf.azimuth, bcf.inclination
            );
        }
        result.push_str("\r\n");
        result
    }
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Shot {
    pub from: String,
    pub to: String,
    pub length: f64,
    pub azimuth: f64,
    pub inclination: f64,
    pub up: f64,
    pub down: f64,
    pub left: f64,
    pub right: f64,
    pub flags: Option<String>,
    pub comment: Option<String>,
}

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Survey {
    pub cave_name: String,
    pub name: String,
    pub date: NaiveDate,
    pub comment: Option<String>,
    pub team: String,
    pub parameters: SurveyParameters,
    pub shots: Vec<Shot>,
}

impl Survey {
    /// Parse a survey from a string
    /// # Arguments
    /// input - A string containing the survey data
    /// # Returns
    /// Result containing the parsed survey or an error message
    /// # Errors
    /// If the input is not a valid survey
    pub fn parse_survey(input: &str) -> Result<Self, String> {
        match parser::parse_survey(input) {
            Ok((_, survey)) => Ok(survey),
            Err(e) => Err(e.to_string()),
        }
    }

    /// Parse the contents of a survey.dat file
    /// # Arguments
    /// input - A string containing the contents of the survey.dat file
    /// # Returns
    /// Result containing the parsed survey or an error message
    /// # Errors
    /// If the input is not a valid survey.dat file
    pub fn parse_dat_file(input: &str) -> Result<Vec<Self>, Error> {
        match parser::parse_dat_file(input) {
            Ok((_, survey)) => Ok(survey),
            Err(e) => Err(Error::CouldntParseSurvey(e.to_string())),
        }
    }

    #[must_use]
    pub fn serialize(&self) -> String {
        let mut result = String::new();
        let _ = writeln!(result, "{}\r", self.cave_name);
        let _ = writeln!(result, "SURVEY NAME: {}\r", self.name);
        let _ = write!(
            result,
            "SURVEY DATE: {} {} {}",
            self.date.month(),
            self.date.day0() + 1,
            self.date.year_ce().1,
        );
        if let Some(comment) = &self.comment {
            let _ = writeln!(result, "  COMMENT:{comment}\r");
        } else {
            result.push_str("\r\n");
        }
        result.push_str("SURVEY TEAM:\r\n");
        let _ = writeln!(result, "{}\r", self.team);
        result.push_str(&self.parameters.serialize());
        result.push_str("\n        FROM           TO   LENGTH  BEARING      INC     LEFT       UP     DOWN    RIGHT   FLAGS  COMMENTS\r\n\r\n");
        for shot in &self.shots {
            let _ = writeln!(
                result,
                "{:>12}{:>13}{:>9.2}{:>9.2}{:>9.2}{:>9.2}{:>9.2}{:>9.2}{:>9.2}\r",
                shot.from,
                shot.to,
                shot.length,
                shot.azimuth,
                shot.inclination,
                shot.left,
                shot.up,
                shot.down,
                shot.right
            );
        }
        result.push_str("\x0c\r\n");
        result
    }
}