PeaksWorkspace.cpp 29.9 KB
Newer Older
1
2
#include "MantidAPI/AlgorithmFactory.h"
#include "MantidAPI/Column.h"
Peterson, Peter's avatar
Peterson, Peter committed
3
#include "MantidAPI/ColumnFactory.h"
4
#include "MantidGeometry/Instrument/Goniometer.h"
5
#include "MantidAPI/MatrixWorkspace.h"
6
7
#include <nexus/NeXusException.hpp>
#include <nexus/NeXusFile.hpp>
Peterson, Peter's avatar
Peterson, Peter committed
8
#include "MantidAPI/WorkspaceFactory.h"
9
#include "MantidAPI/WorkspaceProperty.h"
Peterson, Peter's avatar
Peterson, Peter committed
10
#include "MantidDataObjects/PeaksWorkspace.h"
11
12
13
#include "MantidDataObjects/TableColumn.h"
#include "MantidDataObjects/TableWorkspace.h"
#include "MantidDataObjects/Peak.h"
14
15
#include "MantidKernel/Quat.h"
#include "MantidKernel/V3D.h"
16
17
18
19
#include "MantidKernel/DateAndTime.h"
#include "MantidKernel/Logger.h"
#include "MantidKernel/PhysicalConstants.h"
#include "MantidKernel/Unit.h"
20
#include "MantidGeometry/Crystal/OrientedLattice.h"
Peterson, Peter's avatar
Peterson, Peter committed
21
#include <algorithm>
22
#include <boost/shared_ptr.hpp>
Peterson, Peter's avatar
Peterson, Peter committed
23
24
#include <exception>
#include <fstream>
25
26
27
#include <iostream>
#include <math.h>
#include <ostream>
Peterson, Peter's avatar
Peterson, Peter committed
28
29
#include <stdio.h>
#include <stdlib.h>
30
31
32
33
34
#include <string>

using namespace Mantid::API;
using namespace Mantid::Kernel;
using namespace Mantid::Geometry;
Peterson, Peter's avatar
Peterson, Peter committed
35
36
37

