forked from sandialabs/SpecUtils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpecFile_spc.cpp
More file actions
2867 lines (2466 loc) · 116 KB
/
SpecFile_spc.cpp
File metadata and controls
2867 lines (2466 loc) · 116 KB
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
SpecUtils: a library to parse, save, and manipulate gamma spectrum data files.
Copyright (C) 2016 William Johnson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "SpecUtils_config.h"
#include <cmath>
#include <cctype>
#include <limits>
#include <memory>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include <fstream>
#include <numeric>
#include <iostream>
#include <algorithm>
#include <stdexcept>
#include <functional>
#include "3rdparty/date/include/date/date.h"
#include "SpecUtils/DateTime.h"
#include "SpecUtils/SpecFile.h"
#include "SpecUtils/ParseUtils.h"
#include "SpecUtils/StringAlgo.h"
#include "SpecUtils/EnergyCalibration.h"
#include "SpecUtils/SpecFile_location.h"
#include "SpecUtils/SerialToDetectorModel.h"
using namespace std;
namespace
{
bool not_alpha_numeric(char c)
{
return !(std::isalnum(c) || c==' ');
}
/* IAEA block labels that represent items to put into the remarks_ variable of
SpecFile.
*/
const char * const ns_iaea_comment_labels[] =
{
"Comment", "AcquisitionMode", "CrystalType", "Confidence",
"MinDoseRate", "MaxDoseRate", "AvgDoseRate", "MinNeutrons", "MaxNeutrons",
"BuiltInSrcType", "BuiltInSrcActivity",
"HousingType", "GMType", "He3Pressure", "He3Length", "He3Diameter",
"ModMaterial", "ModVolume", "ModThickness", "LastSourceStabTime",
"LastSourceStabFG", "LastCalibTime", "LastCalibSource", "LastCalibFG",
"LastCalibFWHM", "LastCalibTemp", "StabilType", "StartupStatus",
"TemperatureBoard", "TemperatureBoardRange", "BatteryVoltage", "Uptime",
"DoseRateMax20min", "BackgroundSubtraction",
"FWHMCCoeff", "ROI", "CalibPoint", "NeutronAlarm",
"GammaDetector", "NeutronDetector", "SurveyId", "EventNumber",
"Configuration"
};//const char * const ns_iaea_comment_labels = {...}
/* IAEA block labels that represent information to be put into
component_versions_ member variable of SpecFile.
*/
const char * const ns_iaea_version_labels[] =
{
"Hardware", "TemplateLibraryVersion", "NativeAlgorithmVersion",
"ApiVersion", "Firmware", "Operating System", "Application",
"SoftwareVersion"
};
string pad_iaea_prefix( string label )
{
label.resize( 22, ' ' );
return label + ": ";
}
string print_to_iaea_datetime( const SpecUtils::time_point_t &t )
{
char buffer[256];
const chrono::time_point<chrono::system_clock,date::days> t_as_days = date::floor<date::days>(t);
const date::year_month_day t_ymd = date::year_month_day{t_as_days};
const date::hh_mm_ss<SpecUtils::time_point_t::duration> time_of_day = date::make_time(t - t_as_days);
const int year = static_cast<int>( t_ymd.year() );
const int month = static_cast<int>( static_cast<unsigned>( t_ymd.month() ) );
const int day = static_cast<int>( static_cast<unsigned>( t_ymd.day() ) );
const int hour = static_cast<int>( time_of_day.hours().count() );
const int minutes = static_cast<int>( time_of_day.minutes().count() );
const int seconds = static_cast<int>( time_of_day.seconds().count() );
snprintf( buffer, sizeof(buffer), "%02d.%02d.%04d %02d:%02d:%02d",
day, month, year, hour, minutes, seconds );
return buffer;
}//print_iaea_datetime(...)
}//namespace
namespace SpecUtils
{
bool SpecFile::load_spc_file( const std::string &filename )
{
reset();
std::unique_lock<std::recursive_mutex> scoped_lock( mutex_ );
#ifdef _WIN32
ifstream file( convert_from_utf8_to_utf16(filename).c_str(), ios_base::binary|ios_base::in );
#else
ifstream file( filename.c_str(), ios_base::binary|ios_base::in );
#endif
if( !file.is_open() )
return false;
uint8_t firstbyte;
file.read( (char *) (&firstbyte), 1 );
file.seekg( 0, ios::beg );
const bool isbinary = (firstbyte == 0x1);
// const bool istext = (char(firstbyte) == 'S');
if( !isbinary && /*!istext*/ !isalpha(firstbyte) )
{
// cerr << "SPC file '" << filename << "'is not binary or text firstbyte="
// << (char)firstbyte << endl;
return false;
}//if( !isbinary && !istext )
bool loaded = false;
if( isbinary )
loaded = load_from_binary_spc( file );
else
loaded = load_from_iaea_spc( file );
if( loaded )
filename_ = filename;
return loaded;
}//bool load_spc_file( const std::string &filename )
bool SpecFile::load_from_iaea_spc( std::istream &input )
{
//Function is currently not very robust to line ending changes, or unexpected
// whitespaces. Aslo parsing of channel counts coult be sped up probably.
reset();
std::unique_lock<std::recursive_mutex> scoped_lock( mutex_ );
std::shared_ptr<DetectorAnalysis> analysis;
std::shared_ptr<Measurement> meas = std::make_shared<Measurement>();
if( !input.good() )
return false;
const istream::pos_type orig_pos = input.tellg();
//There are quite a number of fields that Measurement or SpecFile class
// does not yet implement, so for now we will just put them into the remarks
string detector_type, det_length, det_diameter, gamma_det;
try
{
string line;
int Length = -1;
//going through and making sure this is an ASCII file wont work, because
// there is often a subscript 3 (ascii code 179) or infinity symbols...
// So instead we'll insist the first non-empty line of file must start with
// three different alphanumneric characters. We could probably tighten this
// up to apply to all non-empty lines in the file.
int linenum = 0, nnotrecognized = 0;
bool tested_first_line = false;
vector<float> calibcoeff_poly;
shared_ptr<vector<float>> channel_counts;
while( input.good() )
{
const istream::pos_type sol_pos = input.tellg();
// getline( input, line, '\r' );
const size_t max_len = 1024*1024; //allows a line length of 64k fields, each of 16 characters, which his more than any spectrum file should get
SpecUtils::safe_get_line( input, line, max_len );
if( line.size() >= (max_len-1) )
throw runtime_error( "Line greater than 1MB" );
trim( line );
if( line.empty() )
continue;
if( !tested_first_line )
{
tested_first_line = true;
if( line.size() < 3
|| !isalnum(line[0]) || !isalnum(line[1]) || !isalnum(line[2])
|| !(line[0]!=line[1] || line[0]!=line[2] || line[2]!=line[3]) )
throw runtime_error( "File failed constraint that first three charcters"
" on the first non-empty line must be alphanumeric"
" and not be equal" );
}//if( !tested_first_line )
const size_t colonpos = line.find(':');
const size_t info_pos = line.find_first_not_of(": ", colonpos);
bool is_remark = false;
//Check if its a remark field
for( const char * const label : ns_iaea_comment_labels )
{
if( istarts_with( line, label ) )
{
is_remark = true;
if( info_pos != string::npos )
{
string remark = label;
remark += " : " + line.substr(info_pos);
trim( remark );
remarks_.push_back( remark );
// Lets re-read "AvgDoseRate" into Measurement::dose_rate_ later on, but also we'll leave in remarks since remarks might have min/max dose rate, and we'll leave average with them
if( iequals_ascii(label, "AvgDoseRate") )
is_remark = false;
}
break;
}//if( istarts_with( line, label ) )
}//for( const char * const label : ns_iaea_comment_labels )
bool is_version = false;
for( const char * const label : ns_iaea_version_labels )
{
if( istarts_with( line, label ) )
{
is_version = true;
if( info_pos != string::npos )
component_versions_.push_back( make_pair(label,line.substr(info_pos)) );
break;
}//if( istarts_with( line, label ) )
}//for( const char * const label : ns_iaea_comment_labels )
if( is_version )
{
//nothing to to here
}else if( is_remark )
{
//Go through and look for warning signs...
if( istarts_with( line, "BackgroundSubtraction" )
&& info_pos != string::npos
&& !icontains( line.substr(info_pos), "No" ) )
{
#if(PERFORM_DEVELOPER_CHECKS)
/// @TODO should put this message in a parser error/warning section.
string msg = "Instrument may have been in background subtract mode.";
if( !std::count( begin(remarks_), end(remarks_), msg) )
remarks_.emplace_back( std::move(msg) );
#endif
}
if( istarts_with( line, "GammaDetector" ) && (info_pos != string::npos) )
gamma_det = line.substr(info_pos);
}else if( istarts_with( line, "SpectrumName" ) )
{//SpectrumName : ident903558-21_2012-07-26_07-10-55-003.spc
if( info_pos != string::npos )
{
const string info = line.substr(info_pos);
if( SpecUtils::icontains( info, "ident") || SpecUtils::icontains(info, "Field") )
{
if( SpecUtils::icontains( info, "R500") )
{
if( icontains(info,"LG") || icontains(info,"LaBr") )
detector_type_ = DetectorType::IdentiFinderR500LaBr;
else if( icontains(info,"ULCS") || icontains(info,"NaI") )
detector_type_ = DetectorType::IdentiFinderR500NaI;
}else
{
if( SpecUtils::icontains( info, "LaBr") ) //ex. "Identifinder LGH (LaBr)", "Ultra LGH LaBr"
{
if( instrument_model_.empty() )
instrument_model_ = "IdentiFINDER-LaBr3";
detector_type_ = DetectorType::IdentiFinderLaBr3;
}else if( SpecUtils::icontains( info, "400 T1") || SpecUtils::icontains( info, "400 T2") )
{
if( instrument_model_.empty() )
instrument_model_ = "identiFINDER-T";
detector_type_ = DetectorType::IdentiFinderTungsten;
}else
{
if( instrument_model_.empty() )
instrument_model_ = "identiFINDER";
detector_type_ = DetectorType::IdentiFinderUnknown;
}
}//if( R500 ) / else
}else if( SpecUtils::icontains(line, "Raider") )
{
detector_type_ = DetectorType::MicroRaider;
if( instrument_model_.empty() )
instrument_model_ = "MicroRaider";
if( manufacturer_.empty() )
manufacturer_ = "FLIR";
}
}//if( info_pos != string::npos )
}else if( istarts_with( line, "DetectorType" ) )
{//DetectorType : NaI
// Note that at least some LaBr identiFINDERs appear to say NaI
if( info_pos != string::npos && (detector_type_ != DetectorType::IdentiFinderUnknown) )
detector_type = line.substr(info_pos);
}else if( istarts_with( line, "DetectorLength" ) )
{
if( info_pos != string::npos )
det_length = line.substr(info_pos);
}else if( istarts_with( line, "DetectorDiameter" ) )
{
if( info_pos != string::npos )
det_diameter = line.substr(info_pos);
}
//"GammaDetector" now included in ns_iaea_comment_labels[].
//else if( istarts_with( line, "GammaDetector" ) )
//{
//ex: "GammaDetector : NaI 35x51"
//if( info_pos != string::npos )
//remarks_.push_back( "Gamma Detector: " + line.substr(info_pos) );
//meas->detector_type_ = line.substr(info_pos);
//}
//"NeutronDetector" now included in ns_iaea_comment_labels[].
//else if( istarts_with( line, "NeutronDetector" ) )
//{
//if( info_pos != string::npos )
//remarks_.push_back( "Neutron Detector: " + line.substr(info_pos) );
//}
else if( istarts_with( line, "XUnit" ) )
{//XUnit : keV
if( info_pos != string::npos && !istarts_with( line.substr(info_pos), "keV") )
meas->parse_warnings_.push_back( "Unexpected x-unit: " + line.substr(info_pos) );
}else if( istarts_with( line, "YUnit" ) ) // :
{
}else if( istarts_with( line, "Length" ) )
{//Length : 1024
if( info_pos != string::npos )
Length = atoi( line.c_str() + info_pos );
}else if( istarts_with( line, "SubSpcNum" ) )
{//SubSpcNum : 1
int SubSpcNum = 1;
if( info_pos != string::npos )
SubSpcNum = atoi( line.c_str() + info_pos );
if( SubSpcNum > 1 )
{
const string msg = "SpecFile::load_from_iaea_spc(istream &)\n\tASCII Spc files only support "
"reading files with one spectrum right now";
throw std::runtime_error( msg );
}
}else if( istarts_with( line, "StartSubSpc" ) )
{//StartSubSpc : 0
}else if( istarts_with( line, "StopSubSpc" ) )
{//StopSubSpc : 0
}else if( istarts_with( line, "Realtime" ) )
{//Realtime : 300.000
if( info_pos != string::npos )
meas->real_time_ = static_cast<float>( atof( line.c_str() + info_pos ) );
}else if( istarts_with( line, "Livetime" )
|| istarts_with( line, "Liveime" )
|| istarts_with( line, "Lifetime" ) )
{//Livetime : 300.000
if( info_pos != string::npos )
meas->live_time_ = static_cast<float>( atof( line.c_str() + info_pos ) );
}else if( istarts_with( line, "Deadtime" ) )
{//Deadtime : 0.000
}else if( istarts_with( line, "FastChannel" ) )
{//FastChannel : 69008
}else if( istarts_with( line, "Starttime" ) )
{//Starttime : '28.08.2012 16:12:26' or '3.14.2006 10:19:36'
if( info_pos != string::npos )
meas->start_time_ = time_from_string( line.substr( info_pos ).c_str() );
}else if( istarts_with( line, "Stoptime" ) )
{//Stoptime : 28.08.2012 16:17:25
// if( info_pos != string::npos )
// meas-> = time_from_string( line.substr( info_pos ).c_str() );
}else if( istarts_with( line, "NeutronCounts" )
|| istarts_with( line, "SumNeutrons" ) )
{//NeutronCounts : 0
const float num_neut = static_cast<float>( atof( line.substr( info_pos ).c_str() ) );
if( info_pos != string::npos && meas->neutron_counts_.empty() )
meas->neutron_counts_.push_back( num_neut );
else if( info_pos != string::npos )
meas->neutron_counts_[0] += num_neut;
meas->neutron_counts_sum_ += num_neut;
meas->contained_neutron_ = true;
}
// FWHMCCoeff : a=0.000000000E+000 b=0.000000000E+000 c=0.000000000E+000 d=0.000000000E+000'
else if( starts_with( line, "CalibCoeff" ) )
{//CalibCoeff : a=0.000000000E+000 b=0.000000000E+000 c=3.000000000E+000 d=0.000000000E+000
float a = 0.0f, b = 0.0f, c = 0.0f, d = 0.0f;
const size_t apos = line.find( "a=" );
const size_t bpos = line.find( "b=" );
const size_t cpos = line.find( "c=" );
const size_t dpos = line.find( "d=" );
const bool have_a = apos < (line.size()-2);
const bool have_b = bpos < (line.size()-2);
const bool have_c = cpos < (line.size()-2);
const bool have_d = dpos < (line.size()-2);
if( have_a )
a = static_cast<float>( atof( line.c_str() + apos + 2 ) );
if( have_b )
b = static_cast<float>( atof( line.c_str() + bpos + 2 ) );
if( have_c )
c = static_cast<float>( atof( line.c_str() + cpos + 2 ) );
if( have_d )
d = static_cast<float>( atof( line.c_str() + dpos + 2 ) );
if( have_a && have_b && have_c && have_d
&& (a!=0.0 || b!=0.0 || c!=0.0 ) )
{
calibcoeff_poly = {d,c,b,a};
}else if( have_b && have_c && c!=0.0 )
{
calibcoeff_poly = {b,c};
}
}else if( istarts_with( line, "NuclideID1" )
|| istarts_with( line, "NuclideID2" )
|| istarts_with( line, "NuclideID3" )
|| istarts_with( line, "NuclideID4" ) )
{
//"8 Annih. Rad."
//"- Nuc. U-233"
//"5 NORM K-40"
//"- Ind.Ir-192s"
if( info_pos != string::npos )
{
if( !analysis )
analysis = std::make_shared<DetectorAnalysis>();
DetectorAnalysisResult result;
string info = line.substr(info_pos);
string::size_type delim = info.find_first_of( ' ' );
if( delim == 1 && (std::isdigit(info[0]) || info[0]=='-') )
{
result.id_confidence_ = info.substr(0,delim);
info = info.substr(delim);
SpecUtils::trim( info );
delim = info.find_first_of( " ." );
string nuctype = info.substr( 0, delim );
if( SpecUtils::istarts_with(nuctype, "Ann")
|| SpecUtils::istarts_with(nuctype, "Nuc")
|| SpecUtils::istarts_with(nuctype, "NORM")
|| SpecUtils::istarts_with(nuctype, "Ind")
|| SpecUtils::istarts_with(nuctype, "Cal")
|| SpecUtils::istarts_with(nuctype, "x")
|| SpecUtils::istarts_with(nuctype, "med")
|| SpecUtils::istarts_with(nuctype, "cos")
|| SpecUtils::istarts_with(nuctype, "bac")
|| SpecUtils::istarts_with(nuctype, "TENORM")
|| SpecUtils::istarts_with(nuctype, "bre")
//any others? this list so far was just winged
)
{
result.nuclide_type_ = nuctype;
result.nuclide_ = info.substr( delim );
SpecUtils::trim( result.nuclide_ );
if(!result.nuclide_.empty() && result.nuclide_[0]=='.' )
{
result.nuclide_ = result.nuclide_.substr(1);
SpecUtils::trim( result.nuclide_ );
result.nuclide_type_ += ".";
}
result.remark_ = line.substr(info_pos); //just in case
}else
{
#if( PERFORM_DEVELOPER_CHECKS )
//Leaving below line in because I only tested above parsing on a handful of files (20161010).
if( !result.nuclide_type_.empty() )
log_developer_error( __func__, ("Unknown radiation type in ana result: '" + result.nuclide_type_ + "'").c_str() );
#endif
result.nuclide_ = line.substr(info_pos);
}
}else
{
result.nuclide_ = line.substr(info_pos);
}
analysis->results_.push_back( result );
}//if( info_pos != string::npos )
}else if( istarts_with( line, "IDLibrary" ) )
{
//Comes in files with "NuclideID1" and "NuclideID2" lines, after all the
// nuclides.
if( !analysis )
analysis = std::make_shared<DetectorAnalysis>();
analysis->remarks_.push_back( "Library: " + line.substr(info_pos) );
}else if( istarts_with( line, "SpectrumText" ) )
{//SpectrumText : 0
}else if( istarts_with( line, "SerialNumber" ) )
{
if( info_pos != string::npos )
instrument_id_ = line.substr(info_pos);
}else if( istarts_with( line, "UUID" ) )
{
if( info_pos != string::npos )
uuid_ = line.substr(info_pos);
}else if( istarts_with( line, "Manufacturer" ) )
{
if( info_pos != string::npos )
manufacturer_ = line.substr(info_pos);
}else if( istarts_with( line, "ModelNumber" ) )
{
if( info_pos != string::npos )
instrument_model_ = line.substr(info_pos);
}else if( istarts_with( line, "OperatorInformation" ) )
{
measurement_operator_ = line.substr(info_pos);
}else if( istarts_with( line, "GPSValid" ) )
{
if( SpecUtils::icontains(line, "no") )
{
if( meas->location_ && meas->location_->geo_location_ )
{
if( IsNan(meas->location_->speed_)
&& !meas->location_->relative_location_
&& !meas->location_->orientation_ )
{
meas->location_.reset();
}else
{
auto loc = make_shared<LocationState>( *meas->location_ );
loc->geo_location_.reset();
meas->location_ = loc;
}
}//if( meas->location_ && meas->location_->geo_location_ )
}//
}else if( istarts_with( line, "GPS" ) )
{
line = line.substr(info_pos);
const string::size_type pos = line.find( '/' );
if( pos != string::npos )
{
for( size_t i = 0; i < line.size(); ++i )
if( !isalnum(line[i]) )
line[i] = ' ';
const string latstr = trim_copy( line.substr(0,pos) );
const string lonstr = trim_copy( line.substr(pos+1) );
const double lat = conventional_lat_or_long_str_to_flt( latstr );
const double lon = conventional_lat_or_long_str_to_flt( lonstr );
if( valid_latitude(lat) && valid_longitude(lon) )
{
auto loc = make_shared<LocationState>();
// Take our best guess that these GPS coordinates are for the instrument.
loc->type_ = LocationState::StateType::Instrument;
auto geo = make_shared<GeographicPoint>();
loc->geo_location_ = geo;
geo->latitude_ = lat;
geo->longitude_ = lon;
meas->location_ = loc;
}//
}else
{
meas->parse_warnings_.push_back( "Couldnt parse lat/lon." );
}
}else if( istarts_with( line, "DeviceId" ) )
{
instrument_id_ = line.substr(info_pos);
trim( instrument_id_ );
}else if( istarts_with( line, "DoseRate" )
|| istarts_with( line, "AvgDoseRate" ) )
{
// May just be a number, with no units, or could be like "1.2 nSv/h".
if( info_pos != string::npos )
{
string val = SpecUtils::trim_copy( line.substr(info_pos) );
stringstream strm(val);
if( !(strm >> meas->dose_rate_) )
{
meas->parse_warnings_.push_back( "Failed to read dose '" + val + "'" );
}else
{
string units;
strm >> units;
if( units.size() )
{
try
{
meas->dose_rate_ *= dose_units_usvPerH( units.c_str(), units.size() );
}catch(...)
{
meas->parse_warnings_.push_back( "Failed to read dose units '" + units
+ "', assuming uSv/h" );
}//try / catch
}//if( units.size() )
}//if( fail to read number ) / else
}//if( info_pos != string::npos )
}else if( istarts_with( line, "Nuclide0" )
|| istarts_with( line, "Nuclide1" )
|| istarts_with( line, "Nuclide2" )
|| istarts_with( line, "Nuclide3" ) )
{
//some identiFINDER 2 LGH detectors makes it here.
const istream::pos_type currentpos = input.tellg();
//"Nuclide0" line is sometimes followed by "Strength0", "Class0",
// and "Confidence0" lines, so lets try and grab them.
string strengthline, classline, confidenceline;
try
{
SpecUtils::safe_get_line( input, strengthline, max_len );
SpecUtils::safe_get_line( input, classline, max_len );
SpecUtils::safe_get_line( input, confidenceline, max_len );
const size_t strength_colonpos = strengthline.find(':');
const size_t strength_info_pos = strengthline.find_first_not_of(": ", strength_colonpos);
const size_t class_colonpos = classline.find(':');
const size_t class_info_pos = classline.find_first_not_of(": ", class_colonpos);
const size_t conf_colonpos = confidenceline.find(':');
const size_t conf_info_pos = confidenceline.find_first_not_of(": ", conf_colonpos);
if( !SpecUtils::istarts_with( strengthline, "Strength" )
|| !SpecUtils::istarts_with( classline, "Class" )
|| !SpecUtils::istarts_with( confidenceline, "Confidence" )
|| class_info_pos == string::npos
|| strength_info_pos == string::npos
|| conf_info_pos == string::npos )
throw runtime_error( "" );
strengthline = strengthline.substr( strength_info_pos );
classline = classline.substr( class_info_pos );
confidenceline = confidenceline.substr( conf_info_pos );
}catch(...)
{
input.seekg( currentpos );
strengthline.clear();
classline.clear();
confidenceline.clear();
}
if( !analysis )
analysis = std::make_shared<DetectorAnalysis>();
DetectorAnalysisResult result;
result.nuclide_ = line.substr(info_pos);
result.nuclide_type_ = classline;
result.id_confidence_ = confidenceline;
if(!strengthline.empty())
result.remark_ = "Strength " + strengthline;
analysis->results_.push_back( result );
}else if( line.length() && isdigit(line[0]) && ((linenum - nnotrecognized) > 1) )
{
if( channel_counts && !channel_counts->empty() )
{
string warning = "Multiple spectra elements found in IAEA SPC file - combining into single spectrum.";
if( std::find(begin(meas->parse_warnings_), end(meas->parse_warnings_), warning ) == end(meas->parse_warnings_) )
meas->parse_warnings_.push_back( std::move(warning) );
}//if( we have already seend some channel_counts )
input.seekg( sol_pos, ios::beg );
while( SpecUtils::safe_get_line( input, line, 64*1024*16 ) ) //max 64k channels, 16 characters per float
{
trim(line);
if( line.empty() && channel_counts && (Length >= 0) && (channel_counts->size() == Length) )
{
//ref8MLQDKLR3E seems to have a bunch of extra zeros at the end of the
// file (after a line break), so lets deal with this in a way that we
// can still try to enforce Length==channel_counts->size() at the end
if( !input.eof() )
{
istream::pos_type pos;
do
{
pos = input.tellg();
trim( line );
if(!line.empty() && (line[0]<'0' || line[0]>'9') )
{
input.seekg( pos, ios::beg );
break;
}
}while( SpecUtils::safe_get_line( input, line ) );
}//if( not at the end of the file )
break;
}//if( we hit an empty line, and weve read the expected number of channels )
if(!line.empty() && (line[0]<'0' || line[0]>'9') )
break;
vector<float> linefloats;
SpecUtils::split_to_floats( line.c_str(), line.length(), linefloats );
for( float &f : linefloats ) //could probably use vector instructions here...
{
if( IsInf(f) || IsNan(f) )
f = 0.0f;
}
if( !channel_counts )
{
channel_counts = make_shared<vector<float>>( std::move(linefloats) );
}else
{
channel_counts->insert( channel_counts->end(), begin(linefloats), end(linefloats) );
}
assert( channel_counts );
if( channel_counts->size() > (64*1024 + 1) )
{
meas->parse_warnings_.push_back( "Exceeded max of 64k channels for IAEA SPC file; skipping further channels" );
break;
}
}//while( SpecUtils::safe_get_line( input, line ) )
if( (Length > 1) && channel_counts && (size_t(Length) != channel_counts->size()) )
{
bool isPowerOfTwo = ((Length != 0) && !(Length & (Length - 1)));
if( isPowerOfTwo && (Length >= 1024) && (size_t(Length) < channel_counts->size()) )
{
meas->parse_warnings_.push_back( "Reducing channel counts in IAEA SPC file to specified length from "
+ std::to_string(channel_counts->size()) + " read, to "
+ std::to_string(Length) );
channel_counts->resize( Length );
}else if( Length > 0 )
{
string msg = "SpecFile::load_from_iaea_spc(istream &)\n\tExpected to read "
+ std::to_string(Length) + " channel datas, but instead read "
+ std::to_string(channel_counts->size());
throw std::runtime_error( msg );
}//if( Length > 0 && size_t(Length) != channel_data->size() )
}//if( size_t(Length) != channel_data->size() )
if( channel_counts )
{
meas->gamma_counts_ = channel_counts;
meas->gamma_count_sum_ = 0.0;
for( const float a : *channel_counts )
meas->gamma_count_sum_ += a;
}//if( channel_counts )
}else //if( we know this tag ) / else / else if(...) / else if(...) ...
{
if( !linenum && line.length() )
{
for( size_t i = 0; i < line.size(); ++i )
if( (line[i] & 0x80) )
throw runtime_error( "Unknown tag and non-ascii character in first non-empty line" );
}
if( SpecUtils::istarts_with(line, "TSA,") )
throw runtime_error( "This is probably a TSA file, not a Ascii Spc" );
++nnotrecognized;
if( nnotrecognized > 15 && nnotrecognized >= linenum )
throw runtime_error( "To many unregognized begining lines" );
#if(PERFORM_DEVELOPER_CHECKS && !SpecUtils_BUILD_FUZZING_TESTS)
cerr << "Warning: SpecFile::load_from_iaea_spc(...): I didnt recognize line: '"
<< line << "'" << endl;
#endif
}//if / else to figure out what this line cooresponds to
++linenum;
}//while( input.good() )
if( meas && meas->gamma_counts_ && (meas->gamma_counts_->size()>2) && !calibcoeff_poly.empty() )
{
try
{
auto newcal = make_shared<EnergyCalibration>();
newcal->set_polynomial( meas->gamma_counts_->size(), calibcoeff_poly, {} );
meas->energy_calibration_ = newcal;
}catch( std::exception &e )
{
meas->parse_warnings_.push_back( "Energy cal provided invalid: " + string(e.what()) );
}//
}//if( we have energy calibration )
//identiFINDER 2 NGH spectrum files will have spectrum number as their UUID,
// so to create a bit more unique UUID, lets add in the serial number to the
// UUID, like in the other identiFINDER formats.
if(!uuid_.empty() && uuid_.size() < 5 && !instrument_id_.empty())
uuid_ = instrument_id_ + "/" + uuid_;
if( !meas->gamma_counts_ || meas->gamma_counts_->size() < 9 )
{
reset();
// cerr << "SpecFile::load_from_iaea_spc(...): did not read any spectrum info"
// << endl;
return false;
}//if( meas->gamma_counts_->empty() )
if( detector_type_ == DetectorType::IdentiFinderUnknown )
{
if( (icontains(det_length, "51") && icontains(det_diameter, "35"))
|| (icontains(gamma_det, "51") && icontains(gamma_det, "35")) )
{
detector_type_ = DetectorType::IdentiFinderNG;
}else if( (icontains(det_length, "38") && icontains(det_diameter, "30"))
|| (icontains(gamma_det, "38") && icontains(gamma_det, "30")) )
{
detector_type_ = DetectorType::IdentiFinder;
}else if( icontains(det_length, "30") && icontains(det_diameter, "30") )
{
// I havent seen anything that makes it here
detector_type_ = DetectorType::IdentiFinderLaBr3;
}else if( icontains(det_length, "21") && icontains(det_diameter, "23") )
{
// Tungsten shielded; havent seen anything that makes it here
detector_type_ = DetectorType::IdentiFinderTungsten;
}
}//if( an identifinder, but we dont know which type
measurements_.push_back( meas );
detectors_analysis_ = analysis;
cleanup_after_load();
}catch( std::exception & )
{
reset();
input.clear();
input.seekg( orig_pos, ios::beg );
return false;
}
return true;
}//bool load_from_iaea_spc( std::istream &input )
bool SpecFile::write_ascii_spc( std::ostream &output,
std::set<int> sample_nums,
const std::set<int> &det_nums ) const
{
std::unique_lock<std::recursive_mutex> scoped_lock( mutex_ );
//Do a sanity check on samples and detectors, event though #sum_measurements would take care of it
// (but doing it here indicates source a little better)
for( const auto sample : sample_nums )
{
if( !sample_numbers_.count(sample) )
throw runtime_error( "write_ascii_spc: invalid sample number (" + to_string(sample) + ")" );
}
if( sample_nums.empty() )
sample_nums = sample_numbers_;
vector<string> det_names;
for( const int num : det_nums )
{
auto pos = std::find( begin(detector_numbers_), end(detector_numbers_), num );
if( pos == end(detector_numbers_) )
throw runtime_error( "write_ascii_spc: invalid detector number (" + to_string(num) + ")" );
det_names.push_back( detector_names_[pos-begin(detector_numbers_)] );
}
if( det_nums.empty() )
det_names = detector_names_;
std::shared_ptr<Measurement> summed = sum_measurements( sample_nums, det_names, nullptr );
if( !summed || !summed->gamma_counts() || summed->gamma_counts()->empty() )
return false;
try
{
if(!summed->title().empty())
output << pad_iaea_prefix( "SpectrumName" ) << summed->title() << "\r\n";
else
output << pad_iaea_prefix( "SpectrumName" ) << filename_ << "\r\n";
output << pad_iaea_prefix( "XUnit" ) << "keV\r\n";
output << pad_iaea_prefix( "YUnit" ) << "\r\n";
output << pad_iaea_prefix( "Length" ) << summed->gamma_counts_->size() << "\r\n";
output << pad_iaea_prefix( "SubSpcNum" ) << "1\r\n";
output << pad_iaea_prefix( "StartSubSpc" ) << "0\r\n";
output << pad_iaea_prefix( "StopSubSpc" ) << "0\r\n";
int ncomment = 0;
bool printedFWHMCCoeff = false;
for( const string &remark : remarks_ )
{
bool used = false;
for( const char * const label : ns_iaea_comment_labels )
{
const string prefix = label + string(" : ");
if( SpecUtils::istarts_with(remark, prefix) )
{
output << pad_iaea_prefix(label) << remark.substr( prefix.size() ) << "\r\n";
printedFWHMCCoeff |= SpecUtils::iequals_ascii(label,"FWHMCCoeff");
used = true;
break;
}
}//for( const char * const label : ns_iaea_comment_labels )
if( !used )
{
++ncomment;
output << pad_iaea_prefix("Comment") << remark << "\r\n";
}
}//for( const string &remark : remarks_ )
if( !ncomment )
output << pad_iaea_prefix("Comment") << "\r\n";
char buffer[256];
if( summed->real_time_ > 0.0f )
{
snprintf( buffer, sizeof(buffer), "%.3f", summed->real_time_ );
output << pad_iaea_prefix( "Realtime" ) << buffer << "\r\n";
}
if( summed->live_time_ > 0.0f )
{
snprintf( buffer, sizeof(buffer), "%.3f", summed->live_time_ );
output << pad_iaea_prefix( "Livetime" ) << buffer << "\r\n";
}
if( (summed->real_time_ > 0.0f) && (summed->live_time_ > 0.0f) )
{
snprintf( buffer, sizeof(buffer), "%.3f", (summed->real_time_ - summed->live_time_) );
output << pad_iaea_prefix( "Deadtime" ) << buffer << "\r\n";
}
//I dont know what FastChannel is
//output << pad_iaea_prefix( "FastChannel" ) << "3229677" << "\r\n";
for( const pair<std::string,std::string> &cmpnt : component_versions_ )
{
for( const char * const label : ns_iaea_version_labels )
{
if( cmpnt.first == label )
{
output << pad_iaea_prefix(cmpnt.first) << cmpnt.second << "\r\n";
break;
}//if( cmpnt.first == label )
}
}//for( const pair<std::string,std::string> &cmpnt : component_versions_ )
if( !is_special(summed->start_time_) )
{
output << pad_iaea_prefix( "Starttime" ) << print_to_iaea_datetime(summed->start_time_) << "\r\n";
//Add stop time if we
if( (sample_nums.size()==1 && det_nums.size()==1) )
{
float intsec, fracsec;
fracsec = std::modf( summed->real_time_, &intsec );
const int intsec_i = float_to_integral<int>( intsec );
const float nmicro = floor((1.0E6f * fracsec) + 0.5f);
const auto nmicro_i = float_to_integral<chrono::microseconds::rep>( nmicro );
const time_point_t endtime = summed->start_time_
+ chrono::seconds(intsec_i) + chrono::microseconds(nmicro_i);
output << pad_iaea_prefix( "StopTime" ) << print_to_iaea_datetime( endtime ) << "\r\n";
}//
}//if( !is_special(summed->start_time_) )
if( summed->contained_neutron_ )
{
// To avoid potential UB we'll use `float_to_integral`; but since I havent implemented
// `double_to_integral` yet, we'll first convert to a float (if this causes any change of