-
Notifications
You must be signed in to change notification settings - Fork 122
/
LoadNexusProcessed.cpp
1795 lines (1616 loc) · 60.1 KB
/
LoadNexusProcessed.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
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidAPI/AlgorithmFactory.h"
#include "MantidAPI/AlgorithmManager.h"
#include "MantidAPI/FileProperty.h"
#include "MantidAPI/BinEdgeAxis.h"
#include "MantidAPI/NumericAxis.h"
#include "MantidAPI/RegisterFileLoader.h"
#include "MantidAPI/TextAxis.h"
#include "MantidAPI/WorkspaceGroup.h"
#include "MantidDataHandling/LoadNexusProcessed.h"
#include "MantidDataObjects/EventWorkspace.h"
#include "MantidDataObjects/RebinnedOutput.h"
#include "MantidKernel/ArrayProperty.h"
#include "MantidKernel/ConfigService.h"
#include "MantidKernel/DateAndTime.h"
#include "MantidKernel/UnitFactory.h"
#include "MantidKernel/BoundedValidator.h"
#include "MantidNexus/NexusClasses.h"
#include "MantidNexus/NexusFileIO.h"
#include <nexus/NeXusFile.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
#include <cmath>
#include <Poco/DateTimeParser.h>
#include <Poco/Path.h>
#include <Poco/StringTokenizer.h>
#include "MantidDataObjects/PeaksWorkspace.h"
namespace Mantid
{
namespace DataHandling
{
// Register the algorithm into the algorithm factory
DECLARE_NEXUS_FILELOADER_ALGORITHM(LoadNexusProcessed);
using namespace Mantid::NeXus;
using namespace DataObjects;
using namespace Kernel;
using namespace API;
using Geometry::Instrument_const_sptr;
namespace
{
// Helper typedef
typedef boost::shared_array<int> IntArray_shared;
// Struct to contain spectrum information.
struct SpectraInfo
{
// Number of spectra
const int nSpectra;
// Do we have any spectra
const bool hasSpectra;
// Contains spectrum numbers for each workspace index
const IntArray_shared spectraNumbers;
// Index of the detector in the workspace.
const IntArray_shared detectorIndex;
// Number of detectors associated with each spectra
const IntArray_shared detectorCount;
// Detector list contains a list of all of the detector numbers
const IntArray_shared detectorList;
SpectraInfo() :
nSpectra(0), hasSpectra(false)
{
}
SpectraInfo(int _nSpectra, bool _hasSpectra, IntArray_shared _spectraNumbers,
IntArray_shared _detectorIndex, IntArray_shared _detectorCount,
IntArray_shared _detectorList) :
nSpectra(_nSpectra), hasSpectra(_hasSpectra), spectraNumbers(_spectraNumbers), detectorIndex(
_detectorIndex), detectorCount(_detectorCount), detectorList(_detectorList)
{
}
};
// Helper typdef.
typedef boost::optional<SpectraInfo> SpectraInfo_optional;
/**
* Extract ALL the detector, spectrum number and workspace index mapping information.
* @param mtd_entry
* @param logger
* @return
*/
SpectraInfo extractMappingInfo(NXEntry & mtd_entry, Logger& logger)
{
//Instrument information
NXInstrument inst = mtd_entry.openNXInstrument("instrument");
if (!inst.containsGroup("detector"))
{
logger.information()
<< "Detector block not found. The workspace will not contain any detector information.\n";
return SpectraInfo();
}
//Populate the spectra-detector map
NXDetector detgroup = inst.openNXDetector("detector");
//Read necessary arrays from the file
// Detector list contains a list of all of the detector numbers. If it not present then we can't update the spectra
// map
boost::shared_array<int> detectorList;
try
{
NXInt detlist_group = detgroup.openNXInt("detector_list");
detlist_group.load();
detectorList = detlist_group.sharedBuffer();
} catch (std::runtime_error &)
{
logger.information()
<< "detector_list block not found. The workspace will not contain any detector information."
<< std::endl;
return SpectraInfo();
}
//Detector count contains the number of detectors associated with each spectra
NXInt det_count = detgroup.openNXInt("detector_count");
det_count.load();
boost::shared_array<int> detectorCount = det_count.sharedBuffer();
//Detector index - contains the index of the detector in the workspace
NXInt det_index = detgroup.openNXInt("detector_index");
det_index.load();
int nspectra = det_index.dim0();
boost::shared_array<int> detectorIndex = det_index.sharedBuffer();
//Spectra block - Contains spectrum numbers for each workspace index
// This might not exist so wrap and check. If it doesn't exist create a default mapping
bool have_spectra(true);
boost::shared_array<int> spectra;
try
{
NXInt spectra_block = detgroup.openNXInt("spectra");
spectra_block.load();
spectra = spectra_block.sharedBuffer();
} catch (std::runtime_error &)
{
have_spectra = false;
}
return SpectraInfo(nspectra, have_spectra, spectra, detectorIndex, detectorCount, detectorList);
}
}
/// Default constructor
LoadNexusProcessed::LoadNexusProcessed() :
m_shared_bins(false), m_xbins(), m_axis1vals(), m_list(false), m_interval(false), m_spec_list(), m_spec_min(
0), m_spec_max(Mantid::EMPTY_INT()), m_cppFile(NULL)
{
}
/// Delete NexusFileIO in destructor
LoadNexusProcessed::~LoadNexusProcessed()
{
delete m_cppFile;
}
/**
* 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 LoadNexusProcessed::confidence(Kernel::NexusDescriptor & descriptor) const
{
if (descriptor.pathExists("/mantid_workspace_1"))
return 80;
else
return 0;
}
/** Initialisation method.
*
*/
void LoadNexusProcessed::init()
{
// Declare required input parameters for algorithm
std::vector<std::string> exts;
exts.push_back(".nxs");
exts.push_back(".nx5");
exts.push_back(".xml");
declareProperty(new FileProperty("Filename", "", FileProperty::Load, exts),
"The name of the Nexus file to read, as a full or relative path.");
declareProperty(new WorkspaceProperty<Workspace>("OutputWorkspace", "", Direction::Output),
"The name of the workspace to be created as the output of the algorithm. A workspace of this name will be created and stored in the Analysis Data Service. For multiperiod files, one workspace may be generated for each period. Currently only one workspace can be saved at a time so multiperiod Mantid files are not generated.");
// optional
auto mustBePositive = boost::make_shared<BoundedValidator<int64_t> >();
mustBePositive->setLower(0);
declareProperty("SpectrumMin", (int64_t) 1, mustBePositive, "Number of first spectrum to read.");
declareProperty("SpectrumMax", (int64_t) Mantid::EMPTY_INT(), mustBePositive,
"Number of last spectrum to read.");
declareProperty(new ArrayProperty<int64_t>("SpectrumList"), "List of spectrum numbers to read.");
declareProperty("EntryNumber", (int64_t) 0, mustBePositive,
"The particular entry number to read. Default load all workspaces and creates a workspacegroup (default: read all entries).");
declareProperty("LoadHistory", true, "If true, the workspace history will be loaded");
}
//-------------------------------------------------------------------------------------------------
/** Executes the algorithm. Reading in the file and creating and populating
* the output workspace
*
* @throw runtime_error Thrown if algorithm cannot execute
*/
void LoadNexusProcessed::exec()
{
progress(0, "Opening file...");
//Throws an approriate exception if there is a problem with file access
NXRoot root(getPropertyValue("Filename"));
// "Open" the same file but with the C++ interface
m_cppFile = new ::NeXus::File(root.m_fileID);
//Find out how many first level entries there are
int64_t nWorkspaceEntries = static_cast<int64_t>(root.groups().size());
// Check for an entry number property
int64_t entrynumber = static_cast<int64_t>(getProperty("EntryNumber"));
Property const * const entryNumberProperty = this->getProperty("EntryNumber");
bool bDefaultEntryNumber = entryNumberProperty->isDefault();
if (!bDefaultEntryNumber && entrynumber > nWorkspaceEntries)
{
g_log.error() << "Invalid entry number specified. File only contains " << nWorkspaceEntries
<< " entries.\n";
throw std::invalid_argument("Invalid entry number specified.");
}
const std::string basename = "mantid_workspace_";
std::ostringstream os;
if (bDefaultEntryNumber)
{
++entrynumber;
}
os << basename << entrynumber;
const std::string targetEntryName = os.str();
if (nWorkspaceEntries == 1 || !bDefaultEntryNumber)
{ // Load one first level entry, specified if there are several
API::Workspace_sptr workspace = loadEntry(root, targetEntryName, 0, 1);
//API::Workspace_sptr workspace = boost::static_pointer_cast<API::Workspace>(local_workspace);
setProperty("OutputWorkspace", workspace);
}
else
{ // Load all first level entries
WorkspaceGroup_sptr wksp_group(new WorkspaceGroup);
//This forms the name of the group
std::string base_name = getPropertyValue("OutputWorkspace");
// First member of group should be the group itself, for some reason!
//load names of each of the workspaces and check for a common stem
std::vector<std::string> names(nWorkspaceEntries + 1);
bool commonStem = checkForCommonNameStem(root, names);
//remove existing workspace and replace with the one being loaded
bool wsExists = AnalysisDataService::Instance().doesExist(base_name);
if (wsExists)
{
Algorithm_sptr alg = AlgorithmManager::Instance().createUnmanaged("DeleteWorkspace");
alg->initialize();
alg->setChild(true);
alg->setProperty("Workspace", base_name);
alg->execute();
}
base_name += "_";
const std::string prop_name = "OutputWorkspace_";
double nWorkspaceEntries_d = static_cast<double>(nWorkspaceEntries);
for (int64_t p = 1; p <= nWorkspaceEntries; ++p)
{
std::ostringstream os;
os << p;
//decide what the workspace should be called
std::string wsName = buildWorkspaceName(names[p], base_name, p, commonStem);
Workspace_sptr local_workspace = loadEntry(root, basename + os.str(),
static_cast<double>(p - 1) / nWorkspaceEntries_d, 1. / nWorkspaceEntries_d);
declareProperty(
new WorkspaceProperty<API::Workspace>(prop_name + os.str(), wsName, Direction::Output));
//wksp_group->add(base_name + os.str());
wksp_group->addWorkspace(local_workspace);
setProperty(prop_name + os.str(), local_workspace);
}
// The group is the root property value
setProperty("OutputWorkspace", boost::static_pointer_cast<Workspace>(wksp_group));
}
m_axis1vals.clear();
}
/**
* Decides what to call a child of a group workspace.
*
* This function uses information about if the child workspace has a common stem
* and checks if the file contained a workspace name to decide what it should be called
*
* @param name :: The name loaded from the file (possibly the empty string if none was loaded)
* @param baseName :: The name group workspace
* @param wsIndex :: The current index of this workspace
* @param commonStem :: Whether the workspaces share a common name stem
*
* @return The name of the workspace
*/
std::string LoadNexusProcessed::buildWorkspaceName(const std::string& name,
const std::string& baseName, int64_t wsIndex, bool commonStem)
{
std::string wsName;
std::string index = boost::lexical_cast<std::string>(wsIndex);
//if we don't have a common stem then use name tag
if (!commonStem)
{
if (!name.empty())
{
//use name loaded from file there's no common stem
wsName = name;
}
else
{
//if the name property wasn't defined just use <OutputWorkspaceName>_n
wsName = baseName + index;
}
}
else
{
//we have a common stem so rename accordingly
boost::smatch results;
const boost::regex exp(".*_(\\d+$)");
//if we have a common name stem then name is <OutputWorkspaceName>_n
if (boost::regex_search(name, results, exp))
{
wsName = baseName + std::string(results[1].first, results[1].second);
}
else
{
//use default name if we couldn't match for some reason
wsName = baseName + index;
}
}
correctForWorkspaceNameClash(wsName);
return wsName;
}
/**
* Append an index to the name if it already exists in the AnalysisDataService
*
* @param wsName :: Name to call the workspace
*/
void LoadNexusProcessed::correctForWorkspaceNameClash(std::string& wsName)
{
bool noClash(false);
for (int i = 0; !noClash; ++i)
{
std::string wsIndex = ""; //dont use an index if there is no other workspace
if (i > 0)
{
wsIndex = "_" + boost::lexical_cast<std::string>(i);
}
bool wsExists = AnalysisDataService::Instance().doesExist(wsName + wsIndex);
if (!wsExists)
{
wsName += wsIndex;
noClash = true;
}
}
}
/**
* Check if the workspace name contains a common stem and load the workspace names
*
* @param root :: the root for the NeXus document
* @param names :: vector to store the names to be loaded.
* @return Whether there was a common stem.
*/
bool LoadNexusProcessed::checkForCommonNameStem(NXRoot & root, std::vector<std::string>& names)
{
bool success(true);
int64_t nWorkspaceEntries = static_cast<int64_t>(root.groups().size());
for (int64_t p = 1; p <= nWorkspaceEntries; ++p)
{
std::ostringstream os;
os << p;
names[p] = loadWorkspaceName(root, "mantid_workspace_" + os.str());
boost::smatch results;
const boost::regex exp(".*_\\d+$");
//check if the workspace name has an index on the end
if (!boost::regex_match(names[p], results, exp))
{
success = false;
}
}
return success;
}
/**
* Load the workspace name, if the attribute exists
*
* @param root :: Root of NeXus file
* @param entry_name :: Entry in NeXus file to look at
* @return The workspace name. If none found an empty string is returned.
*/
std::string LoadNexusProcessed::loadWorkspaceName(NXRoot & root, const std::string& entry_name)
{
NXEntry mtd_entry = root.openEntry(entry_name);
try
{
return mtd_entry.getString("workspace_name");
} catch (std::runtime_error&)
{
return std::string();
}
}
//-------------------------------------------------------------------------------------------------
/** Load the event_workspace field
*
* @param wksp_cls
* @param xbins
* @param progressStart
* @param progressRange
* @return
*/
API::MatrixWorkspace_sptr LoadNexusProcessed::loadEventEntry(NXData & wksp_cls, NXDouble & xbins,
const double& progressStart, const double& progressRange)
{
NXDataSetTyped<int64_t> indices_data = wksp_cls.openNXDataSet<int64_t>("indices");
indices_data.load();
boost::shared_array<int64_t> indices = indices_data.sharedBuffer();
int numspec = indices_data.dim0() - 1;
int num_xbins = xbins.dim0();
if (num_xbins < 2)
num_xbins = 2;
EventWorkspace_sptr ws = boost::dynamic_pointer_cast<EventWorkspace>(
WorkspaceFactory::Instance().create("EventWorkspace", numspec, num_xbins, num_xbins - 1));
// Set the YUnit label
ws->setYUnit(indices_data.attributes("units"));
std::string unitLabel = indices_data.attributes("unit_label");
if (unitLabel.empty())
unitLabel = indices_data.attributes("units");
ws->setYUnitLabel(unitLabel);
//Handle optional fields.
// TODO: Handle inconsistent sizes
boost::shared_array<int64_t> pulsetimes;
if (wksp_cls.isValid("pulsetime"))
{
NXDataSetTyped<int64_t> pulsetime = wksp_cls.openNXDataSet<int64_t>("pulsetime");
pulsetime.load();
pulsetimes = pulsetime.sharedBuffer();
}
boost::shared_array<double> tofs;
if (wksp_cls.isValid("tof"))
{
NXDouble tof = wksp_cls.openNXDouble("tof");
tof.load();
tofs = tof.sharedBuffer();
}
boost::shared_array<float> error_squareds;
if (wksp_cls.isValid("error_squared"))
{
NXFloat error_squared = wksp_cls.openNXFloat("error_squared");
error_squared.load();
error_squareds = error_squared.sharedBuffer();
}
boost::shared_array<float> weights;
if (wksp_cls.isValid("weight"))
{
NXFloat weight = wksp_cls.openNXFloat("weight");
weight.load();
weights = weight.sharedBuffer();
}
// What type of event lists?
EventType type = TOF;
if (tofs && pulsetimes && weights && error_squareds)
type = WEIGHTED;
else if ((tofs && weights && error_squareds))
type = WEIGHTED_NOTIME;
else if (pulsetimes && tofs)
type = TOF;
else
throw std::runtime_error("Could not figure out the type of event list!");
// Create all the event lists
PARALLEL_FOR_NO_WSP_CHECK()
for (int wi = 0; wi < numspec; wi++)
{
PARALLEL_START_INTERUPT_REGION
int64_t index_start = indices[wi];
int64_t index_end = indices[wi + 1];
if (index_end >= index_start)
{
EventList & el = ws->getEventList(wi);
el.switchTo(type);
// Allocate all the required memory
el.reserve(index_end - index_start);
el.clearDetectorIDs();
for (int64_t i = index_start; i < index_end; i++)
switch (type)
{
case TOF:
el.addEventQuickly(TofEvent(tofs[i], DateAndTime(pulsetimes[i])));
break;
case WEIGHTED:
el.addEventQuickly(
WeightedEvent(tofs[i], DateAndTime(pulsetimes[i]), weights[i], error_squareds[i]));
break;
case WEIGHTED_NOTIME:
el.addEventQuickly(WeightedEventNoTime(tofs[i], weights[i], error_squareds[i]));
break;
}
// Set the X axis
if (this->m_shared_bins)
el.setX(this->m_xbins);
else
{
MantidVec x;
x.resize(xbins.dim0());
for (int i = 0; i < xbins.dim0(); i++)
x[i] = xbins(wi, i);
el.setX(x);
}
}
progress(progressStart + progressRange * (1.0 / numspec));
PARALLEL_END_INTERUPT_REGION
}
PARALLEL_CHECK_INTERUPT_REGION
return ws;
}
//-------------------------------------------------------------------------------------------------
/**
* Load a table
*/
API::Workspace_sptr LoadNexusProcessed::loadTableEntry(NXEntry & entry)
{
API::ITableWorkspace_sptr workspace;
workspace = Mantid::API::WorkspaceFactory::Instance().createTable("TableWorkspace");
NXData nx_tw = entry.openNXData("table_workspace");
bool hasNumberOfRowBeenSet = false;
//int numberOfRows = 0;
int columnNumber = 1;
do
{
std::string str = "column_" + boost::lexical_cast<std::string>(columnNumber);
NXInfo info = nx_tw.getDataSetInfo(str.c_str());
if (info.stat == NX_ERROR)
{
// Assume we done last column of table
break;
}
if (info.rank == 1)
{
if (info.type == NX_FLOAT64)
{
NXDouble nxDouble = nx_tw.openNXDouble(str.c_str());
std::string columnTitle = nxDouble.attributes("name");
if (!columnTitle.empty())
{
workspace->addColumn("double", columnTitle);
nxDouble.load();
int length = nxDouble.dim0();
if (!hasNumberOfRowBeenSet)
{
workspace->setRowCount(length);
hasNumberOfRowBeenSet = true;
}
for (int i = 0; i < length; i++)
workspace->cell<double>(i, columnNumber - 1) = *(nxDouble() + i);
}
}
else if (info.type == NX_INT32)
{
NXInt nxInt = nx_tw.openNXInt(str.c_str());
std::string columnTitle = nxInt.attributes("name");
if (!columnTitle.empty())
{
workspace->addColumn("int", columnTitle);
nxInt.load();
int length = nxInt.dim0();
if (!hasNumberOfRowBeenSet)
{
workspace->setRowCount(length);
hasNumberOfRowBeenSet = true;
}
for (int i = 0; i < length; i++)
workspace->cell<int>(i, columnNumber - 1) = *(nxInt() + i);
}
}
}
else if (info.rank == 2)
{
if (info.type == NX_CHAR)
{
NXChar data = nx_tw.openNXChar(str.c_str());
std::string columnTitle = data.attributes("name");
if (!columnTitle.empty())
{
workspace->addColumn("str", columnTitle);
int nRows = info.dims[0];
if (!hasNumberOfRowBeenSet)
{
workspace->setRowCount(nRows);
hasNumberOfRowBeenSet = true;
}
const int maxStr = info.dims[1];
data.load();
for (int iR = 0; iR < nRows; ++iR)
{
auto& cellContents = workspace->cell<std::string>(iR, columnNumber - 1);
auto startPoint = data() + maxStr * iR;
cellContents.assign(startPoint, startPoint + maxStr);
boost::trim_right(cellContents);
}
}
}
#define IF_VECTOR_COLUMN(Type, ColumnTypeName, NexusType) \
else if ( info.type == NexusType ) \
{ \
loadVectorColumn<Type>(nx_tw, str, workspace, #ColumnTypeName); \
}
IF_VECTOR_COLUMN(int, vector_int, NX_INT32)
IF_VECTOR_COLUMN(double, vector_double, NX_FLOAT64)
}
columnNumber++;
} while (1);
return boost::static_pointer_cast<API::Workspace>(workspace);
}
/**
* Loads a vector column to the TableWorkspace.
* @param tableData :: Table data to load from
* @param dataSetName :: Name of the data set to use to get column data
* @param tableWs :: Workspace to add column to
* @param columnType :: Name of the column type to create
*/
template<typename Type>
void LoadNexusProcessed::loadVectorColumn(const NXData& tableData, const std::string& dataSetName,
const ITableWorkspace_sptr& tableWs, const std::string& columnType)
{
NXDataSetTyped<Type> data = tableData.openNXDataSet<Type>(dataSetName.c_str());
std::string columnTitle = data.attributes("name");
if (!columnTitle.empty())
{
tableWs->addColumn(columnType, columnTitle);
NXInfo info = tableData.getDataSetInfo(dataSetName.c_str());
const size_t rowCount = info.dims[0];
const size_t blockSize = info.dims[1];
// This might've been done already, but doing it twice should't do any harm
tableWs->setRowCount(rowCount);
data.load();
for (size_t i = 0; i < rowCount; ++i)
{
auto& cell = tableWs->cell<std::vector<Type> >(i, tableWs->columnCount() - 1);
Type* from = data() + blockSize * i;
cell.assign(from, from + blockSize);
std::ostringstream rowSizeAttrName;
rowSizeAttrName << "row_size_" << i;
// This is ugly, but I can only get attribute as a string using the API
std::istringstream rowSizeStr(data.attributes(rowSizeAttrName.str()));
int rowSize;
rowSizeStr >> rowSize;
cell.resize(rowSize);
}
}
}
//-------------------------------------------------------------------------------------------------
/**
* Load peaks
*/
API::Workspace_sptr LoadNexusProcessed::loadPeaksEntry(NXEntry & entry)
{
//API::IPeaksWorkspace_sptr workspace;
API::ITableWorkspace_sptr tWorkspace;
//PeaksWorkspace_sptr workspace;
tWorkspace = Mantid::API::WorkspaceFactory::Instance().createTable("PeaksWorkspace");
PeaksWorkspace_sptr peakWS = boost::dynamic_pointer_cast<PeaksWorkspace>(tWorkspace);
NXData nx_tw = entry.openNXData("peaks_workspace");
int columnNumber = 1;
int numberPeaks = 0;
std::vector<std::string> columnNames;
do
{
std::string str = "column_" + boost::lexical_cast<std::string>(columnNumber);
NXInfo info = nx_tw.getDataSetInfo(str.c_str());
if (info.stat == NX_ERROR)
{
// Assume we done last column of table
break;
}
// store column names
columnNames.push_back(str);
// determine number of peaks
// here we assume that a peaks_table has always one column of doubles
if (info.type == NX_FLOAT64)
{
NXDouble nxDouble = nx_tw.openNXDouble(str.c_str());
std::string columnTitle = nxDouble.attributes("name");
if (!columnTitle.empty() && numberPeaks == 0)
{
numberPeaks = nxDouble.dim0();
}
}
columnNumber++;
} while (1);
//Get information from all but data group
std::string parameterStr;
// Hop to the right point
m_cppFile->openPath(entry.path());
try
{
// This loads logs, sample, and instrument.
peakWS->loadExperimentInfoNexus(m_cppFile, parameterStr);
} catch (std::exception & e)
{
g_log.information("Error loading Instrument section of nxs file");
g_log.information(e.what());
}
// std::vector<API::IPeak*> p;
for (int r = 0; r < numberPeaks; r++)
{
Kernel::V3D v3d;
v3d[2] = 1.0;
API::IPeak* p;
p = peakWS->createPeak(v3d);
peakWS->addPeak(*p);
}
for (size_t i = 0; i < columnNames.size(); i++)
{
const std::string str = columnNames[i];
if (!str.compare("column_1"))
{
NXInt nxInt = nx_tw.openNXInt(str.c_str());
nxInt.load();
for (int r = 0; r < numberPeaks; r++)
{
int ival = nxInt[r];
if (ival != -1)
peakWS->getPeak(r).setDetectorID(ival);
}
}
if (!str.compare("column_2"))
{
NXDouble nxDouble = nx_tw.openNXDouble(str.c_str());
nxDouble.load();
for (int r = 0; r < numberPeaks; r++)
{
double val = nxDouble[r];
peakWS->getPeak(r).setH(val);
}
}
if (!str.compare("column_3"))
{
NXDouble nxDouble = nx_tw.openNXDouble(str.c_str());
nxDouble.load();
for (int r = 0; r < numberPeaks; r++)
{
double val = nxDouble[r];
peakWS->getPeak(r).setK(val);
}
}
if (!str.compare("column_4"))
{
NXDouble nxDouble = nx_tw.openNXDouble(str.c_str());
nxDouble.load();
for (int r = 0; r < numberPeaks; r++)
{
double val = nxDouble[r];
peakWS->getPeak(r).setL(val);
}
}
if (!str.compare("column_5"))
{
NXDouble nxDouble = nx_tw.openNXDouble(str.c_str());
nxDouble.load();
for (int r = 0; r < numberPeaks; r++)
{
double val = nxDouble[r];
peakWS->getPeak(r).setIntensity(val);
}
}
if (!str.compare("column_6"))
{
NXDouble nxDouble = nx_tw.openNXDouble(str.c_str());
nxDouble.load();
for (int r = 0; r < numberPeaks; r++)
{
double val = nxDouble[r];
peakWS->getPeak(r).setSigmaIntensity(val);
}
}
if (!str.compare("column_7"))
{
NXDouble nxDouble = nx_tw.openNXDouble(str.c_str());
nxDouble.load();
for (int r = 0; r < numberPeaks; r++)
{
double val = nxDouble[r];
peakWS->getPeak(r).setBinCount(val);
}
}
if (!str.compare("column_10"))
{
NXDouble nxDouble = nx_tw.openNXDouble(str.c_str());
nxDouble.load();
for (int r = 0; r < numberPeaks; r++)
{
double val = nxDouble[r];
peakWS->getPeak(r).setWavelength(val);
}
}
if (!str.compare("column_14"))
{
NXInt nxInt = nx_tw.openNXInt(str.c_str());
nxInt.load();
for (int r = 0; r < numberPeaks; r++)
{
int ival = nxInt[r];
if (ival != -1)
peakWS->getPeak(r).setRunNumber(ival);
}
}
if (!str.compare("column_15"))
{
NXDouble nxDouble = nx_tw.openNXDouble(str.c_str());
nxDouble.load();
Kernel::Matrix<double> gm(3, 3, false);
int k = 0;
for (int r = 0; r < numberPeaks; r++)
{
for (int j = 0; j < 9; j++)
{
double val = nxDouble[k];
k++;
gm[j % 3][j / 3] = val;
}
peakWS->getPeak(r).setGoniometerMatrix(gm);
}
}
}
return boost::static_pointer_cast<API::Workspace>(peakWS);
}
//-------------------------------------------------------------------------------------------------
/**
* Load a single entry into a workspace
* @param root :: The opened root node
* @param entry_name :: The entry name
* @param progressStart :: The percentage value to start the progress reporting for this entry
* @param progressRange :: The percentage range that the progress reporting should cover
* @returns A 2D workspace containing the loaded data
*/
API::Workspace_sptr LoadNexusProcessed::loadEntry(NXRoot & root, const std::string & entry_name,
const double& progressStart, const double& progressRange)
{
progress(progressStart, "Opening entry " + entry_name + "...");
NXEntry mtd_entry = root.openEntry(entry_name);
if (mtd_entry.containsGroup("table_workspace"))
{
return loadTableEntry(mtd_entry);
}
if (mtd_entry.containsGroup("peaks_workspace"))
{
return loadPeaksEntry(mtd_entry);
}
// Determine workspace type and name of group containing workspace characteristics
bool isEvent = false;
std::string workspaceType = "Workspace2D";
std::string group_name = "workspace";
if (mtd_entry.containsGroup("event_workspace"))
{
isEvent = true;
group_name = "event_workspace";
}
else if (mtd_entry.containsGroup("offsets_workspace"))
{
workspaceType = "OffsetsWorkspace";
group_name = "offsets_workspace";
}
// Get workspace characteristics
NXData wksp_cls = mtd_entry.openNXData(group_name);
// Axis information
// "X" axis
NXDouble xbins = wksp_cls.openNXDouble("axis1");
xbins.load();
std::string unit1 = xbins.attributes("units");
// Non-uniform x bins get saved as a 2D 'axis1' dataset
int xlength(-1);
if (xbins.rank() == 2)
{
xlength = xbins.dim1();
m_shared_bins = false;
}
else if (xbins.rank() == 1)
{
xlength = xbins.dim0();
m_shared_bins = true;
xbins.load();
m_xbins.access().assign(xbins(), xbins() + xlength);
}
else
{
throw std::runtime_error("Unknown axis1 dimension encountered.");
}
// MatrixWorkspace axis 1
NXDouble axis2 = wksp_cls.openNXDouble("axis2");
std::string unit2 = axis2.attributes("units");
// The workspace being worked on
API::MatrixWorkspace_sptr local_workspace;
size_t nspectra;
int64_t nchannels;