namespace Mantid
{
Owen Arnold's avatar
Owen Arnold committed
38
  namespace DataObjects
39
  {
Owen Arnold's avatar
Owen Arnold committed
40
41
    /// Register the workspace as a type
    DECLARE_WORKSPACE(PeaksWorkspace);
42

Owen Arnold's avatar
Owen Arnold committed
43
//  Kernel::Logger& PeaksWorkspace::g_log = Kernel::Logger::get("PeaksWorkspace");
44

Owen Arnold's avatar
Owen Arnold committed
45
46
47
48
49
50
51
52
53
54
//---------------------------------------------------------------------------------------------
    /** Constructor. Create a table with all the required columns.
     *
     * @return PeaksWorkspace object
     */
    PeaksWorkspace::PeaksWorkspace() :
        IPeaksWorkspace()
    {
      initColumns();
    }
55

Owen Arnold's avatar
Owen Arnold committed
56
57
58
59
60
61
62
63
64
65
    //---------------------------------------------------------------------------------------------
    /** Virtual constructor. Clone method to duplicate the peaks workspace.
     *
     * @return PeaksWorkspace object
     */
    PeaksWorkspace* PeaksWorkspace::clone() const
    {
      //Deep copy via copy construtor.
      return new PeaksWorkspace(*this);
    }
66

Owen Arnold's avatar
Owen Arnold committed
67
68
69
70
71
72
73
74
75
76
77
    //---------------------------------------------------------------------------------------------
    /** Copy constructor
     *
     * @param other :: other PeaksWorkspace to copy from
     * @return
     */
    PeaksWorkspace::PeaksWorkspace(const PeaksWorkspace & other) :
        IPeaksWorkspace(other), peaks(other.peaks)
    {
      initColumns();
    }
78

Owen Arnold's avatar
Owen Arnold committed
79
80
81
82
83
84
    //---------------------------------------------------------------------------------------------
    /** Clone a shared pointer
     *
     * @return copy of the peaksworkspace
     */
    boost::shared_ptr<PeaksWorkspace> PeaksWorkspace::clone()
85
    {
Owen Arnold's avatar
Owen Arnold committed
86
87
      // Copy construct and return
      return boost::shared_ptr<PeaksWorkspace>(new PeaksWorkspace(*this));
88
89
    }

Owen Arnold's avatar
Owen Arnold committed
90
91
92
93
94
    //=====================================================================================
    //=====================================================================================
    /** Comparator class for sorting peaks by one or more criteria
     */
    class PeakComparator: public std::binary_function<Peak, Peak, bool>
95
    {
Owen Arnold's avatar
Owen Arnold committed
96
97
98
99
100
101
102
103
104
    public:
      std::vector<std::pair<std::string, bool> > & criteria;

      /** Constructor for the comparator for sorting peaks
       * @param criteria : a vector with a list of pairs: column name, bool;
       *        where bool = true for ascending, false for descending sort.
       */
      PeakComparator(std::vector<std::pair<std::string, bool> > & criteria) :
          criteria(criteria)
105
      {
Owen Arnold's avatar
Owen Arnold committed
106
107
108
109
110
111
      }

      /** Compare two peaks using the stored criteria */
      inline bool operator()(const Peak& a, const Peak& b)
      {
        for (size_t i = 0; i < criteria.size(); i++)
112
        {
Owen Arnold's avatar
Owen Arnold committed
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
          std::string & col = criteria[i].first;
          bool ascending = criteria[i].second;
          bool lessThan = false;
          if (col == "BankName")
          {
            // If this criterion is equal, move on to the next one
            std::string valA = a.getBankName();
            std::string valB = b.getBankName();
            // Move on to lesser criterion if equal
            if (valA == valB)
              continue;
            lessThan = (valA < valB);
          }
          else
          {
            // General double comparison
            double valA = a.getValueByColName(col);
            double valB = b.getValueByColName(col);
            // Move on to lesser criterion if equal
            if (valA == valB)
              continue;
            lessThan = (valA < valB);
          }
          // Flip the sign of comparison if descending.
          if (ascending)
            return lessThan;
          else
            return !lessThan;

142
        }
Owen Arnold's avatar
Owen Arnold committed
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
        // If you reach here, all criteria were ==; so not <, so return false
        return false;
      }
    };

    //---------------------------------------------------------------------------------------------
    /** Sort the peaks by one or more criteria
     *
     * @param criteria : a vector with a list of pairs: column name, bool;
     *        where bool = true for ascending, false for descending sort.
     *        The peaks are sorted by the first criterion first, then the 2nd if equal, etc.
     */
    void PeaksWorkspace::sort(std::vector<std::pair<std::string, bool> > & criteria)
    {
      PeakComparator comparator(criteria);
      std::stable_sort(peaks.begin(), peaks.end(), comparator);
    }

    //---------------------------------------------------------------------------------------------
    /** @return the number of peaks
     */
    int PeaksWorkspace::getNumberPeaks() const
    {
      return int(peaks.size());
    }
168

Owen Arnold's avatar
Owen Arnold committed
169
170
171
172
173
174
175
176
177
    //---------------------------------------------------------------------------------------------
    /** Removes the indicated peak
     * @param peakNum  the peak to remove. peakNum starts at 0
     */
    void PeaksWorkspace::removePeak(const int peakNum)
    {
      if (peakNum >= static_cast<int>(peaks.size()) || peakNum < 0)
      {
        throw std::invalid_argument("PeaksWorkspace::removePeak(): peakNum is out of range.");
178
      }
Owen Arnold's avatar
Owen Arnold committed
179
      peaks.erase(peaks.begin() + peakNum);
180
181
    }

Owen Arnold's avatar
Owen Arnold committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
    //---------------------------------------------------------------------------------------------
    /** Add a peak to the list
     * @param ipeak :: Peak object to add (copy) into this.
     */
    void PeaksWorkspace::addPeak(const API::IPeak& ipeak)
    {
      if (dynamic_cast<const Peak*>(&ipeak))
      {
        peaks.push_back((const Peak&) ipeak);
      }
      else
      {
        peaks.push_back(Peak(ipeak));
      }
    }
197

Owen Arnold's avatar
Owen Arnold committed
198
199
200
201
202
    //---------------------------------------------------------------------------------------------
    /** Return a reference to the Peak
     * @param peakNum :: index of the peak to get.
     * @return a reference to a Peak object.
     */
Owen Arnold's avatar
Owen Arnold committed
203
    Peak & PeaksWorkspace::getPeak(const int peakNum)
Owen Arnold's avatar
Owen Arnold committed
204
205
206
207
208
209
210
    {
      if (peakNum >= static_cast<int>(peaks.size()) || peakNum < 0)
      {
        throw std::invalid_argument("PeaksWorkspace::getPeak(): peakNum is out of range.");
      }
      return peaks[peakNum];
    }
211

Owen Arnold's avatar
Owen Arnold committed
212
213
214
215
216
    //---------------------------------------------------------------------------------------------
    /** Return a const reference to the Peak
     * @param peakNum :: index of the peak to get.
     * @return a reference to a Peak object.
     */
Owen Arnold's avatar
Owen Arnold committed
217
    const Peak & PeaksWorkspace::getPeak(const int peakNum) const
Owen Arnold's avatar
Owen Arnold committed
218
219
220
221
222
223
224
    {
      if (peakNum >= static_cast<int>(peaks.size()) || peakNum < 0)
      {
        throw std::invalid_argument("PeaksWorkspace::getPeak(): peakNum is out of range.");
      }
      return peaks[peakNum];
    }
225

Owen Arnold's avatar
Owen Arnold committed
226
227
228
229
230
231
232
    //---------------------------------------------------------------------------------------------
    /** Creates an instance of a Peak BUT DOES NOT ADD IT TO THE WORKSPACE
     * @param QLabFrame :: Q of the center of the peak, in reciprocal space
     * @param detectorDistance :: distance between the sample and the detector.
     * @return a pointer to a new Peak object.
     */
    API::IPeak* PeaksWorkspace::createPeak(Kernel::V3D QLabFrame, double detectorDistance) const
233
    {
Owen Arnold's avatar
Owen Arnold committed
234
      return new Peak(this->getInstrument(), QLabFrame, detectorDistance);
235
    }
236

237
238
239
   /**
    * Returns selected information for a "peak" at QLabFrame.
    *
240
    * @param qFrame      An arbitrary position in Q-space.  This does not have to be the
241
    *                    position of a peak.
242
    * @param labCoords   Set true if the position is in the lab coordinate system, false if
243
    *                    it is in the sample coordinate system.
244
245
246
247
    * @return a vector whose elements contain different information about the "peak" at that position.
    *         each element is a pair of description of information and the string form for the corresponding
    *         value.
    */
248
249
    std::vector<std::pair<std::string, std::string> > PeaksWorkspace::peakInfo(Kernel::V3D qFrame,
        bool labCoords) const
250
    {
251
      std::vector<std::pair<std::string, std::string> > Result;
252
      std::ostringstream oss;
253
      oss<<std::setw(12)<<std::fixed<<std::setprecision(3)<<(qFrame.norm());
254
      std::pair<std::string, std::string> QMag("|Q|",oss.str());
255
      Result.push_back(QMag);
256

257
      oss.str(""); oss.clear();
258
      oss<<std::setw(12)<<std::fixed<<std::setprecision(3)<<(2.0 * M_PI / qFrame.norm());
259
260
261

      std::pair<std::string, std::string> dspc("d-spacing",oss.str());
      oss.str(""); oss.clear();
262
      Result.push_back(dspc);
263

264
265
266
      int seqNum = -1;
      bool hasOneRunNumber = true;
      int runNum = -1;
267
268
      int NPeaks = getNumberPeaks();
      try
269
      {
270
        double minDist = 10000000;
271
        for (int i = 0; i < NPeaks; i++)
272
        {
273
274
          Peak pk = getPeak(i);
          V3D Q = pk.getQLabFrame();
275
          if (!labCoords)
276
            Q = pk.getQSampleFrame();
277
          double D = qFrame.distance(Q);
278
279
280
281
282
          if (D < minDist)
          {
            minDist = D;
            seqNum = i;
          }
283

284
285
286
287
288
289
290
291
292
          int run = pk.getRunNumber();
          if (runNum < 0)
            runNum = run;
          else if (runNum != run)
            hasOneRunNumber = false;
        }
      }catch(...)
      {
        seqNum = -1;//peak could have been removed
293
      }
294
      V3D Qlab = qFrame;
295
296
      V3D Qsamp;
      Kernel::Matrix<double> Gon(3, 3, true);
297
298

      if (seqNum >= 0 && NPeaks == getNumberPeaks())
299
        Gon = getPeak(seqNum).getGoniometerMatrix();
300
      if (labCoords)
301
      {
302

303
304
305
        Kernel::Matrix<double> InvGon(Gon);
        InvGon.Invert();
        Qsamp = InvGon * Qlab;
306

307
308
309
      }
      else
      {
310
        Qsamp = qFrame;
311
312
        Qlab = Gon * Qsamp;
      }
313

314
      if (labCoords || seqNum >= 0)
315

316
317
318
319
      {
        std::pair<std::string, std::string> QlabStr("Qlab", boost::lexical_cast<std::string>(Qlab));
        Result.push_back(QlabStr);
      }
320

321
      if (!labCoords || seqNum >= 0)
322
      {
323

324
325
326
        std::pair<std::string, std::string> QsampStr("QSample", boost::lexical_cast<std::string>(Qsamp));
        Result.push_back(QsampStr);
      }
327

328
329
330
      try
      {
        API::IPeak* peak = createPeak(Qlab);
331

332
333
        if (sample().hasOrientedLattice())
        {
334

335
336
          peak->setGoniometerMatrix(Gon);
          const Geometry::OrientedLattice & lat = (sample().getOrientedLattice());
337

338
339
340
341
          const Kernel::Matrix<double> &UB0 = lat.getUB();
          Kernel::Matrix<double> UB(UB0);
          UB.Invert();
          V3D hkl = UB * Qsamp / 2 / M_PI;
342

343
344
          std::pair<std::string, std::string> HKL("HKL", boost::lexical_cast<std::string>(hkl));
          Result.push_back(HKL);
345

346
        }
347

348
        if (hasOneRunNumber)
349
        {
350
          std::pair<std::string, std::string> runn("RunNumber","   "+
351
352
              boost::lexical_cast<std::string>(runNum));
          Result.push_back(runn);
353

354
        }
355

356
357
358
359
        //------- Now get phi, chi and omega ----------------
        Geometry::Goniometer GonG(Gon);
        std::vector<double> OmegaChiPhi = GonG.getEulerAngles("YZY");
        Kernel::V3D PhiChiOmega(OmegaChiPhi[2], OmegaChiPhi[1], OmegaChiPhi[0]);
360

361
362
363
        std::pair<std::string, std::string> GRead("Goniometer Angles",
            boost::lexical_cast<std::string>(PhiChiOmega));
        Result.push_back(GRead);
364

365
366
        std::pair<std::string, std::string> SeqNum("Seq Num,1st=1","    "+
            boost::lexical_cast<std::string>(seqNum + 1));
367
        Result.push_back(SeqNum);
368

369
370
        oss<<std::setw(12)<<std::fixed<<std::setprecision(3)<<(peak->getWavelength());
        std::pair<std::string, std::string> wl("Wavelength", oss.str());
371
        Result.push_back(wl);
372
        oss.str(""); oss.clear();
373

374
375
376
377
378
379
        if (peak->findDetector())
        {
          V3D detPos = peak->getDetPos();
          std::pair<std::string, std::string> detpos("Position(x,y,z)",
              boost::lexical_cast<std::string>(peak->getDetPos()));
          Result.push_back(detpos);
380

381
382
          oss<<std::setw(15)<<std::fixed<<std::setprecision(3)<< (peak->getTOF());
          std::pair<std::string, std::string> tof("TOF", oss.str());
383
          Result.push_back(tof);
384
          oss.str(""); oss.clear();
385

386
387
          oss<<std::setw(12)<<std::fixed<<std::setprecision(3)<< (peak->getFinalEnergy());
          std::pair<std::string, std::string> Energy("Energy", oss.str());
388
          Result.push_back(Energy);
389
          oss.str(""); oss.clear();
390

391
          std::pair<std::string, std::string> row("Row","    "+
392
393
              boost::lexical_cast<std::string>(peak->getRow()));
          Result.push_back(row);
394

395
          std::pair<std::string, std::string> col("Col","    "+
396
397
              boost::lexical_cast<std::string>(peak->getCol()));
          Result.push_back(col);
398

399
          std::pair<std::string, std::string> bank("Bank", "    "+peak->getBankName());
400
          Result.push_back(bank);
401

402
403
          oss<<std::setw(12)<<std::fixed<<std::setprecision(3)<< (peak->getScattering());
          std::pair<std::string, std::string> scat("Scattering Angle", oss.str());
404
          Result.push_back(scat);
405
406
407

        }

408
      } catch (...)    //Impossible position
409
410
411
412
413
      {

      }
      return Result;
    }
414

415
416
417
    /**
     * Returns selected information for a "peak" at QLabFrame.
     *
418
     * @param qFrame      An arbitrary position in Q-space.  This does not have to be the
419
     *                    position of a peak.
420
     * @param labCoords  Set true if the position is in the lab coordinate system, false if
421
422
423
424
425
     *                    it is in the sample coordinate system.
     * @return a vector whose elements contain different information about the "peak" at that position.
     *         each element is a pair of description of information and the string form for the corresponding
     *         value.
     */
426
427
     int PeaksWorkspace::peakInfoNumber(Kernel::V3D qFrame,
         bool labCoords) const
428
429
430
     {
       std::vector<std::pair<std::string, std::string> > Result;
       std::ostringstream oss;
431
       oss<<std::setw(12)<<std::fixed<<std::setprecision(3)<<(qFrame.norm());
432
433
434
435
       std::pair<std::string, std::string> QMag("|Q|",oss.str());
       Result.push_back(QMag);

       oss.str(""); oss.clear();
436
       oss<<std::setw(12)<<std::fixed<<std::setprecision(3)<<(2.0 * M_PI / qFrame.norm());
437
438
439
440
441
442
443
444
445
446
447
448

       std::pair<std::string, std::string> dspc("d-spacing",oss.str());
       oss.str(""); oss.clear();
       Result.push_back(dspc);

       int seqNum = -1;
       double minDist = 10000000;

       for (int i = 0; i < getNumberPeaks(); i++)
       {
         Peak pk = getPeak(i);
         V3D Q = pk.getQLabFrame();
449
         if (!labCoords)
450
           Q = pk.getQSampleFrame();
451
         double D = qFrame.distance(Q);
452
453
454
455
456
457
458
459
460
         if (D < minDist)
         {
           minDist = D;
           seqNum = i + 1;
         }

       }
       return seqNum;
     }
461

Owen Arnold's avatar
Owen Arnold committed
462
463
464
    //---------------------------------------------------------------------------------------------
    /** Return a reference to the Peaks vector */
    std::vector<Peak> & PeaksWorkspace::getPeaks()
465
    {
Owen Arnold's avatar
Owen Arnold committed
466
      return peaks;
467
    }
Owen Arnold's avatar
Owen Arnold committed
468
469
470

    /** Return a const reference to the Peaks vector */
    const std::vector<Peak> & PeaksWorkspace::getPeaks() const
471
    {
Owen Arnold's avatar
Owen Arnold committed
472
      return peaks;
473
474
    }

Owen Arnold's avatar
Owen Arnold committed
475
476
477
478
    /** Getter for the integration status.
     @return TRUE if it has been integrated using a peak integration algorithm.
     */
    bool PeaksWorkspace::hasIntegratedPeaks() const
479
    {
Owen Arnold's avatar
Owen Arnold committed
480
481
482
483
      bool ret = false;
      const std::string peaksIntegrated = "PeaksIntegrated";
      if (this->run().hasProperty(peaksIntegrated))
      {
484
485
        const int value = boost::lexical_cast<int>(this->run().getProperty(peaksIntegrated)->value());
        ret = (value != 0);
Owen Arnold's avatar
Owen Arnold committed
486
487
      }
      return ret;
488
    }
489

Owen Arnold's avatar
Owen Arnold committed
490
491
492
    //---------------------------------------------------------------------------------------------
    /// Return the memory used in bytes
    size_t PeaksWorkspace::getMemorySize() const
493
    {
Owen Arnold's avatar
Owen Arnold committed
494
      return getNumberPeaks() * sizeof(Peak);
495
    }
496

Owen Arnold's avatar
Owen Arnold committed
497
498
499
500
501
502
503
504
505
506
507
    //---------------------------------------------------------------------------------------------
    /**
     *  Creates a new TableWorkspace with detailing the contributing Detector IDs. The table
     *  will have 2 columns: Index &  DetectorID, where Index maps into the current index
     *  within the PeaksWorkspace of the peak
     */
    API::ITableWorkspace_sptr PeaksWorkspace::createDetectorTable() const
    {
      auto table = API::WorkspaceFactory::Instance().createTable("TableWorkspace");
      table->addColumn("int", "Index");
      table->addColumn("int", "DetectorID");
508

Owen Arnold's avatar
Owen Arnold committed
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
      const int npeaks(static_cast<int>(this->rowCount()));
      int nrows(0);
      for (int i = 0; i < npeaks; ++i)
      {
        const Peak & peak = this->peaks[i];
        auto detIDs = peak.getContributingDetIDs();
        auto itEnd = detIDs.end();
        for (auto it = detIDs.begin(); it != itEnd; ++it)
        {
          table->appendRow();
          table->cell<int>(nrows, 0) = i;
          table->cell<int>(nrows, 1) = *it;
          ++nrows;
        }
      }
524

Owen Arnold's avatar
Owen Arnold committed
525
526
      return table;
    }
527

Owen Arnold's avatar
Owen Arnold committed
528
529
530
    //---------------------------------------------------------------------------------------------
    /** Destructor */
    PeaksWorkspace::~PeaksWorkspace()
531
532
    {
    }
Peterson, Peter's avatar
Peterson, Peter committed
533

Owen Arnold's avatar
Owen Arnold committed
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
    //---------------------------------------------------------------------------------------------
    /** Initialize all columns */
    void PeaksWorkspace::initColumns()
    {
      // Note: The column types are controlled in PeakColumn.cpp
      addPeakColumn("RunNumber");
      addPeakColumn("DetID");
      addPeakColumn("h");
      addPeakColumn("k");
      addPeakColumn("l");
      addPeakColumn("Wavelength");
      addPeakColumn("Energy");
      addPeakColumn("TOF");
      addPeakColumn("DSpacing");
      addPeakColumn("Intens");
      addPeakColumn("SigInt");
      addPeakColumn("BinCount");
      addPeakColumn("BankName");
      addPeakColumn("Row");
      addPeakColumn("Col");
      addPeakColumn("QLab");
      addPeakColumn("QSample");
    }
557

Owen Arnold's avatar
Owen Arnold committed
558
559
560
561
562
563
    //---------------------------------------------------------------------------------------------
    /**
     * Add a PeakColumn
     * @param name :: The name of the column
     **/
    void PeaksWorkspace::addPeakColumn(const std::string& name)
564
    {
Owen Arnold's avatar
Owen Arnold committed
565
566
567
568
569
      // Create the PeakColumn.
      columns.push_back(
          boost::shared_ptr<DataObjects::PeakColumn>(new DataObjects::PeakColumn(this->peaks, name)));
      // Cache the names
      columnNames.push_back(name);
570
571
    }

Owen Arnold's avatar
Owen Arnold committed
572
573
574
575
576
577
578
579
580
    //---------------------------------------------------------------------------------------------
    /// @return the index of the column with the given name.
    size_t PeaksWorkspace::getColumnIndex(const std::string& name) const
    {
      for (size_t i = 0; i < columns.size(); i++)
        if (columns[i]->name() == name)
          return i;
      throw std::invalid_argument("Column named " + name + " was not found in the PeaksWorkspace.");
    }
581

Owen Arnold's avatar
Owen Arnold committed
582
583
584
585
586
587
588
589
    //---------------------------------------------------------------------------------------------
    /// Gets the shared pointer to a column by index.
    boost::shared_ptr<Mantid::API::Column> PeaksWorkspace::getColumn(size_t index)
    {
      if (index >= columns.size())
        throw std::invalid_argument("PeaksWorkspace::getColumn() called with invalid index.");
      return columns[index];
    }
Peterson, Peter's avatar
Peterson, Peter committed
590

Owen Arnold's avatar
Owen Arnold committed
591
592
593
594
595
596
597
598
    //---------------------------------------------------------------------------------------------
    /// Gets the shared pointer to a column by index.
    boost::shared_ptr<const Mantid::API::Column> PeaksWorkspace::getColumn(size_t index) const
    {
      if (index >= columns.size())
        throw std::invalid_argument("PeaksWorkspace::getColumn() called with invalid index.");
      return columns[index];
    }
Peterson, Peter's avatar
Peterson, Peter committed
599

Owen Arnold's avatar
Owen Arnold committed
600
601
    void PeaksWorkspace::saveNexus(::NeXus::File * file) const
    {
Peterson, Peter's avatar
Peterson, Peter committed
602

Owen Arnold's avatar
Owen Arnold committed
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
      //Number of Peaks
      const size_t np(peaks.size());

      // Column vectors for peaks table
      std::vector<int> detectorID(np);
      std::vector<double> H(np);
      std::vector<double> K(np);
      std::vector<double> L(np);
      std::vector<double> intensity(np);
      std::vector<double> sigmaIntensity(np);
      std::vector<double> binCount(np);
      std::vector<double> initialEnergy(np);
      std::vector<double> finalEnergy(np);
      std::vector<double> waveLength(np);
      std::vector<double> scattering(np);
      std::vector<double> dSpacing(np);
      std::vector<double> TOF(np);
      std::vector<int> runNumber(np);
      std::vector<double> goniometerMatrix(9 * np);

      // Populate column vectors from Peak Workspace
      for (size_t i = 0; i < np; i++)
      {
        Peak p = peaks[i];
        detectorID[i] = p.getDetectorID();
        H[i] = p.getH();
        K[i] = p.getK();
        L[i] = p.getL();
        intensity[i] = p.getIntensity();
        sigmaIntensity[i] = p.getSigmaIntensity();
        binCount[i] = p.getBinCount();
        initialEnergy[i] = p.getInitialEnergy();
        finalEnergy[i] = p.getFinalEnergy();
        waveLength[i] = p.getWavelength();
        scattering[i] = p.getScattering();
        dSpacing[i] = p.getDSpacing();
        TOF[i] = p.getTOF();
        runNumber[i] = p.getRunNumber();
        {
          Matrix<double> gm = p.getGoniometerMatrix();
          goniometerMatrix[9 * i] = gm[0][0];
          goniometerMatrix[9 * i + 1] = gm[1][0];
          goniometerMatrix[9 * i + 2] = gm[2][0];
          goniometerMatrix[9 * i + 3] = gm[0][1];
          goniometerMatrix[9 * i + 4] = gm[1][1];
          goniometerMatrix[9 * i + 5] = gm[2][1];
          goniometerMatrix[9 * i + 6] = gm[0][2];
          goniometerMatrix[9 * i + 7] = gm[1][2];
651
          goniometerMatrix[9 * i + 8] = gm[2][2];
Owen Arnold's avatar
Owen Arnold committed
652
653
654
        }
        // etc.
      }
Peterson, Peter's avatar
Peterson, Peter committed
655

Owen Arnold's avatar
Owen Arnold committed
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
      // Start Peaks Workspace in Nexus File
      std::string specifyInteger = "An integer";
      std::string specifyDouble = "A double";
      file->makeGroup("peaks_workspace", "NXentry", true);  // For when peaksWorkspace can be loaded

      // Detectors column
      file->writeData("column_1", detectorID);
      file->openData("column_1");
      file->putAttr("name", "Dectector ID");
      file->putAttr("interpret_as", specifyInteger);
      file->putAttr("units", "Not known");
      file->closeData();

      // H column
      file->writeData("column_2", H);
      file->openData("column_2");
      file->putAttr("name", "H");
      file->putAttr("interpret_as", specifyDouble);
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      // K column
      file->writeData("column_3", K);
      file->openData("column_3");
      file->putAttr("name", "K");
      file->putAttr("interpret_as", specifyDouble);
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      // L column
      file->writeData("column_4", L);
      file->openData("column_4");
      file->putAttr("name", "L");
      file->putAttr("interpret_as", specifyDouble);
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      // Intensity column
      file->writeData("column_5", intensity);
      file->openData("column_5");
      file->putAttr("name", "Intensity");
      file->putAttr("interpret_as", specifyDouble);
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      // Sigma Intensity column
      file->writeData("column_6", sigmaIntensity);
      file->openData("column_6");
      file->putAttr("name", "Sigma Intensity");
      file->putAttr("interpret_as", specifyDouble);
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      // Bin Count column
      file->writeData("column_7", binCount);
      file->openData("column_7");
      file->putAttr("name", "Bin Count");
      file->putAttr("interpret_as", specifyDouble);
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      // Initial Energy column
      file->writeData("column_8", initialEnergy);
      file->openData("column_8");
      file->putAttr("name", "Initial Energy");
      file->putAttr("interpret_as", specifyDouble);
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      // Final Energy column
      file->writeData("column_9", finalEnergy);
      file->openData("column_9");
      file->putAttr("name", "Final Energy");
      file->putAttr("interpret_as", specifyDouble);
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      // Wave Length Column
      file->writeData("column_10", waveLength);
      file->openData("column_10");
      file->putAttr("name", "Wave Length");
      file->putAttr("interpret_as", specifyDouble);
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      // Scattering Column
      file->writeData("column_11", scattering);
      file->openData("column_11");
      file->putAttr("name", "Scattering");
      file->putAttr("interpret_as", specifyDouble);
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      // D Spacing Column
      file->writeData("column_12", dSpacing);
      file->openData("column_12");
      file->putAttr("name", "D Spacing");
      file->putAttr("interpret_as", specifyDouble);
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      // TOF Column
      file->writeData("column_13", TOF);
      file->openData("column_13");
      file->putAttr("name", "TOF");
      file->putAttr("interpret_as", specifyDouble);
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      //Run Number column
      file->writeData("column_14", runNumber);
      file->openData("column_14");
      file->putAttr("name", "Run Number");
      file->putAttr("interpret_as", specifyInteger);
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      // Goniometer Matrix Column
      std::vector<int> array_dims;
      array_dims.push_back(static_cast<int>(peaks.size()));
      array_dims.push_back(9);
      file->writeData("column_15", goniometerMatrix, array_dims);
      file->openData("column_15");
      file->putAttr("name", "Goniometer Matrix");
      file->putAttr("interpret_as", "A matrix of 3x3 doubles");
      file->putAttr("units", "Not known");  // Units may need changing when known
      file->closeData();

      // QLab & QSample are calculated and do not need to be saved

      file->closeGroup(); // end of peaks workpace
Peterson, Peter's avatar
Peterson, Peter committed
787

Owen Arnold's avatar
Owen Arnold committed
788
    }
789

Owen Arnold's avatar
Owen Arnold committed
790
791
792
793
794
795
796
797
    /**
     * Set the special Q3D coordinate system.
     * @param coordinateSystem : Option to set.
     */
    void PeaksWorkspace::setCoordinateSystem(const Mantid::API::SpecialCoordinateSystem coordinateSystem)
    {
      this->mutableRun().addProperty("CoordinateSystem", (int)coordinateSystem, true);
    }
798

Owen Arnold's avatar
Owen Arnold committed
799
800
801
802
    /**
     * @return the special Q3D coordinate system.
     */
    Mantid::API::SpecialCoordinateSystem PeaksWorkspace::getSpecialCoordinateSystem() const
803
    {
Owen Arnold's avatar
Owen Arnold committed
804
805
806
807
808
809
810
811
812
      Mantid::API::SpecialCoordinateSystem result = None;
      try
      {
        Property* prop = this->run().getProperty("CoordinateSystem");
        PropertyWithValue<int>* p = dynamic_cast<PropertyWithValue<int>*>(prop);
        int temp = *p;
        result = (SpecialCoordinateSystem) temp;
      }
      catch (Mantid::Kernel::Exception::NotFoundError&)
813
814
      {
      }
Owen Arnold's avatar
Owen Arnold committed
815
      return result;
816
    }
817

818
    // prevent shared pointer from deleting this
Owen Arnold's avatar
Owen Arnold committed
819
820
821
822
823
824
    struct NullDeleter
    {
      template<typename T> void operator()(T*)
      {
      }
    };
825
    /**Get access to shared pointer containing workspace porperties, cashes the shared pointer
Owen Arnold's avatar
Owen Arnold committed
826
827
828
829
830
     into internal class variable to not allow shared pointer being deleted */
    API::LogManager_sptr PeaksWorkspace::logs()
    {
      if (m_logCash)
        return m_logCash;
831

Owen Arnold's avatar
Owen Arnold committed
832
833
834
      m_logCash = API::LogManager_sptr(&(this->mutableRun()), NullDeleter());
      return m_logCash;
    }
835

Owen Arnold's avatar
Owen Arnold committed
836
  }
Peterson, Peter's avatar
Peterson, Peter committed
837
}
838
839
840
841
842
843
844
845
846

