-
Notifications
You must be signed in to change notification settings - Fork 1
/
msa.go
404 lines (339 loc) · 11.8 KB
/
msa.go
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
// Licensed to NASA JPL under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. NASA JPL licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package importerutils
import (
"errors"
"fmt"
"strconv"
"strings"
"github.com/pixlise/core/v4/api/dataimport/internal/dataConvertModels"
"github.com/pixlise/core/v4/core/utils"
protos "github.com/pixlise/core/v4/generated-protos"
)
func ReadMSAFileLines(lines []string, singleDetectorMSA bool, expectPMC bool, detectorADuplicate bool) ([]dataConvertModels.DetectorSample, error) {
var err error
// If single detector, we're reading:
meta := dataConvertModels.MetaData{}
var spectra []int64
// If multi-detector, we also read:
metaB := dataConvertModels.MetaData{}
var spectraB []int64
msaNumColumns := 1
expColCount := 2
if detectorADuplicate {
expColCount = 1
}
startMarker := "#SPECTRUM"
endMarker := "#ENDOFDATA"
readingSpectra := false
lc := 0
for _, l := range lines {
l = strings.TrimSpace(l)
if len(l) > 0 {
if strings.HasPrefix(l, startMarker) {
if readingSpectra == true {
return nil, fmt.Errorf("Unexpected spectrum start marker at %v", lc)
}
readingSpectra = true
if singleDetectorMSA {
err = verifyDetectorMSAMeta(meta, []string{"DETECTOR_ID", "NPOINTS", "DATATYPE", "NCOLUMNS"}, "Y", 1)
if err != nil {
return nil, err
}
} else {
err = verifyDetectorMSAMeta(meta, []string{"NPOINTS", "DATATYPE", "NCOLUMNS"}, "YY", expColCount)
if err != nil {
return nil, err
}
msaNumColumns = expColCount
if _, ok := meta["DETECTOR_ID"]; ok {
return nil, errors.New("Unexpected DETECTOR_ID in multi-detector MSA")
}
}
} else if len(l) >= len(endMarker) && l[0:len(endMarker)] == endMarker {
if readingSpectra == false {
return nil, fmt.Errorf("Unexpected end of data marker at %v", lc)
}
readingSpectra = false
break
} else if l[0] == '#' {
if readingSpectra == true {
return nil, errors.New("Unexpected # after started spectra read")
}
f, v, err := parseMSAMetadataLine(l)
if err != nil {
return nil, err
}
if _, ok := meta[f]; ok {
if f == "COMMENT" {
meta[f] = dataConvertModels.MetaValue{
SValue: meta[f].SValue + " " + v,
IValue: meta[f].IValue,
FValue: meta[f].FValue,
DataType: meta[f].DataType,
}
} else {
return nil, fmt.Errorf("Duplicate meta data lines found for: %v", f)
}
} else {
// Don't store it if there's no data!
if len(v) > 0 {
// At this point, if we're going to split this, save these as strings, because we know we will split
// and convert them to the right data type in the next step
if !singleDetectorMSA && (f == "XPERCHAN" || f == "OFFSET" || f == "LIVETIME" || f == "REALTIME") {
meta[f] = dataConvertModels.StringMetaValue(v)
} else {
meta[f], err = makeMetaValue(f, v)
if err != nil {
return nil, err
}
}
}
}
} else {
if readingSpectra != true {
return nil, fmt.Errorf("Unexpected potential spectra found at %v: %v", lc, l)
}
spectrumRowData, err := parseMSASpectraLine(l, lc, msaNumColumns)
if err != nil {
return nil, err
}
spectra = append(spectra, spectrumRowData[0])
if !singleDetectorMSA {
readFromIdx := 1
if detectorADuplicate {
readFromIdx = 0
}
spectraB = append(spectraB, spectrumRowData[readFromIdx])
}
}
}
lc = lc + 1
}
if len(spectra) <= 0 {
return nil, errors.New("No spectra data found to be read")
}
// Read point count
npoints, err := strconv.Atoi(meta["NPOINTS"].SValue)
if err != nil {
return nil, errors.New("Failed to read NPOINTS, got: " + meta["NPOINTS"].SValue)
}
if int64(len(spectra)) != int64(npoints) {
return nil, fmt.Errorf("Expected %v spectra, got %v", meta["NPOINTS"].SValue, len(spectra))
}
if !singleDetectorMSA && int64(len(spectraB)) != int64(npoints) {
return nil, fmt.Errorf("Expected %v B spectra, got %v", meta["NPOINTS"].SValue, len(spectraB))
}
if _, ok := meta["PMC"]; ok {
if !expectPMC {
return nil, errors.New("PMC NOT expected, but was found in MSA")
}
} else {
if expectPMC {
return nil, errors.New("PMC expected, but not found in MSA")
}
}
if !singleDetectorMSA {
meta, metaB, err = splitMSAMetaFor2Detectors(meta, detectorADuplicate)
if err != nil {
return nil, err
}
verifyDetectorMSAMeta(metaB, []string{"NPOINTS", "DATATYPE", "NCOLUMNS"}, "YY", expColCount)
if err != nil {
return nil, err
}
}
result := []dataConvertModels.DetectorSample{
{
Meta: meta,
Spectrum: spectra,
},
}
if !singleDetectorMSA {
second := dataConvertModels.DetectorSample{
Meta: metaB,
Spectrum: spectraB,
}
result = append(result, second)
}
return result, nil
}
func splitMSAMetaFor2Detectors(meta dataConvertModels.MetaData, detectorADuplicate bool) (dataConvertModels.MetaData, dataConvertModels.MetaData, error) {
/*
An example of what we're splitting...
#XPERCHAN : 10.0, 10.0 eV per channel
#OFFSET : 0.0, 0.0 eV of first channel
#SIGNALTYPE : XRF
#COMMENT : 2500 point scan of Scotland RR4 - Mar. 13, 2018.
#COMMENT : 28 kV at 155 uA, 20 s spot scans, 200 micron steps, 10 mm (y) x 10 mm (x) area
#XPOSITION : 0.000
#YPOSITION : 0.000
#ZPOSITION : 2.443
#LIVETIME : 25.09, 25.08
#REALTIME : 25.11, 25.11
##TRIGGERS : 45993, 43902
##EVENTS : 44690, 42823
##KETEK_ICR : 1833.1, 1750.7
##KETEK_OCR : 1780.1, 1705.7
*/
metaA := dataConvertModels.MetaData{"DETECTOR_ID": dataConvertModels.StringMetaValue("A")}
metaB := dataConvertModels.MetaData{"DETECTOR_ID": dataConvertModels.StringMetaValue("B")}
needsSplit := []string{"XPERCHAN", "OFFSET", "LIVETIME", "REALTIME", "TRIGGERS", "EVENTS", "KETEK_ICR", "KETEK_OCR", "OVERFLOWS", "UNDERFLOWS", "BASE_EVENTS", "RESETS", "OVER_ADCMAX"}
var err error
for k, val := range meta {
if utils.ItemInSlice(k, needsSplit) && val.DataType == protos.Experiment_MT_STRING {
v := val.SValue
v = strings.TrimSpace(v)
parts := strings.Split(v, ", ")
if len(parts) != 2 && !detectorADuplicate {
return nil, nil, errors.New("Metadata row cannot be split for 2 detectors due to commas")
}
readBIdx := 1
if detectorADuplicate {
readBIdx = 0
}
metaA[k], err = makeMetaValue(k, strings.TrimSpace(parts[0]))
if err != nil {
return nil, nil, err
}
metaB[k], err = makeMetaValue(k, strings.TrimSpace(parts[readBIdx]))
if err != nil {
return nil, nil, err
}
} else {
if val.DataType == protos.Experiment_MT_STRING {
val.SValue = strings.TrimSpace(val.SValue)
}
metaA[k] = val
metaB[k] = val
}
}
return metaA, metaB, nil
}
func makeMetaValue(label string, value string) (dataConvertModels.MetaValue, error) {
asInt := []string{"PMC", "SCLK", "RTT"}
asFloat := []string{"XPERCHAN", "OFFSET", "LIVETIME", "REALTIME", "XPOSITION", "YPOSITION", "ZPOSITION"}
// Some fields need to be saved as different data types...
if utils.ItemInSlice(label, asInt) {
// Must parse it as an int
iV, err := strconv.ParseInt(value, 0, 32)
if err != nil {
return dataConvertModels.StringMetaValue(""), fmt.Errorf("Failed to read integer for: %v, got: %v", label, value)
}
return dataConvertModels.IntMetaValue(int32(iV)), nil
} else if utils.ItemInSlice(label, asFloat) {
// Must parse it as float
fV, err := strconv.ParseFloat(value, 32)
if err != nil {
return dataConvertModels.StringMetaValue(""), fmt.Errorf("Failed to read float for: %v, got: %v", label, value)
}
return dataConvertModels.FloatMetaValue(float32(fV)), nil
}
// Default is string...
return dataConvertModels.StringMetaValue(value), nil
}
func verifyDetectorMSAMeta(meta dataConvertModels.MetaData, expFields []string, datatype string, ncolumns int) error {
for _, exp := range expFields {
if _, ok := meta[exp]; !ok {
return fmt.Errorf("Failed to find %v in metadata", exp)
}
}
if meta["DATATYPE"].SValue != datatype {
return fmt.Errorf("Expected DATATYPE \"%v\" in MSA metadata", datatype)
}
nColsRead, err := strconv.Atoi(meta["NCOLUMNS"].SValue)
if err != nil {
return errors.New("Failed to read NCOLUMNS, got: " + meta["NCOLUMNS"].SValue)
}
if int64(ncolumns) != int64(nColsRead) {
return fmt.Errorf("Expected NCOLUMNS \"%v\" in MSA metadata", ncolumns)
}
return nil
}
func parseMSAMetadataLine(line string) (string, string, error) {
if line[0] != '#' {
return "", "", errors.New("Expected # at start of metadata: " + line)
}
colIdx := strings.Index(line, ":")
if colIdx < 0 {
return "", "", errors.New("Failed to parse metadata line: " + line)
}
field := strings.TrimLeft(strings.TrimSpace(line[:colIdx]), "#")
value := line[colIdx+1:]
// NOTE: we get some weird situations where there are comments on the line after real data
// for now, it looks like there are always several spaces before the comment, so for example:
// #NCOLUMNS : 2 Number of data columns
// we can find the first value text, and if there is anything after it with multiple spaces, we
// can trim it there
// Another situation is it seems if the entire thing is a comment it has more than 4 spaces
// at the start. Some valid values start at up to 4 spaces, so if we see 5+ spaces at the start
// we consider the entire thing to be a comment
// Another weirder consideration... if we have this:
// "0.0, 0.0 eV of first channel"
// We really want to determine that there is float,float and cut the rest off. So first test for that
bits := strings.Split(value, ",")
done := false
if len(bits) >= 2 {
// if the first 2 values are floats, assume we've just read float,float and stop
str1 := strings.Trim(bits[0], " ")
_, e1 := strconv.ParseFloat(str1, 32)
secondbits := strings.Split(strings.Trim(bits[1], " "), " ")
if len(secondbits) >= 1 {
str2 := strings.Trim(secondbits[0], " ")
_, e2 := strconv.ParseFloat(str2, 32)
if e1 == nil && e2 == nil {
value = fmt.Sprintf("%v, %v", str1, str2)
done = true
}
}
}
if !done {
if len(value) > 5 && value[0:5] == " " {
value = ""
} else {
// Trim left hand spaces
value = strings.TrimLeft(value, " ")
// Now find anything we can chop off inside
multiSpacePos := strings.Index(value, " ")
if multiSpacePos > 0 {
value = value[0:multiSpacePos]
}
}
}
// Final trim, in case we had a space before/after, eg // #NCOLUMNS : 2
value = strings.TrimSpace(value)
return field, value, nil
}
func parseMSASpectraLine(line string, lc int, ncolumns int) ([]int64, error) {
items := strings.Split(line, ",")
if len(items) != ncolumns {
return nil, fmt.Errorf("Expected %d spectrum columns, got %d on line [%d]:%s", ncolumns, len(items), lc, line)
}
var specvals []int64
for _, v := range items {
val := strings.TrimSpace(v)
specval, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return nil, fmt.Errorf("Failed to read spectra \"%v\" on line [%v]:%v", val, lc, line)
}
if specval < 0 {
return nil, fmt.Errorf("Spectra expected non-negative value \"%v\" on line [%v]:%v", val, lc, line)
}
specvals = append(specvals, specval)
}
return specvals, nil
}