forked from sandialabs/SpecUtils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpecFile_n42.cpp
More file actions
9698 lines (7912 loc) · 416 KB
/
SpecFile_n42.cpp
File metadata and controls
9698 lines (7912 loc) · 416 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 <memory>
#include <string>
#include <limits>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include <float.h>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <functional>
#include <type_traits>
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_print.hpp"
#include "rapidxml/rapidxml_utils.hpp"
#include "SpecUtils/SpecFile.h"
#include "SpecUtils/DateTime.h"
#include "SpecUtils/StringAlgo.h"
#include "SpecUtils/ParseUtils.h"
#include "SpecUtils/Filesystem.h"
#include "SpecUtils/SpecUtilsAsync.h"
#include "SpecUtils/RapidXmlUtils.hpp"
#include "SpecUtils/SpecFile_location.h"
#include "SpecUtils/EnergyCalibration.h"
using namespace std;
static_assert( RAPIDXML_USE_SIZED_INPUT_WCJOHNS == 1,
"The modified version of RapidXml is somehow not being used to compile SpecFile" );
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#if( defined(_MSC_VER) && _MSC_VER <= 1700 )
#define SRC_LOCATION (std::string("File " TOSTRING(__FILE__) ": Function '") \
+ std::string(__FUNCTION__) \
+ std::string( "': Line " TOSTRING(__LINE__)))
#else
#define SRC_LOCATION (std::string("File " TOSTRING(__FILE__) ": Function '") \
+ std::string(__func__) \
+ std::string( "': Line " TOSTRING(__LINE__)))
#endif
namespace
{
static const char * const s_parser_warn_prefix = "Parser Warning: ";
//Sometimes a detector wont have a name, but we still need to refer to it in
// 2012 XML files in various places, so we'll use s_unnamed_det_placeholder
// to do this. A side effect to this is we have to be careful to use it
// everywhere, and account for it when reading it back in.
const std::string s_unnamed_det_placeholder = "unamed"; //TODO: fix this spelling to "unnamed"
static const char * const s_energy_cal_not_available_remark = "Energy calibration not available.";
static const std::string s_frf_to_poly_remark = "Energy calibration was originally specified as full-range-fraction.";
//Take absolute difference between unsigned integers.
template<typename T>
T abs_diff(T a, T b) {
return a > b ? a - b : b - a;
}
bool dev_pair_less_than( const std::pair<float,float> &lhs,
const std::pair<float,float> &rhs )
{
return (lhs.first < rhs.first);
}
bool toInt( const std::string &str, int &f )
{
const int nconvert = sscanf( str.c_str(), "%i", &f );
return (nconvert == 1);
}
bool xml_value_to_flt( const rapidxml::xml_base<char> *node, float &val )
{
val = 0.0f;
if( !node )
return false;
return SpecUtils::parse_float( node->value(), node->value_size(), val );
}
std::string get_n42_xmlns( const rapidxml::xml_node<char> *node )
{
const char * const default_xmlns = "dndons:"; //or maybe "n42:"
if( !node )
return default_xmlns;
string node_name = SpecUtils::xml_name_str(node);
size_t colon_pos = node_name.find(':');
if( (colon_pos != string::npos) && (colon_pos > 0) && ((colon_pos+1) < node_name.size()) )
return node_name.substr( 0, colon_pos + 1 );
node_name = SpecUtils::xml_name_str(node->parent());
colon_pos = node_name.find(':');
if( (colon_pos != string::npos) && (colon_pos > 0) && ((colon_pos+1) < node_name.size()) )
return node_name.substr( 0, colon_pos + 1 );
if( node->first_node() )
{
node_name = SpecUtils::xml_name_str(node->first_node());
colon_pos = node_name.find(':');
if( (colon_pos != string::npos) && (colon_pos > 0) && ((colon_pos+1) < node_name.size()) )
return node_name.substr( 0, colon_pos + 1 );
node_name = SpecUtils::xml_name_str(node->first_node()->first_node());
colon_pos = node_name.find(':');
if( (colon_pos != string::npos) && (colon_pos > 0) && ((colon_pos+1) < node_name.size()) )
return node_name.substr( 0, colon_pos + 1 );
}//if( node->first_node() )
const rapidxml::xml_node<char> *docnode = node->document();
if( !docnode )
return default_xmlns;
if( docnode->name_size() == 0 )
docnode = docnode->first_node(); //N42InstrumentData
for( auto attrib = docnode->first_attribute(); attrib; attrib = attrib->next_attribute() )
{
//Some files use the "n42ns" namespace, IDK
const string name = SpecUtils::xml_name_str(attrib);
if( SpecUtils::starts_with(name, "xmlns:" )
&& (SpecUtils::icontains(name, "n42") || SpecUtils::icontains(name, "dndons")) )
return name.substr(6) + ":";
}//for( check for xmlns:n42ns="..."
return default_xmlns;
}//std::string get_n42_xmlns( const rapidxml::xml_node<char> *node )
void add_multimedia_data_to_2012_N42(
const vector<shared_ptr<const SpecUtils::MultimediaData>> &multimedia_data,
rapidxml::xml_node<char> * const RadInstrumentData )
{
using namespace rapidxml;
assert( RadInstrumentData );
if( !RadInstrumentData )
return;
xml_document<char> *doc = RadInstrumentData->document();
assert( doc );
if( !doc )
return;
for( const shared_ptr<const SpecUtils::MultimediaData> &data_ptr : multimedia_data )
{
assert( data_ptr );
if( !data_ptr )
continue;
const auto &data = *data_ptr;
xml_node<char> *MultimediaData = doc->allocate_node( node_element, "MultimediaData" );
RadInstrumentData->append_node( MultimediaData );
if( !data.remark_.empty() )
{
char *val = doc->allocate_string( data.remark_.c_str(), data.remark_.size() + 1 );
xml_node<char> *node = doc->allocate_node( node_element, "Remark", val );
MultimediaData->append_node( node );
}
if( !data.descriptions_.empty() )
{
char *val = doc->allocate_string( data.descriptions_.c_str(), data.descriptions_.size() + 1 );
xml_node<char> *node = doc->allocate_node( node_element, "MultimediaDataDescription", val );
MultimediaData->append_node( node );
}
if( !data.data_.empty() )
{
const char *node_name = nullptr;
switch( data.data_encoding_ )
{
case SpecUtils::MultimediaData::EncodingType::BinaryUTF8:
node_name = "BinaryUTF8Object";
break;
case SpecUtils::MultimediaData::EncodingType::BinaryHex:
node_name = "BinaryHexObject";
break;
case SpecUtils::MultimediaData::EncodingType::BinaryBase64:
node_name = "BinaryBase64Object";
break;
}//switch( data.data_encoding_ )
assert( node_name );
if( node_name )
{
const size_t data_size = data.data_.size();
char *val = doc->allocate_string( nullptr, data_size + 1 );
memcpy( val, data.data_.data(), data_size );
val[data_size] = '\0';
xml_node<char> *node = doc->allocate_node( node_element, node_name, val, 0, data.data_.size() );
MultimediaData->append_node( node );
}
}//if( !data.data_.empty() )
if( !SpecUtils::is_special(data.capture_start_time_) )
{
const string dt = SpecUtils::to_extended_iso_string(data.capture_start_time_) + "Z";
char *val = doc->allocate_string( dt.c_str(), dt.size()+1 );
xml_node<char> *node = doc->allocate_node( node_element, "MultimediaCaptureStartDateTime", val );
MultimediaData->append_node( node );
}//if( !is_special(data.capture_start_time_) )
//<MultimediaCaptureDuration>,
if( !data.file_uri_.empty() )
{
char *val = doc->allocate_string( data.file_uri_.c_str(), data.file_uri_.size() + 1 );
xml_node<char> *node = doc->allocate_node( node_element, "MultimediaFileURI", val );
MultimediaData->append_node( node );
}
//<MultimediaFileSizeValue>,
//<MultimediaDataMIMEKind>,
if( !data.mime_type_.empty() )
{
char *val = doc->allocate_string( data.mime_type_.c_str(), data.mime_type_.size() + 1 );
xml_node<char> *node = doc->allocate_node( node_element, "MultimediaDataMIMEKind", val );
MultimediaData->append_node( node );
}
//<MultimediaDeviceCategoryCode>,
//<MultimediaDeviceIdentifier>,
//<ImagePerspectiveCode>,
//<ImageWidthValue>,
//<ImageHeightValue>,
//<MultimediaDataExtension>
}//for( const SpecUtils::MultimediaData &data : multimedia_data )
}//add_multimedia_data_to_2012_N42(...)
bool set_multimedia_data_from_xml( SpecUtils::MultimediaData &data,
const rapidxml::xml_node<char> * const multimedia_node )
{
if( !multimedia_node )
return false;
auto node = XML_FIRST_INODE(multimedia_node,"Remark");
if( node )
data.remark_ = SpecUtils::xml_value_str( node );
node = XML_FIRST_INODE(multimedia_node,"MultimediaDataDescription");
if( node )
data.descriptions_ = SpecUtils::xml_value_str( node );
data.data_.resize( 0 );
data.data_encoding_ = SpecUtils::MultimediaData::EncodingType::BinaryHex;
const char *data_begin = nullptr, *data_end = nullptr;
if( (node = XML_FIRST_INODE(multimedia_node,"BinaryUTF8Object")) )
{
data.data_encoding_ = SpecUtils::MultimediaData::EncodingType::BinaryUTF8;
data_begin = (const char *)node->value();
data_end = data_begin + node->value_size();
}else if( (node = XML_FIRST_INODE(multimedia_node,"BinaryHexObject")) )
{
data.data_encoding_ = SpecUtils::MultimediaData::EncodingType::BinaryHex;
data_begin = (const char *)node->value();
data_end = data_begin + node->value_size();
}else if( (node = XML_FIRST_INODE(multimedia_node,"BinaryBase64Object")) )
{
data.data_encoding_ = SpecUtils::MultimediaData::EncodingType::BinaryBase64;
data_begin = (const char *)node->value();
data_end = data_begin + node->value_size();
}
if( data_begin && data_end )
data.data_.insert( end(data.data_), data_begin, data_end );
node = XML_FIRST_INODE(multimedia_node,"MultimediaCaptureStartDateTime");
const string capture_time_str = SpecUtils::xml_value_str(node);
if( !capture_time_str.empty() )
data.capture_start_time_ = SpecUtils::time_from_string( capture_time_str.c_str() );
//<MultimediaCaptureDuration>,
node = XML_FIRST_INODE(multimedia_node,"MultimediaFileURI");
if( node )
data.file_uri_ = SpecUtils::xml_value_str( node );
//<MultimediaFileSizeValue>,
//<MultimediaDataMIMEKind>,
node = XML_FIRST_INODE(multimedia_node,"MultimediaDataMIMEKind");
if( node )
data.mime_type_ = SpecUtils::xml_value_str( node );
//<MultimediaDeviceCategoryCode>,
//<MultimediaDeviceIdentifier>,
//<ImagePerspectiveCode>,
//<ImageWidthValue>,
//<ImageHeightValue>,
//<MultimediaDataExtension>
if( data.file_uri_.empty() && data.data_.empty() )
return false;
return true;
}//set_multimedia_data_from_xml(...)
}//anonymous namespace for XML utilities
//getCalibrationToSpectrumMap(...): builds map from the binning shared vector to
// the the index of a std::shared_ptr<Measurement> that has that binning
namespace
{
typedef std::map< std::shared_ptr<const SpecUtils::EnergyCalibration>, size_t > EnergyCalToIndexMap;
//add_calibration_to_2012_N42_xml(): writes calibration information to the
// xml document, with the "id" == caliId for the <EnergyCalibration> tag.
// Note, this funciton should probably be protected or private, but isnt
// currently due to an implementation detail.
// If invalid equation type, will throw exception.
void add_calibration_to_2012_N42_xml( const SpecUtils::EnergyCalibration &energy_cal,
const size_t num_gamma_channel,
rapidxml::xml_node<char> *RadInstrumentData,
std::mutex &xmldocmutex,
const int cal_number )
{
using namespace rapidxml;
const char *val = (const char *)0;
char buffer[32];
rapidxml::xml_document<char> *doc = RadInstrumentData->document();
assert( doc );
if( !doc )
throw runtime_error( "add_calibration_to_2012_N42_xml: failed to get xml document." );
const char *coefname = 0;
xml_node<char> *EnergyCalibration = 0, *node = 0;
string remark;
stringstream valuestrm;
vector<float> coefs;
switch( energy_cal.type() )
{
case SpecUtils::EnergyCalType::InvalidEquationType:
coefs = { 0.0f, 0.0f, 0.0f };
coefname = "CoefficientValues";
valuestrm << "0 0 0";
remark = s_energy_cal_not_available_remark;
break;
case SpecUtils::EnergyCalType::FullRangeFraction:
/// \TODO: add a "EnergyCalibrationExtension" element to cover Full Range Fraction calibration
remark = s_frf_to_poly_remark;
coefs = energy_cal.coefficients();
coefs = SpecUtils::fullrangefraction_coef_to_polynomial( coefs, num_gamma_channel );
//note intential fallthrough
case SpecUtils::EnergyCalType::Polynomial:
case SpecUtils::EnergyCalType::UnspecifiedUsingDefaultPolynomial:
{
assert( num_gamma_channel == energy_cal.num_channels() );
if( coefs.empty() )
coefs = energy_cal.coefficients();
coefname = "CoefficientValues";
//Technically this node must have exactly three coeficients, but here we'll
// slip in some more if we have them...
const size_t ncoef = std::max( size_t(3), coefs.size() );
for( size_t j = 0; j < ncoef; ++j )
{
snprintf( buffer, sizeof(buffer), "%s%.9g", (j?" ":""), (j<coefs.size() ? coefs[j] : 0.0f) );
valuestrm << buffer;
}
break;
}//case SpecUtils::EnergyCalType::Polynomial:
case SpecUtils::EnergyCalType::LowerChannelEdge:
{
assert( num_gamma_channel == energy_cal.num_channels() );
coefname = "EnergyBoundaryValues";
const std::vector<float> &b = energy_cal.coefficients();
//This next part should be formatted better!
for( size_t j = 0; j < b.size(); ++j )
valuestrm << (j?" ":"") << b[j];
//According to N42 2012 standard, we must give energy of upper channel
if( b.size() && b.size()<= num_gamma_channel )
valuestrm << " " << ((2.0f*b[b.size()-1])-b[b.size()-2]);
break;
}//case SpecUtils::EnergyCalType::LowerChannelEdge:
}//switch( energy_calibration_model() )
if( coefname )
{
std::lock_guard<std::mutex> lock( xmldocmutex );
EnergyCalibration = doc->allocate_node( node_element, "EnergyCalibration" );
RadInstrumentData->append_node( EnergyCalibration );
snprintf( buffer, sizeof(buffer), "EnergyCal%i", cal_number );
val = doc->allocate_string( buffer );
EnergyCalibration->append_attribute( doc->allocate_attribute( "id", val ) );
if( !remark.empty() )
{
val = doc->allocate_string( remark.c_str() );
node = doc->allocate_node( node_element, "Remark", val );
EnergyCalibration->append_node( node );
}//if( !remark.empty() )
val = doc->allocate_string( valuestrm.str().c_str() );
node = doc->allocate_node( node_element, coefname, val );
EnergyCalibration->append_node( node );
}//if( coefname )
const vector<pair<float,float>> &devpairs = energy_cal.deviation_pairs();
if( devpairs.size() )
{
stringstream EnergyValuesStrm, EnergyDeviationValuesStrm;
for( size_t j = 0; j < devpairs.size(); ++j )
{
snprintf( buffer, sizeof(buffer), "%s%.9g", (j?" ":""), devpairs[j].first );
EnergyValuesStrm << buffer;
snprintf( buffer, sizeof(buffer), "%s%.9g", (j?" ":""), devpairs[j].second );
EnergyDeviationValuesStrm << buffer;
}
std::lock_guard<std::mutex> lock( xmldocmutex );
if( !EnergyCalibration )
{
EnergyCalibration = doc->allocate_node( node_element, "EnergyCalibration" );
RadInstrumentData->append_node( EnergyCalibration );
}
val = doc->allocate_string( EnergyValuesStrm.str().c_str() );
node = doc->allocate_node( node_element, "EnergyValues", val );
EnergyCalibration->append_node( node );
val = doc->allocate_string( EnergyDeviationValuesStrm.str().c_str() );
node = doc->allocate_node( node_element, "EnergyDeviationValues", val );
EnergyCalibration->append_node( node );
}//if( devpairs.size() )
}//void add_calibration_to_2012_N42_xml(...)
void insert_N42_calibration_nodes( const std::vector< std::shared_ptr<SpecUtils::Measurement> > &measurements,
::rapidxml::xml_node<char> *RadInstrumentData,
std::mutex &xmldocmutex,
EnergyCalToIndexMap &calToSpecMap )
{
using namespace rapidxml;
calToSpecMap.clear();
for( size_t i = 0; i < measurements.size(); ++i )
{
const std::shared_ptr<SpecUtils::Measurement> &meas = measurements[i];
if( !meas || !meas->gamma_counts() || meas->gamma_counts()->empty() )
continue;
const auto energy_cal = meas->energy_calibration();
const auto iter = calToSpecMap.find( energy_cal );
if( iter == calToSpecMap.end() )
{
calToSpecMap[energy_cal] = i;
add_calibration_to_2012_N42_xml( *energy_cal, meas->gamma_counts()->size(),
RadInstrumentData, xmldocmutex, static_cast<int>(i) );
}//if( iter == calToSpecMap.end() )
}//for( size_t i = 0; i < measurements.size(); ++i )
}//void insert_N42_calibration_nodes(...)
/** Returns the N42-2012 <RadDetectorKindCode> element value - for the gamma detector
*/
std::string determine_gamma_detector_kind_code( const SpecUtils::SpecFile &sf )
{
string det_kind = "Other";
switch( sf.detector_type() )
{
case SpecUtils::DetectorType::DetectiveUnknown:
case SpecUtils::DetectorType::DetectiveEx:
case SpecUtils::DetectorType::DetectiveEx100:
case SpecUtils::DetectorType::DetectiveEx200:
case SpecUtils::DetectorType::Falcon5000:
case SpecUtils::DetectorType::MicroDetective:
case SpecUtils::DetectorType::DetectiveX:
case SpecUtils::DetectorType::Fulcrum40h:
case SpecUtils::DetectorType::Fulcrum:
det_kind = "HPGe";
break;
case SpecUtils::DetectorType::Exploranium:
case SpecUtils::DetectorType::IdentiFinder:
case SpecUtils::DetectorType::IdentiFinderNG:
case SpecUtils::DetectorType::IdentiFinderUnknown:
case SpecUtils::DetectorType::IdentiFinderTungsten:
case SpecUtils::DetectorType::IdentiFinderR500NaI:
case SpecUtils::DetectorType::RadHunterNaI:
case SpecUtils::DetectorType::Rsi701:
case SpecUtils::DetectorType::Rsi705:
case SpecUtils::DetectorType::AvidRsi:
case SpecUtils::DetectorType::OrtecRadEagleNai:
case SpecUtils::DetectorType::Sam940:
case SpecUtils::DetectorType::Sam945:
case SpecUtils::DetectorType::RIIDEyeNaI:
case SpecUtils::DetectorType::RadSeekerNaI:
case SpecUtils::DetectorType::VerifinderNaI:
case SpecUtils::DetectorType::IdentiFinderR425NaI:
case SpecUtils::DetectorType::Sam950:
det_kind = "NaI";
break;
case SpecUtils::DetectorType::IdentiFinderLaBr3:
case SpecUtils::DetectorType::IdentiFinderR425LaBr:
case SpecUtils::DetectorType::IdentiFinderR500LaBr:
case SpecUtils::DetectorType::RadHunterLaBr3:
case SpecUtils::DetectorType::Sam940LaBr3:
case SpecUtils::DetectorType::OrtecRadEagleLaBr:
case SpecUtils::DetectorType::RIIDEyeLaBr:
case SpecUtils::DetectorType::RadSeekerLaBr:
case SpecUtils::DetectorType::VerifinderLaBr:
det_kind = "LaBr3";
break;
case SpecUtils::DetectorType::OrtecRadEagleCeBr2Inch:
case SpecUtils::DetectorType::OrtecRadEagleCeBr3Inch:
det_kind = "CeBr3";
break;
case SpecUtils::DetectorType::SAIC8:
case SpecUtils::DetectorType::Srpm210:
det_kind = "PVT";
break;
case SpecUtils::DetectorType::MicroRaider:
case SpecUtils::DetectorType::Interceptor:
case SpecUtils::DetectorType::KromekGR1:
det_kind = "CZT";
break;
case SpecUtils::DetectorType::KromekD3S:
case SpecUtils::DetectorType::RadiaCodeCsI10:
case SpecUtils::DetectorType::RadiaCodeCsI14:
case SpecUtils::DetectorType::Raysid:
det_kind = "CsI";
break;
// GAGG (gadolinium aluminum gallium garnet) is not defined in my copy of N42, but neither is CLLBC
case SpecUtils::DetectorType::RadiaCodeGAGG10:
det_kind = "GAGG";
break;
case SpecUtils::DetectorType::KromekD5:
det_kind = "CLLBC";
case SpecUtils::DetectorType::Unknown:
{
const string &manufacturer = sf.manufacturer();
const string &model = sf.instrument_model();
if( manufacturer=="Raytheon" && SpecUtils::icontains(model,"Variant") )
det_kind = "NaI";
else if( manufacturer=="Mirion Technologies" && SpecUtils::icontains(model,"Pedestrian") )
det_kind = "NaI";
else if( manufacturer=="Nucsafe" && SpecUtils::icontains(model,"Predator") )
det_kind = "PVT";
break;
}
}//switch( detector_type_ )
return det_kind;
}//determine_gamma_detector_kind_code()
}//namespace
namespace
{
//anaonomous namespace for functions to help parse N42 files, that wont be
// usefull outside of this file
//is_gamma_spectrum(): Trys to determine if the spectrum_node cooresponds
// to a gamma or neutron node in the XML. If it cant tell, will return true.
bool is_gamma_spectrum( const rapidxml::xml_attribute<char> *detector_attrib,
const rapidxml::xml_attribute<char> *type_attrib,
const rapidxml::xml_node<char> *det_type_node,
const rapidxml::xml_node<char> *spectrum_node )
{
bool is_gamma = false, is_nuetron = false;
//The ICD1 Spec it shall be the case that <DetectorType>
// will say 'Neutron' for neutron detectors, so if we find this, we
// wont bother to mess with names
if( det_type_node && det_type_node->value_size() )
{
const string det_type = SpecUtils::xml_value_str(det_type_node);
if( SpecUtils::icontains(det_type,"neutron")
|| SpecUtils::icontains(det_type,"GMTube")
//|| SpecUtils::icontains(det_type,"He-3")
//|| SpecUtils::icontains(det_type,"He3")
)
return false;
if( SpecUtils::icontains(det_type,"Gamma") )
return true;
}//if( det_type_node && det_type_node->value_size() )
if( detector_attrib )
{
string name = SpecUtils::xml_value_str(detector_attrib);
SpecUtils::to_lower_ascii( name );
if( SpecUtils::contains(name, "neutron") )
is_nuetron = true;
if( SpecUtils::iends_with(name, "1N") || SpecUtils::iends_with(name, "2N")
|| SpecUtils::iends_with(name, "3N") || SpecUtils::iends_with(name, "4N") )
is_nuetron = true;
if( SpecUtils::icontains(name, "GMTube") )
is_nuetron = true;
if( SpecUtils::contains(name, "pha") )
is_gamma = true;
if( SpecUtils::contains(name, "gamma") )
is_gamma = true;
if( name == "tungsten" ) //some FLIR identiFINDER
return true;
if( !is_nuetron && !is_gamma ) //try to match the name
{
const size_t len = name.length();
bool matches_convention = (len >= 2);
if( len >= 1 )
{
const char c = name[0];
matches_convention |= (c=='a' || c=='b' || c=='c' || c=='d' );
}
if( len >= 2 )
{
const char c = name[1];
matches_convention |= (isdigit(c) || c=='a' || c=='b' || c=='c' || c=='d' );
}
if( len >= 3 )
{
const char c = name[2];
matches_convention |= (isdigit(c) || c=='n');
}
if( matches_convention )
matches_convention = !SpecUtils::icontains( name, "Unknown" );
if( matches_convention )
{
const char c = name[name.size()-1];
is_nuetron = (c == 'n');
is_gamma = (isdigit(c) != 0);
}//if( matches_convention )
}//if( !is_nuetron && !is_gamma ) //try to match the name
}//if( detector_attrib )
if( type_attrib )
{
const string name = SpecUtils::xml_value_str(type_attrib);
if( SpecUtils::icontains(name, "pha") || SpecUtils::icontains(name, "Gamma") )
is_gamma = true;
}//if( type_attrib )
if( is_nuetron == is_gamma )
{
for( const rapidxml::xml_node<char> *node = spectrum_node; node; node = node->parent() )
{
const rapidxml::xml_attribute<char> *attrib = node->first_attribute( "DetectorType", 12 );
const string textstr = SpecUtils::xml_value_str(attrib);
if( textstr.length() )
{
is_gamma = (SpecUtils::icontains( textstr, "gamma" ) || SpecUtils::icontains( textstr, "LaBr" ) || SpecUtils::icontains( textstr, "NaI" ) );
is_nuetron = SpecUtils::icontains( textstr, "neutron" );
break;
}//if( textstr.length() )
}//while( (parent = det_type_node->parent()) )
}//if( is_nuetron == is_gamma )
if( (is_nuetron == is_gamma) && !is_gamma && spectrum_node )
{
const auto node = XML_FIRST_INODE(spectrum_node,"ChannelData");
//A cheap check to make sure the <ChannelData> is more than a single neutron count
is_gamma = (node && node->value() && node->value_size() > 11); //11 is arbitrary
}//if( is_nuetron == is_gamma && !is_gamma )
#if( PERFORM_DEVELOPER_CHECKS && !SpecUtils_BUILD_FUZZING_TESTS )
if( is_nuetron == is_gamma )
{
stringstream msg;
msg << SRC_LOCATION << "\n\tFound spectrum thats ";
if( is_nuetron )
msg << "a neutron and a gamma spectrum Detector=";
else
msg << "neither neutron or gamma spectrum Detector=";
if( detector_attrib && detector_attrib->value_size() )
msg << SpecUtils::xml_value_str(detector_attrib);
else
msg << "NULL";
msg << ", Type=";
if( type_attrib && type_attrib->value_size() )
msg << SpecUtils::xml_value_str(type_attrib);
else
msg << "NULL";
log_developer_error( __func__, msg.str().c_str() );
}//if( is_nuetron && is_gamma )
#endif //#if( PERFORM_DEVELOPER_CHECKS )
if( is_nuetron && !is_gamma )
return false;
//Lets just assume its a gamma detector here....
return true;
}//bool is_gamma_spectrum()
// Tries to get the occupancy status from the <Occupied> xml element
SpecUtils::OccupancyStatus parse_occupancy_status( const rapidxml::xml_node<char> *uccupied_node )
{
if( !uccupied_node || !uccupied_node->value_size() )
return SpecUtils::OccupancyStatus::Unknown;
if( uccupied_node->value()[0] == '0' )
return SpecUtils::OccupancyStatus::NotOccupied;
if( uccupied_node->value()[0] == '1' )
return SpecUtils::OccupancyStatus::Occupied;
if( XML_VALUE_ICOMPARE(uccupied_node, "true") )
return SpecUtils::OccupancyStatus::Occupied;
if( XML_VALUE_ICOMPARE(uccupied_node, "false") )
return SpecUtils::OccupancyStatus::NotOccupied;
#if( PERFORM_DEVELOPER_CHECKS && !SpecUtils_BUILD_FUZZING_TESTS )
const string errmsg = "Found un-expected occupancy status value '"
+ SpecUtils::xml_value_str(uccupied_node) + "'";
log_developer_error( __func__, errmsg.c_str() );
#endif //#if( PERFORM_DEVELOPER_CHECKS )
return SpecUtils::OccupancyStatus::Unknown;
}//bool parse_occupancy_status( rapidxml::xml_node<char> *uccupied_node )
const rapidxml::xml_attribute<char> *find_detector_attribute( const rapidxml::xml_node<char> *spectrum )
{
rapidxml::xml_attribute<char> *attribute = spectrum->first_attribute( "Detector", 8 );
if( attribute )
return attribute;
using rapidxml::internal::compare;
for( const rapidxml::xml_node<char> *node = spectrum->parent();
(node && !XML_VALUE_ICOMPARE(node, "DetectorData"));
node = node->parent() )
{
attribute = node->first_attribute( "Detector", 8 );
if( attribute )
return attribute;
}//for( search parents incase it was out in the wrong node )
//Avid N42 files contain a "Sensor" attribute in the <Spectrum> node that
// I think should be the detector name (unconfirmed for multiple detector
// systems as of 20150528)
attribute = spectrum->first_attribute( "Sensor", 6 );
return attribute;
}//const rapidxml::xml_attribute<char> *find_detector_attribute( const rapidxml::xml_node<char> *spectrum )
//speed_from_node(): returns speed in m/s; throws exception on error
float speed_from_node( const rapidxml::xml_node<char> *speed_node )
{
if( !speed_node || !speed_node->value_size() )
throw std::runtime_error( "speed_from_node(...): NULL <Speed> node" );
float speed = 0.0f;
if( !SpecUtils::parse_float( speed_node->value(), speed_node->value_size(), speed ) )
{
stringstream msg;
msg << SRC_LOCATION << "\n\tUnable to convert '" << SpecUtils::xml_value_str(speed_node)
<< "' to a float";
#if( PERFORM_DEVELOPER_CHECKS && !SpecUtils_BUILD_FUZZING_TESTS )
log_developer_error( __func__, msg.str().c_str() );
#endif
throw runtime_error( msg.str() );
}//if( couldnt convert to float
if( speed < 0.00000001f )
return 0.0f;
const rapidxml::xml_attribute<char> *unit_attrib = XML_FIRST_ATTRIB( speed_node, "Units" );
if( !unit_attrib || !unit_attrib->value_size() )
{
#if( PERFORM_DEVELOPER_CHECKS && !SpecUtils_BUILD_FUZZING_TESTS )
const string msg = "Warning no units attribute available in <Speed> node, assuming m/s";
cerr << "\n\t" << msg << endl;
#endif
return speed;
}//if( no unit attribute" )
string units = SpecUtils::xml_value_str( unit_attrib );
SpecUtils::trim( units );
SpecUtils::to_lower_ascii( units );
if( units == "mph" )
return 0.44704f * speed;
if( units == "m/s" )
return speed;
const string msg = "Unknown speed units: '" + units + "' - please fix";
#if( PERFORM_DEVELOPER_CHECKS && !SpecUtils_BUILD_FUZZING_TESTS )
log_developer_error( __func__, msg.c_str() );
#endif
throw std::runtime_error( msg );
return speed;
}//float speed_from_node( rapidxml::xml_node<char> *speed_node )
/** Horrible hack for SpirMobile systems
At least some of the files from SpirMobile systems have multiple _nested_
<RadInstrumentData> tags, that it looks like we have to flatten out into
a single <RadInstrumentData> tag. Because the xml_node passed in is
const, we cant modify it, so instead we will create a new xml_document
and modify it.
If this hack is not needed, the pointer passed in will not be modified, and the
unique_ptr returned will be nullptr.
If this hack is needed, the pointer passed in will be modified to point to the
"RadInstrumentData" node on the new document, and the returned unique_ptr
will own the created document (you must keep in scope for duration of use).
Note that for the returned document, the xml names and values will still belong
to the original document, not the new one.
*/
unique_ptr<rapidxml::xml_document<char>> spir_mobile_2012_n42_hack( const rapidxml::xml_node<char> *&data_node )
{
size_t num_recursive_rad_item_tags = 0;
for( auto node = data_node; node; node = XML_FIRST_NODE(node,"RadInstrumentData") )
++num_recursive_rad_item_tags;
if( num_recursive_rad_item_tags <= 1 )
return nullptr;
unique_ptr<rapidxml::xml_document<char>> dummydoc( new rapidxml::xml_document<char>() );
auto dummy_data_node = dummydoc->clone_node( data_node );
dummydoc->append_node( dummy_data_node );
vector<rapidxml::xml_node<char> *> inst_nodes;
for( auto node = XML_FIRST_NODE(dummy_data_node,"RadInstrumentData");
node; node = XML_FIRST_NODE(node,"RadInstrumentData") )
inst_nodes.push_back( node );
assert( inst_nodes.size() > 0 );
for( auto subdatanode : inst_nodes )
{
vector<rapidxml::xml_node<char> *> children;
for( auto node = subdatanode->first_node(); node; node = node->next_sibling() )
children.push_back( node );
for( auto child : children )
{
subdatanode->remove_node( child );
dummy_data_node->append_node( child );
}
subdatanode->parent()->remove_node( subdatanode );
}//for( size_t i = inst_nodes.size()-1; i > 0; --i )
data_node = dummy_data_node;
//std::ofstream tmpoutfile( "/Users/wcjohns/Downloads/fixedup.xml", ios::out | ios::binary );
//rapidxml::print( static_cast<std::basic_ostream<char> &>(tmpoutfile), *dummy_data_node->document() );
return dummydoc;
}//shared_ptr<rapidxml::xml_document<char>> spir_mobile_2012_n42_hack( const rapidxml::xml_node<char> *&data_node )
//add_spectra_to_measurement_node_in_2012_N42_xml(...): Adds the given
// spectra to the specified RadMeasurementNode. All measurements should
// have the sample sample number, and the entries in calibid should
// correspond one to one to the entries in measurements.
// If something drastically goes wrong, and an exception is thrown somewhere
// this function will not throw, it will print an error to stderror and not
// insert itself into the DOM; this is so this function is safe to call in
// its own thread with no error handling. I expect this to never happen, so
// I'm not bothering with any better error handling.
void add_spectra_to_measurement_node_in_2012_N42_xml( ::rapidxml::xml_node<char> *RadMeasurement,
const std::vector< std::shared_ptr<const SpecUtils::Measurement> > measurements,
const std::vector<size_t> calibids,
std::mutex &xmldocmutex )
{
using namespace SpecUtils;
using namespace ::rapidxml;
try
{
//Some checks that should never actually trigger
if( !RadMeasurement )
throw runtime_error( "null RadMeasurement" );
if( measurements.empty() )
throw runtime_error( "with empty input" );
if( measurements.size() != calibids.size() )
throw runtime_error( "measurements.size != calibids.size" );
string radMeasID;
xml_document<char> *doc = nullptr;
{
std::lock_guard<std::mutex> lock( xmldocmutex );
doc = RadMeasurement->document();
radMeasID = xml_value_str( XML_FIRST_ATTRIB(RadMeasurement, "id") );
}
assert( doc );
if( !doc )
throw runtime_error( "failed to get xml document." );
const char *val = 0;
char buffer[256];
//not dealing with radItemInformationReferences and radMeasurementGroupReferences attributes
//Need child tags of <RadMeasurement> in following order
//MeasurementClassCode, exactly once
//StartDateTime, exactly once
//RealTimeDuration, exactly once
//Spectrum, 0 or more
//GrossCounts, 0 or more
//DoseRate, 0 or more
//TotalDose, 0 or more
//ExposureRate, 0 or more
//TotalExposure, 0 or more
//RadInstrumentState, 0 or more
//RadDetectorState, 0 or more
//RadItemState, 0 or more
//OccupancyIndicator, 0 or more
//RadMeasurementExtension, 0 or more
//Since all samples might not have occupancy/speed/gps info, lets loop