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
use crate::frame::{Array, Frame, Header, HeaderEntry};
use byteorder::{LittleEndian, ReadBytesExt};
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::num::ParseFloatError;
use std::path::Path;
use std::{io, mem};

pub struct BrukerFrame {
    header: Header,
    array: Array,
    data_start: usize,
    overflow_start: usize,
    dim1: usize,
    dim2: usize,
}

impl BrukerFrame {
    pub fn new() -> BrukerFrame {
        BrukerFrame {
            header: HashMap::new(),
            array: Array::new(),
            data_start: 0,
            overflow_start: 0,
            dim1: 0,
            dim2: 0,
        }
    }

    pub fn read_file<P: AsRef<Path>>(path: P) -> io::Result<BrukerFrame> {
        let mut file = File::open(path)?;
        let size = file.metadata()?.len() as usize;
        let mut data = Vec::with_capacity(size);
        unsafe { data.set_len(size) };
        file.read_exact(&mut data)?;
        let mut frame = BrukerFrame::new();
        frame.read(&data)?;
        Ok(frame)
    }

    fn read(&mut self, data: &[u8]) -> io::Result<()> {
        self.read_header(data)?;
        self.read_array(data)?;
        self.read_overflow(data)?;
        self.check_linearity();
        Ok(())
    }

    fn read_header_chunks(&mut self, start: usize, end: usize, data: &[u8]) -> io::Result<()> {
        for i in (start..end).step_by(HEADER_CHUNK_SIZE) {
            let j = i + HEADER_CHUNK_SIZE;
            if j >= data.len() {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "not enough data in buffer",
                ));
            }
            self.fill_header(&data[i..j])
        }
        Ok(())
    }

    fn read_header(&mut self, data: &[u8]) -> io::Result<()> {
        self.read_header_chunks(0, N_BLOCKS, data)?;
        if let Ok(v) = self.get_header_str_as_i64(KEY_HEADER_BLOCKS) {
            self.data_start = v as usize;
        } else {
            self.data_start = N_HEADER_BLOCKS
        };
        self.data_start *= BLOCK_SIZE;
        self.read_header_chunks(N_BLOCKS, self.data_start, data)?;
        if let Ok(dim1) = self.get_header_str_as_i64(KEY_N_ROWS) {
            if let Ok(dim2) = self.get_header_str_as_i64(KEY_N_COLS) {
                if dim1 == 0 || dim2 == 0 {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "zero dimensions in the header",
                    ));
                }
                self.dim1 = dim1 as usize;
                self.dim2 = dim2 as usize;
            } else {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "could not find dim2 in the header",
                ));
            }
        } else {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "could not find dim1 in the header",
            ));
        };
        if let Ok(v) = self.get_header_str_as_i64(KEY_VERSION) {
            if v != VERSION {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("version {} is not yet supported", v),
                ));
            }
        }
        Ok(())
    }

    fn fill_header(&mut self, chunk: &[u8]) {
        if chunk.is_empty() {
            return;
        }
        let chunk = unsafe { std::str::from_utf8_unchecked(chunk) };
        let parts: Vec<&str> = chunk.split(':').map(|x| x.trim()).collect();
        if parts.len() < 2 {
            return;
        }
        self.header
            .entry(parts[0].to_string())
            .or_insert(HeaderEntry::String(parts[1].to_string()));
    }

    fn read_array(&mut self, data: &[u8]) -> io::Result<()> {
        let npixelb;
        if let Ok(v) = self.get_header_str_as_i64(KEY_N_PIXELB) {
            npixelb = v as usize;
        } else {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("could not find {} in the header", KEY_N_PIXELB),
            ));
        }
        if self.data_start >= data.len() {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "not enough binary data",
            ));
        }
        let array = &data[self.data_start..];
        self.array = match npixelb {
            SIZE_U8 => Array::from_slice_u8(self.dim1, self.dim2, array)?,
            SIZE_U16 => Array::from_slice_u16::<LittleEndian>(self.dim1, self.dim2, array)?,
            SIZE_U32 => Array::from_slice_u32::<LittleEndian>(self.dim1, self.dim2, array)?,
            _ => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("bad value for {} = {} in the header", KEY_N_PIXELB, npixelb),
                ))
            }
        };
        self.overflow_start = self.array.len() * npixelb + self.data_start;
        Ok(())
    }

    fn check_linearity(&mut self) {
        if let Ok(s) = self.get_header_str(KEY_LINEAR) {
            let parts: Vec<Result<f64, ParseFloatError>> = s
                .split_ascii_whitespace()
                .map(|x| x.trim().parse::<f64>())
                .collect();
            if parts.len() < 2 {
                return;
            }
            if let Ok(slope) = parts[0] {
                if let Ok(offset) = parts[1] {
                    if slope != 1.0 || offset != 0.0 {
                        for value in self.array.data_mut() {
                            *value = *value * slope + offset;
                        }
                    }
                }
            }
        }
    }

    fn read_overflow(&mut self, data: &[u8]) -> io::Result<()> {
        let mut n;
        if let Ok(v) = self.get_header_str_as_i64(KEY_N_OVERFLOW) {
            n = v as usize;
        } else {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("bad value for {} in the header", KEY_N_OVERFLOW),
            ));
        }
        let mut reader = io::Cursor::new(&data[self.overflow_start..]);
        while n > 0 {
            let intensity = reader.read_u64::<LittleEndian>()? as f64;
            reader.read_u8()?;
            let position = reader.read_u32::<LittleEndian>()? as usize;
            if position >= self.array.len() {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("bad overflow position: {}", position),
                ));
            }
            reader.read_u24::<LittleEndian>()?;
            self.array[position] = intensity;
            n -= 1;
        }
        Ok(())
    }
}

