/** Select background points via a given background function */ void ProcessBackground::selectFromGivenFunction() { // Process properties BackgroundFunction_sptr bkgdfunc = createBackgroundFunction(m_bkgdType); TableWorkspace_sptr bkgdtablews = getProperty("BackgroundTableWorkspace"); // Set up background function from table size_t numrows = bkgdtablews->rowCount(); map<string, double> parmap; for (size_t i = 0; i < numrows; ++i) { TableRow row = bkgdtablews->getRow(i); string parname; double parvalue; row >> parname >> parvalue; if (parname[0] == 'A') parmap.emplace(parname, parvalue); } int bkgdorder = static_cast<int>(parmap.size() - 1); // A0 - A(n) total n+1 parameters bkgdfunc->setAttributeValue("n", bkgdorder); for (auto &mit : parmap) { string parname = mit.first; double parvalue = mit.second; bkgdfunc->setParameter(parname, parvalue); } // Filter out m_outputWS = filterForBackground(bkgdfunc); return; }
/** Select background points via a given background function */ void ProcessBackground::execSelectBkgdPoints2() { // Process properties BackgroundFunction_sptr bkgdfunc = createBackgroundFunction(m_bkgdType); TableWorkspace_sptr bkgdtablews = getProperty("BackgroundTableWorkspace"); // Set up background function from table size_t numrows = bkgdtablews->rowCount(); map<string, double> parmap; for (size_t i = 0; i < numrows; ++i) { TableRow row = bkgdtablews->getRow(i); string parname; double parvalue; row >> parname >> parvalue; if (parname[0] == 'A') parmap.insert(make_pair(parname, parvalue)); } int bkgdorder = static_cast<int>(parmap.size()-1); // A0 - A(n) total n+1 parameters bkgdfunc->setAttributeValue("n", bkgdorder); for (map<string, double>::iterator mit = parmap.begin(); mit != parmap.end(); ++mit) { string parname = mit->first; double parvalue = mit->second; bkgdfunc->setParameter(parname, parvalue); } // Filter out m_outputWS = filterForBackground(bkgdfunc); return; }
/** Parse table workspace */ void RemovePeaks::parsePeakTableWorkspace(TableWorkspace_sptr peaktablews, vector<double> &vec_peakcentre, vector<double> &vec_peakfwhm) { // Get peak table workspace information vector<string> colnames = peaktablews->getColumnNames(); int index_centre = -1; int index_fwhm = -1; for (int i = 0; i < static_cast<int>(colnames.size()); ++i) { string colname = colnames[i]; if (colname.compare("TOF_h") == 0) index_centre = i; else if (colname.compare("FWHM") == 0) index_fwhm = i; } if (index_centre < 0 || index_fwhm < 0) { throw runtime_error( "Input Bragg peak table workspace does not have TOF_h and/or FWHM"); } // Get values size_t numrows = peaktablews->rowCount(); vec_peakcentre.resize(numrows, 0.); vec_peakfwhm.resize(numrows, 0.); for (size_t i = 0; i < numrows; ++i) { double centre = peaktablews->cell<double>(i, index_centre); double fwhm = peaktablews->cell<double>(i, index_fwhm); vec_peakcentre[i] = centre; vec_peakfwhm[i] = fwhm; } return; }
/** Executes the algorithm * * @throw Exception::RuntimeError If ... ... */ void GetDetOffsetsMultiPeaks::importFitWindowTableWorkspace(TableWorkspace_sptr windowtablews) { // Check number of columns matches number of peaks size_t numcols = windowtablews->columnCount(); size_t numpeaks = m_peakPositions.size(); if (numcols != 2*numpeaks+1) throw std::runtime_error("Number of columns is not 2 times of number of referenced peaks. "); // Check number of spectra should be same to input workspace size_t numrows = windowtablews->rowCount(); if (numrows != m_inputWS->getNumberHistograms()) throw std::runtime_error("Number of spectra in fit window workspace does not match input workspace. "); // Create workspace m_vecFitWindow.clear(); m_vecFitWindow.resize(numrows); for (size_t i = 0; i < numrows; ++i) { // spectrum number int spec = windowtablews->cell<int>(i, 0); if (spec < 0 || spec >= static_cast<int>(numrows)) { std::stringstream ess; ess << "Peak fit windows at row " << i << " has spectrum " << spec << ", which is out of allowed range! "; throw std::runtime_error(ess.str()); } else if (m_vecFitWindow[spec].size() != 0) { std::stringstream ess; ess << "Peak fit windows at row " << i << " has spectrum " << spec << ", which appears before in fit window table workspace. "; throw std::runtime_error(ess.str()); } // fit windows std::vector<double> fitwindows(numcols-1); for (size_t j = 1; j < numcols; ++j) { double dtmp = windowtablews->cell<double>(i, j); fitwindows[j-1] = dtmp; } // add to vector of fit windows m_vecFitWindow[spec] = fitwindows; } return; }
/** Copy table workspace content from one workspace to another * @param sourceWS :: table workspace from which the content is copied; * @param targetWS :: table workspace to which the content is copied; */ void ExtractMaskToTable::copyTableWorkspaceContent( TableWorkspace_sptr sourceWS, TableWorkspace_sptr targetWS) { // Compare the column names. They must be exactly the same vector<string> sourcecolnames = sourceWS->getColumnNames(); vector<string> targetcolnames = targetWS->getColumnNames(); if (sourcecolnames.size() != targetcolnames.size()) { stringstream errmsg; errmsg << "Soruce table workspace " << sourceWS->name() << " has different number of columns (" << sourcecolnames.size() << ") than target table workspace's (" << targetcolnames.size() << ")"; throw runtime_error(errmsg.str()); } for (size_t i = 0; i < sourcecolnames.size(); ++i) { if (sourcecolnames[i].compare(targetcolnames[i])) { stringstream errss; errss << "Source and target have incompatible column name at column " << i << ". " << "Column name of source is " << sourcecolnames[i] << "; " << "Column name of target is " << targetcolnames[i]; throw runtime_error(errss.str()); } } // Copy over the content size_t numrows = sourceWS->rowCount(); for (size_t i = 0; i < numrows; ++i) { double xmin, xmax; string speclist; TableRow tmprow = sourceWS->getRow(i); tmprow >> xmin >> xmax >> speclist; TableRow newrow = targetWS->appendRow(); newrow << xmin << xmax << speclist; } return; }
void PoldiPeakCollection::constructFromTableWorkspace( const TableWorkspace_sptr &tableWorkspace) { if (checkColumns(tableWorkspace)) { size_t newPeakCount = tableWorkspace->rowCount(); m_peaks.resize(newPeakCount); recoverDataFromLog(tableWorkspace); for (size_t i = 0; i < newPeakCount; ++i) { TableRow nextRow = tableWorkspace->getRow(i); std::string hklString; double d, deltaD, q, deltaQ, intensity, deltaIntensity, fwhm, deltaFwhm; nextRow >> hklString >> d >> deltaD >> q >> deltaQ >> intensity >> deltaIntensity >> fwhm >> deltaFwhm; PoldiPeak_sptr peak = PoldiPeak::create( MillerIndicesIO::fromString(hklString), UncertainValue(d, deltaD), UncertainValue(intensity, deltaIntensity), UncertainValue(fwhm, deltaFwhm)); m_peaks[i] = peak; } } }
/** Fit background function */ void ProcessBackground::fitBackgroundFunction(std::string bkgdfunctiontype) { // Get background type and create bakground function BackgroundFunction_sptr bkgdfunction = createBackgroundFunction(bkgdfunctiontype); int bkgdorder = getProperty("OutputBackgroundOrder"); bkgdfunction->setAttributeValue("n", bkgdorder); if (bkgdfunctiontype == "Chebyshev") { double xmin = m_outputWS->readX(0).front(); double xmax = m_outputWS->readX(0).back(); g_log.information() << "Chebyshev Fit range: " << xmin << ", " << xmax << "\n"; bkgdfunction->setAttributeValue("StartX", xmin); bkgdfunction->setAttributeValue("EndX", xmax); } g_log.information() << "Fit selected background " << bkgdfunctiontype << " to data workspace with " << m_outputWS->getNumberHistograms() << " spectra." << "\n"; // Fit input (a few) background pionts to get initial guess API::IAlgorithm_sptr fit; try { fit = this->createChildAlgorithm("Fit", 0.9, 1.0, true); } catch (Exception::NotFoundError &) { g_log.error() << "Requires CurveFitting library." << std::endl; throw; } g_log.information() << "Fitting background function: " << bkgdfunction->asString() << "\n"; double startx = m_lowerBound; double endx = m_upperBound; fit->setProperty("Function", boost::dynamic_pointer_cast<API::IFunction>(bkgdfunction)); fit->setProperty("InputWorkspace", m_outputWS); fit->setProperty("WorkspaceIndex", 0); fit->setProperty("MaxIterations", 500); fit->setProperty("StartX", startx); fit->setProperty("EndX", endx); fit->setProperty("Minimizer", "Levenberg-MarquardtMD"); fit->setProperty("CostFunction", "Least squares"); fit->executeAsChildAlg(); // Get fit status and chi^2 std::string fitStatus = fit->getProperty("OutputStatus"); bool allowedfailure = (fitStatus.find("cannot") < fitStatus.size()) && (fitStatus.find("tolerance") < fitStatus.size()); if (fitStatus.compare("success") != 0 && !allowedfailure) { g_log.error() << "ProcessBackground: Fit Status = " << fitStatus << ". Not to update fit result" << std::endl; throw std::runtime_error("Bad Fit"); } const double chi2 = fit->getProperty("OutputChi2overDoF"); g_log.information() << "Fit background: Fit Status = " << fitStatus << ", chi2 = " << chi2 << "\n"; // Get out the parameter names API::IFunction_sptr funcout = fit->getProperty("Function"); TableWorkspace_sptr outbkgdparws = boost::make_shared<TableWorkspace>(); outbkgdparws->addColumn("str", "Name"); outbkgdparws->addColumn("double", "Value"); TableRow typerow = outbkgdparws->appendRow(); typerow << bkgdfunctiontype << 0.; vector<string> parnames = funcout->getParameterNames(); size_t nparam = funcout->nParams(); for (size_t i = 0; i < nparam; ++i) { TableRow newrow = outbkgdparws->appendRow(); newrow << parnames[i] << funcout->getParameter(i); } TableRow chi2row = outbkgdparws->appendRow(); chi2row << "Chi-square" << chi2; g_log.information() << "Set table workspace (#row = " << outbkgdparws->rowCount() << ") to OutputBackgroundParameterTable. " << "\n"; setProperty("OutputBackgroundParameterWorkspace", outbkgdparws); // Set output workspace const MantidVec &vecX = m_outputWS->readX(0); const MantidVec &vecY = m_outputWS->readY(0); FunctionDomain1DVector domain(vecX); FunctionValues values(domain); funcout->function(domain, values); MantidVec &dataModel = m_outputWS->dataY(1); MantidVec &dataDiff = m_outputWS->dataY(2); for (size_t i = 0; i < dataModel.size(); ++i) { dataModel[i] = values[i]; dataDiff[i] = vecY[i] - dataModel[i]; } return; }
/** Parse table workspace to a map of Parameters */ void RefinePowderInstrumentParameters2::parseTableWorkspace(TableWorkspace_sptr tablews, map<string, Parameter>& parammap) { // 1. Process Table column names std::vector<std::string> colnames = tablews->getColumnNames(); map<string, size_t> colnamedict; convertToDict(colnames, colnamedict); int iname = getStringIndex(colnamedict, "Name"); int ivalue = getStringIndex(colnamedict, "Value"); int ifit = getStringIndex(colnamedict, "FitOrTie"); int imin = getStringIndex(colnamedict, "Min"); int imax = getStringIndex(colnamedict, "Max"); int istep = getStringIndex(colnamedict, "StepSize"); if (iname < 0 || ivalue < 0 || ifit < 0) throw runtime_error("TableWorkspace does not have column Name, Value and/or Fit."); // 3. Parse size_t numrows = tablews->rowCount(); for (size_t irow = 0; irow < numrows; ++irow) { string parname = tablews->cell<string>(irow, iname); double parvalue = tablews->cell<double>(irow, ivalue); string fitq = tablews->cell<string>(irow, ifit); double minvalue; if (imin >= 0) minvalue = tablews->cell<double>(irow, imin); else minvalue = -DBL_MAX; double maxvalue; if (imax >= 0) maxvalue = tablews->cell<double>(irow, imax); else maxvalue = DBL_MAX; double stepsize; if (istep >= 0) stepsize = tablews->cell<double>(irow, istep); else stepsize = 1.0; Parameter newpar; newpar.name = parname; newpar.value = parvalue; newpar.minvalue = minvalue; newpar.maxvalue = maxvalue; newpar.stepsize = stepsize; // If empty string, fit is default to be false bool fit = false; if (fitq.size() > 0) { if (fitq[0] == 'F' || fitq[0] == 'f') fit = true; } newpar.fit = fit; parammap.insert(make_pair(parname, newpar)); } return; }
/** Executes the algorithm * * @throw Exception::RuntimeError If ... ... */ void GetDetOffsetsMultiPeaks::importFitWindowTableWorkspace( TableWorkspace_sptr windowtablews) { // Check number of columns matches number of peaks size_t numcols = windowtablews->columnCount(); size_t numpeaks = m_peakPositions.size(); if (numcols != 2 * numpeaks + 1) throw std::runtime_error( "Number of columns is not 2 times of number of referenced peaks. "); // Check number of spectra should be same to input workspace size_t numrows = windowtablews->rowCount(); bool needuniversal = false; if (numrows < m_inputWS->getNumberHistograms()) needuniversal = true; else if (numrows > m_inputWS->getNumberHistograms()) throw std::runtime_error( "Number of rows in table workspace is larger than number of spectra."); // Clear and re-size of the vector for fit windows m_vecFitWindow.clear(); m_vecFitWindow.resize(m_inputWS->getNumberHistograms()); std::vector<double> vec_univFitWindow; bool founduniversal = false; // Parse the table workspace for (size_t i = 0; i < numrows; ++i) { // spectrum number int spec = windowtablews->cell<int>(i, 0); if (spec >= static_cast<int>(numrows)) { std::stringstream ess; ess << "Peak fit windows at row " << i << " has spectrum " << spec << ", which is out of allowed range! "; throw std::runtime_error(ess.str()); } if (spec < 0 && founduniversal) { throw std::runtime_error("There are more than 1 universal spectrum (spec " "< 0) in TableWorkspace."); } else if (spec >= 0 && m_vecFitWindow[spec].size() != 0) { std::stringstream ess; ess << "Peak fit windows at row " << i << " has spectrum " << spec << ", which appears before in fit window table workspace. "; throw std::runtime_error(ess.str()); } // fit windows std::vector<double> fitwindows(numcols - 1); for (size_t j = 1; j < numcols; ++j) { double dtmp = windowtablews->cell<double>(i, j); fitwindows[j - 1] = dtmp; } // add to vector of fit windows if (spec >= 0) m_vecFitWindow[spec] = fitwindows; else { vec_univFitWindow = fitwindows; founduniversal = true; } } // Check and fill if using universal if (needuniversal && !founduniversal) { // Invalid case throw std::runtime_error("Number of rows in TableWorkspace is smaller than " "number of spectra. But " "there is no universal fit window given!"); } else if (founduniversal) { // Fill the universal for (size_t i = 0; i < m_inputWS->getNumberHistograms(); ++i) if (m_vecFitWindow[i].size() == 0) m_vecFitWindow[i] = vec_univFitWindow; } return; }
/** Process input Mask bin TableWorkspace. * It will convert detector IDs list to spectra list * @param masktblws :: TableWorkspace for mask bins * @param dataws :: MatrixWorkspace to mask */ void MaskBinsFromTable::processMaskBinWorkspace( TableWorkspace_sptr masktblws, API::MatrixWorkspace_sptr dataws) { // Check input if (!masktblws) throw std::invalid_argument("Input workspace is not a table workspace."); g_log.debug() << "Lines of parameters workspace = " << masktblws->rowCount() << '\n'; // Check column names type and sequence vector<std::string> colnames = masktblws->getColumnNames(); // check colum name order id_xmin = -1; id_xmax = -1; id_spec = -1; id_dets = -1; m_useDetectorID = false; m_useSpectrumID = false; for (int i = 0; i < static_cast<int>(colnames.size()); ++i) { string colname = colnames[i]; transform(colname.begin(), colname.end(), colname.begin(), ::tolower); if (colname.compare("xmin") == 0) id_xmin = i; else if (colname.compare("xmax") == 0) id_xmax = i; else if (boost::algorithm::starts_with(colname, "spec")) { id_spec = i; } else if (boost::algorithm::starts_with(colname, "detectorid")) { id_dets = i; } else { g_log.warning() << "In TableWorkspace " << masktblws->name() << ", column " << i << " with name " << colname << " is not used by MaskBinsFromTable."; } } if (id_xmin < 0 || id_xmax < 0 || id_xmin == id_xmax) throw runtime_error("Either Xmin nor Xmax is not given. "); if (id_spec == id_dets) throw runtime_error("Neither SpectraList nor DetectorIDList is given."); else if (id_dets >= 0) m_useDetectorID = true; else m_useSpectrumID = true; // Construct vectors for xmin, xmax and spectra-list size_t numrows = masktblws->rowCount(); for (size_t i = 0; i < numrows; ++i) { double xmin = masktblws->cell<double>(i, static_cast<size_t>(id_xmin)); double xmax = masktblws->cell<double>(i, static_cast<size_t>(id_xmax)); string spectralist; if (m_useSpectrumID) { spectralist = masktblws->cell<string>(i, static_cast<size_t>(id_spec)); } else { // Convert detectors list to spectra list string detidslist = masktblws->cell<string>(i, static_cast<size_t>(id_dets)); spectralist = convertToSpectraList(dataws, detidslist); } g_log.debug() << "Row " << i << " XMin = " << xmin << " XMax = " << xmax << " SpectraList = " << spectralist << ".\n"; // Store to class variables m_xminVec.push_back(xmin); m_xmaxVec.push_back(xmax); m_spectraVec.push_back(spectralist); } }
int PeakIntegration::fitneighbours(int ipeak, std::string det_name, int x0, int y0, int idet, double qspan, PeaksWorkspace_sptr &Peaks, const detid2index_map &pixel_to_wi) { UNUSED_ARG(ipeak); UNUSED_ARG(det_name); UNUSED_ARG(x0); UNUSED_ARG(y0); Geometry::IPeak &peak = Peaks->getPeak(ipeak); // Number of slices int TOFmax = 0; IAlgorithm_sptr slice_alg = createChildAlgorithm("IntegratePeakTimeSlices"); slice_alg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", inputW); std::ostringstream tab_str; tab_str << "LogTable" << ipeak; slice_alg->setPropertyValue("OutputWorkspace", tab_str.str()); slice_alg->setProperty<PeaksWorkspace_sptr>("Peaks", Peaks); slice_alg->setProperty("PeakIndex", ipeak); slice_alg->setProperty("PeakQspan", qspan); int nPixels = std::max<int>(0, getProperty("NBadEdgePixels")); slice_alg->setProperty("NBadEdgePixels", nPixels); slice_alg->executeAsChildAlg(); Mantid::API::MemoryManager::Instance().releaseFreeMemory(); MantidVec &Xout = outputW->dataX(idet); MantidVec &Yout = outputW->dataY(idet); MantidVec &Eout = outputW->dataE(idet); TableWorkspace_sptr logtable = slice_alg->getProperty("OutputWorkspace"); peak.setIntensity(slice_alg->getProperty("Intensity")); peak.setSigmaIntensity(slice_alg->getProperty("SigmaIntensity")); TOFmax = static_cast<int>(logtable->rowCount()); for (int iTOF = 0; iTOF < TOFmax; iTOF++) { Xout[iTOF] = logtable->getRef<double>(std::string("Time"), iTOF); if (m_IC) // Ikeda-Carpenter fit { Yout[iTOF] = logtable->getRef<double>(std::string("TotIntensity"), iTOF); Eout[iTOF] = logtable->getRef<double>(std::string("TotIntensityError"), iTOF); } else { Yout[iTOF] = logtable->getRef<double>(std::string("ISAWIntensity"), iTOF); Eout[iTOF] = logtable->getRef<double>(std::string("ISAWIntensityError"), iTOF); } } outputW->getSpectrum(idet)->clearDetectorIDs(); // Find the pixel ID at that XY position on the rectangular detector int pixelID = peak.getDetectorID(); // det->getAtXY(x0,y0)->getID(); // Find the corresponding workspace index, if any auto wiEntry = pixel_to_wi.find(pixelID); if (wiEntry != pixel_to_wi.end()) { size_t wi = wiEntry->second; // Set detectorIDs outputW->getSpectrum(idet) ->addDetectorIDs(inputW->getSpectrum(wi)->getDetectorIDs()); } return TOFmax - 1; }