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
//! #Lasrs
//!
//! lasrs is a crate used to parse geophysical well log files `.las`.
//! Provides utilities for extracting strongly typed information from the files.
//! Supports Las Version 2.0 by [Canadian Well Logging Society](http://www.cwls.org) -
//! [Specification](https://www.cwls.org/wp-content/uploads/2017/02/Las2_Update_Feb2017.pdf)

#[macro_use]
extern crate lazy_static;

use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Write};
use std::{collections::HashMap, path::Path};

mod util;
use util::{metadata, property, remove_comment, SPACES, SPACES_AND_DOT};

pub use util::WellProp;

/// Represents a parsed well log file
pub struct Las {
    /// blob holds the String data read from the file
    /// ## Note
    /// There's no need to access the blob field, only exposed for debugging
    pub blob: String,
}

impl Las {
    /// Returns a `Las` read from a las file with the given path
    ///
    /// ## Arguments
    ///
    /// `path` - Path to well log file
    ///
    /// ## Example
    ///
    /// ```
    /// use lasrs::Las;
    /// let log = Las::new("./sample/example.las");
    /// assert_eq!(&log.blob[..=7], "~VERSION");
    /// ```
    pub fn new<T: AsRef<Path>>(path: T) -> Self {
        let mut blob = String::new();
        let f = File::open(path.as_ref()).expect("Invalid path, verify existence of file");
        let mut br = BufReader::new(f);
        br.read_to_string(&mut blob).expect("Unable to read file");
        Self { blob }
    }

    /// Returns `f64` representing the version of Las specification
    ///
    /// ## Example
    ///
    /// ```
    /// use lasrs::Las;
    /// let log = Las::new("./sample/example.las");
    /// assert_eq!(log.version(), 2.0);
    /// ```
    pub fn version(&self) -> f64 {
        let (res, _) = metadata(&self.blob);
        match res {
            Some(v) => v,
            None => panic!("Invalid version"),
        }
    }

    /// Returns a `bool` denoting the wrap mode
    ///
    /// ## Example
    ///
    /// ```
    /// use lasrs::Las;
    /// let log = Las::new("./sample/example.las");
    /// assert_eq!(log.wrap(), false);
    /// ```
    pub fn wrap(&self) -> bool {
        let (_, v) = metadata(&self.blob);
        v
    }

    /// Returns `Vec<String>` representing the titles of the curves (~C),
    /// Which can be mapped to a row in ~A (data) section
    ///
    /// ## Example
    ///
    /// ```
    /// use lasrs::Las;
    /// let log = Las::new("./sample/A10.las");
    /// assert_eq!(
    ///     log.headers(),
    ///     vec!["DEPT", "Perm", "Gamma", "Porosity", "Fluvialfacies", "NetGross"],
    /// );
    /// ```
    pub fn headers(&self) -> Vec<String> {
        self.blob
            .splitn(2, "~C")
            .nth(1)
            .unwrap_or("")
            .splitn(2, "~")
            .nth(0)
            .map(|x| remove_comment(x))
            .unwrap_or(vec![])
            .into_iter()
            .skip(1)
            .filter_map(|x| {
                SPACES_AND_DOT
                    .splitn(x.trim(), 2)
                    .next()
                    .map(|x| x.to_string())
            })
            .collect()
    }

    /// Returns `Vec<Vec<f64>>` where every Vec<f64> represents a row in ~A (data) section,
    /// and every f64 represents an entry in a column/curve
    ///
    /// ## Example
    ///
    /// ```
    /// use lasrs::Las;
    /// let log = Las::new("./sample/A10.las");
    /// let expected: Vec<Vec<f64>> = vec![
    ///                     vec![1501.129, -999.25, -999.25, 0.270646, 0.0, 0.0],
    ///                     vec![1501.629, 124.5799, 78.869453, 0.267428, 0.0, 0.0],
    ///                   ];
    /// assert_eq!(expected, &log.data()[3..5]);
    /// ```
    pub fn data(&self) -> Vec<Vec<f64>> {
        self.blob
            .splitn(2, "~A")
            .nth(1)
            .unwrap_or("")
            .lines()
            .skip(1)
            .flat_map(|x| {
                SPACES
                    .split(x.trim())
                    .map(|v| v.trim().parse::<f64>().unwrap_or(0.0))
            })
            .collect::<Vec<f64>>()
            .chunks(self.headers().len())
            .map(|ch| Vec::from(ch))
            .collect()
    }

    /// Returns `Vec<f64>` - all reading for a curve/column
    ///
    /// ## Arguments
    ///
    /// `col` - string slice representing the title of the column
    ///
    /// ## Example
    ///
    /// ```
    /// use lasrs::Las;
    /// let log = Las::new("./sample/example.las");
    /// assert_eq!(
    ///     vec![1670.0, 1669.875, 1669.75, 1669.745],
    ///     log.column("DEPT")
    /// );
    /// ```
    pub fn column(self, col: &str) -> Vec<f64> {
        let index = self
            .headers()
            .into_iter()
            .position(|x| x == col.to_owned())
            .expect("msg");
        self.data().into_iter().map(|x| x[index]).collect()
    }

