-
Notifications
You must be signed in to change notification settings - Fork 122
/
LoadEventNexus.cpp
1366 lines (1235 loc) · 51.4 KB
/
LoadEventNexus.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
#include "MantidDataHandling/LoadEventNexus.h"
#include "MantidDataHandling/LoadEventNexusIndexSetup.h"
#include "MantidDataHandling/EventWorkspaceCollection.h"
#include "MantidDataHandling/DefaultEventLoader.h"
#include "MantidDataHandling/ParallelEventLoader.h"
#include "MantidAPI/Axis.h"
#include "MantidAPI/FileProperty.h"
#include "MantidAPI/RegisterFileLoader.h"
#include "MantidAPI/Run.h"
#include "MantidAPI/Sample.h"
#include "MantidGeometry/Instrument.h"
#include "MantidGeometry/Instrument/Goniometer.h"
#include "MantidGeometry/Instrument/RectangularDetector.h"
#include "MantidKernel/ArrayProperty.h"
#include "MantidKernel/BoundedValidator.h"
#include "MantidKernel/DateAndTimeHelpers.h"
#include "MantidKernel/ListValidator.h"
#include "MantidKernel/MultiThreaded.h"
#include "MantidKernel/TimeSeriesProperty.h"
#include "MantidKernel/Timer.h"
#include "MantidKernel/UnitFactory.h"
#include "MantidKernel/VisibleWhenProperty.h"
#include "MantidIndexing/IndexInfo.h"
#include <boost/function.hpp>
#include <boost/shared_array.hpp>
#include <boost/shared_ptr.hpp>
using Mantid::Types::Core::DateAndTime;
using Mantid::Types::Event::TofEvent;
using std::map;
using std::string;
using std::vector;
using namespace ::NeXus;
namespace Mantid {
namespace DataHandling {
DECLARE_NEXUS_FILELOADER_ALGORITHM(LoadEventNexus)
using namespace Kernel;
using namespace DateAndTimeHelpers;
using namespace Geometry;
using namespace API;
using namespace DataObjects;
using Types::Core::DateAndTime;
using Types::Event::TofEvent;
//----------------------------------------------------------------------------------------------
/** Empty default constructor
*/
LoadEventNexus::LoadEventNexus()
: filter_tof_min(0), filter_tof_max(0), m_specMin(0), m_specMax(0),
longest_tof(0), shortest_tof(0), bad_tofs(0), discarded_events(0),
compressTolerance(0), m_instrument_loaded_correctly(false),
loadlogs(false), m_logs_loaded_correctly(false), event_id_is_spec(false) {
}
//----------------------------------------------------------------------------------------------
/**
* Return the confidence with with this algorithm can load the file
* @param descriptor A descriptor for the file
* @returns An integer specifying the confidence level. 0 indicates it will not
* be used
*/
int LoadEventNexus::confidence(Kernel::NexusDescriptor &descriptor) const {
int confidence(0);
if (descriptor.classTypeExists("NXevent_data")) {
if (descriptor.pathOfTypeExists("/entry", "NXentry") ||
descriptor.pathOfTypeExists("/raw_data_1", "NXentry")) {
confidence = 80;
}
}
return confidence;
}
//----------------------------------------------------------------------------------------------
/** Initialisation method.
*/
void LoadEventNexus::init() {
const std::vector<std::string> exts{"_event.nxs", ".nxs.h5", ".nxs"};
this->declareProperty(
Kernel::make_unique<FileProperty>("Filename", "", FileProperty::Load,
exts),
"The name of the Event NeXus file to read, including its full or "
"relative path. "
"The file name is typically of the form INST_####_event.nxs (N.B. case "
"sensitive if running on Linux).");
this->declareProperty(
make_unique<WorkspaceProperty<Workspace>>("OutputWorkspace", "",
Direction::Output),
"The name of the output EventWorkspace or WorkspaceGroup in which to "
"load the EventNexus file.");
declareProperty(
make_unique<PropertyWithValue<string>>("NXentryName", "",
Direction::Input),
"Optional: Name of the NXentry to load if it's not the default.");
declareProperty(make_unique<PropertyWithValue<double>>(
"FilterByTofMin", EMPTY_DBL(), Direction::Input),
"Optional: To exclude events that do not fall within a range "
"of times-of-flight. "
"This is the minimum accepted value in microseconds. Keep "
"blank to load all events.");
declareProperty(make_unique<PropertyWithValue<double>>(
"FilterByTofMax", EMPTY_DBL(), Direction::Input),
"Optional: To exclude events that do not fall within a range "
"of times-of-flight. "
"This is the maximum accepted value in microseconds. Keep "
"blank to load all events.");
declareProperty(make_unique<PropertyWithValue<double>>(
"FilterByTimeStart", EMPTY_DBL(), Direction::Input),
"Optional: To only include events after the provided start "
"time, in seconds (relative to the start of the run).");
declareProperty(make_unique<PropertyWithValue<double>>(
"FilterByTimeStop", EMPTY_DBL(), Direction::Input),
"Optional: To only include events before the provided stop "
"time, in seconds (relative to the start of the run).");
std::string grp1 = "Filter Events";
setPropertyGroup("FilterByTofMin", grp1);
setPropertyGroup("FilterByTofMax", grp1);
setPropertyGroup("FilterByTimeStart", grp1);
setPropertyGroup("FilterByTimeStop", grp1);
declareProperty(
make_unique<ArrayProperty<string>>("BankName", Direction::Input),
"Optional: To only include events from one bank. Any bank "
"whose name does not match the given string will have no "
"events.");
declareProperty(make_unique<PropertyWithValue<bool>>("SingleBankPixelsOnly",
true, Direction::Input),
"Optional: Only applies if you specified a single bank to "
"load with BankName. "
"Only pixels in the specified bank will be created if true; "
"all of the instrument's pixels will be created otherwise.");
setPropertySettings("SingleBankPixelsOnly", make_unique<VisibleWhenProperty>(
"BankName", IS_NOT_DEFAULT));
std::string grp2 = "Loading a Single Bank";
setPropertyGroup("BankName", grp2);
setPropertyGroup("SingleBankPixelsOnly", grp2);
declareProperty(
make_unique<PropertyWithValue<bool>>("Precount", true, Direction::Input),
"Pre-count the number of events in each pixel before allocating memory "
"(optional, default True). "
"This can significantly reduce memory use and memory fragmentation; it "
"may also speed up loading.");
declareProperty(make_unique<PropertyWithValue<double>>(
"CompressTolerance", -1.0, Direction::Input),
"Run CompressEvents while loading (optional, leave blank or "
"negative to not do). "
"This specified the tolerance to use (in microseconds) when "
"compressing.");
auto mustBePositive = boost::make_shared<BoundedValidator<int>>();
mustBePositive->setLower(1);
declareProperty("ChunkNumber", EMPTY_INT(), mustBePositive,
"If loading the file by sections ('chunks'), this is the "
"section number of this execution of the algorithm.");
declareProperty("TotalChunks", EMPTY_INT(), mustBePositive,
"If loading the file by sections ('chunks'), this is the "
"total number of sections.");
// TotalChunks is only meaningful if ChunkNumber is set
// Would be nice to be able to restrict ChunkNumber to be <= TotalChunks at
// validation
setPropertySettings("TotalChunks", make_unique<VisibleWhenProperty>(
"ChunkNumber", IS_NOT_DEFAULT));
std::string grp3 = "Reduce Memory Use";
setPropertyGroup("Precount", grp3);
setPropertyGroup("CompressTolerance", grp3);
setPropertyGroup("ChunkNumber", grp3);
setPropertyGroup("TotalChunks", grp3);
declareProperty(make_unique<PropertyWithValue<bool>>("LoadMonitors", false,
Direction::Input),
"Load the monitors from the file (optional, default False).");
std::vector<std::string> options{"", "Events", "Histogram"};
declareProperty("MonitorsLoadOnly", "",
boost::make_shared<Kernel::StringListValidator>(options),
"If multiple repesentations exist, which one to load. "
"Default is to load the one that is present.");
declareProperty(make_unique<PropertyWithValue<double>>(
"FilterMonByTofMin", EMPTY_DBL(), Direction::Input),
"Optional: To exclude events from monitors that do not fall "
"within a range of times-of-flight. "
"This is the minimum accepted value in microseconds.");
declareProperty(make_unique<PropertyWithValue<double>>(
"FilterMonByTofMax", EMPTY_DBL(), Direction::Input),
"Optional: To exclude events from monitors that do not fall "
"within a range of times-of-flight. "
"This is the maximum accepted value in microseconds.");
declareProperty(make_unique<PropertyWithValue<double>>(
"FilterMonByTimeStart", EMPTY_DBL(), Direction::Input),
"Optional: To only include events from monitors after the "
"provided start time, in seconds (relative to the start of "
"the run).");
declareProperty(make_unique<PropertyWithValue<double>>(
"FilterMonByTimeStop", EMPTY_DBL(), Direction::Input),
"Optional: To only include events from monitors before the "
"provided stop time, in seconds (relative to the start of "
"the run).");
setPropertySettings(
"MonitorsLoadOnly",
make_unique<VisibleWhenProperty>("LoadMonitors", IS_EQUAL_TO, "1"));
auto asEventsIsOn = [] {
std::unique_ptr<IPropertySettings> prop =
make_unique<VisibleWhenProperty>("LoadMonitors", IS_EQUAL_TO, "1");
return prop;
};
setPropertySettings("FilterMonByTofMin", asEventsIsOn());
setPropertySettings("FilterMonByTofMax", asEventsIsOn());
setPropertySettings("FilterMonByTimeStart", asEventsIsOn());
setPropertySettings("FilterMonByTimeStop", asEventsIsOn());
std::string grp4 = "Monitors";
setPropertyGroup("LoadMonitors", grp4);
setPropertyGroup("MonitorsLoadOnly", grp4);
setPropertyGroup("FilterMonByTofMin", grp4);
setPropertyGroup("FilterMonByTofMax", grp4);
setPropertyGroup("FilterMonByTimeStart", grp4);
setPropertyGroup("FilterMonByTimeStop", grp4);
declareProperty("SpectrumMin", EMPTY_INT(), mustBePositive,
"The number of the first spectrum to read.");
declareProperty("SpectrumMax", EMPTY_INT(), mustBePositive,
"The number of the last spectrum to read.");
declareProperty(make_unique<ArrayProperty<int32_t>>("SpectrumList"),
"A comma-separated list of individual spectra to read.");
declareProperty(
make_unique<PropertyWithValue<bool>>("MetaDataOnly", false,
Direction::Input),
"If true, only the meta data and sample logs will be loaded.");
declareProperty(
make_unique<PropertyWithValue<bool>>("LoadLogs", true, Direction::Input),
"Load the Sample/DAS logs from the file (default True).");
#ifdef MPI_EXPERIMENTAL
declareProperty(make_unique<PropertyWithValue<bool>>("UseParallelLoader",
true, Direction::Input),
"Use experimental parallel loader for loading event data.");
#endif
}
//----------------------------------------------------------------------------------------------
/** set the name of the top level NXentry m_top_entry_name
*/
void LoadEventNexus::setTopEntryName() {
std::string nxentryProperty = getProperty("NXentryName");
if (!nxentryProperty.empty()) {
m_top_entry_name = nxentryProperty;
return;
}
using string_map_t = std::map<std::string, std::string>;
try {
string_map_t::const_iterator it;
// assume we're at the top, otherwise: m_file->openPath("/");
string_map_t entries = m_file->getEntries();
// Choose the first entry as the default
m_top_entry_name = entries.begin()->first;
for (it = entries.begin(); it != entries.end(); ++it) {
if (((it->first == "entry") || (it->first == "raw_data_1")) &&
(it->second == "NXentry")) {
m_top_entry_name = it->first;
break;
}
}
} catch (const std::exception &) {
g_log.error() << "Unable to determine name of top level NXentry - assuming "
"\"entry\".\n";
m_top_entry_name = "entry";
}
}
template <typename T> void LoadEventNexus::filterDuringPause(T workspace) {
try {
if ((!ConfigService::Instance().hasProperty(
"loadeventnexus.keeppausedevents")) &&
(m_ws->run().getLogData("pause")->size() > 1)) {
g_log.notice("Filtering out events when the run was marked as paused. "
"Set the loadeventnexus.keeppausedevents configuration "
"property to override this.");
auto filter = createChildAlgorithm("FilterByLogValue");
filter->setProperty("InputWorkspace", workspace);
filter->setProperty("OutputWorkspace", workspace);
filter->setProperty("LogName", "pause");
// The log value is set to 1 when the run is paused, 0 otherwise.
filter->setProperty("MinimumValue", 0.0);
filter->setProperty("MaximumValue", 0.0);
filter->setProperty("LogBoundary", "Left");
filter->execute();
}
} catch (Exception::NotFoundError &) {
// No "pause" log, just carry on
}
}
template <>
void LoadEventNexus::filterDuringPause<EventWorkspaceCollection_sptr>(
EventWorkspaceCollection_sptr workspace) {
// We provide a function pointer to the filter method of the object
boost::function<void(MatrixWorkspace_sptr)> func = std::bind1st(
std::mem_fun(&LoadEventNexus::filterDuringPause<MatrixWorkspace_sptr>),
this);
workspace->applyFilter(func);
}
//------------------------------------------------------------------------------------------------
/** Executes the algorithm. Reading in the file and creating and populating
* the output workspace
*/
void LoadEventNexus::exec() {
// Retrieve the filename from the properties
m_filename = getPropertyValue("Filename");
compressTolerance = getProperty("CompressTolerance");
loadlogs = getProperty("LoadLogs");
// Check to see if the monitors need to be loaded later
bool load_monitors = this->getProperty("LoadMonitors");
// this must make absolutely sure that m_file is a valid (and open)
// NeXus::File object
safeOpenFile(m_filename);
setTopEntryName();
// Initialize progress reporting.
int reports = 3;
if (load_monitors)
reports++;
Progress prog(this, 0.0, 0.3, reports);
// Load the detector events
m_ws = boost::make_shared<EventWorkspaceCollection>(); // Algorithm currently
// relies on an
// object-level workspace ptr
loadEvents(&prog, false); // Do not load monitor blocks
if (discarded_events > 0) {
g_log.information() << discarded_events
<< " events were encountered coming from pixels which "
"are not in the Instrument Definition File."
"These events were discarded.\n";
}
// If the run was paused at any point, filter out those events (SNS only, I
// think)
filterDuringPause(m_ws->getSingleHeldWorkspace());
// add filename
m_ws->mutableRun().addProperty("Filename", m_filename);
// Save output
this->setProperty("OutputWorkspace", m_ws->combinedWorkspace());
// close the file since LoadNexusMonitors will take care of its own file
// handle
m_file->close();
// Load the monitors with child algorithm 'LoadNexusMonitors'
if (load_monitors) {
prog.report("Loading monitors");
this->runLoadMonitors();
}
}
/**
* Get the number of events in the currently opened group.
*
* @param file The handle to the nexus file opened to the group to look at.
* @param hasTotalCounts Whether to try looking at the total_counts field. This
* variable will be changed if the field is not there.
* @param oldNeXusFileNames Whether to try using old names. This variable will
* be changed if it is determined that old names are being used.
*
* @return The number of events.
*/
std::size_t numEvents(::NeXus::File &file, bool &hasTotalCounts,
bool &oldNeXusFileNames) {
// try getting the value of total_counts
if (hasTotalCounts) {
try {
uint64_t numEvents;
file.readData("total_counts", numEvents);
return numEvents;
} catch (::NeXus::Exception &) {
hasTotalCounts = false; // carry on with the field not existing
}
}
// just get the length of the event pixel ids
try {
if (oldNeXusFileNames)
file.openData("event_pixel_id");
else
file.openData("event_id");
} catch (::NeXus::Exception &) {
// Older files (before Nov 5, 2010) used this field.
try {
file.openData("event_pixel_id");
oldNeXusFileNames = true;
} catch (::NeXus::Exception &) {
// Some groups have neither indicating there are not events here
return 0;
}
}
size_t numEvents = static_cast<std::size_t>(file.getInfo().dims[0]);
file.closeData();
return numEvents;
}
/** Load the instrument from the nexus file
*
* @param nexusfilename :: The name of the nexus file being loaded
* @param localWorkspace :: Templated workspace in which to put the instrument
*geometry
* @param alg :: Handle of the algorithm
* @param returnpulsetimes :: flag to return shared pointer for BankPulseTimes,
*otherwise NULL.
* @param nPeriods : Number of periods (write to)
* @param periodLog : Period logs DateAndTime to int map.
*
* @return Pulse times given in the DAS logs
*/
template <typename T>
boost::shared_ptr<BankPulseTimes> LoadEventNexus::runLoadNexusLogs(
const std::string &nexusfilename, T localWorkspace, API::Algorithm &alg,
bool returnpulsetimes, int &nPeriods,
std::unique_ptr<const TimeSeriesProperty<int>> &periodLog) {
// --------------------- Load DAS Logs -----------------
// The pulse times will be empty if not specified in the DAS logs.
// BankPulseTimes * out = NULL;
boost::shared_ptr<BankPulseTimes> out;
API::IAlgorithm_sptr loadLogs = alg.createChildAlgorithm("LoadNexusLogs");
// Now execute the Child Algorithm. Catch and log any error, but don't stop.
try {
alg.getLogger().information() << "Loading logs from NeXus file..."
<< "\n";
loadLogs->setPropertyValue("Filename", nexusfilename);
loadLogs->setProperty<API::MatrixWorkspace_sptr>("Workspace",
localWorkspace);
try {
loadLogs->setPropertyValue("NXentryName",
alg.getPropertyValue("NXentryName"));
} catch (...) {
}
loadLogs->execute();
const Run &run = localWorkspace->run();
// Get the number of periods
if (run.hasProperty("nperiods")) {
nPeriods = run.getPropertyValueAsType<int>("nperiods");
}
// Get the period log. Map of DateAndTime to Period int values.
if (run.hasProperty("period_log")) {
auto *temp = run.getProperty("period_log");
periodLog.reset(dynamic_cast<TimeSeriesProperty<int> *>(temp->clone()));
}
// If successful, we can try to load the pulse times
Kernel::TimeSeriesProperty<double> *log =
dynamic_cast<Kernel::TimeSeriesProperty<double> *>(
localWorkspace->mutableRun().getProperty("proton_charge"));
std::vector<Types::Core::DateAndTime> temp;
if (log)
temp = log->timesAsVector();
// if (returnpulsetimes) out = new BankPulseTimes(temp);
if (returnpulsetimes)
out = boost::make_shared<BankPulseTimes>(temp);
// Use the first pulse as the run_start time.
if (!temp.empty()) {
if (temp[0] < Types::Core::DateAndTime("1991-01-01T00:00:00"))
alg.getLogger().warning() << "Found entries in the proton_charge "
"sample log with invalid pulse time!\n";
Types::Core::DateAndTime run_start = localWorkspace->getFirstPulseTime();
// add the start of the run as a ISO8601 date/time string. The start =
// first non-zero time.
// (this is used in LoadInstrument to find the right instrument file to
// use).
localWorkspace->mutableRun().addProperty(
"run_start", run_start.toISO8601String(), true);
} else {
alg.getLogger().warning() << "Empty proton_charge sample log. You will "
"not be able to filter by time.\n";
}
/// Attempt to make a gonoimeter from the logs
try {
Geometry::Goniometer gm;
gm.makeUniversalGoniometer();
localWorkspace->mutableRun().setGoniometer(gm, true);
} catch (std::runtime_error &) {
}
} catch (...) {
alg.getLogger().error() << "Error while loading Logs from SNS Nexus. Some "
"sample logs may be missing."
<< "\n";
return out;
}
return out;
}
/** Load the instrument from the nexus file
*
* @param nexusfilename :: The name of the nexus file being loaded
* @param localWorkspace :: EventWorkspaceCollection in which to put the
*instrument
*geometry
* @param alg :: Handle of the algorithm
* @param returnpulsetimes :: flag to return shared pointer for BankPulseTimes,
*otherwise NULL.
* @param nPeriods : Number of periods (write to)
* @param periodLog : Period logs DateAndTime to int map.
*
* @return Pulse times given in the DAS logs
*/
template <>
boost::shared_ptr<BankPulseTimes>
LoadEventNexus::runLoadNexusLogs<EventWorkspaceCollection_sptr>(
const std::string &nexusfilename,
EventWorkspaceCollection_sptr localWorkspace, API::Algorithm &alg,
bool returnpulsetimes, int &nPeriods,
std::unique_ptr<const TimeSeriesProperty<int>> &periodLog) {
auto ws = localWorkspace->getSingleHeldWorkspace();
auto ret = runLoadNexusLogs<MatrixWorkspace_sptr>(
nexusfilename, ws, alg, returnpulsetimes, nPeriods, periodLog);
return ret;
}
//-----------------------------------------------------------------------------
/**
* Load events from the file.
* @param prog :: A pointer to the progress reporting object
* @param monitors :: If true the events from the monitors are loaded and not the
* main banks
*
* This also loads the instrument, but only if it has not been set in the
*workspace
* being used as input (m_ws data member). Same applies to the logs.
*/
void LoadEventNexus::loadEvents(API::Progress *const prog,
const bool monitors) {
bool metaDataOnly = getProperty("MetaDataOnly");
// Get the time filters
setTimeFilters(monitors);
// The run_start will be loaded from the pulse times.
DateAndTime run_start(0, 0);
// Initialize the counter of bad TOFs
bad_tofs = 0;
int nPeriods = 1;
auto periodLog = make_unique<const TimeSeriesProperty<int>>("period_log");
if (!m_logs_loaded_correctly) {
if (loadlogs) {
prog->doReport("Loading DAS logs");
m_allBanksPulseTimes = runLoadNexusLogs<EventWorkspaceCollection_sptr>(
m_filename, m_ws, *this, true, nPeriods, periodLog);
run_start = m_ws->getFirstPulseTime();
m_logs_loaded_correctly = true;
} else {
g_log.information() << "Skipping the loading of sample logs!\n"
<< "Reading the start time directly from /"
<< m_top_entry_name << "/start_time\n";
// start_time is read and set
m_file->openPath("/");
m_file->openGroup(m_top_entry_name, "NXentry");
std::string tmp;
m_file->readData("start_time", tmp);
m_file->closeGroup();
run_start = createFromSanitizedISO8601(tmp);
m_ws->mutableRun().addProperty("run_start", run_start.toISO8601String(),
true);
}
}
m_ws->setNPeriods(
nPeriods, periodLog); // This is how many workspaces we are going to make.
// Make sure you have a non-NULL m_allBanksPulseTimes
if (m_allBanksPulseTimes == nullptr) {
std::vector<DateAndTime> temp;
m_allBanksPulseTimes = boost::make_shared<BankPulseTimes>(temp);
}
if (!m_ws->getInstrument() || !m_instrument_loaded_correctly) {
// Load the instrument (if not loaded before)
prog->report("Loading instrument");
m_instrument_loaded_correctly =
loadInstrument(m_filename, m_ws, m_top_entry_name, this);
if (!m_instrument_loaded_correctly)
throw std::runtime_error(
"Instrument was not initialized correctly! Loading cannot continue.");
}
// top level file information
m_file->openPath("/");
// Start with the base entry
m_file->openGroup(m_top_entry_name, "NXentry");
// Now we want to go through all the bankN_event entries
vector<string> bankNames;
vector<std::size_t> bankNumEvents;
map<string, string> entries = m_file->getEntries();
map<string, string>::const_iterator it = entries.begin();
std::string classType = monitors ? "NXmonitor" : "NXevent_data";
::NeXus::Info info;
bool oldNeXusFileNames(false);
bool hasTotalCounts(true);
bool haveWeights = false;
for (; it != entries.end(); ++it) {
std::string entry_name(it->first);
std::string entry_class(it->second);
if (entry_class == classType) {
// open the group
m_file->openGroup(entry_name, classType);
// get the number of events
std::size_t num = numEvents(*m_file, hasTotalCounts, oldNeXusFileNames);
bankNames.push_back(entry_name);
bankNumEvents.push_back(num);
// Look for weights in simulated file
try {
m_file->openData("event_weight");
haveWeights = true;
m_file->closeData();
} catch (::NeXus::Exception &) {
// Swallow exception since flag is already false;
}
m_file->closeGroup();
}
}
loadSampleDataISIScompatibility(*m_file, *m_ws);
// Close the 'top entry' group (raw_data_1 for NexusProcessed, etc.)
m_file->closeGroup();
// Delete the output workspace name if it existed
std::string outName = getPropertyValue("OutputWorkspace");
if (AnalysisDataService::Instance().doesExist(outName))
AnalysisDataService::Instance().remove(outName);
// set more properties on the workspace
try {
// this is a static method that is why it is passing the
// file object and the file path
loadEntryMetadata<EventWorkspaceCollection_sptr>(m_filename, m_ws,
m_top_entry_name);
} catch (std::runtime_error &e) {
// Missing metadata is not a fatal error. Log and go on with your life
g_log.error() << "Error loading metadata: " << e.what() << '\n';
}
// --------------------------- Time filtering
// ------------------------------------
double filter_time_start_sec, filter_time_stop_sec;
filter_time_start_sec = getProperty("FilterByTimeStart");
filter_time_stop_sec = getProperty("FilterByTimeStop");
// Default to ALL pulse times
bool is_time_filtered = false;
filter_time_start = Types::Core::DateAndTime::minimum();
filter_time_stop = Types::Core::DateAndTime::maximum();
if (m_allBanksPulseTimes->numPulses > 0) {
// If not specified, use the limits of doubles. Otherwise, convert from
// seconds to absolute PulseTime
if (filter_time_start_sec != EMPTY_DBL()) {
filter_time_start = run_start + filter_time_start_sec;
is_time_filtered = true;
}
if (filter_time_stop_sec != EMPTY_DBL()) {
filter_time_stop = run_start + filter_time_stop_sec;
is_time_filtered = true;
}
// Silly values?
if (filter_time_stop < filter_time_start) {
std::string msg = "Your ";
if (monitors)
msg += "monitor ";
msg += "filter for time's Stop value is smaller than the Start value.";
throw std::invalid_argument(msg);
}
}
if (is_time_filtered) {
// Now filter out the run, using the DateAndTime type.
m_ws->mutableRun().filterByTime(filter_time_start, filter_time_stop);
}
if (metaDataOnly) {
// Now, create a default X-vector for histogramming, with just 2 bins.
auto axis = HistogramData::BinEdges{
1, static_cast<double>(std::numeric_limits<uint32_t>::max()) * 0.1 - 1};
// Set the binning axis using this.
m_ws->setAllX(axis);
createSpectraMapping(m_filename, monitors, std::vector<std::string>());
return;
}
// --------- Loading only one bank ? ----------------------------------
std::vector<std::string> someBanks = getProperty("BankName");
bool SingleBankPixelsOnly = getProperty("SingleBankPixelsOnly");
if ((!someBanks.empty()) && (!monitors)) {
// check that all of the requested banks are in the file
for (auto &someBank : someBanks) {
bool foundIt = false;
for (auto &bankName : bankNames) {
if (bankName == someBank + "_events") {
foundIt = true;
break;
}
}
if (!foundIt) {
throw std::invalid_argument("No entry named '" + someBank +
"' was found in the .NXS file.\n");
}
}
// change the number of banks to load
bankNames.clear();
for (auto &someBank : someBanks)
bankNames.push_back(someBank + "_events");
// how many events are in a bank
bankNumEvents.clear();
bankNumEvents.assign(someBanks.size(),
1); // TODO this equally weights the banks
if (!SingleBankPixelsOnly)
someBanks.clear(); // Marker to load all pixels
} else {
someBanks.clear();
}
prog->report("Initializing all pixels");
// Remove unused banks if parameter is set
if (m_ws->getInstrument()->hasParameter("remove-unused-banks")) {
std::vector<double> instrumentUnused =
m_ws->getInstrument()->getNumberParameter("remove-unused-banks", true);
if (!instrumentUnused.empty()) {
const int unused = static_cast<int>(instrumentUnused.front());
if (unused == 1)
deleteBanks(m_ws, bankNames);
}
}
//----------------- Pad Empty Pixels -------------------------------
createSpectraMapping(m_filename, monitors, someBanks);
// Set all (empty) event lists as sorted by pulse time. That way, calling
// SortEvents will not try to sort these empty lists.
for (size_t i = 0; i < m_ws->getNumberHistograms(); i++)
m_ws->getSpectrum(i).setSortOrder(DataObjects::PULSETIME_SORT);
// Count the limits to time of flight
shortest_tof =
static_cast<double>(std::numeric_limits<uint32_t>::max()) * 0.1;
longest_tof = 0.;
bool loaded{false};
if (canUseParallelLoader(haveWeights, oldNeXusFileNames, classType)) {
auto ws = m_ws->getSingleHeldWorkspace();
m_file->close();
try {
ParallelEventLoader::load(*ws, m_filename, m_top_entry_name, bankNames,
event_id_is_spec);
g_log.information() << "Used ParallelEventLoader.\n";
loaded = true;
shortest_tof = 0.0;
longest_tof = 1e10;
} catch (const std::runtime_error &) {
g_log.warning()
<< "ParallelEventLoader failed, falling back to default loader.\n";
}
safeOpenFile(m_filename);
}
if (!loaded) {
bool precount = getProperty("Precount");
int chunk = getProperty("ChunkNumber");
int totalChunks = getProperty("TotalChunks");
DefaultEventLoader::load(this, *m_ws, haveWeights, event_id_is_spec,
bankNames, periodLog->valuesAsVector(), classType,
bankNumEvents, oldNeXusFileNames, precount, chunk,
totalChunks);
}
// Info reporting
const std::size_t eventsLoaded = m_ws->getNumberEvents();
g_log.information() << "Read " << eventsLoaded << " events"
<< ". Shortest TOF: " << shortest_tof
<< " microsec; longest TOF: " << longest_tof
<< " microsec.\n";
if (shortest_tof < 0)
g_log.warning() << "The shortest TOF was negative! At least 1 event has an "
"invalid time-of-flight.\n";
if (bad_tofs > 0)
g_log.warning() << "Found " << bad_tofs << " events with TOF > 2e8. This "
"may indicate errors in the raw "
"TOF data.\n";
// Use T0 offset from TOPAZ Parameter file if it exists
if (m_ws->getInstrument()->hasParameter("T0")) {
std::vector<double> instrumentT0 =
m_ws->getInstrument()->getNumberParameter("T0", true);
if (!instrumentT0.empty()) {
const double mT0 = instrumentT0.front();
if (mT0 != 0.0) {
int64_t numHistograms =
static_cast<int64_t>(m_ws->getNumberHistograms());
PARALLEL_FOR_IF(Kernel::threadSafe(*m_ws))
for (int64_t i = 0; i < numHistograms; ++i) {
PARALLEL_START_INTERUPT_REGION
// Do the offsetting
m_ws->getSpectrum(i).addTof(mT0);
PARALLEL_END_INTERUPT_REGION
}
PARALLEL_CHECK_INTERUPT_REGION
// set T0 in the run parameters
API::Run &run = m_ws->mutableRun();
run.addProperty<double>("T0", mT0, true);
}
}
}
// Now, create a default X-vector for histogramming, with just 2 bins.
if (eventsLoaded > 0)
m_ws->setAllX(HistogramData::BinEdges{shortest_tof - 1, longest_tof + 1});
else
m_ws->setAllX(HistogramData::BinEdges{0.0, 1.0});
// if there is time_of_flight load it
adjustTimeOfFlightISISLegacy(*m_file, m_ws, m_top_entry_name, classType);
}
//-----------------------------------------------------------------------------
/** Load the instrument from the nexus file
*
* @param nexusfilename :: The name of the nexus file being loaded
* @param localWorkspace :: EventWorkspaceCollection in which to put the
*instrument
*geometry
* @param top_entry_name :: entry name at the top of the Nexus file
* @param alg :: Handle of the algorithm
* @return true if successful
*/
template <>
bool LoadEventNexus::runLoadIDFFromNexus<EventWorkspaceCollection_sptr>(
const std::string &nexusfilename,
EventWorkspaceCollection_sptr localWorkspace,
const std::string &top_entry_name, Algorithm *alg) {
auto ws = localWorkspace->getSingleHeldWorkspace();
auto hasLoaded = runLoadIDFFromNexus<MatrixWorkspace_sptr>(
nexusfilename, ws, top_entry_name, alg);
localWorkspace->setInstrument(ws->getInstrument());
return hasLoaded;
}
/** method used to return instrument name for some old ISIS files where it is
* not written properly within the instrument
* @param hFile :: A reference to the NeXus file opened at the root entry
*/
std::string
LoadEventNexus::readInstrumentFromISIS_VMSCompat(::NeXus::File &hFile) {
std::string instrumentName;
try {
hFile.openGroup("isis_vms_compat", "IXvms");
} catch (std::runtime_error &) {
return instrumentName;
}
try {
hFile.openData("NAME");
} catch (std::runtime_error &) {
hFile.closeGroup();
return instrumentName;
}
instrumentName = hFile.getStrData();
hFile.closeData();
hFile.closeGroup();
return instrumentName;
}
//-----------------------------------------------------------------------------
/** Load the instrument definition file specified by info in the NXS file for
* a EventWorkspaceCollection
*
* @param nexusfilename :: Used to pick the instrument.
* @param localWorkspace :: EventWorkspaceCollection in which to put the
*instrument
*geometry
* @param top_entry_name :: entry name at the top of the NXS file
* @param alg :: Handle of the algorithm
* @return true if successful
*/
template <>
bool LoadEventNexus::runLoadInstrument<EventWorkspaceCollection_sptr>(
const std::string &nexusfilename,
EventWorkspaceCollection_sptr localWorkspace,
const std::string &top_entry_name, Algorithm *alg) {
auto ws = localWorkspace->getSingleHeldWorkspace();
auto hasLoaded = runLoadInstrument<MatrixWorkspace_sptr>(nexusfilename, ws,
top_entry_name, alg);
localWorkspace->setInstrument(ws->getInstrument());
return hasLoaded;
}
//-----------------------------------------------------------------------------
/**
* Deletes banks for a workspace given the bank names.
* @param workspace :: The workspace to contain the spectra mapping
* @param bankNames :: Bank names that are in Nexus file
*/
void LoadEventNexus::deleteBanks(EventWorkspaceCollection_sptr workspace,
std::vector<std::string> bankNames) {
Instrument_sptr inst = boost::const_pointer_cast<Instrument>(
workspace->getInstrument()->baseInstrument());
// Build a list of Rectangular Detectors
std::vector<boost::shared_ptr<RectangularDetector>> detList;
for (int i = 0; i < inst->nelements(); i++) {
boost::shared_ptr<RectangularDetector> det;
boost::shared_ptr<ICompAssembly> assem;
boost::shared_ptr<ICompAssembly> assem2;
det = boost::dynamic_pointer_cast<RectangularDetector>((*inst)[i]);
if (det) {
detList.push_back(det);
} else {
// Also, look in the first sub-level for RectangularDetectors (e.g. PG3).
// We are not doing a full recursive search since that will be very long
// for lots of pixels.
assem = boost::dynamic_pointer_cast<ICompAssembly>((*inst)[i]);
if (assem) {
for (int j = 0; j < assem->nelements(); j++) {
det = boost::dynamic_pointer_cast<RectangularDetector>((*assem)[j]);
if (det) {
detList.push_back(det);
} else {
// Also, look in the second sub-level for RectangularDetectors (e.g.
// PG3).
// We are not doing a full recursive search since that will be very
// long for lots of pixels.
assem2 = boost::dynamic_pointer_cast<ICompAssembly>((*assem)[j]);
if (assem2) {
for (int k = 0; k < assem2->nelements(); k++) {
det = boost::dynamic_pointer_cast<RectangularDetector>(
(*assem2)[k]);
if (det) {
detList.push_back(det);
}
}
}
}
}
}
}
}
if (detList.empty())
return;
for (auto &det : detList) {
bool keep = false;
std::string det_name = det->getName();
for (auto &bankName : bankNames) {
size_t pos = bankName.find("_events");
if (det_name == bankName.substr(0, pos))