/** Calculate and show the full (integrated) line, using the latest * integrated workspace. The apply() method must have been called * before calling this. */ void LineViewer::showFull() { if (!m_sliceWS) return; MatrixWorkspace_const_sptr sliceMatrix = boost::dynamic_pointer_cast<const MatrixWorkspace>(m_sliceWS); if (sliceMatrix) { MantidQwtMatrixWorkspaceData curveData(sliceMatrix, 0, false /*not logScale*/); m_fullCurve->setData(curveData); Unit_const_sptr unit = sliceMatrix->getAxis(0)->unit(); std::string title = unit->caption() + " (" + unit->label() + ")"; m_plot->setAxisTitle( QwtPlot::xBottom, QString::fromStdString(title));; title = sliceMatrix->YUnit() + " (" + sliceMatrix->YUnitLabel() + ")"; m_plot->setAxisTitle( QwtPlot::yLeft, QString::fromStdString(title));; } else { MantidQwtIMDWorkspaceData curveData(m_sliceWS, false, VMD(), VMD(), m_lineOptions->getNormalization()); curveData.setPreviewMode(false); curveData.setPlotAxisChoice(m_lineOptions->getPlotAxis()); m_fullCurve->setData(curveData); m_plot->setAxisTitle( QwtPlot::xBottom, QString::fromStdString( curveData.getXAxisLabel() ));; m_plot->setAxisTitle( QwtPlot::yLeft, QString::fromStdString( curveData.getYAxisLabel() ));; } if (m_previewCurve->isVisible()) { m_previewCurve->setVisible(false); m_previewCurve->detach(); m_fullCurve->attach(m_plot); } m_fullCurve->setVisible(true); m_plot->replot(); m_plot->setTitle("Integrated Line Plot"); }
/** Check whether the spectra for the given workspaces are the same. @param ws1 : First workspace to compare @param ws2 : Second workspace to compare against exception. Otherwise a warning is generated. */ void ReflectometryReductionOne2::verifySpectrumMaps( MatrixWorkspace_const_sptr ws1, MatrixWorkspace_const_sptr ws2) { bool mismatch = false; // Check that the number of histograms is the same if (ws1->getNumberHistograms() != ws2->getNumberHistograms()) { mismatch = true; } // Check that the spectrum numbers match for each histogram if (!mismatch) { for (size_t i = 0; i < ws1->getNumberHistograms(); ++i) { if (ws1->indexInfo().spectrumNumber(i) != ws2->indexInfo().spectrumNumber(i)) { mismatch = true; break; } } } // Handle if error if (mismatch) { const std::string message = "Spectrum maps between workspaces do NOT match up."; g_log.warning(message); } }
void ALCDataLoadingPresenter::updateAvailableLogs() { Workspace_sptr loadedWs; try //... to load the first run { IAlgorithm_sptr load = AlgorithmManager::Instance().create("LoadMuonNexus"); load->setChild(true); // Don't want workspaces in the ADS load->setProperty("Filename", m_view->firstRun()); // Don't load any data - we need logs only load->setPropertyValue("SpectrumMin","0"); load->setPropertyValue("SpectrumMax","0"); load->setPropertyValue("OutputWorkspace", "__NotUsed"); load->execute(); loadedWs = load->getProperty("OutputWorkspace"); } catch(...) { m_view->setAvailableLogs(std::vector<std::string>()); // Empty logs list return; } MatrixWorkspace_const_sptr ws = MuonAnalysisHelper::firstPeriod(loadedWs); std::vector<std::string> logs; const auto& properties = ws->run().getProperties(); for(auto it = properties.begin(); it != properties.end(); ++it) { logs.push_back((*it)->name()); } m_view->setAvailableLogs(logs); }
/** * Computes the square root of the errors and if the input was a distribution * this divides by the new bin-width * @param outputWS The workspace containing the output data * @param inputWS The input workspace used for testing distribution state */ void Rebin2D::normaliseOutput(MatrixWorkspace_sptr outputWS, MatrixWorkspace_const_sptr inputWS) { //PARALLEL_FOR1(outputWS) for(int64_t i = 0; i < static_cast<int64_t>(outputWS->getNumberHistograms()); ++i) { PARALLEL_START_INTERUPT_REGION MantidVec & outputY = outputWS->dataY(i); MantidVec & outputE = outputWS->dataE(i); for(size_t j = 0; j < outputWS->blocksize(); ++j) { m_progress->report("Calculating errors"); const double binWidth = (outputWS->readX(i)[j+1] - outputWS->readX(i)[j]); double eValue = std::sqrt(outputE[j]); // Don't do this for a RebinnedOutput workspace. The fractions // take care of such things. if( inputWS->isDistribution() && inputWS->id() != "RebinnedOutput") { outputY[j] /= binWidth; eValue /= binWidth; } outputE[j] = eValue; } PARALLEL_END_INTERUPT_REGION } PARALLEL_CHECK_INTERUPT_REGION outputWS->isDistribution(inputWS->isDistribution()); }
/** * Construct a DataSource object around the specifed MatrixWorkspace. * * @param matWs Shared pointer to the matrix workspace being "wrapped" */ MatrixWSDataSource::MatrixWSDataSource( MatrixWorkspace_const_sptr matWs ) : SpectrumDataSource( 0.0, 1.0, 0.0, 1.0, 0, 0 ), m_matWs(matWs), m_emodeHandler(NULL) { m_totalXMin = matWs->getXMin(); m_totalXMax = matWs->getXMax(); m_totalYMin = 0; // Y direction is spectrum index m_totalYMax = (double)matWs->getNumberHistograms(); m_totalRows = matWs->getNumberHistograms(); m_totalCols = 1000000; // Default data resolution m_instrument = m_matWs->getInstrument(); if ( m_instrument ) { m_source = m_instrument->getSource(); if ( !m_source ) { g_log.debug("No SOURCE on instrument in MatrixWorkspace"); } m_sample = m_instrument->getSample(); if ( !m_sample ) { g_log.debug("No SAMPLE on instrument in MatrixWorkspace"); } } else { g_log.debug("No INSTRUMENT on MatrixWorkspace"); } }
/** Create a new instance of the same type of workspace as that given as * argument. * If the optional size parameters are given, the workspace will be initialised * using * those; otherwise it will be initialised to the same size as the parent. * This method should be used when you want to carry over the Workspace data * members * relating to the Instrument, Spectra-Detector Map, Sample & Axes to the new * workspace. * If the workspace is the same size as its parent, then the X data, axes and * mask list are * copied. If its a different size then they are not. * @param parent A shared pointer to the parent workspace * @param NVectors (Optional) The number of vectors/histograms/detectors in * the workspace * @param XLength (Optional) The number of X data points/bin boundaries in * each vector (must all be the same) * @param YLength (Optional) The number of data/error points in each vector * (must all be the same) * @return A shared pointer to the newly created instance * @throw std::out_of_range If invalid (0 or less) size arguments are given * @throw NotFoundException If the class is not registered in the factory */ MatrixWorkspace_sptr WorkspaceFactoryImpl::create(const MatrixWorkspace_const_sptr &parent, size_t NVectors, size_t XLength, size_t YLength) const { bool differentSize(true); // Use the parent sizes if new ones are not specified if (NVectors == size_t(-1)) NVectors = parent->getNumberHistograms(); if (XLength == size_t(-1)) XLength = parent->dataX(0).size(); if (YLength == size_t(-1)) { differentSize = false; YLength = parent->blocksize(); } // If the parent is an EventWorkspace, we want it to spawn a Workspace2D (or // managed variant) as a child std::string id(parent->id()); if (id == "EventWorkspace") id = "Workspace2D"; // Create an 'empty' workspace of the appropriate type and size MatrixWorkspace_sptr ws = create(id, NVectors, XLength, YLength); // Copy over certain parent data members initializeFromParent(parent, ws, differentSize); return ws; }
/** * Execute the algorithm */ void ExtractMasking::exec() { MatrixWorkspace_const_sptr inputWS = getProperty("InputWorkspace"); const int nHist = static_cast<int>(inputWS->getNumberHistograms()); const int xLength(1), yLength(1); // Create a new workspace for the results, copy from the input to ensure that we copy over the instrument and current masking MatrixWorkspace_sptr outputWS = WorkspaceFactory::Instance().create(inputWS, nHist, xLength, yLength); Progress prog(this,0.0,1.0,nHist); MantidVecPtr xValues; xValues.access() = MantidVec(1, 0.0); PARALLEL_FOR2(inputWS, outputWS) for( int i = 0; i < nHist; ++i ) { PARALLEL_START_INTERUPT_REGION // Spectrum in the output workspace ISpectrum * outSpec = outputWS->getSpectrum(i); // Spectrum in the input workspace const ISpectrum * inSpec = inputWS->getSpectrum(i); // Copy X, spectrum number and detector IDs outSpec->setX(xValues); outSpec->copyInfoFrom(*inSpec); IDetector_const_sptr inputDet; bool inputIsMasked(false); try { inputDet = inputWS->getDetector(i); if( inputDet->isMasked() ) { inputIsMasked = true; } } catch(Kernel::Exception::NotFoundError &) { inputIsMasked = false; } if( inputIsMasked ) { outSpec->dataY()[0] = 0.0; outSpec->dataE()[0] = 0.0; } else { outSpec->dataY()[0] = 1.0; outSpec->dataE()[0] = 1.0; } prog.report(); PARALLEL_END_INTERUPT_REGION } PARALLEL_CHECK_INTERUPT_REGION setProperty("OutputWorkspace", outputWS); }
void ALCDataLoadingPresenter::updateAvailableInfo() { Workspace_sptr loadedWs; double firstGoodData = 0, timeZero = 0; try //... to load the first run { IAlgorithm_sptr load = AlgorithmManager::Instance().create("LoadMuonNexus"); load->setChild(true); // Don't want workspaces in the ADS load->setProperty("Filename", m_view->firstRun()); // We need logs only but we have to use LoadMuonNexus // (can't use LoadMuonLogs as not all the logs would be // loaded), so we load the minimum amount of data, i.e., one spectrum load->setPropertyValue("SpectrumMin", "1"); load->setPropertyValue("SpectrumMax", "1"); load->setPropertyValue("OutputWorkspace", "__NotUsed"); load->execute(); loadedWs = load->getProperty("OutputWorkspace"); firstGoodData = load->getProperty("FirstGoodData"); timeZero = load->getProperty("TimeZero"); } catch (...) { m_view->setAvailableLogs(std::vector<std::string>()); // Empty logs list m_view->setAvailablePeriods( std::vector<std::string>()); // Empty period list m_view->setTimeLimits(0, 0); // "Empty" time limits return; } // Set logs MatrixWorkspace_const_sptr ws = MuonAnalysisHelper::firstPeriod(loadedWs); std::vector<std::string> logs; const auto &properties = ws->run().getProperties(); for (auto it = properties.begin(); it != properties.end(); ++it) { logs.push_back((*it)->name()); } m_view->setAvailableLogs(logs); // Set periods size_t numPeriods = MuonAnalysisHelper::numPeriods(loadedWs); std::vector<std::string> periods; for (size_t i = 0; i < numPeriods; i++) { std::stringstream buffer; buffer << i + 1; periods.push_back(buffer.str()); } m_view->setAvailablePeriods(periods); // Set time limits if this is the first data loaded (will both be zero) if (auto timeLimits = m_view->timeRange()) { if (std::abs(timeLimits->first) < 0.0001 && std::abs(timeLimits->second) < 0.0001) { m_view->setTimeLimits(firstGoodData - timeZero, ws->readX(0).back()); } } // Update number of detectors for this new first run m_numDetectors = ws->getInstrument()->getNumberDetectors(); }
/** * Creates QwtData using X and Y values from the workspace spectra. * @param ws :: Workspace with X and Y values to use * @param wsIndex :: Workspace index to use * @return Pointer to created QwtData */ boost::shared_ptr<QwtData> curveDataFromWs(MatrixWorkspace_const_sptr ws, size_t wsIndex) { const double* x = &ws->readX(wsIndex)[0]; const double* y = &ws->readY(wsIndex)[0]; size_t size = ws->blocksize(); return boost::make_shared<QwtArrayData>(x,y,size); }
void SumRowColumn::exec() { // First task is to integrate the input workspace MatrixWorkspace_const_sptr integratedWS = integrateWorkspace(); const size_t numSpec = integratedWS->getNumberHistograms(); // Check number of spectra is 128*128 or 192*192. Print warning if not. if (numSpec != 16384 && numSpec != 36864) { g_log.warning() << "The input workspace has " << numSpec << " spectra." << "This is not 128*128 or 192*192 - did you make a mistake?\n"; } // This is the dimension if all rows/columns are included const int dim = static_cast<int>( std::sqrt(static_cast<double>(numSpec)) ); // Check the column range properties int start = getProperty("HOverVMin"); int end = getProperty("HOverVMax"); if ( isEmpty(start) ) start = 0; if ( isEmpty(end) || end > dim-1 ) end = dim-1; if ( start > end ) { g_log.error("H/V_Min must be less than H/V_Max"); throw std::out_of_range("H/V_Min must be less than H/V_Max"); } MatrixWorkspace_sptr outputWS = WorkspaceFactory::Instance().create(integratedWS,1,dim,dim); // Remove the unit outputWS->getAxis(0)->unit().reset(); // Get references to the vectors for the results MantidVec& X = outputWS->dataX(0); MantidVec& Y = outputWS->dataY(0); // Get the orientation const std::string orientation = getProperty("Orientation"); const bool horizontal = ( orientation=="D_H" ? 1 : 0 ); Progress progress(this,0,1,dim); for (int i = 0; i < dim; ++i) { // Copy X values X[i] = i; // Now loop over calculating Y's for (int j = start; j <= end; ++j) { const int index = ( horizontal ? ( i + j*dim) : ( i*dim + j) ); Y[i] += integratedWS->readY(index)[0]; } } setProperty("OutputWorkspace",outputWS); }
std::map<std::string, std::string> EditInstrumentGeometry::validateInputs() { std::map<std::string, std::string> result; // everything depends on being parallel to the workspace # histo size_t numHist(0); bool hasWorkspacePtr(false); { MatrixWorkspace_const_sptr workspace = getProperty("Workspace"); // this is to guard against WorkspaceGroups // fallthrough is to skip workspace check and make sure if (bool(workspace)) { hasWorkspacePtr = true; numHist = workspace->getNumberHistograms(); } } std::string error; const std::vector<int32_t> specids = this->getProperty("SpectrumIDs"); if (!hasWorkspacePtr) { // use the number of spectra for the number of histograms numHist = specids.size(); // give up if it is empty if (numHist == 0) { return result; } } error = checkValues(specids, numHist); if (!error.empty()) result["SpectrumIDs"] = error; const std::vector<double> l2 = this->getProperty("L2"); error = checkValues(l2, numHist); if (!error.empty()) result["L2"] = error; const std::vector<double> tth = this->getProperty("Polar"); error = checkValues(tth, numHist); if (!error.empty()) result["Polar"] = error; const std::vector<double> phi = this->getProperty("Azimuthal"); error = checkValues(phi, numHist); if (!error.empty()) result["Azimuthal"] = error; const vector<int> detids = getProperty("DetectorIDs"); error = checkValues(detids, numHist); if (!error.empty()) result["DetectorIDs"] = error; // TODO verify that SpectrumIDs, L2, Polar, Azimuthal, and DetectorIDs are // parallel or not specified return result; }
/** Calculate the interpolation of the input points against the spline * * @param inputWorkspace :: The input workspace * @param outputWorkspace :: The output workspace * @param row :: The row of spectra to use */ void SplineInterpolation::calculateSpline( MatrixWorkspace_const_sptr inputWorkspace, MatrixWorkspace_sptr outputWorkspace, int row) const { // setup input parameters const size_t nData = inputWorkspace->y(0).size(); const double *xValues = &(inputWorkspace->x(0)[0]); double *yValues = &(outputWorkspace->mutableY(row)[0]); // calculate the interpolation m_cspline->function1D(yValues, xValues, nData); }
// read the monitors list from the workspace and try to do it once for any // particular ws; bool MonIDPropChanger::monitorIdReader( MatrixWorkspace_const_sptr inputWS) const { // no workspace if (!inputWS) return false; // no instrument Geometry::Instrument_const_sptr pInstr = inputWS->getInstrument(); if (!pInstr) return false; // are these monitors really there? std::vector<detid_t> monitorIDList = pInstr->getMonitors(); { const auto &specInfo = inputWS->spectrumInfo(); std::set<detid_t> idsInWorkspace; size_t i = 0; // Loop over spectra, but finish early if we find everything while (i < specInfo.size() && idsInWorkspace.size() < monitorIDList.size()) { if (specInfo.isMonitor(i)) idsInWorkspace.insert(specInfo.detector(i).getID()); ++i; } monitorIDList = std::vector<detid_t>(idsInWorkspace.begin(), idsInWorkspace.end()); } if (monitorIDList.empty()) { if (iExistingAllowedValues.empty()) { return false; } else { iExistingAllowedValues.clear(); return true; } } // are known values the same as the values we have just identified? if (iExistingAllowedValues.size() != monitorIDList.size()) { iExistingAllowedValues.clear(); iExistingAllowedValues.assign(monitorIDList.begin(), monitorIDList.end()); return true; } // the monitor list has the same size as before. Is it equivalent to the // existing one? bool values_redefined = false; for (size_t i = 0; i < monitorIDList.size(); i++) { if (iExistingAllowedValues[i] != monitorIDList[i]) { values_redefined = true; iExistingAllowedValues[i] = monitorIDList[i]; } } return values_redefined; }
/** Initialise a workspace from its parent * This sets values such as title, instrument, units, sample, spectramap. * This does NOT copy any data. * * @param parent :: the parent workspace * @param child :: the child workspace * @param differentSize :: A flag to indicate if the two workspace will be different sizes */ void WorkspaceFactoryImpl::initializeFromParent(const MatrixWorkspace_const_sptr parent, const MatrixWorkspace_sptr child, const bool differentSize) const { child->setTitle(parent->getTitle()); child->setComment(parent->getComment()); child->setInstrument(parent->getInstrument()); // This call also copies the SHARED POINTER to the parameter map // This call will (should) perform a COPY of the parameter map. child->instrumentParameters(); child->m_sample = parent->m_sample; child->m_run = parent->m_run; child->setYUnit(parent->m_YUnit); child->setYUnitLabel(parent->m_YUnitLabel); child->isDistribution(parent->isDistribution()); // Only copy the axes over if new sizes are not given if ( !differentSize ) { // Only copy mask map if same size for now. Later will need to check continued validity. child->m_masks = parent->m_masks; } // Same number of histograms = copy over the spectra data if (parent->getNumberHistograms() == child->getNumberHistograms()) { for (size_t wi=0; wi<parent->getNumberHistograms(); wi++) { ISpectrum * childSpec = child->getSpectrum(wi); const ISpectrum * parentSpec = parent->getSpectrum(wi); // Copy spectrum number and detector IDs childSpec->copyInfoFrom(*parentSpec); } } // deal with axis for (size_t i = 0; i < parent->m_axes.size(); ++i) { const size_t newAxisLength = child->getAxis(i)->length(); const size_t oldAxisLength = parent->getAxis(i)->length(); if ( !differentSize || newAxisLength == oldAxisLength ) { // Need to delete the existing axis created in init above delete child->m_axes[i]; // Now set to a copy of the parent workspace's axis child->m_axes[i] = parent->m_axes[i]->clone(child.get()); } else { if (! parent->getAxis(i)->isSpectra()) // WHY??? { delete child->m_axes[i]; // Call the 'different length' clone variant child->m_axes[i] = parent->m_axes[i]->clone(newAxisLength,child.get()); } } } return; }
/** * Rebin the input quadrilateral to the output grid * @param inputQ The input polygon * @param inputWS The input workspace containing the input intensity values * @param i The index in the vertical axis direction that inputQ references * @param j The index in the horizontal axis direction that inputQ references * @param outputWS A pointer to the output workspace that accumulates the data * @param verticalAxis A vector containing the output vertical axis bin boundaries */ void Rebin2D::rebinToFractionalOutput(const Geometry::Quadrilateral & inputQ, MatrixWorkspace_const_sptr inputWS, const size_t i, const size_t j, RebinnedOutput_sptr outputWS, const std::vector<double> & verticalAxis) { const MantidVec & X = outputWS->readX(0); size_t qstart(0), qend(verticalAxis.size()-1), en_start(0), en_end(X.size() - 1); if( !getIntersectionRegion(outputWS, verticalAxis, inputQ, qstart, qend, en_start, en_end)) return; for( size_t qi = qstart; qi < qend; ++qi ) { const double vlo = verticalAxis[qi]; const double vhi = verticalAxis[qi+1]; for( size_t ei = en_start; ei < en_end; ++ei ) { const V2D ll(X[ei], vlo); const V2D lr(X[ei+1], vlo); const V2D ur(X[ei+1], vhi); const V2D ul(X[ei], vhi); const Quadrilateral outputQ(ll, lr, ur, ul); double yValue = inputWS->readY(i)[j]; if (boost::math::isnan(yValue)) { continue; } try { ConvexPolygon overlap = intersectionByLaszlo(outputQ, inputQ); const double weight = overlap.area()/inputQ.area(); yValue *= weight; double eValue = inputWS->readE(i)[j] * weight; const double overlapWidth = overlap.largestX() - overlap.smallestX(); // Don't do the overlap removal if already RebinnedOutput. // This wreaks havoc on the data. if(inputWS->isDistribution() && inputWS->id() != "RebinnedOutput") { yValue *= overlapWidth; eValue *= overlapWidth; } eValue *= eValue; PARALLEL_CRITICAL(overlap) { outputWS->dataY(qi)[ei] += yValue; outputWS->dataE(qi)[ei] += eValue; outputWS->dataF(qi)[ei] += weight; } } catch(Geometry::NoIntersectionException &) {} } } }
// calculate time from sample to detector void ModeratorTzeroLinear::calculateTfLi(MatrixWorkspace_const_sptr inputWS, size_t i, double &t_f, double &L_i) { static const double convFact = 1.0e-6 * sqrt(2 * PhysicalConstants::meV / PhysicalConstants::NeutronMass); static const double TfError = -1.0; // signal error when calculating final // time // Get detector position IDetector_const_sptr det; try { det = inputWS->getDetector(i); } catch (Exception::NotFoundError &) { t_f = TfError; return; } if (det->isMonitor()) { L_i = m_instrument->getSource()->getDistance(*det); t_f = 0.0; // t_f=0.0 since there is no sample to detector path } else { IComponent_const_sptr sample = m_instrument->getSample(); try { L_i = m_instrument->getSource()->getDistance(*sample); } catch (Exception::NotFoundError &) { g_log.error("Unable to calculate source-sample distance"); throw Exception::InstrumentDefinitionError( "Unable to calculate source-sample distance", inputWS->getTitle()); } // Get final energy E_f, final velocity v_f std::vector<double> wsProp = det->getNumberParameter("Efixed"); if (!wsProp.empty()) { double E_f = wsProp.at(0); //[E_f]=meV double v_f = convFact * sqrt(E_f); //[v_f]=meter/microsec try { // obtain L_f, calculate t_f double L_f = det->getDistance(*sample); t_f = L_f / v_f; // g_log.debug() << "detector: " << i << " L_f=" << L_f << " t_f=" << // t_f << '\n'; } catch (Exception::NotFoundError &) { g_log.error("Unable to calculate detector-sample distance"); throw Exception::InstrumentDefinitionError( "Unable to calculate detector-sample distance", inputWS->getTitle()); } } else { g_log.debug() << "Efixed not found for detector " << i << '\n'; t_f = TfError; } } } // end of CalculateTf(const MatrixWorkspace_sptr inputWS, size_t i)
/// Executes the algorithm for events void UnaryOperation::execEvent() { g_log.information("Processing event workspace"); const MatrixWorkspace_const_sptr matrixInputWS = getProperty(inputPropName()); // generate the output workspace pointer API::MatrixWorkspace_sptr matrixOutputWS = getProperty(outputPropName()); if (matrixOutputWS != matrixInputWS) { matrixOutputWS = matrixInputWS->clone(); setProperty(outputPropName(), matrixOutputWS); } auto outputWS = boost::dynamic_pointer_cast<EventWorkspace>(matrixOutputWS); // Now fetch any properties defined by concrete algorithm retrieveProperties(); int64_t numHistograms = static_cast<int64_t>(outputWS->getNumberHistograms()); API::Progress prog = API::Progress(this, 0.0, 1.0, numHistograms); PARALLEL_FOR_IF(Kernel::threadSafe(*outputWS)) for (int64_t i = 0; i < numHistograms; ++i) { PARALLEL_START_INTERUPT_REGION // switch to weighted events if needed, and use the appropriate helper // function auto &evlist = outputWS->getSpectrum(i); switch (evlist.getEventType()) { case TOF: // Switch to weights if needed. evlist.switchTo(WEIGHTED); /* no break */ // Fall through case WEIGHTED: unaryOperationEventHelper(evlist.getWeightedEvents()); break; case WEIGHTED_NOTIME: unaryOperationEventHelper(evlist.getWeightedEventsNoTime()); break; } prog.report(); PARALLEL_END_INTERUPT_REGION } PARALLEL_CHECK_INTERUPT_REGION outputWS->clearMRU(); auto inputWS = boost::dynamic_pointer_cast<EventWorkspace>(matrixOutputWS); if (inputWS->getNumberEvents() != outputWS->getNumberEvents()) { g_log.information() << "Number of events has changed!!!\n"; } }
/** Sets the points defining the spline * * @param inputWorkspace :: The input workspace containing the points of the *spline * @param row :: The row of spectra to use */ void SplineInterpolation::setInterpolationPoints( MatrixWorkspace_const_sptr inputWorkspace, const int row) const { const auto &xIn = inputWorkspace->x(row); const auto &yIn = inputWorkspace->y(row); int size = static_cast<int>(xIn.size()); // pass x attributes and y parameters to CubicSpline m_cspline->setAttributeValue("n", size); for (int i = 0; i < size; ++i) { m_cspline->setXAttribute(i, xIn[i]); m_cspline->setParameter(i, yIn[i]); } }
void StepScan::fillPlotVarCombobox( const MatrixWorkspace_const_sptr & ws ) { // Hold the name of the scan index log in a common place const std::string scan_index("scan_index"); // Clear the combobox and immediately re-insert 'scan_index' (so it's the first entry) m_uiForm.plotVariable->clear(); m_uiForm.plotVariable->addItem( QString::fromStdString(scan_index) ); // First check that the provided workspace has the scan_index - complain if it doesn't try { auto scan_index_prop = ws->run().getTimeSeriesProperty<int>(scan_index); if ( scan_index_prop->realSize() < 2 ) { // TODO: This might be mistakenly triggered for live datasets. QMessageBox::warning(this,"scan_index log empty","This data does not appear to be an alignment scan"); return; } } catch ( std::exception& ) { // Old way: ws->run().hasProperty(scan_index) QMessageBox::warning(this,"scan_index log not found","Is this an ADARA-style dataset?"); return; } // This is unfortunately more or less a copy of SumEventsByLogValue::getNumberSeriesLogs // but I want to populate the box before running the algorithm const auto & logs = ws->run().getLogData(); for ( auto log = logs.begin(); log != logs.end(); ++log ) { const std::string logName = (*log)->name(); // Don't add scan_index - that's already there if ( logName == scan_index ) continue; // Try to cast to an ITimeSeriesProperty auto tsp = dynamic_cast<const ITimeSeriesProperty*>(*log); // Move on to the next one if this is not a TSP if ( tsp == NULL ) continue; // Don't keep ones with only one entry if ( tsp->realSize() < 2 ) continue; // Now make sure it's either an int or double tsp, and if so add log to the list if ( dynamic_cast<TimeSeriesProperty<double>* >(*log) || dynamic_cast<TimeSeriesProperty<int>* >(*log)) { m_uiForm.plotVariable->addItem( QString::fromStdString( logName ) ); } } // Now that this has been populated, allow the user to select from it m_uiForm.plotVariable->setEnabled(true); // Now's the time to enable the start button as well m_uiForm.startButton->setEnabled(true); }
double ConvertSpectrumAxis::getEfixed(const Mantid::Geometry::IDetector &detector, MatrixWorkspace_const_sptr inputWS, int emode) const { double efixed(0); double efixedProp = getProperty("Efixed"); if (efixedProp != EMPTY_DBL()) { efixed = efixedProp; g_log.debug() << "Detector: " << detector.getID() << " Efixed: " << efixed << "\n"; } else { if (emode == 1) { if (inputWS->run().hasProperty("Ei")) { Kernel::Property *p = inputWS->run().getProperty("Ei"); Kernel::PropertyWithValue<double> *doublep = dynamic_cast<Kernel::PropertyWithValue<double> *>(p); if (doublep) { efixed = (*doublep)(); } else { efixed = 0.0; g_log.warning() << "Efixed could not be found for detector " << detector.getID() << ", set to 0.0\n"; } } else { efixed = 0.0; g_log.warning() << "Efixed could not be found for detector " << detector.getID() << ", set to 0.0\n"; } } else if (emode == 2) { std::vector<double> efixedVec = detector.getNumberParameter("Efixed"); if (efixedVec.empty()) { int detid = detector.getID(); IDetector_const_sptr detectorSingle = inputWS->getInstrument()->getDetector(detid); efixedVec = detectorSingle->getNumberParameter("Efixed"); } if (!efixedVec.empty()) { efixed = efixedVec.at(0); g_log.debug() << "Detector: " << detector.getID() << " EFixed: " << efixed << "\n"; } else { efixed = 0.0; g_log.warning() << "Efixed could not be found for detector " << detector.getID() << ", set to 0.0\n"; } } } return efixed; }
/** * Determine the minimum and maximum spectra ids. * * @param axis The axis to search through. * @param min The minimum id (output). * @param max The maximum id (output). */ void getMinMax(MatrixWorkspace_const_sptr ws, specid_t& min, specid_t& max) { specid_t temp; size_t length = ws->getNumberHistograms(); // initial values min = max = ws->getSpectrum(0)->getSpectrumNo(); for (size_t i = 0; i < length; i++) { temp = ws->getSpectrum(i)->getSpectrumNo(); // Adjust min/max if (temp < min) min = temp; if (temp > max) max = temp; } }
/** * Search each spectrum for y-values that are less than zero and reset * them to the supplied value. * * @param minWS A workspace of minimum values for each spectra. * @param value Reset negative values in the spectra to this number. * @param wksp The workspace to modify. * @param prog The progress. */ void ResetNegatives::changeNegatives(MatrixWorkspace_const_sptr minWS, const double value, MatrixWorkspace_sptr wksp, Progress &prog) { int64_t nHist = wksp->getNumberHistograms(); PARALLEL_FOR2(minWS, wksp) for (int64_t i = 0; i < nHist; i++) { PARALLEL_START_INTERUPT_REGION if (minWS->readY(i)[0] <= 0.) // quick check to see if there is a reason to bother { MantidVec & y = wksp->dataY(i); for (MantidVec::iterator it = y.begin(); it != y.end(); ++it) { if (*it < 0.) { *it = value; } else *it = fixZero(*it); } } prog.report(); PARALLEL_END_INTERUPT_REGION } PARALLEL_CHECK_INTERUPT_REGION }
/** * Set default background and rebinning properties for a given instument * and analyser * * @param ws :: Mantid workspace containing the loaded instument */ void ISISCalibration::calSetDefaultResolution(MatrixWorkspace_const_sptr ws) { auto inst = ws->getInstrument(); auto analyser = inst->getStringParameter("analyser"); if(analyser.size() > 0) { auto comp = inst->getComponentByName(analyser[0]); if(!comp) return; auto params = comp->getNumberParameter("resolution", true); //Set the default instrument resolution if(params.size() > 0) { double res = params[0]; // Set default rebinning bounds QPair<double, double> peakRange(-res*10, res*10); auto resPeak = m_uiForm.ppResolution->getRangeSelector("ResPeak"); setRangeSelector(resPeak, m_properties["ResELow"], m_properties["ResEHigh"], peakRange); // Set default background bounds QPair<double, double> backgroundRange(-res*9, -res*8); auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground"); setRangeSelector(resBackground, m_properties["ResStart"], m_properties["ResEnd"], backgroundRange); } } }
/* Execute the transformtion. Generates an output IMDEventWorkspace. @return the constructed IMDEventWorkspace following the transformation. @param ws: Input MatrixWorkspace const shared pointer */ IMDEventWorkspace_sptr ReflectometryTransformQxQz::execute(MatrixWorkspace_const_sptr inputWs) const { const size_t nbinsx = 10; const size_t nbinsz = 10; auto ws = boost::make_shared<MDEventWorkspace<MDLeanEvent<2>,2> >(); MDHistoDimension_sptr qxDim = MDHistoDimension_sptr(new MDHistoDimension("Qx","qx","(Ang^-1)", static_cast<Mantid::coord_t>(m_qxMin), static_cast<Mantid::coord_t>(m_qxMax), nbinsx)); MDHistoDimension_sptr qzDim = MDHistoDimension_sptr(new MDHistoDimension("Qz","qz","(Ang^-1)", static_cast<Mantid::coord_t>(m_qzMin), static_cast<Mantid::coord_t>(m_qzMax), nbinsz)); ws->addDimension(qxDim); ws->addDimension(qzDim); // Set some reasonable values for the box controller BoxController_sptr bc = ws->getBoxController(); bc->setSplitInto(2); bc->setSplitThreshold(10); // Initialize the workspace. ws->initialize(); // Start with a MDGridBox. ws->splitBox(); 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_QxCalculation.setThetaFinal(theta_final); m_QzCalculation.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 _qx = m_QxCalculation.execute(wavelength); double _qz = m_QzCalculation.execute(wavelength); double centers[2] = {_qx, _qz}; ws->addEvent(MDLeanEvent<2>(float(counts[binIndex]), float(errors[binIndex]*errors[binIndex]), centers)); } ws->splitAllIfNeeded(NULL); } return ws; }
void ConvertToMatrixWorkspace::exec() { MatrixWorkspace_const_sptr inputWorkspace = getProperty("InputWorkspace"); // Let's see if we have to do anything first. Basically we want to avoid the data copy if we can DataObjects::EventWorkspace_const_sptr eventW = boost::dynamic_pointer_cast<const DataObjects::EventWorkspace>(inputWorkspace); MatrixWorkspace_sptr outputWorkspace; if( eventW ) { g_log.information() << "Converting EventWorkspace to Workspace2D.\n"; const size_t numHists = inputWorkspace->getNumberHistograms(); Progress prog(this,0.0,1.0,numHists*2); // Sort the input workspace in-place by TOF. This can be faster if there are few event lists. eventW->sortAll(TOF_SORT, &prog); // Create the output workspace. This will copy many aspects fron the input one. outputWorkspace = WorkspaceFactory::Instance().create(inputWorkspace); // ...but not the data, so do that here. PARALLEL_FOR2(inputWorkspace,outputWorkspace) for (int64_t i = 0; i < (int64_t)numHists; ++i) { PARALLEL_START_INTERUPT_REGION const ISpectrum * inSpec = inputWorkspace->getSpectrum(i); ISpectrum * outSpec = outputWorkspace->getSpectrum(i); outSpec->copyInfoFrom(*inSpec); outSpec->setX(inSpec->ptrX()); outSpec->dataY() = inSpec->dataY(); outSpec->dataE() = inSpec->dataE(); prog.report("Binning"); PARALLEL_END_INTERUPT_REGION } PARALLEL_CHECK_INTERUPT_REGION outputWorkspace->generateSpectraMap(); } else {
/** Test a workspace for compatibility with others on the basis of the arguments provided. @param ws : Workspace to test @param xUnitID : Unit id for the x axis @param YUnit : Y Unit @param dist : flag indicating that the workspace should be a distribution @param instrument : name of the instrument @throws an invalid argument if a full match is not acheived. */ void MergeRuns::testCompatibility(MatrixWorkspace_const_sptr ws, const std::string &xUnitID, const std::string &YUnit, const bool dist, const std::string instrument) const { std::string errors; if (ws->getAxis(0)->unit()->unitID() != xUnitID) errors += "different X units; "; if (ws->YUnit() != YUnit) errors += "different Y units; "; if (ws->isDistribution() != dist) errors += "not all distribution or all histogram type; "; if (ws->getInstrument()->getName() != instrument) errors += "different instrument names; "; if (errors.length() > 0) { g_log.error("Input workspaces are not compatible: " + errors); throw std::invalid_argument("Input workspaces are not compatible: " + errors); } }
/** * Plots the loaded file to the miniplot and sets the guides * and the range * * @param filename :: The name of the workspace to plot */ void Stretch::handleSampleInputReady(const QString &filename) { m_uiForm.ppPlot->addSpectrum("Sample", filename, 0); // update the maximum and minimum range bar positions QPair<double, double> range = m_uiForm.ppPlot->getCurveRange("Sample"); auto eRangeSelector = m_uiForm.ppPlot->getRangeSelector("StretchERange"); setRangeSelector(eRangeSelector, m_properties["EMin"], m_properties["EMax"], range); setPlotPropertyRange(eRangeSelector, m_properties["EMin"], m_properties["EMax"], range); // update the current positions of the range bars eRangeSelector->setMinimum(range.first); eRangeSelector->setMaximum(range.second); // set the max spectrum MatrixWorkspace_const_sptr sampleWs = getADSMatrixWorkspace(filename.toStdString()); const int spectra = static_cast<int>(sampleWs->getNumberHistograms()); m_uiForm.spPreviewSpectrum->setMaximum(spectra - 1); }
/** * Add -1.*minValue on each spectra. * * @param minWS A workspace of minimum values for each spectra. This is *calculated in * the @see exec portion of the algorithm. * @param wksp The workspace to modify. * @param prog The progress. */ void ResetNegatives::pushMinimum(MatrixWorkspace_const_sptr minWS, MatrixWorkspace_sptr wksp, Progress &prog) { int64_t nHist = minWS->getNumberHistograms(); PARALLEL_FOR_IF(Kernel::threadSafe(*wksp, *minWS)) for (int64_t i = 0; i < nHist; i++) { PARALLEL_START_INTERUPT_REGION double minValue = minWS->y(i)[0]; if (minValue <= 0) { minValue *= -1.; auto &y = wksp->mutableY(i); for (double &value : y) { value = fixZero(value + minValue); } } prog.report(); PARALLEL_END_INTERUPT_REGION } PARALLEL_CHECK_INTERUPT_REGION }
void ExtractFFTSpectrum::exec() { MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace"); MatrixWorkspace_sptr inputImagWS = getProperty("InputImagWorkspace"); const int fftPart = getProperty("FFTPart"); const int numHists = static_cast<int>(inputWS->getNumberHistograms()); MatrixWorkspace_sptr outputWS = WorkspaceFactory::Instance().create(inputWS); Progress prog(this, 0.0, 1.0, numHists); PARALLEL_FOR1(outputWS) for ( int i = 0; i < numHists; i++ ) { PARALLEL_START_INTERUPT_REGION IAlgorithm_sptr childFFT = createChildAlgorithm("FFT"); childFFT->setProperty<MatrixWorkspace_sptr>("InputWorkspace", inputWS); childFFT->setProperty<int>("Real", i); if( inputImagWS ) { childFFT->setProperty<MatrixWorkspace_sptr>("InputImagWorkspace", inputImagWS); childFFT->setProperty<int>("Imaginary", i); } childFFT->execute(); MatrixWorkspace_const_sptr fftTemp = childFFT->getProperty("OutputWorkspace"); outputWS->dataE(i) = fftTemp->readE(fftPart); outputWS->dataY(i) = fftTemp->readY(fftPart); outputWS->dataX(i) = fftTemp->readX(fftPart); prog.report(); PARALLEL_END_INTERUPT_REGION } PARALLEL_CHECK_INTERUPT_REGION boost::shared_ptr<Kernel::Units::Label> lblUnit = boost::dynamic_pointer_cast<Kernel::Units::Label>(UnitFactory::Instance().create("Label")); lblUnit->setLabel("Time", "ns"); outputWS->getAxis(0)->unit() = lblUnit; setProperty("OutputWorkspace", outputWS); }
/** * Determine the minimum spectrum id for summing. This requires that * SumSpectra::indices has already been set. * @param localworkspace The workspace to use. * @return The minimum spectrum id for all the spectra being summed. */ specid_t SumSpectra::getOutputSpecId(MatrixWorkspace_const_sptr localworkspace) { // initial value specid_t specId = localworkspace->getSpectrum(*(this->m_indices.begin()))->getSpectrumNo(); // the total number of spectra int totalSpec = static_cast<int>(localworkspace->getNumberHistograms()); specid_t temp; for (auto index : this->m_indices) { if (index < totalSpec) { temp = localworkspace->getSpectrum(index)->getSpectrumNo(); if (temp < specId) specId = temp; } } return specId; }