-
Notifications
You must be signed in to change notification settings - Fork 9
/
SpecFile_py.cpp
1670 lines (1423 loc) · 77.5 KB
/
SpecFile_py.cpp
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
*/
// For statically linking on Windows, we need this following define
#define BOOST_PYTHON_STATIC_LIB
// TODO: It would be nice to have the compiled results compatible with
// any python >= 3.5, which would require this next line, but this
// would require significant changes to use this limited API
// #define Py_LIMITED_API 0x03050000
#include "SpecUtils_config.h"
#include "3rdparty/date/include/date/date.h"
#include "SpecUtils/SpecFile.h"
#include "SpecUtils/EnergyCalibration.h"
#if( SpecUtils_ENABLE_D3_CHART )
#include "SpecUtils/D3SpectrumExport.h"
static_assert( SpecUtils_D3_SUPPORT_FILE_STATIC,
"For python support you should enable static D3 resources (although this isnt"
" strictly necessary... you can comment out this static_assert at your own risk)" );
#endif //SpecUtils_ENABLE_D3_CHART
#include <set>
#include <iosfwd>
#include <vector>
#include <string>
#include <locale>
#include <limits>
#include <memory>
#include <iostream>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <boost/python.hpp>
#include <boost/python/args.hpp>
#include <boost/python/list.hpp>
#include <boost/python/exception_translator.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/concepts.hpp>
#include <datetime.h> // compile with -I/path/to/python/include
using namespace std;
namespace
{
//Begin structs to help convert between c++ and python
class PythonInputDevice
{
public:
typedef char char_type;
// XXX - not working when tellg needs to be called
// struct category : boost::iostreams::source_tag, boost::iostreams::seekable_device_tag
// {};
// struct category : boost::iostreams::source_tag {};
typedef boost::iostreams::seekable_device_tag category;
explicit PythonInputDevice( boost::python::object object ) : object_(object)
{}
std::streamsize write( const char *s, std::streamsize n )
{
return 0;
}
std::streamsize read( char_type *buffer, std::streamsize buffer_size )
{
boost::python::object pyread = object_.attr( "read" );
if( pyread.is_none() )
throw std::runtime_error( "Python stream has no attibute 'read'" );
boost::python::object py_data = pyread( buffer_size );
const std::string data = boost::python::extract<std::string>( py_data );
if( data.empty() && buffer_size != 0 )
return -1;
std::copy( data.begin(), data.end(), buffer );
return data.size();
}//read()
boost::iostreams::stream_offset seek( boost::iostreams::stream_offset offset,
std::ios_base::seekdir way )
{
int pway = 0;
switch( way )
{
case std::ios_base::beg: pway = 0; break;
case std::ios_base::cur: pway = 1; break;
case std::ios_base::end: pway = 2; break;
}//switch( way )
boost::python::object pyseek = object_.attr( "seek" );
boost::python::object pytell = object_.attr( "tell" );
if( pyseek.is_none() )
throw std::runtime_error( "Python stream has no attribute 'seek'" );
if( pytell.is_none() )
throw std::runtime_error( "Python stream has no attribute 'tell'" );
const boost::python::object pynewpos = pyseek( offset, pway );
const boost::python::object pyoffset = pytell();
const boost::python::extract<std::streamoff> newpos( pyoffset );
return newpos;
}//seek()
private:
boost::python::object object_;
};//class PythonInputDevice
class PythonOutputDevice
{
//see http://stackoverflow.com/questions/26033781/converting-python-io-object-to-stdostream-when-using-boostpython
public:
typedef char char_type;
struct category : boost::iostreams::sink_tag, boost::iostreams::flushable_tag
{};
explicit PythonOutputDevice( boost::python::object object ) : object_( object )
{}
std::streamsize write( const char *buffer, std::streamsize buffer_size )
{
boost::python::object pywrite = object_.attr( "write" );
if( pywrite.is_none() )
throw std::runtime_error( "Python stream has no attribute 'write'" );
// If we are writing a large output (buffer_size >= 4096), we wont necassarily write
// all the bytes in one go. When this happens, it seems future writes fail, and we dont
// get the output we want. So instead, we will do a loop here to force writing everything...
std::streamsize nwritten = 0;
while( nwritten < buffer_size )
{
const auto buff_start = buffer + nwritten;
const auto nbytes_to_write = buffer_size - nwritten;
//Fine for Python 2 - just use a string
//boost::python::str data(buff_start, nbytes_to_write);
// Python 3
Py_buffer buffer;
int res = PyBuffer_FillInfo(&buffer, 0, (void *)buff_start, nbytes_to_write, true, PyBUF_CONTIG_RO);
if (res == -1) {
PyErr_Print();
throw std::runtime_error( "Python stream error writing to buffer" );
}
boost::python::object data( boost::python::handle<>(PyMemoryView_FromBuffer(&buffer)) );
// Python >3.2, avoids a copy of data, but requires casting away a const
//boost::python::object data(boost::python::handle<>(PyMemoryView_FromMemory((char *)buff_start, nbytes_to_write, PyBUF_READ)));
boost::python::object pynwrote = pywrite( data );
const boost::python::extract<std::streamsize> bytes_written( pynwrote );
nwritten += bytes_written.check() ? bytes_written : nbytes_to_write;
}
return nwritten;
}
bool flush()
{
boost::python::object flush = object_.attr( "flush" );
if( flush.is_none() )
throw std::runtime_error( "Python stream has no attribute 'flush'" );
flush();
return true;
}
private:
boost::python::object object_;
};//class PythonOutputDevice
//wcjohns adapted the datetime convention code 20150515 from
// http://en.sharejs.com/python/13125
//There is also a time duration conversion code as wel, but removed it.
/**
* Convert boost::posix_ptime objects (ptime and time_duration)
* to/from python datetime objects (datetime and timedelta).
*
* Credits:
* http://libtorrent.svn.sourceforge.net/viewvc/libtorrent/trunk/bindings/python/src/datetime.cpp
* http://www.nabble.com/boost::posix_time::ptime-conversion-td16857866.html
*/
/* Convert std::chrono::time_point to/from python */
struct chrono_time_point_to_python_datetime
{
static PyObject* convert(SpecUtils::time_point_t const &t)
{
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 mins = static_cast<int>( time_of_day.minutes().count() );
const int secs = static_cast<int>( time_of_day.seconds().count() );
const auto microsecs = date::round<chrono::microseconds>( time_of_day.subseconds() );
return PyDateTime_FromDateAndTime( year, month, day, hour, mins, secs, microsecs.count() );
}
};//struct chrono_time_point_to_python_datetime
struct chrono_time_point_from_python_datetime
{
chrono_time_point_from_python_datetime()
{
boost::python::converter::registry::push_back( &convertible, &construct, boost::python::type_id<SpecUtils::time_point_t>() );
}
static void* convertible(PyObject * obj_ptr)
{
if ( ! PyDateTime_Check(obj_ptr))
return 0;
return obj_ptr;
}
static void construct(
PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data * data)
{
PyDateTime_DateTime const* pydate
= reinterpret_cast<PyDateTime_DateTime*>(obj_ptr);
// Create date object
const short year = PyDateTime_GET_YEAR(pydate);
const unsigned month = PyDateTime_GET_MONTH(pydate);
const unsigned day = PyDateTime_GET_DAY(pydate);
const int hour = PyDateTime_DATE_GET_HOUR(pydate);
const int minute = PyDateTime_DATE_GET_MINUTE(pydate);
const int second = PyDateTime_DATE_GET_SECOND(pydate);
const int64_t nmicro = PyDateTime_DATE_GET_MICROSECOND(pydate);
date::year_month_day ymd{ date::year(year), date::month(month), date::day(day) };
date::sys_days days = ymd;
SpecUtils::time_point_t tp = days;
tp += chrono::seconds(second + 60*minute + 3600*hour);
tp += chrono::microseconds(nmicro);
// Create posix time object
void* storage = (
(boost::python::converter::rvalue_from_python_storage<SpecUtils::time_point_t>*)
data)->storage.bytes;
new (storage)
SpecUtils::time_point_t(tp);
data->convertible = storage;
}
};
void pyListToSampleNumsOrNames( const boost::python::list &dn_list,
std::vector<std::string> &det_names,
std::set<int> &det_nums )
{
det_names.clear();
det_nums.clear();
boost::python::ssize_t n = boost::python::len( dn_list );
for( boost::python::ssize_t i = 0; i < n; ++i )
{
boost::python::extract<int> as_int( dn_list[i] );
if( as_int.check() )
{
det_nums.insert( as_int );
}else
{
boost::python::extract<std::string> as_str( dn_list[i] );
if( !as_str.check() )
throw std::runtime_error( "'DetectorNamesOrNumbers' must be a list of either detector numbers, or detector names." );
det_names.push_back( as_str );
}
}
if( det_names.size() && det_nums.size() )
throw std::runtime_error( "'DetectorNamesOrNumbers' list can not mix detector numbers and detector names." );
}//pyListToSampleNumsOrNames
//Begin wrapper functions
void loadFile( SpecUtils::SpecFile *info,
const std::string &filename,
SpecUtils::ParserType parser_type,
std::string file_ending_hint = "" )
{
const bool success = info->load_file( filename, parser_type, file_ending_hint );
if( !success )
{
if( parser_type == SpecUtils::ParserType::Auto )
throw std::runtime_error( "Couldnt parse file " + filename );
string type;
switch( parser_type )
{
case SpecUtils::ParserType::N42_2006: type = "N42-2006"; break;
case SpecUtils::ParserType::N42_2012: type = "N42-2012"; break;
case SpecUtils::ParserType::Spc: type = "SPC"; break;
case SpecUtils::ParserType::Exploranium: type = "Exploranium"; break;
case SpecUtils::ParserType::Pcf: type = "PCF"; break;
case SpecUtils::ParserType::Chn: type = "CHN"; break;
case SpecUtils::ParserType::SpeIaea: type = "IAEA"; break;
case SpecUtils::ParserType::TxtOrCsv: type = "TXT or CSV"; break;
case SpecUtils::ParserType::Cnf: type = "CNF"; break;
case SpecUtils::ParserType::TracsMps: type = "MPS"; break;
case SpecUtils::ParserType::SPMDailyFile: type = "SpectroscopicPortalMonitor"; break;
case SpecUtils::ParserType::AmptekMca: type = "Amptek MCA"; break;
case SpecUtils::ParserType::MicroRaider: type = "Micro Raider"; break;
case SpecUtils::ParserType::RadiaCode: type = "RadiaCode"; break;
case SpecUtils::ParserType::Aram: type = "Aram"; break;
case SpecUtils::ParserType::OrtecListMode: type = "Ortec Listmode"; break;
case SpecUtils::ParserType::LsrmSpe: type = "LSRM"; break;
case SpecUtils::ParserType::Tka: type = "TKA"; break;
case SpecUtils::ParserType::MultiAct: type = "MultiAct"; break;
case SpecUtils::ParserType::Lzs: type = "LZS"; break;
case SpecUtils::ParserType::Phd: type = "PHD"; break;
case SpecUtils::ParserType::ScanDataXml: type = "ScanData"; break;
case SpecUtils::ParserType::Json: type = "JSON"; break;
case SpecUtils::ParserType::CaenHexagonGXml: type = "GXml"; break;
case SpecUtils::ParserType::Auto: type = ""; break;
}//switch( parser_type )
throw std::runtime_error( filename + " couldnt be parsed as a " + type + " file." );
}//if( !success )
}//loadFile(...)
//I couldnt quite figure out how to get Python to play nicely with const
// references to smart pointers, so instead am using some thin wrapper
// functions to return a smart pointer by value.
boost::python::list channel_energies_wrapper( const SpecUtils::Measurement *meas )
{
boost::python::list l;
if( !meas->channel_energies() )
return l;
for( auto p : *meas->channel_energies() )
l.append( p );
return l;
}
boost::python::list gamma_counts_wrapper( const SpecUtils::Measurement *meas )
{
boost::python::list l;
if( !meas->gamma_counts() )
return l;
for( auto p : *meas->gamma_counts() )
l.append( p );
return l;
}
std::shared_ptr<SpecUtils::Measurement> makeCopy_wrapper( const SpecUtils::Measurement *meas )
{
auto m = std::make_shared<SpecUtils::Measurement>();
*m = *meas;
return m;
}
std::shared_ptr<SpecUtils::Measurement> makeMeasurement_wrapper()
{
return std::make_shared<SpecUtils::Measurement>();
}
void setGammaCounts_wrapper( SpecUtils::Measurement *meas,
boost::python::list py_counts,
const float live_time,
const float real_time )
{
auto counts = std::make_shared<vector<float>>();
boost::python::ssize_t n = boost::python::len( py_counts );
for( boost::python::ssize_t i = 0; i < n; ++i )
counts->push_back( boost::python::extract<float>( py_counts[i] ) );
meas->set_gamma_counts( counts, live_time, real_time );
}
void setNeutronCounts_wrapper( SpecUtils::Measurement *meas,
boost::python::list py_counts,
const float live_time )
{
vector<float> counts;
boost::python::ssize_t n = boost::python::len( py_counts );
for( boost::python::ssize_t i = 0; i < n; ++i )
counts.push_back( boost::python::extract<float>( py_counts[i] ) );
meas->set_neutron_counts( counts, live_time );
}
SpecUtils::time_point_t start_time_wrapper( const SpecUtils::Measurement *meas )
{
return meas->start_time();
}
boost::python::list get_measurements_wrapper( const SpecUtils::SpecFile *info )
{
//This function overcomes an issue where returning a vector of
// std::shared_ptr<const measurement> objects to python, and then in python
// derefrencing an element and using it causes an issue in python to say
// that std::shared_ptr<const measurement> is an unknown class.
boost::python::list l;
for( auto p : info->measurements() )
l.append( p );
return l;
}
boost::python::list measurement_remarks_wrapper( const SpecUtils::Measurement *info )
{
boost::python::list l;
for( const string &p : info->remarks() )
l.append( p );
return l;
}
boost::python::list SpecFile_remarks_wrapper( const SpecUtils::SpecFile *info )
{
boost::python::list l;
for( const string &p : info->remarks() )
l.append( p );
return l;
}
boost::python::list SpecFile_parseWarnings_wrapper( const SpecUtils::SpecFile *info )
{
boost::python::list l;
for( const string &p : info->parse_warnings() )
l.append( p );
return l;
}
boost::python::list gamma_channel_counts_wrapper( const SpecUtils::SpecFile *info )
{
boost::python::list l;
for( size_t p : info->gamma_channel_counts() )
l.append( p );
return l;
}
boost::python::list sample_numbers_wrapper( const SpecUtils::SpecFile *info )
{
boost::python::list l;
for( size_t p : info->sample_numbers() )
l.append( p );
return l;
}
boost::python::list detector_numbers_wrapper( const SpecUtils::SpecFile *info )
{
boost::python::list l;
for( size_t p : info->detector_numbers() )
l.append( p );
return l;
}
boost::python::list neutron_detector_names_wrapper( const SpecUtils::SpecFile *info )
{
boost::python::list l;
for( const string &p : info->neutron_detector_names() )
l.append( p );
return l;
}
boost::python::list gamma_detector_names_wrapper( const SpecUtils::SpecFile *info )
{
boost::python::list l;
for( const string &p : info->gamma_detector_names() )
l.append( p );
return l;
}
boost::python::list detector_names_wrapper( const SpecUtils::SpecFile *info )
{
boost::python::list l;
for( const string &p : info->detector_names() )
l.append( p );
return l;
}
std::shared_ptr<SpecUtils::Measurement> sum_measurements_wrapper( const SpecUtils::SpecFile *info,
boost::python::list py_samplenums,
boost::python::list py_detnames )
{
set<int> samplenums;
set<string> detnames;
boost::python::ssize_t n = boost::python::len( py_samplenums );
for( boost::python::ssize_t i = 0; i < n; ++i )
samplenums.insert( boost::python::extract<int>( py_samplenums[i] ) );
n = boost::python::len( py_detnames );
for( boost::python::ssize_t i = 0; i < n; ++i )
detnames.insert( boost::python::extract<std::string>( py_detnames[i] ) );
const vector<string> detname_vec( begin(detnames), end(detnames) );
return info->sum_measurements( samplenums, detname_vec, nullptr );
}//sum_measurements_wrapper(...)
void writePcf_wrapper( const SpecUtils::SpecFile *info, boost::python::object pystream )
{
boost::iostreams::stream<PythonOutputDevice> output( pystream );
if( !info->write_pcf( output ) )
throw std::runtime_error( "Failed to write PCF file." );
}
void write2006N42_wrapper( const SpecUtils::SpecFile *info, boost::python::object pystream )
{
boost::iostreams::stream<PythonOutputDevice> output( pystream );
if( !info->write_2006_N42( output ) )
throw std::runtime_error( "Failed to write 2006 N42 file." );
}
void write2012N42Xml_wrapper( const SpecUtils::SpecFile *info, boost::python::object pystream )
{
boost::iostreams::stream<PythonOutputDevice> output( pystream );
if( !info->write_2012_N42( output ) )
throw std::runtime_error( "Failed to write 2012 N42 file." );
}
void writeCsv_wrapper( const SpecUtils::SpecFile *info, boost::python::object pystream )
{
boost::iostreams::stream<PythonOutputDevice> output( pystream );
if( !info->write_csv( output ) )
throw std::runtime_error( "Failed to write CSV file." );
}
void writeTxt_wrapper( const SpecUtils::SpecFile *info, boost::python::object pystream )
{
boost::iostreams::stream<PythonOutputDevice> output( pystream );
if( !info->write_txt( output ) )
throw std::runtime_error( "Failed to TXT file." );
}
void writeIntegerChn_wrapper( const SpecUtils::SpecFile *info,
boost::python::object pystream,
boost::python::object py_sample_nums,
boost::python::object py_det_names )
{
std::vector<std::string> det_names;
std::set<int> sample_nums;
boost::python::list sn_list = boost::python::extract<boost::python::list>(py_sample_nums);
boost::python::list dn_list = boost::python::extract<boost::python::list>(py_det_names);
boost::python::ssize_t n = boost::python::len( sn_list );
for( boost::python::ssize_t i = 0; i < n; ++i )
sample_nums.insert( boost::python::extract<int>( sn_list[i] ) );
n = boost::python::len( dn_list );
for( boost::python::ssize_t i = 0; i < n; ++i )
det_names.push_back( boost::python::extract<std::string>( dn_list[i] ) );
boost::iostreams::stream<PythonOutputDevice> output( pystream );
if( !info->write_integer_chn( output, sample_nums, det_names ) )
throw std::runtime_error( "Failed to write Integer CHN file." );
}
void setInfoFromN42File_wrapper( SpecUtils::SpecFile *info,
boost::python::object pystream )
{
boost::iostreams::stream<PythonInputDevice> input( pystream );
if( !info->load_from_N42( input ) )
throw std::runtime_error( "Failed to decode input as a valid N42 file." );
}//setInfoFromN42File_wrapper(...)
void setInfoFromPcfFile_wrapper( SpecUtils::SpecFile *info,
boost::python::object pystream )
{
boost::iostreams::stream<PythonInputDevice> input( pystream );
if( !info->load_from_pcf( input ) )
throw std::runtime_error( "Failed to decode input as a valid PCF file." );
}//setInfoFromPcfFile_wrapper(...)
void writeAllToFile_wrapper( const SpecUtils::SpecFile *info,
const std::string &filename,
const SpecUtils::SaveSpectrumAsType type )
{
info->write_to_file( filename, type );
}//setInfoFromPcfFile_wrapper(...)
void writeToFile_wrapper( const SpecUtils::SpecFile *info,
const std::string &filename,
boost::python::object py_sample_nums,
boost::python::object py_det_nums,
const SpecUtils::SaveSpectrumAsType type )
{
std::vector<std::string> det_names;
std::set<int> sample_nums, det_nums;
boost::python::list sn_list = boost::python::extract<boost::python::list>(py_sample_nums);
boost::python::list dn_list = boost::python::extract<boost::python::list>(py_det_nums);
boost::python::ssize_t n = boost::python::len( sn_list );
for( boost::python::ssize_t i = 0; i < n; ++i )
sample_nums.insert( boost::python::extract<int>( sn_list[i] ) );
pyListToSampleNumsOrNames( dn_list, det_names, det_nums );
if( det_names.size() )
info->write_to_file( filename, sample_nums, det_names, type );
else
info->write_to_file( filename, sample_nums, det_nums, type );
}//writeToFile_wrapper(...)
void writeToStream_wrapper( const SpecUtils::SpecFile *info,
boost::python::object pystream,
boost::python::object py_sample_nums,
boost::python::object py_det_nums,
const SpecUtils::SaveSpectrumAsType type )
{
std::vector<std::string> det_names;
std::set<int> sample_nums, det_nums;
boost::python::list sn_list = boost::python::extract<boost::python::list>(py_sample_nums);
boost::python::list dn_list = boost::python::extract<boost::python::list>(py_det_nums);
boost::python::ssize_t n = boost::python::len( sn_list );
for( boost::python::ssize_t i = 0; i < n; ++i )
sample_nums.insert( boost::python::extract<int>( sn_list[i] ) );
pyListToSampleNumsOrNames( dn_list, det_names, det_nums );
boost::iostreams::stream<PythonOutputDevice> output( pystream );
if( det_names.size() )
info->write( output, sample_nums, det_names, type );
else
info->write( output, sample_nums, det_nums, type );
}
void removeMeasurement_wrapper( SpecUtils::SpecFile *info,
boost::python::object py_meas )
{
std::shared_ptr<const SpecUtils::Measurement> m = boost::python::extract<std::shared_ptr<const SpecUtils::Measurement>>(py_meas);
info->remove_measurement( m, true );
}
void addMeasurement_wrapper( SpecUtils::SpecFile *info,
boost::python::object py_meas )
{
std::shared_ptr<SpecUtils::Measurement> m = boost::python::extract<std::shared_ptr<SpecUtils::Measurement>>(py_meas);
info->add_measurement( m, true );
}
std::vector<std::string> to_cpp_remarks( boost::python::object py_remarks )
{
std::vector<std::string> remarks;
boost::python::extract<std::string> remark_as_str(py_remarks);
if( remark_as_str.check() )
{
remarks.push_back( remark_as_str );
}else
{
boost::python::list remarks_list = boost::python::extract<boost::python::list>(py_remarks);
boost::python::ssize_t n = boost::python::len( remarks_list );
for( boost::python::ssize_t i = 0; i < n; ++i )
remarks.push_back( boost::python::extract<std::string>( remarks_list[i] ) );
}
return remarks;
}
void setMeasurementRemarks_wrapper( SpecUtils::SpecFile *info,
boost::python::object py_remarks,
boost::python::object py_meas )
{
std::shared_ptr<const SpecUtils::Measurement> m = boost::python::extract<std::shared_ptr<const SpecUtils::Measurement>>(py_meas);
std::vector<std::string> remarks = to_cpp_remarks( py_remarks );
info->set_remarks( remarks, m );
}
void setMeasRemarks_wrapper( SpecUtils::Measurement *meas,
boost::python::object py_remarks )
{
std::vector<std::string> remarks = to_cpp_remarks( py_remarks );
meas->set_remarks( remarks );
}
void setRemarks_wrapper( SpecUtils::SpecFile *info,
boost::python::object py_remarks )
{
std::vector<std::string> remarks;
boost::python::extract<std::string> remark_as_str(py_remarks);
if( remark_as_str.check() )
{
remarks.push_back( remark_as_str );
}else
{
boost::python::list remarks_list = boost::python::extract<boost::python::list>(py_remarks);
boost::python::ssize_t n = boost::python::len( remarks_list );
for( boost::python::ssize_t i = 0; i < n; ++i )
remarks.push_back( boost::python::extract<std::string>( remarks_list[i] ) );
}
info->set_remarks( remarks );
}
void setParseWarnings_wrapper( SpecUtils::SpecFile *info,
boost::python::object py_warnings )
{
std::vector<std::string> remarks;
boost::python::extract<std::string> warning_as_str(py_warnings);
if( warning_as_str.check() )
{
remarks.push_back( warning_as_str );
}else
{
boost::python::list remarks_list = boost::python::extract<boost::python::list>(py_warnings);
boost::python::ssize_t n = boost::python::len( remarks_list );
for( boost::python::ssize_t i = 0; i < n; ++i )
remarks.push_back( boost::python::extract<std::string>( remarks_list[i] ) );
}
info->set_parse_warnings( remarks );
}
std::shared_ptr<SpecUtils::EnergyCalibration> energyCalFromPolynomial_wrapper( const size_t num_channels,
boost::python::list py_coefs )
{
vector<float> coefs;
boost::python::ssize_t n = boost::python::len( py_coefs );
for( boost::python::ssize_t i = 0; i < n; ++i )
coefs.push_back( boost::python::extract<float>( py_coefs[i] ) );
auto cal = std::make_shared<SpecUtils::EnergyCalibration>();
cal->set_polynomial( num_channels, coefs, {} );
return cal;
}
std::shared_ptr<SpecUtils::EnergyCalibration> energyCalFromPolynomial_2_wrapper( const size_t num_channels,
boost::python::list py_coefs,
boost::python::list py_dev_pairs )
{
vector<float> coefs;
boost::python::ssize_t n = boost::python::len( py_coefs );
for( boost::python::ssize_t i = 0; i < n; ++i )
coefs.push_back( boost::python::extract<float>( py_coefs[i] ) );
std::vector<std::pair<float,float>> dev_pairs;
n = boost::python::len( py_dev_pairs );
for( boost::python::ssize_t i = 0; i < n; ++i )
{
auto devpair = boost::python::extract<boost::python::tuple>( py_dev_pairs[i] )();
dev_pairs.push_back( {boost::python::extract<float>(devpair[0]), boost::python::extract<float>(devpair[1]) } );
}
auto cal = std::make_shared<SpecUtils::EnergyCalibration>();
cal->set_polynomial( num_channels, coefs, dev_pairs );
return cal;
}
std::shared_ptr<SpecUtils::EnergyCalibration> energyCalFromFullRangeFraction_wrapper( const size_t num_channels,
boost::python::list py_coefs )
{
vector<float> coefs;
boost::python::ssize_t n = boost::python::len( py_coefs );
for( boost::python::ssize_t i = 0; i < n; ++i )
coefs.push_back( boost::python::extract<float>( py_coefs[i] ) );
auto cal = std::make_shared<SpecUtils::EnergyCalibration>();
cal->set_full_range_fraction( num_channels, coefs, {} );
return cal;
}
std::shared_ptr<SpecUtils::EnergyCalibration> energyCalFromFullRangeFraction_2_wrapper( const size_t num_channels,
boost::python::list py_coefs,
boost::python::list py_dev_pairs )
{
vector<float> coefs;
boost::python::ssize_t n = boost::python::len( py_coefs );
for( boost::python::ssize_t i = 0; i < n; ++i )
coefs.push_back( boost::python::extract<float>( py_coefs[i] ) );
std::vector<std::pair<float,float>> dev_pairs;
n = boost::python::len( py_dev_pairs );
for( boost::python::ssize_t i = 0; i < n; ++i )
{
auto devpair = boost::python::extract<boost::python::tuple>( py_dev_pairs[i] )();
dev_pairs.push_back( {boost::python::extract<float>(devpair[0]), boost::python::extract<float>(devpair[1]) } );
}
auto cal = std::make_shared<SpecUtils::EnergyCalibration>();
cal->set_full_range_fraction( num_channels, coefs, dev_pairs );
return cal;
}
std::shared_ptr<SpecUtils::EnergyCalibration> energyCalFromLowerChannelEnergies_wrapper( const size_t num_channels,
const std::vector<float> energies )
{
auto cal = std::make_shared<SpecUtils::EnergyCalibration>();
cal->set_lower_channel_energy( num_channels, energies );
return cal;
}
#if( SpecUtils_ENABLE_D3_CHART )
bool write_spectrum_data_js_wrapper( boost::python::object pystream,
const SpecUtils::Measurement *meas,
const D3SpectrumExport::D3SpectrumOptions *options,
const size_t specID, const int backgroundID )
{
boost::iostreams::stream<PythonOutputDevice> output( pystream );
return D3SpectrumExport::write_spectrum_data_js( output, *meas, *options, specID, backgroundID );
}
bool write_d3_html_wrapper( boost::python::object pystream,
boost::python::list meas_list,
D3SpectrumExport::D3SpectrumChartOptions options )
{
boost::iostreams::stream<PythonOutputDevice> output( pystream );
// From python the list would be like: [(meas_0,options_0),(meas_1,options_1),(meas_2,options_2)]
vector<pair<const SpecUtils::Measurement *,D3SpectrumExport::D3SpectrumOptions>> meass;
boost::python::ssize_t n = boost::python::len(meas_list);
for( boost::python::ssize_t i = 0; i < n; ++i )
{
boost::python::tuple elem = boost::python::extract<boost::python::tuple>( meas_list[i] )();
const SpecUtils::Measurement * meas = boost::python::extract<const SpecUtils::Measurement *>( elem[0] )();
D3SpectrumExport::D3SpectrumOptions opts = boost::python::extract<D3SpectrumExport::D3SpectrumOptions>( elem[1] )();
meass.push_back( std::make_pair(meas,opts) );
}
return D3SpectrumExport::write_d3_html( output, meass, options );
}
bool write_and_set_data_for_chart_wrapper( boost::python::object pystream,
const std::string &div_name,
boost::python::list meas_list )
{
boost::iostreams::stream<PythonOutputDevice> output( pystream );
vector<pair<const SpecUtils::Measurement *,D3SpectrumExport::D3SpectrumOptions>> meass;
boost::python::ssize_t n = boost::python::len(meas_list);
for( boost::python::ssize_t i = 0; i < n; ++i )
{
boost::python::tuple elem = boost::python::extract<boost::python::tuple>( meas_list[i] )();
const SpecUtils::Measurement * meas = boost::python::extract<const SpecUtils::Measurement *>( elem[0] )();
D3SpectrumExport::D3SpectrumOptions opts = boost::python::extract<D3SpectrumExport::D3SpectrumOptions>( elem[1] )();
meass.push_back( std::make_pair(meas,opts) );
}
return write_and_set_data_for_chart( output, div_name, meass );
}
bool write_html_page_header_wrapper( boost::python::object pystream, const std::string &page_title )
{
boost::iostreams::stream<PythonOutputDevice> output( pystream );
return D3SpectrumExport::write_html_page_header( output, page_title );
}
bool write_js_for_chart_wrapper( boost::python::object pystream, const std::string &div_name,
const std::string &chart_title,
const std::string &x_axis_title,
const std::string &y_axis_title )
{
boost::iostreams::stream<PythonOutputDevice> output( pystream );
return D3SpectrumExport::write_js_for_chart( output, div_name, chart_title,
x_axis_title, y_axis_title );
}
bool write_set_options_for_chart_wrapper( boost::python::object pystream,
const std::string &div_name,
const D3SpectrumExport::D3SpectrumChartOptions &options )
{
boost::iostreams::stream<PythonOutputDevice> output( pystream );
return write_set_options_for_chart( output, div_name, options );
}
bool write_html_display_options_for_chart_wrapper( boost::python::object pystream,
const std::string &div_name,
const D3SpectrumExport::D3SpectrumChartOptions &options )
{
boost::iostreams::stream<PythonOutputDevice> output( pystream );
return write_html_display_options_for_chart( output, div_name, options );
}
#endif
}//namespace
//Begin definition of python functions
//make is so loadFile will take at least 3 arguments, but can take 4 (e.g. allow
// default last argument)
BOOST_PYTHON_FUNCTION_OVERLOADS(loadFile_overloads, loadFile, 3, 4)
BOOST_PYTHON_MODULE(SpecUtils)
{
using namespace boost::python;
//enable python signature and user document string, but disable c++ signature
// for all docstrings created in the scope of local_docstring_options.
docstring_options local_docstring_options( true, true, false );
//Register our enums
enum_<SpecUtils::ParserType>( "ParserType" )
.value( "N42_2006", SpecUtils::ParserType::N42_2006 )
.value( "N42_2012", SpecUtils::ParserType::N42_2012 )
.value( "Spc", SpecUtils::ParserType::Spc )
.value( "Exploranium", SpecUtils::ParserType::Exploranium )
.value( "Pcf", SpecUtils::ParserType::Pcf )
.value( "Chn", SpecUtils::ParserType::Chn )
.value( "SpeIaea", SpecUtils::ParserType::SpeIaea )
.value( "TxtOrCsv", SpecUtils::ParserType::TxtOrCsv )
.value( "Cnf", SpecUtils::ParserType::Cnf )
.value( "TracsMps", SpecUtils::ParserType::TracsMps )
.value( "SPMDailyFile", SpecUtils::ParserType::SPMDailyFile )
.value( "AmptekMca", SpecUtils::ParserType::AmptekMca )
.value( "MicroRaider", SpecUtils::ParserType::MicroRaider )
.value( "RadiaCode", SpecUtils::ParserType::RadiaCode )
.value( "OrtecListMode", SpecUtils::ParserType::OrtecListMode )
.value( "LsrmSpe", SpecUtils::ParserType::LsrmSpe )
.value( "Tka", SpecUtils::ParserType::Tka )
.value( "MultiAct", SpecUtils::ParserType::MultiAct )
.value( "Phd", SpecUtils::ParserType::Phd )
.value( "Lzs", SpecUtils::ParserType::Lzs )
.value( "Aram", SpecUtils::ParserType::Aram )
.value( "ScanDataXml", SpecUtils::ParserType::ScanDataXml )
.value( "Json", SpecUtils::ParserType::Json )
.value( "CaenHexagonGXml", SpecUtils::ParserType::CaenHexagonGXml )
.value( "Auto", SpecUtils::ParserType::Auto );