///\cond TEMPLATE

namespace Mantid
{
  namespace Kernel
  {

    template<> DLLExport
Owen Arnold's avatar
Owen Arnold committed
847
848
    Mantid::DataObjects::PeaksWorkspace_sptr IPropertyManager::getValue<
        Mantid::DataObjects::PeaksWorkspace_sptr>(const std::string &name) const
849
    {
Owen Arnold's avatar
Owen Arnold committed
850
851
      PropertyWithValue<Mantid::DataObjects::PeaksWorkspace_sptr>* prop = dynamic_cast<PropertyWithValue<
          Mantid::DataObjects::PeaksWorkspace_sptr>*>(getPointerToProperty(name));
852
853
854
855
856
857
      if (prop)
      {
        return *prop;
      }
      else
      {
Owen Arnold's avatar
Owen Arnold committed
858
859
        std::string message = "Attempt to assign property " + name
            + " to incorrect type. Expected PeaksWorkspace.";
860
861
862
863
864
        throw std::runtime_error(message);
      }
    }

    template<> DLLExport
Owen Arnold's avatar
Owen Arnold committed
865
866
    Mantid::DataObjects::PeaksWorkspace_const_sptr IPropertyManager::getValue<
        Mantid::DataObjects::PeaksWorkspace_const_sptr>(const std::string &name) const
867
    {
Owen Arnold's avatar
Owen Arnold committed
868
869
      PropertyWithValue<Mantid::DataObjects::PeaksWorkspace_sptr>* prop = dynamic_cast<PropertyWithValue<
          Mantid::DataObjects::PeaksWorkspace_sptr>*>(getPointerToProperty(name));
870
871
872
873
874
875
      if (prop)
      {
        return prop->operator()();
      }
      else
      {
Owen Arnold's avatar
Owen Arnold committed
876
877
        std::string message = "Attempt to assign property " + name
            + " to incorrect type. Expected const PeaksWorkspace.";
878
879
880
881
882
883
884
        throw std::runtime_error(message);
      }
    }

  } // namespace Kernel
} // namespace Mantid

885
///\endcond TEMPLATE