    /// Returns `usize` representing the total number of columns/curves
    ///
    /// ## Example
    ///
    /// ```
    /// use lasrs::Las;
    /// let log = Las::new("./sample/example.las");
    /// assert_eq!(8, log.column_count());
    /// ```
    pub fn column_count(&self) -> usize {
        self.headers().len()
    }

    /// Returns `usize` representing the total number of entry in ~A (data) section
    ///
    /// ## Example
    ///
    /// ```
    /// use lasrs::Las;
    /// let log = Las::new("./sample/example.las");
    /// assert_eq!(4, log.row_count());
    /// ```
    pub fn row_count(&self) -> usize {
        self.data().len()
    }

    /// Returns `Vec<(String, String)>` where the first item in the tuple is the title of curve
    /// and the second is the full description of the curve
    ///
    /// ## Example
    ///
    /// ```
    /// use lasrs::Las;
    /// let log = Las::new("./sample/example.las");
    /// let mut expected = vec![
    ///     ("DEPT".to_owned(), "DEPTH".to_owned()),
    ///     ("DT".to_owned(), "SONIC TRANSIT TIME".to_owned()),
    ///     ("ILD".to_owned(), "DEEP RESISTIVITY".to_owned()),
    /// ];
    /// let mut result = log.headers_and_desc();
    /// result.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
    /// assert_eq!(expected, &result[..3]);
    /// ```
    pub fn headers_and_desc(&self) -> Vec<(String, String)> {
        property(self.blob.as_str(), "~C")
            .into_iter()
            .map(|(title, body)| (title, body.description))
            .collect()
    }

    /// Returns `HashMap<String, WellProp>` containing all the `WellProp`(s) in a ~C (curve) section
    ///
    /// ## Example
    ///
    /// ```
    /// use lasrs::{Las, WellProp};
    /// let log = Las::new("./sample/example.las");
    /// let curve_section = log.curve_params();
    /// assert_eq!(
    ///     &WellProp::new("OHMM", "SHALLOW RESISTIVITY", "07 220 04 00"),
    ///     curve_section.get("SFLU").unwrap()
    /// );
    /// ```
    pub fn curve_params(&self) -> HashMap<String, WellProp> {
        property(&self.blob, "~C")
    }

    /// Returns `HashMap<String, WellProp>` containing all the `WellProp`(s) in a ~W (well) section
    ///
    /// ## Example
    ///
    /// ```
    /// use lasrs::{Las, WellProp};
    /// let log = Las::new("./sample/example.las");
    /// let well_section = log.well_info();
    /// assert_eq!(
    ///     &WellProp::new("M", "STOP DEPTH", "1669.7500"),
    ///     well_section.get("STOP").unwrap()
    /// );
    /// ```
    pub fn well_info(&self) -> HashMap<String, WellProp> {
        property(&self.blob, "~W")
    }

    /// Returns `HashMap<String, WellProp>` containing all the `WellProp`(s) in a ~P (parameter) section
    ///
    /// ## Example
    ///
    /// ```
    /// use lasrs::{Las, WellProp};
    /// let log = Las::new("./sample/example.las");
    /// let params = log.log_params();
    /// assert_eq!(
    ///     &WellProp::new("", "MUD TYPE", "GEL CHEM"),
    ///     params.get("MUD").unwrap()
    /// );
    pub fn log_params(&self) -> HashMap<String, WellProp> {
        property(&self.blob, "~P")
    }

    /// Returns a `String` representing extra information in ~O (other) section
    ///
    /// ## Example
    /// ```
    /// use lasrs::Las;
    /// let log = Las::new("./sample/example.las");
    /// let expected = [
    ///     "Note: The logging tools became stuck at 625 metres causing the data",
    ///     "between 625 metres and 615 metres to be invalid.",
    /// ];
    /// assert_eq!(log.other(), expected.join("\n").to_string());
    /// ```
    pub fn other(&self) -> String {
        self.blob
            .splitn(2, "~O")
            .nth(1)
            .unwrap_or("")
            .splitn(2, "~")
            .nth(0)
            .map(|x| remove_comment(x))
            .unwrap_or(vec![])
            .into_iter()
            .skip(1)
            .map(|x| x.to_string())
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Converts file to csv and saves it to the current directory
    /// ## Arguments
    ///
    /// `filename` - string slice, the name used to save the csv file
    pub fn to_csv(&self, filename: &str) {
        let f = File::create(format!("{}.csv", filename)).expect("Unable to create csv file");
        let mut f = BufWriter::new(f);
        let mut headers = self.headers().join(",");
        headers.push_str("\n");
        f.write(headers.as_bytes())
            .expect("Unable to write headers");
        let data = self
            .data()
            .into_iter()
            .map(|x| x.into_iter().map(|d| d.to_string()))
            .map(|x| x.collect::<Vec<_>>().join(","))
            .collect::<Vec<_>>()
            .join("\n");
        f.write_all(data.as_bytes())
            .expect("Unable to write data to file");
    }
}