impl Frame for BrukerFrame {
    fn array(&self) -> &Array {
        &self.array
    }

    fn header(&self) -> &Header {
        &self.header
    }

    fn header_mut(&mut self) -> &mut Header {
        &mut self.header
    }

    fn array_mut(&mut self) -> &mut Array {
        &mut self.array
    }

    fn set_array(&mut self, array: Array) {
        self.array = array;
    }
}

const BLOCK_SIZE: usize = 512;
const N_HEADER_BLOCKS: usize = 5;
const VERSION: i64 = 8;
const HEADER_CHUNK_SIZE: usize = 80;
const N_BLOCKS: usize = BLOCK_SIZE * N_HEADER_BLOCKS;
const KEY_HEADER_BLOCKS: &'static str = "HDRBLKS";
const KEY_N_ROWS: &'static str = "NROWS";
const KEY_N_COLS: &'static str = "NCOLS";
const KEY_N_PIXELB: &'static str = "NPIXELB";
const KEY_N_OVERFLOW: &'static str = "NOVERFL";
const KEY_LINEAR: &'static str = "LINEAR";
const KEY_VERSION: &'static str = "VERSION";
const SIZE_U8: usize = mem::size_of::<u8>();
const SIZE_U16: usize = mem::size_of::<u16>();
const SIZE_U32: usize = mem::size_of::<u32>();

#[cfg(test)]
mod tests {
    use crate::bruker::BrukerFrame;
    use crate::frame::Frame;
    use std::path::Path;

    fn read_test_file<P: AsRef<Path>>(path: P) {
        let frame = BrukerFrame::read_file(path).unwrap();
        if frame.dim1() != 1024 || frame.dim2() != 1024 {
            panic!(
                "Bad frame dimensions: expected 1024x1024, found {}x{}",
                frame.dim1(),
                frame.dim2(),
            );
        }
        let sum = frame.sum();
        if sum != 21268323. {
            panic!("Expected sum is 21268323 but found {}", sum);
        }
        let min = frame.min();
        if min != 0. {
            panic!("Expected min is 0 but found {}", min);
        }
        let max = frame.max();
        if max != 6886. {
            panic!("Expected max is 6886. but found {}", max);
        }
    }

    #[test]
    fn test_bruker_read() {
        read_test_file("testdata/test.gfrm");
    }
}