void MantidMatrix::setup(Mantid::API::MatrixWorkspace_const_sptr ws, int start, int end) { if (!ws) { QMessageBox::critical(0, "WorkspaceMatrixModel error", "2D workspace expected."); m_rows = 0; m_cols = 0; m_startRow = 0; m_endRow = 0; return; } m_workspace = ws; m_workspaceTotalHist = static_cast<int>(ws->getNumberHistograms()); m_startRow = (start < 0 || start >= m_workspaceTotalHist) ? 0 : start; m_endRow = (end < 0 || end >= m_workspaceTotalHist || end < start) ? m_workspaceTotalHist - 1 : end; m_rows = m_endRow - m_startRow + 1; m_cols = static_cast<int>(ws->blocksize()); if (ws->isHistogramData()) m_histogram = true; connect(this, SIGNAL(needsUpdating()), this, SLOT(repaintAll())); m_bk_color = QColor(128, 255, 255); m_matrix_icon = getQPixmap("mantid_matrix_xpm"); m_column_width = 100; }
void MantidWSIndexDialog::checkForSpectraAxes() { // Check to see if *all* workspaces have a spectrum axis. // If even one does not have a spectra axis, then we wont // ask the user to enter spectra IDs - only workspace indices. QList<QString>::const_iterator it = m_wsNames.constBegin(); m_spectra = true; for ( ; it != m_wsNames.constEnd(); ++it ) { Mantid::API::MatrixWorkspace_const_sptr ws = boost::dynamic_pointer_cast<const Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve((*it).toStdString())); if ( NULL == ws ) continue; bool hasSpectra = false; for(int i = 0; i < ws->axes(); i++) { if(ws->getAxis(i)->isSpectra()) hasSpectra = true; } if(hasSpectra == false) { m_spectra = false; break; } } }
/** * Creates and returns a "mini plot", from the given QwtPlot and QwtPlotCurve objects, as well as the given workspace * and workspace index. * * @param plot :: the QwtPlot object * @param curve :: the QwtPlotCurve object * @param workspace :: the workspace to use * @param wsIndex :: the workspace index * * @returns the resulting QwtPlotCurve object */ QwtPlotCurve* IDATab::plotMiniplot(QwtPlot* plot, QwtPlotCurve* curve, const std::string & workspace, size_t wsIndex) { if ( curve != NULL ) { curve->attach(0); delete curve; curve = 0; } Mantid::API::MatrixWorkspace_const_sptr ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(workspace)); size_t nhist = ws->getNumberHistograms(); if ( wsIndex >= nhist ) { showInformationBox("Error: Workspace index out of range."); return NULL; } using Mantid::MantidVec; const MantidVec & dataX = ws->readX(wsIndex); const MantidVec & dataY = ws->readY(wsIndex); curve = new QwtPlotCurve(); curve->setData(&dataX[0], &dataY[0], static_cast<int>(ws->blocksize())); curve->attach(plot); plot->replot(); return curve; }
void MantidWSIndexDialog::generateWsIndexIntervals() { // Get the available interval for each of the workspaces, and then // present the user with interval which is the INTERSECTION of each of // those intervals. QList<QString>::const_iterator it = m_wsNames.constBegin(); // Cycle through the workspaces ... for ( ; it != m_wsNames.constEnd(); ++it ) { Mantid::API::MatrixWorkspace_const_sptr ws = boost::dynamic_pointer_cast<const Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve((*it).toStdString())); if ( NULL == ws ) continue; const int endWs = static_cast<int>(ws->getNumberHistograms() - 1);//= static_cast<int> (end->first); Interval interval(0,endWs); // If no interval has been added yet, just add it ... if(it == m_wsNames.constBegin()) m_wsIndexIntervals.addInterval(interval); // ... else set the list as the intersection of what's already there // and what has just been added. else m_wsIndexIntervals.setIntervalList(IntervalList::intersect(m_wsIndexIntervals,interval)); } }
/** * Convert to the output dimensions * @param inputWs : Input Matrix workspace * @return workspace group containing output matrix workspaces of ki and kf */ Mantid::API::MatrixWorkspace_sptr ReflectometryTransform::execute( Mantid::API::MatrixWorkspace_const_sptr inputWs) const { auto ws = boost::make_shared<Mantid::DataObjects::Workspace2D>(); ws->initialize(m_d1NumBins, m_d0NumBins, m_d0NumBins); // Create the output workspace as a distribution // Mapping so that d0 and d1 values calculated can be added to the matrix // workspace at the correct index. const double gradD0 = double(m_d0NumBins) / (m_d0Max - m_d0Min); // The x - axis const double gradD1 = double(m_d1NumBins) / (m_d1Max - m_d1Min); // Actually the y-axis const double cxToIndex = -gradD0 * m_d0Min; const double cyToIndex = -gradD1 * m_d1Min; const double cxToD0 = m_d0Min - (1 / gradD0); const double cyToD1 = m_d1Min - (1 / gradD1); // Create an X - Axis. MantidVec xAxisVec = createXAxis(ws.get(), gradD0, cxToD0, m_d0NumBins, m_d0Label, "1/Angstroms"); // Create a Y (vertical) Axis createVerticalAxis(ws.get(), xAxisVec, gradD1, cyToD1, m_d1NumBins, m_d1Label, "1/Angstroms"); // Loop over all entries in the input workspace and calculate d0 and d1 // for each. auto spectraAxis = inputWs->getAxis(1); for (size_t index = 0; index < inputWs->getNumberHistograms(); ++index) { auto counts = inputWs->readY(index); auto wavelengths = inputWs->readX(index); auto errors = inputWs->readE(index); const size_t nInputBins = wavelengths.size() - 1; const double theta_final = spectraAxis->getValue(index); m_calculator->setThetaFinal(theta_final); // Loop over all bins in spectra for (size_t binIndex = 0; binIndex < nInputBins; ++binIndex) { const double wavelength = 0.5 * (wavelengths[binIndex] + wavelengths[binIndex + 1]); double _d0 = m_calculator->calculateDim0(wavelength); double _d1 = m_calculator->calculateDim1(wavelength); if (_d0 >= m_d0Min && _d0 <= m_d0Max && _d1 >= m_d1Min && _d1 <= m_d1Max) // Check that the calculated ki and kf are in range { const int outIndexX = static_cast<int>((gradD0 * _d0) + cxToIndex); const int outIndexZ = static_cast<int>((gradD1 * _d1) + cyToIndex); ws->dataY(outIndexZ)[outIndexX] += counts[binIndex]; ws->dataE(outIndexZ)[outIndexX] += errors[binIndex]; } } } return ws; }
/** function retrieves copy of the oriented lattice from the workspace */ boost::shared_ptr<Geometry::OrientedLattice> MDWSDescription::getOrientedLattice( Mantid::API::MatrixWorkspace_const_sptr inWS2D) { // try to get the WS oriented lattice boost::shared_ptr<Geometry::OrientedLattice> orl; if (inWS2D->sample().hasOrientedLattice()) orl = boost::shared_ptr<Geometry::OrientedLattice>( new Geometry::OrientedLattice(inWS2D->sample().getOrientedLattice())); return orl; }
void MantidWSIndexDialog::generateSpectraIdIntervals() { // Get the list of available intervals for each of the workspaces, and then // present the user with intervals which are the INTERSECTION of each of // those lists of intervals. QList<QString>::const_iterator it = m_wsNames.constBegin(); // Cycle through the workspaces ... for ( ; it != m_wsNames.constEnd(); ++it ) { Mantid::API::MatrixWorkspace_const_sptr ws = boost::dynamic_pointer_cast<const Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve((*it).toStdString())); if ( NULL == ws ) continue; Mantid::spec2index_map * spec2index = ws->getSpectrumToWorkspaceIndexMap(); Mantid::spec2index_map::const_iterator last = spec2index->end(); --last; Mantid::spec2index_map::const_iterator first = spec2index->begin(); const int startSpectrum = static_cast<int> (first->first); const int endSpectrum = static_cast<int> (last->first); const int size = static_cast<int> (spec2index->size()); if(size == (1 + endSpectrum - startSpectrum)) { // Here we make the assumption (?) that the spectra IDs are sorted, and so // are a list of ints from startSpectrum to endSpectrum without any gaps. Interval interval(startSpectrum, endSpectrum); if(it == m_wsNames.constBegin()) m_spectraIdIntervals.addInterval(interval); else m_spectraIdIntervals.setIntervalList(IntervalList::intersect(m_spectraIdIntervals,interval)); } else { // The spectra IDs do not appear to be an uninterrupted list of numbers, // and so we must go through each one and construct the intervals that way. // TODO - is this at all feasible for large workspaces, and/or many workspaces? ++last; for ( ; first != last; ++first) { const int spectraId = static_cast<int> (first->first); Interval interval(spectraId); if(it == m_wsNames.constBegin()) m_spectraIdIntervals.addInterval(interval); else m_spectraIdIntervals.setIntervalList(IntervalList::intersect(m_spectraIdIntervals,interval)); } } } }
void StepScan::fillNormalizationCombobox( const Mantid::API::MatrixWorkspace_const_sptr & ws ) { // If there are more than 3 entries in the combobox (nothing, time, proton_charge) then // remove any stale ones while ( m_uiForm.normalization->count() > 3 ) { m_uiForm.normalization->removeItem(m_uiForm.normalization->count()-1); } for ( std::size_t i = 0; i < ws->getNumberHistograms(); ++i ) { const std::string monitorName = ws->getDetector(i)->getName(); m_uiForm.normalization->addItem( QString::fromStdString( monitorName ) ); } }
/** * Sum counts in detectors for purposes of rough plotting against the units on the x-axis. * Assumes that all spectra share the x vector. * * @param dets :: A list of detector IDs to sum. * @param x :: (output) Time of flight values (or whatever values the x axis has) to plot against. * @param y :: (output) The sums of the counts for each bin. */ void InstrumentActor::sumDetectorsUniform(QList<int>& dets, std::vector<double>&x, std::vector<double>&y) const { size_t wi; bool isDataEmpty = dets.isEmpty(); if ( !isDataEmpty ) { try { wi = getWorkspaceIndex( dets[0] ); } catch (Mantid::Kernel::Exception::NotFoundError &) { isDataEmpty = true; // Detector doesn't have a workspace index relating to it } } if ( isDataEmpty ) { x.clear(); y.clear(); return; } // find the bins inside the integration range size_t imin,imax; getBinMinMaxIndex(wi,imin,imax); Mantid::API::MatrixWorkspace_const_sptr ws = getWorkspace(); const Mantid::MantidVec& X = ws->readX(wi); x.assign(X.begin() + imin, X.begin() + imax); if ( ws->isHistogramData() ) { // calculate the bin centres std::transform(x.begin(),x.end(),X.begin() + imin + 1,x.begin(),std::plus<double>()); std::transform(x.begin(),x.end(),x.begin(),std::bind2nd(std::divides<double>(),2.0)); } y.resize(x.size(),0); // sum the spectra foreach(int id, dets) { try { size_t index = getWorkspaceIndex( id ); const Mantid::MantidVec& Y = ws->readY(index); std::transform(y.begin(),y.end(),Y.begin() + imin,y.begin(),std::plus<double>()); } catch (Mantid::Kernel::Exception::NotFoundError &) { continue; // Detector doesn't have a workspace index relating to it } } }
DataObjects::TableWorkspace_sptr ConvertToMDParent::runPreprocessDetectorsToMDChildUpdatingMasks(Mantid::API::MatrixWorkspace_const_sptr InWS2D, const std::string &OutWSName,const std::string &dEModeRequested,Kernel::DeltaEMode::Type &Emode) { // prospective result DataObjects::TableWorkspace_sptr TargTableWS; // if input workspace does not exist in analysis data service, we have to add it there to work with the Child Algorithm std::string InWSName = InWS2D->getName(); if(!API::AnalysisDataService::Instance().doesExist(InWSName)) { throw std::runtime_error("Can not retrieve input matrix workspace "+InWSName+" from the analysis data service"); } Mantid::API::Algorithm_sptr childAlg = createChildAlgorithm("PreprocessDetectorsToMD",0.,1.); if(!childAlg)throw(std::runtime_error("Can not create child ChildAlgorithm to preprocess detectors")); childAlg->setProperty("InputWorkspace",InWSName); childAlg->setProperty("OutputWorkspace",OutWSName); childAlg->setProperty("GetMaskState",true); childAlg->setProperty("UpdateMasksInfo",true); childAlg->setProperty("OutputWorkspace",OutWSName); // check and get energy conversion mode to define additional ChildAlgorithm parameters Emode = Kernel::DeltaEMode().fromString(dEModeRequested); if(Emode == Kernel::DeltaEMode::Indirect) childAlg->setProperty("GetEFixed",true); childAlg->execute(); if(!childAlg->isExecuted())throw(std::runtime_error("Can not properly execute child algorithm PreprocessDetectorsToMD")); TargTableWS = childAlg->getProperty("OutputWorkspace"); if(!TargTableWS)throw(std::runtime_error("Can not retrieve results of child algorithm PreprocessDetectorsToMD")); return TargTableWS; }
/** function extracts the coordinates from additional workspace properties and *places them to proper position within * the vector of MD coordinates for the particular workspace. * * @param inWS2D -- input workspace * @param dimPropertyNames -- names of properties which should be treated as *dimensions * @param AddCoord -- * * @return AddCoord -- vector of additional coordinates (derived from WS *properties) for current multidimensional event */ void MDWSDescription::fillAddProperties( Mantid::API::MatrixWorkspace_const_sptr inWS2D, const std::vector<std::string> &dimPropertyNames, std::vector<coord_t> &AddCoord) { size_t nDimPropNames = dimPropertyNames.size(); if (AddCoord.size() != nDimPropNames) AddCoord.resize(nDimPropNames); for (size_t i = 0; i < nDimPropNames; i++) { // HACK: A METHOD, Which converts TSP into value, correspondent to time // scale of matrix workspace has to be developed and deployed! Kernel::Property *pProperty = (inWS2D->run().getProperty(dimPropertyNames[i])); Kernel::TimeSeriesProperty<double> *run_property = dynamic_cast<Kernel::TimeSeriesProperty<double> *>(pProperty); if (run_property) { AddCoord[i] = coord_t(run_property->firstValue()); } else { // e.g Ei can be a property and dimension Kernel::PropertyWithValue<double> *proc_property = dynamic_cast<Kernel::PropertyWithValue<double> *>(pProperty); if (!proc_property) { std::string ERR = " Can not interpret property, used as dimension.\n Property: " + dimPropertyNames[i] + " is neither a time series (run) property " "nor a property with value<double>"; throw(std::invalid_argument(ERR)); } AddCoord[i] = coord_t(*(proc_property)); } } }
/// function checks if source workspace still has information about detectors. Some ws (like rebinned one) do not have this information any more. bool PreprocessDetectorsToMD::isDetInfoLost(Mantid::API::MatrixWorkspace_const_sptr inWS2D)const { auto pYAxis = dynamic_cast<API::NumericAxis *>(inWS2D->getAxis(1)); // if this is numeric axis, then the detector's information has been lost: if(pYAxis) return true; return false; }
/** * Find all of the spectra in the workspace that have width data * * @param ws :: The workspace to search */ void JumpFit::findAllWidths(Mantid::API::MatrixWorkspace_const_sptr ws) { m_uiForm.cbWidth->clear(); m_spectraList.clear(); for (size_t i = 0; i < ws->getNumberHistograms(); ++i) { auto axis = dynamic_cast<Mantid::API::TextAxis*>(ws->getAxis(1)); if(!axis) return; std::string title = axis->label(i); //check if the axis labels indicate this spectrum is width data size_t qLinesWidthIndex = title.find(".Width"); size_t convFitWidthIndex = title.find(".FWHM"); bool qLinesWidth = qLinesWidthIndex != std::string::npos; bool convFitWidth = convFitWidthIndex != std::string::npos; //if we get a match, add this spectrum to the combobox if(convFitWidth || qLinesWidth) { std::string cbItemName = ""; size_t substrIndex = 0; if (qLinesWidth) { substrIndex = qLinesWidthIndex; } else if (convFitWidth) { substrIndex = convFitWidthIndex; } cbItemName = title.substr(0, substrIndex); m_spectraList[cbItemName] = static_cast<int>(i); m_uiForm.cbWidth->addItem(QString(cbItemName.c_str())); //display widths f1.f1, f2.f1 and f2.f2 if (m_uiForm.cbWidth->count() == 3) { return; } } } }
void InstrumentWindowPickTab::getBinMinMaxIndex(size_t wi,size_t& imin, size_t& imax) { InstrumentActor* instrActor = m_instrWindow->getInstrumentActor(); Mantid::API::MatrixWorkspace_const_sptr ws = instrActor->getWorkspace(); const Mantid::MantidVec& x = ws->readX(wi); if (instrActor->wholeRange()) { imin = 0; imax = x.size() - 1; } else { Mantid::MantidVec::const_iterator x_begin = std::lower_bound(x.begin(),x.end(),instrActor->minBinValue()); Mantid::MantidVec::const_iterator x_end = std::lower_bound(x.begin(),x.end(),instrActor->maxBinValue()); imin = static_cast<size_t>(x_begin - x.begin()); imax = static_cast<size_t>(x_end - x.begin()) - 1; } }
/** * Sum counts in detectors for purposes of rough plotting against the units on the x-axis. * Checks (approximately) if the workspace is ragged or not and uses the appropriate summation * method. * * @param dets :: A list of detector IDs to sum. * @param x :: (output) Time of flight values (or whatever values the x axis has) to plot against. * @param y :: (output) The sums of the counts for each bin. * @param size :: (optional input) Size of the output vectors. If not given it will be determined automatically. */ void InstrumentActor::sumDetectors(QList<int> &dets, std::vector<double> &x, std::vector<double> &y, size_t size) const { Mantid::API::MatrixWorkspace_const_sptr ws = getWorkspace(); if ( size > ws->blocksize() || size == 0 ) { size = ws->blocksize(); } if ( m_ragged ) { // could be slower than uniform sumDetectorsRagged( dets, x, y, size ); } else { // should be faster than ragged sumDetectorsUniform( dets, x, y ); } }
std::tuple<double, double, double> EnggDiffFittingModel::getDifcDifaTzero( Mantid::API::MatrixWorkspace_const_sptr ws) { const auto run = ws->run(); const auto difc = run.getPropertyValueAsType<double>("difc"); const auto difa = run.getPropertyValueAsType<double>("difa"); const auto tzero = run.getPropertyValueAsType<double>("tzero"); return std::tuple<double, double, double>(difc, difa, tzero); }
QMultiMap<QString,std::set<int> > MantidWSIndexDialog::getPlots() const { // Map of workspace names to set of indices to be plotted. QMultiMap<QString,std::set<int> > plots; // If the user typed in the wsField ... if(m_wsIndexChoice.getList().size() > 0) { for(int i = 0; i < m_wsNames.size(); i++) { std::set<int> intSet = m_wsIndexChoice.getIntSet(); plots.insert(m_wsNames[i],intSet); } } // Else if the user typed in the spectraField ... else if(m_spectraIdChoice.getList().size() > 0) { for(int i = 0; i < m_wsNames.size(); i++) { // Convert the spectra choices of the user into workspace indices for us to use. Mantid::API::MatrixWorkspace_const_sptr ws = boost::dynamic_pointer_cast<const Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(m_wsNames[i].toStdString())); if ( NULL == ws ) continue; Mantid::spec2index_map *spec2index = ws->getSpectrumToWorkspaceIndexMap(); std::set<int> origSet = m_spectraIdChoice.getIntSet(); std::set<int>::iterator it = origSet.begin(); std::set<int> convertedSet; for( ; it != origSet.end(); ++it) { int origInt = (*it); int convertedInt = static_cast<int>(spec2index->find(origInt)->second); convertedSet.insert(convertedInt); } plots.insert(m_wsNames[i],convertedSet); } } return plots; }
/** * Plot data for a detector. * @param detid :: ID of the detector to be plotted. */ void InstrumentWindowPickTab::plotSingle(int detid) { m_plot->clearLabels(); InstrumentActor* instrActor = m_instrWindow->getInstrumentActor(); Mantid::API::MatrixWorkspace_const_sptr ws = instrActor->getWorkspace(); size_t wi; try { wi = instrActor->getWorkspaceIndex(detid); } catch (Mantid::Kernel::Exception::NotFoundError) { return; // Detector doesn't have a workspace index relating to it } // get the data const Mantid::MantidVec& x = ws->readX(wi); const Mantid::MantidVec& y = ws->readY(wi); // find min and max for x size_t imin,imax; getBinMinMaxIndex(wi,imin,imax); Mantid::MantidVec::const_iterator y_begin = y.begin() + imin; Mantid::MantidVec::const_iterator y_end = y.begin() + imax; m_plot->setXScale(x[imin],x[imax]); // fins min and max for y Mantid::MantidVec::const_iterator min_it = std::min_element(y_begin,y_end); Mantid::MantidVec::const_iterator max_it = std::max_element(y_begin,y_end); // set the data m_plot->setData(&x[0],&y[0],static_cast<int>(y.size())); m_plot->setYScale(*min_it,*max_it); // find any markers ProjectionSurface* surface = mInstrumentDisplay->getSurface(); if (surface) { QList<PeakMarker2D*> markers = surface->getMarkersWithID(detid); foreach(PeakMarker2D* marker,markers) { m_plot->addLabel(new PeakLabel(marker)); //std::cerr << marker->getLabel().toStdString() << std::endl; } }
/** * Find the offsets in the spectrum's x vector of the bounds of integration. * @param wi :: The works[ace index of the spectrum. * @param imin :: Index of the lower bound: x_min == readX(wi)[imin] * @param imax :: Index of the upper bound: x_max == readX(wi)[imax] */ void InstrumentActor::getBinMinMaxIndex( size_t wi, size_t& imin, size_t& imax ) const { Mantid::API::MatrixWorkspace_const_sptr ws = getWorkspace(); const Mantid::MantidVec& x = ws->readX(wi); Mantid::MantidVec::const_iterator x_begin = x.begin(); Mantid::MantidVec::const_iterator x_end = x.end(); if (x_begin == x_end) { throw std::runtime_error("No bins found to plot"); } if (ws->isHistogramData()) { --x_end; } if ( wholeRange() ) { imin = 0; imax = static_cast<size_t>(x_end - x_begin); } else { Mantid::MantidVec::const_iterator x_from = std::lower_bound( x_begin, x_end, minBinValue() ); Mantid::MantidVec::const_iterator x_to = std::upper_bound( x_begin, x_end, maxBinValue() ); imin = static_cast<size_t>(x_from - x_begin); imax = static_cast<size_t>(x_to - x_begin); if (imax <= imin) { if (x_from == x_end) { --x_from; x_to = x_end; } else { x_to = x_from + 1; } imin = static_cast<size_t>(x_from - x_begin); imax = static_cast<size_t>(x_to - x_begin); } } }
/** * Performs centre-point rebinning and produces an MDWorkspace * @param inputWs : The workspace you wish to perform centre-point rebinning on. * @param boxController : controls how the MDWorkspace will be split * @param frame: the md frame for the two MDHistoDimensions * @returns An MDWorkspace based on centre-point rebinning of the inputWS */ Mantid::API::IMDEventWorkspace_sptr ReflectometryTransform::executeMD( Mantid::API::MatrixWorkspace_const_sptr inputWs, BoxController_sptr boxController, Mantid::Geometry::MDFrame_uptr frame) const { auto dim0 = boost::make_shared<MDHistoDimension>( m_d0Label, m_d0ID, *frame, static_cast<Mantid::coord_t>(m_d0Min), static_cast<Mantid::coord_t>(m_d0Max), m_d0NumBins); auto dim1 = boost::make_shared<MDHistoDimension>( m_d1Label, m_d1ID, *frame, static_cast<Mantid::coord_t>(m_d1Min), static_cast<Mantid::coord_t>(m_d1Max), m_d1NumBins); auto ws = createMDWorkspace(dim0, dim1, boxController); auto spectraAxis = inputWs->getAxis(1); for (size_t index = 0; index < inputWs->getNumberHistograms(); ++index) { auto counts = inputWs->readY(index); auto wavelengths = inputWs->readX(index); auto errors = inputWs->readE(index); const size_t nInputBins = wavelengths.size() - 1; const double theta_final = spectraAxis->getValue(index); m_calculator->setThetaFinal(theta_final); // Loop over all bins in spectra for (size_t binIndex = 0; binIndex < nInputBins; ++binIndex) { const double &wavelength = 0.5 * (wavelengths[binIndex] + wavelengths[binIndex + 1]); double _d0 = m_calculator->calculateDim0(wavelength); double _d1 = m_calculator->calculateDim1(wavelength); double centers[2] = {_d0, _d1}; ws->addEvent(MDLeanEvent<2>(float(counts[binIndex]), float(errors[binIndex] * errors[binIndex]), centers)); } } ws->splitAllIfNeeded(nullptr); ws->refreshCache(); return ws; }
void Elwin::setDefaultSampleLog(Mantid::API::MatrixWorkspace_const_sptr ws) { auto inst = ws->getInstrument(); // Set sample environment log name auto log = inst->getStringParameter("Workflow.SE-log"); QString logName("sample"); if (log.size() > 0) { logName = QString::fromStdString(log[0]); } m_uiForm.leLogName->setText(logName); // Set sample environment log value auto logval = inst->getStringParameter("Workflow.SE-log-value"); if (logval.size() > 0) { auto logValue = QString::fromStdString(logval[0]); int index = m_uiForm.leLogValue->findText(logValue); if (index >= 0) { m_uiForm.leLogValue->setCurrentIndex(index); } } }
/** * Checks the workspace's intrument for a resolution parameter to use as * a default for the energy range on the mini plot * * @param ws :: Pointer to the workspace to use * @param res :: The retrieved values for the resolution parameter (if one was *found) */ bool IndirectTab::getResolutionRangeFromWs( Mantid::API::MatrixWorkspace_const_sptr ws, QPair<double, double> &res) { auto inst = ws->getInstrument(); auto analyser = inst->getStringParameter("analyser"); if (analyser.size() > 0) { auto comp = inst->getComponentByName(analyser[0]); if (comp) { auto params = comp->getNumberParameter("resolution", true); // set the default instrument resolution if (params.size() > 0) { res = qMakePair(-params[0], params[0]); return true; } } } return false; }
Mantid::API::ITableWorkspace_sptr EnggDiffFittingModel::createCalibrationParamsTable( Mantid::API::MatrixWorkspace_const_sptr inputWS) { double difc, difa, tzero; std::tie(difc, difa, tzero) = getDifcDifaTzero(inputWS); auto calibrationParamsTable = Mantid::API::WorkspaceFactory::Instance().createTable(); calibrationParamsTable->addColumn("int", "detid"); calibrationParamsTable->addColumn("double", "difc"); calibrationParamsTable->addColumn("double", "difa"); calibrationParamsTable->addColumn("double", "tzero"); Mantid::API::TableRow row = calibrationParamsTable->appendRow(); const auto &spectrum = inputWS->getSpectrum(0); Mantid::detid_t detID = *(spectrum.getDetectorIDs().cbegin()); row << detID << difc << difa << tzero; return calibrationParamsTable; }
void Elwin::setDefaultResolution(Mantid::API::MatrixWorkspace_const_sptr ws) { auto inst = ws->getInstrument(); auto analyser = inst->getStringParameter("analyser"); if(analyser.size() > 0) { auto comp = inst->getComponentByName(analyser[0]); auto params = comp->getNumberParameter("resolution", true); //set the default instrument resolution if(params.size() > 0) { double res = params[0]; m_dblManager->setValue(m_properties["IntegrationStart"], -res); m_dblManager->setValue(m_properties["IntegrationEnd"], res); m_dblManager->setValue(m_properties["BackgroundStart"], -10*res); m_dblManager->setValue(m_properties["BackgroundEnd"], -9*res); } } }
MantidMatrix::MantidMatrix(Mantid::API::MatrixWorkspace_const_sptr ws, QWidget *parent, const QString &label, const QString &name, int start, int end) : MdiSubWindow(parent, label, name, 0), WorkspaceObserver(), m_workspace(ws), y_start(0.0), y_end(0.0), m_histogram(false), m_min(0), m_max(0), m_are_min_max_set(false), m_boundingRect(), m_strName(name.toStdString()), m_selectedRows(), m_selectedCols() { m_workspace = ws; setup(ws, start, end); setWindowTitle(name); setName(name); m_modelY = new MantidMatrixModel(this, ws.get(), m_rows, m_cols, m_startRow, MantidMatrixModel::Y); m_table_viewY = new QTableView(); connectTableView(m_table_viewY, m_modelY); setColumnsWidth(0, MantidPreferences::MantidMatrixColumnWidthY()); setNumberFormat(0, MantidPreferences::MantidMatrixNumberFormatY(), MantidPreferences::MantidMatrixNumberPrecisionY()); m_modelX = new MantidMatrixModel(this, ws.get(), m_rows, m_cols, m_startRow, MantidMatrixModel::X); m_table_viewX = new QTableView(); connectTableView(m_table_viewX, m_modelX); setColumnsWidth(1, MantidPreferences::MantidMatrixColumnWidthX()); setNumberFormat(1, MantidPreferences::MantidMatrixNumberFormatX(), MantidPreferences::MantidMatrixNumberPrecisionX()); m_modelE = new MantidMatrixModel(this, ws.get(), m_rows, m_cols, m_startRow, MantidMatrixModel::E); m_table_viewE = new QTableView(); connectTableView(m_table_viewE, m_modelE); setColumnsWidth(2, MantidPreferences::MantidMatrixColumnWidthE()); setNumberFormat(2, MantidPreferences::MantidMatrixNumberFormatE(), MantidPreferences::MantidMatrixNumberPrecisionE()); m_YTabLabel = QString("Y values"); m_XTabLabel = QString("X values"); m_ETabLabel = QString("Errors"); m_tabs = new QTabWidget(this); m_tabs->insertTab(0, m_table_viewY, m_YTabLabel); m_tabs->insertTab(1, m_table_viewX, m_XTabLabel); m_tabs->insertTab(2, m_table_viewE, m_ETabLabel); setWidget(m_tabs); // for synchronizing the views // index is zero for the defualt view m_PrevIndex = 0; // install event filter on these objects m_table_viewY->installEventFilter(this); m_table_viewX->installEventFilter(this); m_table_viewE->installEventFilter(this); connect(m_tabs, SIGNAL(currentChanged(int)), this, SLOT(viewChanged(int))); setGeometry(50, 50, qMin(5, numCols()) * m_table_viewY->horizontalHeader()->sectionSize(0) + 55, (qMin(10, numRows()) + 1) * m_table_viewY->verticalHeader()->sectionSize(0) + 100); // Add an extension for the DX component if required if (ws->hasDx(0)) { addMantidMatrixTabExtension(MantidMatrixModel::DX); } observeAfterReplace(); observePreDelete(); observeADSClear(); connect(this, SIGNAL(needWorkspaceChange(Mantid::API::MatrixWorkspace_sptr)), this, SLOT(changeWorkspace(Mantid::API::MatrixWorkspace_sptr))); connect(this, SIGNAL(needToClose()), this, SLOT(closeMatrix())); connect(this, SIGNAL(closedWindow(MdiSubWindow *)), this, SLOT(selfClosed(MdiSubWindow *))); confirmClose(false); }
/** * @param g :: The Graph widget which will display the curve * @param distr :: True for a distribution * @param style :: The curve type to use */ void MantidMatrixCurve::init(Graph *g, bool distr, GraphOptions::CurveType style) { // Will throw if name not found but return NULL ptr if the type is incorrect MatrixWorkspace_const_sptr workspace = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( m_wsName.toStdString()); if (!workspace) // The respective *Data classes will check for index validity { std::stringstream ss; ss << "Workspace named '" << m_wsName.toStdString() << "' found but it is not a MatrixWorkspace. ID='" << AnalysisDataService::Instance().retrieve(m_wsName.toStdString())->id() << "'"; throw std::invalid_argument(ss.str()); } // Set the curve name if it the non-naming constructor was called if (this->title().isEmpty()) { // If there's only one spectrum in the workspace, title is simply workspace // name if (workspace->getNumberHistograms() == 1) this->setTitle(m_wsName); else this->setTitle(createCurveName(workspace)); } Mantid::API::MatrixWorkspace_const_sptr matrixWS = boost::dynamic_pointer_cast<const Mantid::API::MatrixWorkspace>( workspace); // we need to censor the data if there is a log scale because it can't deal // with negative values, only the y-axis has been found to be problem so far const bool log = g->isLog(QwtPlot::yLeft); // Y units are the same for both spectrum and bin plots, e.g. counts m_yUnits.reset(new Mantid::Kernel::Units::Label(matrixWS->YUnit(), matrixWS->YUnitLabel())); if (m_indexType == Spectrum) // Spectrum plot { QwtWorkspaceSpectrumData data(*matrixWS, m_index, log, distr); setData(data); // For spectrum plots, X axis are actual X axis, e.g. TOF m_xUnits = matrixWS->getAxis(0)->unit(); } else // Bin plot { QwtWorkspaceBinData data(*matrixWS, m_index, log); setData(data); // For bin plots, X axis are "spectra axis", e.g. spectra numbers m_xUnits = matrixWS->getAxis(1)->unit(); } if (!m_xUnits) { m_xUnits.reset(new Mantid::Kernel::Units::Empty()); } int lineWidth = 1; MultiLayer *ml = dynamic_cast<MultiLayer *>(g->parent()->parent()->parent()); if (ml && (style == GraphOptions::Unspecified || ml->applicationWindow()->applyCurveStyleToMantid)) { applyStyleChoice(style, ml, lineWidth); } else if (matrixWS->isHistogramData() && !matrixWS->isDistribution()) { setStyle(QwtPlotCurve::Steps); setCurveAttribute( Inverted, true); // this is the Steps style modifier that makes horizontal steps } else { setStyle(QwtPlotCurve::Lines); } g->insertCurve(this, lineWidth); // set the option to draw all error bars from the global settings if (hasErrorBars()) { setErrorBars(true, g->multiLayer()->applicationWindow()->drawAllErrors); } // Initialise error bar colour to match curve colour m_errorSettings->m_color = pen().color(); m_errorSettings->setWidth(pen().widthF()); connect(g, SIGNAL(axisScaleChanged(int, bool)), this, SLOT(axisScaleChanged(int, bool))); observePostDelete(); connect(this, SIGNAL(resetData(const QString &)), this, SLOT(dataReset(const QString &))); observeAfterReplace(); observeADSClear(); }
/**The method responsible for analyzing input workspace parameters and preprocessing detectors positions into reciprocal space * * @param InWS2D -- input Matrix workspace with defined instrument * @param dEModeRequested -- energy conversion mode (direct/indirect/elastic) * @param updateMasks -- if full detector positions calculations or just update masking requested * @param OutWSName -- the name for the preprocessed detectors workspace to have in the analysis data service * * @return shared pointer to the workspace with preprocessed detectors information. */ DataObjects::TableWorkspace_const_sptr ConvertToMDParent::preprocessDetectorsPositions( Mantid::API::MatrixWorkspace_const_sptr InWS2D,const std::string &dEModeRequested, bool updateMasks, const std::string & OutWSName) { DataObjects::TableWorkspace_sptr TargTableWS; Kernel::DeltaEMode::Type Emode; // Do we need to reuse output workspace bool storeInDataService(true); std::string tOutWSName(OutWSName); if(tOutWSName=="-"||tOutWSName.empty()) // TargTableWS is recalculated each time; { storeInDataService = false; tOutWSName = "ServiceTableWS"; // TODO: should be hidden? } else { storeInDataService = true; } // if output workspace exists in dataservice, we may try to use it if(storeInDataService && API::AnalysisDataService::Instance().doesExist(tOutWSName) ) { TargTableWS = API::AnalysisDataService::Instance().retrieveWS<DataObjects::TableWorkspace>(tOutWSName); // get number of all histograms (may be masked or invalid) size_t nHist = InWS2D->getNumberHistograms(); size_t nDetMap=TargTableWS->rowCount(); if(nHist==nDetMap) { // let's take at least some precaution to ensure that instrument have not changed std::string currentWSInstrumentName = InWS2D->getInstrument()->getName(); std::string oldInstrName = TargTableWS->getLogs()->getPropertyValueAsType<std::string>("InstrumentName"); if(oldInstrName==currentWSInstrumentName) { if(!updateMasks) return TargTableWS; //Target workspace with preprocessed detectors exists and seems is correct one. // We still need to update masked detectors information TargTableWS = this->runPreprocessDetectorsToMDChildUpdatingMasks(InWS2D,tOutWSName,dEModeRequested,Emode); return TargTableWS; } } else // there is a workspace in the data service with the same name but this ws is not suitable as target for this algorithm. { // Should delete this WS from the dataservice API::AnalysisDataService::Instance().remove(tOutWSName); } } // No result found in analysis data service or the result is unsatisfactory. Try to calculate target workspace. TargTableWS =this->runPreprocessDetectorsToMDChildUpdatingMasks(InWS2D,tOutWSName,dEModeRequested,Emode); if(storeInDataService) API::AnalysisDataService::Instance().addOrReplace(tOutWSName,TargTableWS); // else // TargTableWS->setName(OutWSName); // check if we got what we wanted: // in direct or indirect mode input ws has to have input energy if(Emode==Kernel::DeltaEMode::Direct||Emode==Kernel::DeltaEMode::Indirect) { double m_Ei = TargTableWS->getLogs()->getPropertyValueAsType<double>("Ei"); if(isNaN(m_Ei)) { // Direct mode needs Ei if(Emode==Kernel::DeltaEMode::Direct)throw(std::invalid_argument("Input neutron's energy has to be defined in inelastic mode ")); // Do we have at least something for Indirect? float *eFixed = TargTableWS->getColDataArray<float>("eFixed"); if(!eFixed) throw(std::invalid_argument("Input neutron's energy has to be defined in inelastic mode ")); uint32_t NDetectors = TargTableWS->getLogs()->getPropertyValueAsType<uint32_t>("ActualDetectorsNum"); for(uint32_t i=0;i<NDetectors;i++) if(isNaN(*(eFixed+i)))throw(std::invalid_argument("Undefined eFixed energy for detector N: "+boost::lexical_cast<std::string>(i))); } } return TargTableWS; }
/** * Sum counts in detectors for purposes of rough plotting against the units on the x-axis. * Assumes that all spectra have different x vectors. * * @param dets :: A list of detector IDs to sum. * @param x :: (output) Time of flight values (or whatever values the x axis has) to plot against. * @param y :: (output) The sums of the counts for each bin. * @param size :: (input) Size of the output vectors. */ void InstrumentActor::sumDetectorsRagged(QList<int> &dets, std::vector<double> &x, std::vector<double> &y, size_t size) const { if ( dets.isEmpty() || size == 0 ) { x.clear(); y.clear(); return; } Mantid::API::MatrixWorkspace_const_sptr ws = getWorkspace(); // create a workspace to hold the data from the selected detectors Mantid::API::MatrixWorkspace_sptr dws = Mantid::API::WorkspaceFactory::Instance().create(ws,dets.size()); // x-axis limits double xStart = maxBinValue(); double xEnd = minBinValue(); size_t nSpec = 0; // number of actual spectra to add // fill in the temp workspace with the data from the detectors foreach(int id, dets) { try { size_t index = getWorkspaceIndex( id ); dws->dataX(nSpec) = ws->readX(index); dws->dataY(nSpec) = ws->readY(index); dws->dataE(nSpec) = ws->readE(index); double xmin = dws->readX(nSpec).front(); double xmax = dws->readX(nSpec).back(); if ( xmin < xStart ) { xStart = xmin; } if ( xmax > xEnd ) { xEnd = xmax; } ++nSpec; } catch (Mantid::Kernel::Exception::NotFoundError &) { continue; // Detector doesn't have a workspace index relating to it } } if ( nSpec == 0 ) { x.clear(); y.clear(); return; } // limits should exceed the integration range if ( xStart < minBinValue() ) { xStart = minBinValue(); } if ( xEnd > maxBinValue() ) { xEnd = maxBinValue(); } double dx = (xEnd - xStart) / static_cast<double>(size - 1); std::string params = QString("%1,%2,%3").arg(xStart).arg(dx).arg(xEnd).toStdString(); std::string outName = "_TMP_sumDetectorsRagged"; try { // rebin all spectra to the same binning Mantid::API::IAlgorithm * alg = Mantid::API::FrameworkManager::Instance().createAlgorithm("Rebin",-1); alg->setProperty( "InputWorkspace", dws ); alg->setPropertyValue( "OutputWorkspace", outName ); alg->setPropertyValue( "Params", params ); alg->execute(); ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(outName)); Mantid::API::AnalysisDataService::Instance().remove( outName ); x = ws->readX(0); y = ws->readY(0); // add the spectra for(size_t i = 0; i < nSpec; ++i) { const Mantid::MantidVec& Y = ws->readY(i); std::transform( y.begin(), y.end(), Y.begin(), y.begin(), std::plus<double>() ); } } catch(std::invalid_argument&) { // wrong Params for any reason x.resize(size,(xEnd + xStart)/2); y.resize(size,0.0); } }