/** Fits each spectrum in the workspace to f(x) = A * sin( w * x + p) * @param ws :: [input] The workspace to fit * @param freq :: [input] Hint for the frequency (w) * @param groupName :: [input] The name of the output workspace group * @param resTab :: [output] Table workspace storing the asymmetries and phases * @param resGroup :: [output] Workspace group storing the fitting results */ void CalMuonDetectorPhases::fitWorkspace(const API::MatrixWorkspace_sptr &ws, double freq, std::string groupName, API::ITableWorkspace_sptr &resTab, API::WorkspaceGroup_sptr &resGroup) { int nhist = static_cast<int>(ws->getNumberHistograms()); // Create the fitting function f(x) = A * sin ( w * x + p ) // The same function and initial parameters are used for each fit std::string funcStr = createFittingFunction(freq, true); // Set up results table resTab->addColumn("int", "Spectrum number"); resTab->addColumn("double", "Asymmetry"); resTab->addColumn("double", "Phase"); // Loop through fitting all spectra individually const static std::string success = "success"; for (int wsIndex = 0; wsIndex < nhist; wsIndex++) { reportProgress(wsIndex, nhist); auto fit = createChildAlgorithm("Fit"); fit->initialize(); fit->setPropertyValue("Function", funcStr); fit->setProperty("InputWorkspace", ws); fit->setProperty("WorkspaceIndex", wsIndex); fit->setProperty("CreateOutput", true); fit->setPropertyValue("Output", groupName); fit->execute(); std::string status = fit->getProperty("OutputStatus"); if (!fit->isExecuted() || status != success) { std::ostringstream error; error << "Fit failed for spectrum at workspace index " << wsIndex; error << ": " << status; throw std::runtime_error(error.str()); } API::MatrixWorkspace_sptr fitOut = fit->getProperty("OutputWorkspace"); resGroup->addWorkspace(fitOut); API::ITableWorkspace_sptr tab = fit->getProperty("OutputParameters"); // Now we have our fitting results stored in tab // but we need to extract the relevant information, i.e. // the detector phases (parameter 'p') and asymmetries ('A') const auto &spectrum = ws->getSpectrum(static_cast<size_t>(wsIndex)); extractDetectorInfo(tab, resTab, spectrum.getSpectrumNo()); } }
/** This method loops through the response return_vector and saves the datasets details to a table workspace * @param response :: const reference to response object * @param outputws :: shred pointer to workspace * @returns shared pointer to table workspace which stores the data */ void CICatHelper::saveDataSets(const ns1__getInvestigationIncludesResponse& response,API::ITableWorkspace_sptr& outputws) { //create table workspace if (outputws->getColumnNames().empty()) { outputws->addColumn("str","Name");//File name outputws->addColumn("str","Status"); outputws->addColumn("str","Type"); outputws->addColumn("str","Description"); outputws->addColumn("long64","Sample Id"); } try { std::vector<ns1__dataset*> datasetVec; datasetVec.assign((response.return_)->datasetCollection.begin(),(response.return_)->datasetCollection.end()); std::vector<ns1__dataset*>::const_iterator dataset_citr; for(dataset_citr=datasetVec.begin();dataset_citr!=datasetVec.end();++dataset_citr) { API::TableRow t = outputws->appendRow(); // DataSet Name savetoTableWorkspace((*dataset_citr)->name,t); // DataSet Status savetoTableWorkspace((*dataset_citr)->datasetStatus,t); //DataSet Type savetoTableWorkspace((*dataset_citr)->datasetType,t); //DataSet Type savetoTableWorkspace((*dataset_citr)->description,t); //DataSet Type savetoTableWorkspace((*dataset_citr)->sampleId,t); } } catch(std::runtime_error& ) { throw; } //return outputws; }
/** This method saves the search response( investigations )data to a table * workspace * @param response :: const reference to response object * @param outputws :: shared pointer to output workspace */ void CICatHelper::saveSearchRessults( const ns1__searchByAdvancedPaginationResponse &response, API::ITableWorkspace_sptr &outputws) { if (outputws->getColumnNames().empty()) { outputws->addColumn("str", "Investigation id"); outputws->addColumn("str", "Facility"); outputws->addColumn("str", "Title"); outputws->addColumn("str", "Instrument"); outputws->addColumn("str", "Run range"); outputws->addColumn("str", "Start date"); outputws->addColumn("str", "End date"); outputws->addColumn("str", "SessionID"); } saveInvestigations(response.return_, outputws); }
/** Read from the instrument file the dead wires and store the information in a TableWorkspace. If asked, the dead wires are removed from the data set. @param localWorkspace :: input raw data workspace, containing the information about the instrument @param outputws :: input dead wire liste workspace */ void PoldiRemoveDeadWires::runExcludWires3 ( DataObjects::Workspace2D_sptr &localWorkspace, API::ITableWorkspace_sptr &outputws ) { outputws->addColumn("int","DeadWires"); boost::shared_ptr<const Mantid::Geometry::IComponent> comp = localWorkspace->getInstrument()->getComponentByName("holder"); boost::shared_ptr<const Mantid::Geometry::ICompAssembly> bank = boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(comp); if (bank) { // Get a vector of children (recursively) std::vector<boost::shared_ptr<const Mantid::Geometry::IComponent> > children; bank->getChildren(children, true); std::vector<double> defaultDeadWires; int ewLine = 0; for (unsigned int it = 0; it < children.size(); ++it) { string wireName = children.at(it)->getName(); std::vector<boost::shared_ptr<const Mantid::Geometry::IComponent> > tyty = localWorkspace.get()->getInstrument().get()->getAllComponentsWithName(wireName); std::vector<double> tempWire = tyty[0]->getNumberParameter("excluded"); if(tempWire.size()>0) { int val = (int)tempWire[0]; g_log.debug() << "_poldi : dead wires :" << val << std::endl; defaultDeadWires.push_back(val); for(unsigned int j=0; j<m_channelsPerSpectrum; j++) { localWorkspace->maskBin(val-1,j,1); } ewLine++; TableRow t = outputws->appendRow(); t << val ; } } g_log.information() << "_poldi : dead wires set to 0 (nb:" << ewLine << ")" << std::endl; setProperty("nbExcludedWires",ewLine); } else { g_log.information() << "_poldi : no dead wire removed" << std::endl; } }
/** * Saves result from "getDataFiles" to workspace. * @param response :: result response from the catalog. * @param outputws :: shared pointer to datasets */ void ICat4Catalog::saveDataFiles(std::vector<xsd__anyType *> response, API::ITableWorkspace_sptr &outputws) { if (outputws->getColumnNames().empty()) { // Add rows headers to the output workspace. outputws->addColumn("str", "Name"); outputws->addColumn("str", "Location"); outputws->addColumn("str", "Create Time"); outputws->addColumn("long64", "Id"); outputws->addColumn("long64", "File size(bytes)"); outputws->addColumn("str", "File size"); outputws->addColumn("str", "Description"); } std::vector<xsd__anyType *>::const_iterator iter; for (iter = response.begin(); iter != response.end(); ++iter) { ns1__datafile *datafile = dynamic_cast<ns1__datafile *>(*iter); if (datafile) { API::TableRow table = outputws->appendRow(); // Now add the relevant investigation data to the table. savetoTableWorkspace(datafile->name, table); savetoTableWorkspace(datafile->location, table); std::string createDate = formatDateTime(*datafile->createTime, "%Y-%m-%d %H:%M:%S"); savetoTableWorkspace(&createDate, table); savetoTableWorkspace(datafile->id, table); savetoTableWorkspace(datafile->fileSize, table); std::string fileSize = bytesToString(*datafile->fileSize); savetoTableWorkspace(&fileSize, table); if (datafile->description) savetoTableWorkspace(datafile->description, table); } else { throw std::runtime_error("ICat4Catalog::saveDataFiles expected a " "datafile. Please contact the Mantid " "development team."); } } }
/** * Loops through the response vector and saves the datasets details to a table * workspace. * @param response :: A vector containing the results of the search query. * @param outputws :: Shared pointer to output workspace. */ void ICat4Catalog::saveDataSets(std::vector<xsd__anyType *> response, API::ITableWorkspace_sptr &outputws) { if (outputws->getColumnNames().empty()) { // Add rows headers to the output workspace. outputws->addColumn("long64", "ID"); outputws->addColumn("str", "Name"); outputws->addColumn("str", "Description"); outputws->addColumn("str", "Type"); outputws->addColumn("str", "Related investigation ID"); outputws->addColumn("size_t", "Number of datafiles"); } std::string emptyCell; for (auto &iter : response) { ns1__dataset *dataset = dynamic_cast<ns1__dataset *>(iter); if (dataset) { API::TableRow table = outputws->appendRow(); savetoTableWorkspace(dataset->id, table); savetoTableWorkspace(dataset->name, table); if (dataset->description) savetoTableWorkspace(dataset->description, table); else savetoTableWorkspace(&emptyCell, table); if (dataset->type) savetoTableWorkspace(dataset->type->name, table); else savetoTableWorkspace(&emptyCell, table); if (dataset->investigation) savetoTableWorkspace(dataset->investigation->name, table); else savetoTableWorkspace(&emptyCell, table); size_t datafileCount = dataset->datafiles.size(); savetoTableWorkspace(&datafileCount, table); } else { throw std::runtime_error("ICat4Catalog::saveDataSets expected a dataset. " "Please contact the Mantid development team."); } } }
/** * Load a table */ API::Workspace_sptr LoadNexusProcessed::loadTableEntry(NXEntry & entry) { API::ITableWorkspace_sptr workspace; workspace = Mantid::API::WorkspaceFactory::Instance().createTable("TableWorkspace"); NXData nx_tw = entry.openNXData("table_workspace"); std::vector<double> values; bool hasNumberOfRowBeenSet = false; //int numberOfRows = 0; int columnNumber = 1; do { std::string str = "column_" + boost::lexical_cast<std::string>(columnNumber); NXInfo info = nx_tw.getDataSetInfo(str.c_str()); if (info.stat == NX_ERROR) { break; } if ( info.type == NX_FLOAT64 ) { NXDouble nxDouble = nx_tw.openNXDouble(str.c_str()); std::string columnTitle = nxDouble.attributes("name"); if (!columnTitle.empty()) { workspace->addColumn("double", columnTitle); nxDouble.load(); int length = nxDouble.dim0(); if ( !hasNumberOfRowBeenSet ) { workspace->setRowCount(length); hasNumberOfRowBeenSet = true; } for (int i = 0; i < length; i++) workspace->cell<double>(i,columnNumber-1) = *(nxDouble() + i); } } else if ( info.type == NX_CHAR ) { NXChar data = nx_tw.openNXChar(str.c_str()); std::string columnTitle = data.attributes("name"); if (!columnTitle.empty()) { workspace->addColumn("str", columnTitle); int nRows = info.dims[0]; if ( !hasNumberOfRowBeenSet ) { workspace->setRowCount(nRows); hasNumberOfRowBeenSet = true; } int maxStr = info.dims[1]; std::string fromCrap(maxStr,' '); data.load(); for (int iR = 0; iR < nRows; iR++) { for (int i = 0; i < maxStr; i++) fromCrap[i] = *(data()+i+maxStr*iR); workspace->cell<std::string>(iR,columnNumber-1) = fromCrap; } } } columnNumber++; } while ( 1 ); return boost::static_pointer_cast<API::Workspace>(workspace); }
/** * This method loops through the response return_vector and saves the datafile * details to a table workspace * @param response :: const reference to response object * @param outputws :: shared pointer to table workspace which stores the data */ void CICatHelper::saveInvestigationIncludesResponse( const ns1__getInvestigationIncludesResponse &response, API::ITableWorkspace_sptr &outputws) { if (outputws->getColumnNames().empty()) { outputws->addColumn("str", "Name"); outputws->addColumn("str", "Location"); outputws->addColumn("str", "Create Time"); outputws->addColumn("long64", "Id"); outputws->addColumn("long64", "File size(bytes)"); outputws->addColumn("str", "File size"); outputws->addColumn("str", "Description"); } try { std::vector<ns1__dataset *> datasetVec; datasetVec.assign((response.return_)->datasetCollection.begin(), (response.return_)->datasetCollection.end()); if (datasetVec.empty()) { throw std::runtime_error("No data files exists in the ICAT database for " "the selected investigation"); } std::vector<ns1__dataset *>::const_iterator dataset_citr; for (dataset_citr = datasetVec.begin(); dataset_citr != datasetVec.end(); ++dataset_citr) { std::vector<ns1__datafile *> datafileVec; datafileVec.assign((*dataset_citr)->datafileCollection.begin(), (*dataset_citr)->datafileCollection.end()); if (datafileVec.empty()) { throw std::runtime_error("No data files exists in the ICAT database " "for the selected investigation "); } std::vector<ns1__datafile *>::const_iterator datafile_citr; for (datafile_citr = datafileVec.begin(); datafile_citr != datafileVec.end(); ++datafile_citr) { API::TableRow t = outputws->appendRow(); // File Name savetoTableWorkspace((*datafile_citr)->name, t); savetoTableWorkspace((*datafile_citr)->location, t); // File creation Time. std::string *creationtime = nullptr; if ((*datafile_citr)->datafileCreateTime != nullptr) { time_t crtime = *(*datafile_citr)->datafileCreateTime; char temp[25]; strftime(temp, 25, "%Y-%b-%d %H:%M:%S", localtime(&crtime)); std::string ftime(temp); creationtime = new std::string; creationtime->assign(ftime); } savetoTableWorkspace(creationtime, t); if (creationtime) delete creationtime; // savetoTableWorkspace((*datafile_citr)->id, t); LONG64 fileSize = boost::lexical_cast<LONG64>(*(*datafile_citr)->fileSize); savetoTableWorkspace(&fileSize, t); savetoTableWorkspace((*datafile_citr)->description, t); } } } catch (std::runtime_error &) { throw; } }
/** Fits each spectrum in the workspace to f(x) = A * sin( w * x + p) * @param ws :: [input] The workspace to fit * @param freq :: [input] Hint for the frequency (w) * @param groupName :: [input] The name of the output workspace group * @param resTab :: [output] Table workspace storing the asymmetries and phases * @param resGroup :: [output] Workspace group storing the fitting results */ void CalMuonDetectorPhases::fitWorkspace(const API::MatrixWorkspace_sptr &ws, double freq, std::string groupName, API::ITableWorkspace_sptr resTab, API::WorkspaceGroup_sptr &resGroup) { int nhist = static_cast<int>(ws->getNumberHistograms()); // Create the fitting function f(x) = A * sin ( w * x + p ) // The same function and initial parameters are used for each fit std::string funcStr = createFittingFunction(freq, true); // Set up results table resTab->addColumn("int", "Spectrum number"); resTab->addColumn("double", "Asymmetry"); resTab->addColumn("double", "Phase"); const auto &indexInfo = ws->indexInfo(); // Loop through fitting all spectra individually const static std::string success = "success"; for (int wsIndex = 0; wsIndex < nhist; wsIndex++) { reportProgress(wsIndex, nhist); const auto &yValues = ws->y(wsIndex); auto emptySpectrum = std::all_of(yValues.begin(), yValues.end(), [](double value) { return value == 0.; }); if (emptySpectrum) { g_log.warning("Spectrum " + std::to_string(wsIndex) + " is empty"); TableWorkspace_sptr tab = boost::make_shared<TableWorkspace>(); tab->addColumn("str", "Name"); tab->addColumn("double", "Value"); tab->addColumn("double", "Error"); for (int j = 0; j < 4; j++) { API::TableRow row = tab->appendRow(); if (j == PHASE_ROW) { row << "dummy" << 0.0 << 0.0; } else { row << "dummy" << ASYMM_ERROR << 0.0; } } extractDetectorInfo(*tab, *resTab, indexInfo.spectrumNumber(wsIndex)); } else { auto fit = createChildAlgorithm("Fit"); fit->initialize(); fit->setPropertyValue("Function", funcStr); fit->setProperty("InputWorkspace", ws); fit->setProperty("WorkspaceIndex", wsIndex); fit->setProperty("CreateOutput", true); fit->setPropertyValue("Output", groupName); fit->execute(); std::string status = fit->getProperty("OutputStatus"); if (!fit->isExecuted()) { std::ostringstream error; error << "Fit failed for spectrum at workspace index " << wsIndex; error << ": " << status; throw std::runtime_error(error.str()); } else if (status != success) { g_log.warning("Fit failed for spectrum at workspace index " + std::to_string(wsIndex) + ": " + status); } API::MatrixWorkspace_sptr fitOut = fit->getProperty("OutputWorkspace"); resGroup->addWorkspace(fitOut); API::ITableWorkspace_sptr tab = fit->getProperty("OutputParameters"); // Now we have our fitting results stored in tab // but we need to extract the relevant information, i.e. // the detector phases (parameter 'p') and asymmetries ('A') extractDetectorInfo(*tab, *resTab, indexInfo.spectrumNumber(wsIndex)); } } }
/** * Calculates the EISF if the fit includes a Delta function * @param tableWs - The TableWorkspace to append the EISF calculation to */ void ConvolutionFitSequential::calculateEISF( API::ITableWorkspace_sptr &tableWs) { // Get height data from parameter table const auto columns = tableWs->getColumnNames(); const auto height = searchForFitParams("Height", columns).at(0); const auto heightErr = searchForFitParams("Height_Err", columns).at(0); auto heightY = tableWs->getColumn(height)->numeric_fill<>(); auto heightE = tableWs->getColumn(heightErr)->numeric_fill<>(); // Get amplitude column names const auto ampNames = searchForFitParams("Amplitude", columns); const auto ampErrorNames = searchForFitParams("Amplitude_Err", columns); // For each lorentzian, calculate EISF size_t maxSize = ampNames.size(); if (ampErrorNames.size() > maxSize) { maxSize = ampErrorNames.size(); } for (size_t i = 0; i < maxSize; i++) { // Get amplitude from column in table workspace const auto ampName = ampNames.at(i); auto ampY = tableWs->getColumn(ampName)->numeric_fill<>(); const auto ampErrorName = ampErrorNames.at(i); auto ampErr = tableWs->getColumn(ampErrorName)->numeric_fill<>(); // Calculate EISF and EISF error // total = heightY + ampY auto total = cloneVector(heightY); std::transform(total.begin(), total.end(), ampY.begin(), total.begin(), std::plus<double>()); // eisfY = heightY / total auto eisfY = cloneVector(heightY); std::transform(eisfY.begin(), eisfY.end(), total.begin(), eisfY.begin(), std::divides<double>()); // heightE squared auto heightESq = cloneVector(heightE); heightESq = squareVector(heightESq); // ampErr squared auto ampErrSq = cloneVector(ampErr); ampErrSq = squareVector(ampErrSq); // totalErr = heightE squared + ampErr squared auto totalErr = cloneVector(heightESq); std::transform(totalErr.begin(), totalErr.end(), ampErrSq.begin(), totalErr.begin(), std::plus<double>()); // heightY squared auto heightYSq = cloneVector(heightY); heightYSq = squareVector(heightYSq); // total Squared auto totalSq = cloneVector(total); totalSq = squareVector(totalSq); // errOverTotalSq = totalErr / total squared auto errOverTotalSq = cloneVector(totalErr); std::transform(errOverTotalSq.begin(), errOverTotalSq.end(), totalSq.begin(), errOverTotalSq.begin(), std::divides<double>()); // heightESqOverYSq = heightESq / heightYSq auto heightESqOverYSq = cloneVector(heightESq); std::transform(heightESqOverYSq.begin(), heightESqOverYSq.end(), heightYSq.begin(), heightESqOverYSq.begin(), std::divides<double>()); // sqrtESqOverYSq = squareRoot( heightESqOverYSq ) auto sqrtESqOverYSq = cloneVector(heightESqOverYSq); std::transform(sqrtESqOverYSq.begin(), sqrtESqOverYSq.end(), sqrtESqOverYSq.begin(), static_cast<double (*)(double)>(sqrt)); // eisfYSumRoot = eisfY * sqrtESqOverYSq auto eisfYSumRoot = cloneVector(eisfY); std::transform(eisfYSumRoot.begin(), eisfYSumRoot.end(), sqrtESqOverYSq.begin(), eisfYSumRoot.begin(), std::multiplies<double>()); // eisfErr = eisfYSumRoot + errOverTotalSq auto eisfErr = cloneVector(eisfYSumRoot); std::transform(eisfErr.begin(), eisfErr.end(), errOverTotalSq.begin(), eisfErr.begin(), std::plus<double>()); // Append the calculated values to the table workspace auto columnName = ampName.substr(0, (ampName.size() - std::string("Amplitude").size())); columnName += "EISF"; auto errorColumnName = ampErrorName.substr( 0, (ampErrorName.size() - std::string("Amplitude_Err").size())); errorColumnName += "EISF_Err"; tableWs->addColumn("double", columnName); tableWs->addColumn("double", errorColumnName); size_t maxEisf = eisfY.size(); if (eisfErr.size() > maxEisf) { maxEisf = eisfErr.size(); } Column_sptr col = tableWs->getColumn(columnName); Column_sptr errCol = tableWs->getColumn(errorColumnName); for (size_t j = 0; j < maxEisf; j++) { col->cell<double>(j) = eisfY.at(j); errCol->cell<double>(j) = eisfErr.at(j); } } }
/** * Saves investigations to a table workspace. * @param response :: A vector containing the results of the search query. * @param outputws :: Shared pointer to output workspace. */ void ICat4Catalog::saveInvestigations(std::vector<xsd__anyType *> response, API::ITableWorkspace_sptr &outputws) { if (outputws->getColumnNames().empty()) { // Add rows headers to the output workspace. outputws->addColumn("long64", "DatabaseID"); outputws->addColumn("str", "InvestigationID"); outputws->addColumn("str", "Facility"); outputws->addColumn("str", "Title"); outputws->addColumn("str", "Instrument"); outputws->addColumn("str", "Run range"); outputws->addColumn("str", "Start date"); outputws->addColumn("str", "End date"); outputws->addColumn("str", "SessionID"); } // Add data to each row in the output workspace. std::vector<xsd__anyType *>::const_iterator iter; for (iter = response.begin(); iter != response.end(); ++iter) { // Cast from xsd__anyType to subclass (xsd__string). ns1__investigation *investigation = dynamic_cast<ns1__investigation *>(*iter); if (investigation) { API::TableRow table = outputws->appendRow(); // Used to insert an empty string into the cell if value does not exist. std::string emptyCell; // Now add the relevant investigation data to the table (They always // exist). savetoTableWorkspace(investigation->id, table); savetoTableWorkspace(investigation->name, table); savetoTableWorkspace(investigation->facility->name, table); savetoTableWorkspace(investigation->title, table); savetoTableWorkspace( investigation->investigationInstruments.at(0)->instrument->name, table); // Verify that the run parameters vector exist prior to doing anything. // Since some investigations may not have run parameters. if (!investigation->parameters.empty()) { savetoTableWorkspace(investigation->parameters[0]->stringValue, table); } else { savetoTableWorkspace(&emptyCell, table); } // Again, we need to check first if start and end date exist prior to // insertion. if (investigation->startDate) { std::string startDate = formatDateTime(*investigation->startDate, "%Y-%m-%d"); savetoTableWorkspace(&startDate, table); } else { savetoTableWorkspace(&emptyCell, table); } if (investigation->endDate) { std::string endDate = formatDateTime(*investigation->endDate, "%Y-%m-%d"); savetoTableWorkspace(&endDate, table); } else { savetoTableWorkspace(&emptyCell, table); } std::string sessionID = m_session->getSessionId(); savetoTableWorkspace(&sessionID, table); } else { throw std::runtime_error("ICat4Catalog::saveInvestigations expected an " "investigation. Please contact the Mantid " "development team."); } } }