/** * @brief MDHWInMemoryLoadingPresenter::transposeWs * * vtkDataSets are usually provided in 3D, trying to create these where one of *those dimensions * might be integrated out leads to empty datasets. To avoid this we reorder the *dimensions in our workspace * prior to visualisation by transposing if if needed. * * @param inHistoWs : An input workspace that may integrated dimensions *anywhere. * @param outCachedHistoWs : Cached histo workspace. To write to if needed. * @return A workspace that can be directly rendered from. Integrated dimensions *are always last. */ void MDHWLoadingPresenter::transposeWs( Mantid::API::IMDHistoWorkspace_sptr &inHistoWs, Mantid::API::IMDHistoWorkspace_sptr &outCachedHistoWs) { using namespace Mantid::API; if (!outCachedHistoWs) { /* Construct dimension indexes list for transpose. We do this by forcing integrated dimensions to be the last in the list. All other orderings are kept. */ std::vector<int> integratedDims; std::vector<int> nonIntegratedDims; for (int i = 0; i < int(inHistoWs->getNumDims()); ++i) { auto dim = inHistoWs->getDimension(i); if (dim->getIsIntegrated()) { integratedDims.push_back(i); } else { nonIntegratedDims.push_back(i); } } std::vector<int> orderedDims = nonIntegratedDims; orderedDims.insert(orderedDims.end(), integratedDims.begin(), integratedDims.end()); /* If there has been any reordering above, then the dimension indexes will no longer be sorted. We use that to determine if we can avoid transposing the workspace. */ if (!std::is_sorted(orderedDims.begin(), orderedDims.end())) { IAlgorithm_sptr alg = AlgorithmManager::Instance().create("TransposeMD"); alg->setChild(true); alg->initialize(); alg->setProperty("InputWorkspace", inHistoWs); alg->setPropertyValue("OutputWorkspace", "dummy"); alg->setProperty("Axes", orderedDims); alg->execute(); IMDHistoWorkspace_sptr visualHistoWs = alg->getProperty("OutputWorkspace"); outCachedHistoWs = visualHistoWs; } else { // No need to transpose anything. outCachedHistoWs = inHistoWs; } } }
/// Run the LoadLog Child Algorithm void LoadMuonNexus1::runLoadLog(DataObjects::Workspace2D_sptr localWorkspace) { IAlgorithm_sptr loadLog = createChildAlgorithm("LoadMuonLog"); // Pass through the same input filename loadLog->setPropertyValue("Filename", m_filename); // Set the workspace property to be the same one filled above loadLog->setProperty<MatrixWorkspace_sptr>("Workspace", localWorkspace); // Now execute the Child Algorithm. Catch and log any error, but don't stop. try { loadLog->execute(); } catch (std::runtime_error &) { g_log.error("Unable to successfully run LoadMuonLog Child Algorithm"); } catch (std::logic_error &) { g_log.error("Unable to successfully run LoadMuonLog Child Algorithm"); } if (!loadLog->isExecuted()) g_log.error("Unable to successfully run LoadMuonLog Child Algorithm"); NXRoot root(m_filename); // Get main field direction std::string mainFieldDirection = "Longitudinal"; // default try { NXChar orientation = root.openNXChar("run/instrument/detector/orientation"); // some files have no data there orientation.load(); if (orientation[0] == 't') { auto p = Kernel::make_unique<Kernel::TimeSeriesProperty<double>>("fromNexus"); std::string start_time = root.getString("run/start_time"); p->addValue(start_time, -90.0); localWorkspace->mutableRun().addLogData(std::move(p)); mainFieldDirection = "Transverse"; } } catch (...) { // no data - assume main field was longitudinal } // set output property and add to workspace logs auto &run = localWorkspace->mutableRun(); setProperty("MainFieldDirection", mainFieldDirection); run.addProperty("main_field_direction", mainFieldDirection); ISISRunLogs runLogs(run); runLogs.addStatusLog(run); }
/** * Run the Child Algorithm LoadInstrument. */ void LoadILLIndirect::runLoadInstrument() { IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument"); // Now execute the Child Algorithm. Catch and log any error, but don't stop. try { loadInst->setPropertyValue("InstrumentName", m_instrumentName); loadInst->setProperty<MatrixWorkspace_sptr>("Workspace", m_localWorkspace); loadInst->setProperty("RewriteSpectraMap", Mantid::Kernel::OptionalBool(true)); loadInst->execute(); } catch (...) { g_log.information("Cannot load the instrument definition."); } }
/** * Run the Child Algorithm LoadInstrument. */ void LoadSINQFocus::runLoadInstrument() { IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument"); // Now execute the Child Algorithm. Catch and log any error, but don't stop. try { // TODO: depending on the m_numberOfPixelsPerTube we might need to load a different IDF loadInst->setPropertyValue("InstrumentName", m_instrumentName); loadInst->setProperty<MatrixWorkspace_sptr>("Workspace", m_localWorkspace); loadInst->execute(); } catch (...) { g_log.information("Cannot load the instrument definition."); } }
/// Run the LoadLog Child Algorithm void LoadMuonNexus1::runLoadLog(DataObjects::Workspace2D_sptr localWorkspace) { IAlgorithm_sptr loadLog = createChildAlgorithm("LoadMuonLog"); // Pass through the same input filename loadLog->setPropertyValue("Filename", m_filename); // Set the workspace property to be the same one filled above loadLog->setProperty<MatrixWorkspace_sptr>("Workspace", localWorkspace); // Now execute the Child Algorithm. Catch and log any error, but don't stop. try { loadLog->execute(); } catch (std::runtime_error &) { g_log.error("Unable to successfully run LoadLog Child Algorithm"); } catch (std::logic_error &) { g_log.error("Unable to successfully run LoadLog Child Algorithm"); } if (!loadLog->isExecuted()) g_log.error("Unable to successfully run LoadLog Child Algorithm"); NXRoot root(m_filename); try { NXChar orientation = root.openNXChar("run/instrument/detector/orientation"); // some files have no data there orientation.load(); if (orientation[0] == 't') { Kernel::TimeSeriesProperty<double> *p = new Kernel::TimeSeriesProperty<double>("fromNexus"); std::string start_time = root.getString("run/start_time"); p->addValue(start_time, -90.0); localWorkspace->mutableRun().addLogData(p); setProperty("MainFieldDirection", "Transverse"); } else { setProperty("MainFieldDirection", "Longitudinal"); } } catch (...) { setProperty("MainFieldDirection", "Longitudinal"); } auto &run = localWorkspace->mutableRun(); int n = static_cast<int>(m_numberOfPeriods); ISISRunLogs runLogs(run, n); runLogs.addStatusLog(run); }
/// Run the Child Algorithm LoadInstrument. void LoadILLReflectometry::loadInstrument() { // execute the Child Algorithm. Catch and log any error, but don't stop. g_log.debug("Loading instrument definition..."); try { IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument"); const std::string instrumentName = m_instrument == Supported::D17 ? "D17" : "Figaro"; loadInst->setPropertyValue("InstrumentName", instrumentName); loadInst->setProperty("RewriteSpectraMap", Mantid::Kernel::OptionalBool(true)); loadInst->setProperty<MatrixWorkspace_sptr>("Workspace", m_localWorkspace); loadInst->executeAsChildAlg(); } catch (std::runtime_error &e) { g_log.information() << "Unable to succesfully run LoadInstrument child algorithm: " << e.what() << '\n'; } }
/** Execute the algorithm. */ void MergeMDFiles::exec() { // clear disk buffer which can remain from previous runs // the existance/ usage of the buffer idicates if the algorithm works with file based or memory based target workspaces; // pDiskBuffer = NULL; MultipleFileProperty * multiFileProp = dynamic_cast<MultipleFileProperty*>(getPointerToProperty("Filenames")); m_Filenames = MultipleFileProperty::flattenFileNames(multiFileProp->operator()()); if (m_Filenames.size() == 0) throw std::invalid_argument("Must specify at least one filename."); std::string firstFile = m_Filenames[0]; std::string outputFile = getProperty("OutputFilename"); m_fileBasedTargetWS = false; if (!outputFile.empty()) { m_fileBasedTargetWS = true; if (Poco::File(outputFile).exists()) throw std::invalid_argument(" File "+outputFile+" already exists. Can not use existing file as the target to MergeMD files.\n"+ " Use it as one of source files if you want to add MD data to it" ); } // Start by loading the first file but just the box structure, no events, and not file-backed //m_BoxStruct.loadBoxStructure(firstFile, IAlgorithm_sptr loader = createChildAlgorithm("LoadMD", 0.0, 0.05, false); loader->setPropertyValue("Filename", firstFile); loader->setProperty("MetadataOnly", false); loader->setProperty("BoxStructureOnly", true); loader->setProperty("FileBackEnd", false); loader->executeAsChildAlg(); IMDWorkspace_sptr result= (loader->getProperty("OutputWorkspace")); auto firstWS = boost::dynamic_pointer_cast<API::IMDEventWorkspace>(result); if(!firstWS) throw std::runtime_error("Can not load MDEventWorkspace from initial file "+firstFile); // do the job this->doExecByCloning(firstWS,outputFile); m_OutIWS->setFileNeedsUpdating(false); setProperty("OutputWorkspace", m_OutIWS); }
Workspace_sptr GenericDataProcessorAlgorithm<Base>::assemble(Workspace_sptr partialWS) { Workspace_sptr outputWS = partialWS; #ifdef MPI_BUILD IAlgorithm_sptr gatherAlg = createChildAlgorithm("GatherWorkspaces"); gatherAlg->setLogging(true); gatherAlg->setAlwaysStoreInADS(true); gatherAlg->setProperty("InputWorkspace", partialWS); gatherAlg->setProperty("PreserveEvents", true); gatherAlg->setPropertyValue("OutputWorkspace", "_total"); gatherAlg->execute(); if (isMainThread()) { outputWS = AnalysisDataService::Instance().retrieve("_total"); } #endif return outputWS; }
/// Run LoadInstrumentFromRaw as a Child Algorithm (only if loading from instrument definition file fails) void LoadRaw::runLoadInstrumentFromRaw(DataObjects::Workspace2D_sptr localWorkspace) { IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrumentFromRaw"); loadInst->setPropertyValue("Filename", m_filename); // Set the workspace property to be the same one filled above loadInst->setProperty<MatrixWorkspace_sptr>("Workspace",localWorkspace); // Now execute the Child Algorithm. Catch and log any error, but don't stop. try { loadInst->execute(); } catch (std::runtime_error&) { g_log.error("Unable to successfully run LoadInstrumentFromRaw Child Algorithm"); } if ( ! loadInst->isExecuted() ) g_log.error("No instrument definition loaded"); }
/** Using the [Post]ProcessingAlgorithm and [Post]ProcessingProperties *properties, * create and initialize an algorithm for processing. * * @param postProcessing :: true to create the PostProcessingAlgorithm. * false to create the ProcessingAlgorithm * @return shared pointer to the algorithm, ready for execution. * Returns a NULL pointer if no algorithm was chosen. */ IAlgorithm_sptr LiveDataAlgorithm::makeAlgorithm(bool postProcessing) { std::string prefix = ""; if (postProcessing) prefix = "Post"; // Get the name of the algorithm to run std::string algoName = this->getPropertyValue(prefix + "ProcessingAlgorithm"); algoName = Strings::strip(algoName); // Get the script to run. Ignored if algo is specified std::string script = this->getPropertyValue(prefix + "ProcessingScript"); script = Strings::strip(script); if (!algoName.empty()) { // Properties to pass to algo std::string props = this->getPropertyValue(prefix + "ProcessingProperties"); // Create the UNMANAGED algorithm IAlgorithm_sptr alg = this->createChildAlgorithm(algoName); // Skip some of the properties when setting std::set<std::string> ignoreProps; ignoreProps.insert("InputWorkspace"); ignoreProps.insert("OutputWorkspace"); // ...and pass it the properties alg->setPropertiesWithSimpleString(props, ignoreProps); // Warn if someone put both values. if (!script.empty()) g_log.warning() << "Running algorithm " << algoName << " and ignoring the script code in " << prefix + "ProcessingScript" << std::endl; return alg; } else if (!script.empty()) { // Run a snippet of python IAlgorithm_sptr alg = this->createChildAlgorithm("RunPythonScript"); alg->setLogging(false); alg->setPropertyValue("Code", script); return alg; } else return IAlgorithm_sptr(); }
/** * Execute the algorithm */ void RebinToWorkspace::exec() { // The input workspaces ... MatrixWorkspace_sptr toRebin = getProperty("WorkspaceToRebin"); MatrixWorkspace_sptr toMatch = getProperty("WorkspaceToMatch"); bool PreserveEvents = getProperty("PreserveEvents"); // First we need to create the parameter vector from the workspace with which // we are matching std::vector<double> rb_params = createRebinParameters(toMatch); IAlgorithm_sptr runRebin = createChildAlgorithm("Rebin"); runRebin->setProperty<MatrixWorkspace_sptr>("InputWorkspace", toRebin); runRebin->setPropertyValue("OutputWorkspace", "rebin_out"); runRebin->setProperty("params", rb_params); runRebin->setProperty("PreserveEvents", PreserveEvents); runRebin->executeAsChildAlg(); progress(1); MatrixWorkspace_sptr ws = runRebin->getProperty("OutputWorkspace"); setProperty("OutputWorkspace", ws); }
/// Run the LoadLog Child Algorithm void LoadRaw::runLoadLog(DataObjects::Workspace2D_sptr localWorkspace) { IAlgorithm_sptr loadLog = createChildAlgorithm("LoadLog"); // Pass through the same input filename loadLog->setPropertyValue("Filename",m_filename); // Set the workspace property to be the same one filled above loadLog->setProperty<MatrixWorkspace_sptr>("Workspace",localWorkspace); // Now execute the Child Algorithm. Catch and log any error, but don't stop. try { loadLog->execute(); } catch (std::runtime_error&) { g_log.error("Unable to successfully run LoadLog Child Algorithm"); } if ( ! loadLog->isExecuted() ) g_log.error("Unable to successfully run LoadLog Child Algorithm"); }
/// Creates a PoldiPeak from the given profile function/hkl pair. PoldiPeak_sptr PoldiFitPeaks2D::getPeakFromPeakFunction(IPeakFunction_sptr profileFunction, const V3D &hkl) { // Use EstimatePeakErrors to calculate errors of FWHM and so on IAlgorithm_sptr errorAlg = createChildAlgorithm("EstimatePeakErrors"); errorAlg->setProperty( "Function", boost::dynamic_pointer_cast<IFunction>(profileFunction)); errorAlg->setPropertyValue("OutputWorkspace", "Errors"); errorAlg->execute(); double centre = profileFunction->centre(); double fwhmValue = profileFunction->fwhm(); ITableWorkspace_sptr errorTable = errorAlg->getProperty("OutputWorkspace"); double centreError = errorTable->cell<double>(0, 2); double fwhmError = errorTable->cell<double>(2, 2); UncertainValue d(centre, centreError); UncertainValue fwhm(fwhmValue, fwhmError); UncertainValue intensity; bool useIntegratedIntensities = getProperty("OutputIntegratedIntensities"); if (useIntegratedIntensities) { double integratedIntensity = profileFunction->intensity(); double integratedIntensityError = errorTable->cell<double>(3, 2); intensity = UncertainValue(integratedIntensity, integratedIntensityError); } else { double height = profileFunction->height(); double heightError = errorTable->cell<double>(1, 2); intensity = UncertainValue(height, heightError); } // Create peak with extracted parameters and supplied hkl PoldiPeak_sptr peak = PoldiPeak::create(MillerIndices(hkl), d, intensity, UncertainValue(1.0)); peak->setFwhm(fwhm, PoldiPeak::FwhmRelation::AbsoluteD); return peak; }
/** Calls CropWorkspace as a sub-algorithm and passes to it the InputWorkspace property * @param specInd :: the index number of the histogram to extract * @param start :: the number of the first bin to include (starts counting bins at 0) * @param end :: the number of the last bin to include (starts counting bins at 0) * @throw out_of_range if start, end or specInd are set outside of the vaild range for the workspace * @throw runtime_error if the algorithm just falls over * @throw invalid_argument if the input workspace does not have common binning */ void GetEi::extractSpec(int64_t specInd, double start, double end) { IAlgorithm_sptr childAlg = createSubAlgorithm("CropWorkspace", 100*m_fracCompl, 100*(m_fracCompl+CROP) ); m_fracCompl += CROP; childAlg->setPropertyValue( "InputWorkspace", getPropertyValue("InputWorkspace") ); childAlg->setProperty( "XMin", start); childAlg->setProperty( "XMax", end); childAlg->setProperty( "StartWorkspaceIndex", specInd); childAlg->setProperty( "EndWorkspaceIndex", specInd); childAlg->executeAsSubAlg(); m_tempWS = childAlg->getProperty("OutputWorkspace"); //DEBUGGING CODE uncomment out the line below if you want to see the TOF window that was analysed //AnalysisDataService::Instance().addOrReplace("croped_dist_del", m_tempWS); progress(m_fracCompl); interruption_point(); }
void LoadNexus::runLoadNexusProcessed() { IAlgorithm_sptr loadNexusPro = createChildAlgorithm("LoadNexusProcessed", 0., 1.); // Pass through the same input filename loadNexusPro->setPropertyValue("Filename", m_filename); // Set the workspace property loadNexusPro->setPropertyValue("OutputWorkspace", m_workspace); loadNexusPro->setPropertyValue("SpectrumMin", getPropertyValue("SpectrumMin")); loadNexusPro->setPropertyValue("SpectrumMax", getPropertyValue("SpectrumMax")); loadNexusPro->setPropertyValue("SpectrumList", getPropertyValue("SpectrumList")); /* !!! The spectrum min/max/list properties are currently missing from LoadNexus so don't pass them through here, just print a warning !!! */ // Get the array passed in the spectrum_list, if an empty array was passed use // the default // std::vector<int> specList = getProperty("SpectrumList"); // if ( !specList.empty() ) //{ // g_log.warning("SpectrumList property ignored - it is not implemented in // LoadNexusProcessed."); // //loadNexusPro->setProperty("SpectrumList",specList); //} // int specMin = getProperty("SpectrumMin"); // int specMax = getProperty("SpectrumMax"); // if ( specMax != Mantid::EMPTY_INT() || specMin != 0 ) //{ // g_log.warning("SpectrumMin/Max properties ignored - they are not // implemented in LoadNexusProcessed."); // //loadNexusPro->setProperty("SpectrumMax",specMin); // //loadNexusPro->setProperty("SpectrumMin",specMax); //} loadNexusPro->setPropertyValue("EntryNumber", getPropertyValue("EntryNumber")); // Now execute the Child Algorithm. Catch and log any error, but don't stop. loadNexusPro->execute(); if (!loadNexusPro->isExecuted()) g_log.error( "Unable to successfully run LoadNexusProcessed Child Algorithm"); setOutputWorkspace(loadNexusPro); }
/** Load the instrument geometry File * @param instrument :: instrument name. * @param localWorkspace :: MatrixWorkspace in which to put the instrument geometry */ void LoadPreNexusMonitors::runLoadInstrument(const std::string &instrument, MatrixWorkspace_sptr localWorkspace) { IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument"); // Now execute the Child Algorithm. Catch and log any error, but don't stop. bool executionSuccessful(true); try { loadInst->setPropertyValue("InstrumentName", instrument); loadInst->setProperty<MatrixWorkspace_sptr> ("Workspace", localWorkspace); loadInst->setProperty("RewriteSpectraMap", false); // We have a custom mapping loadInst->execute(); // Populate the instrument parameters in this workspace - this works around a bug localWorkspace->populateInstrumentParameters(); } catch (std::invalid_argument& e) { g_log.information() << "Invalid argument to LoadInstrument Child Algorithm : " << e.what() << std::endl; executionSuccessful = false; } catch (std::runtime_error& e) { g_log.information() << "Unable to successfully run LoadInstrument Child Algorithm : " << e.what() << std::endl; executionSuccessful = false; } // If loading instrument definition file fails if (!executionSuccessful) { g_log.error() << "Error loading Instrument definition file\n"; } else { this->instrument_loaded_correctly = true; } }
/** Load the instrument geometry File * @param eventfilename :: Used to pick the instrument. * @param localWorkspace :: MatrixWorkspace in which to put the instrument * geometry */ void LoadEventPreNexus::runLoadInstrument(const std::string &eventfilename, MatrixWorkspace_sptr localWorkspace) { // determine the instrument parameter file string instrument = Poco::Path(eventfilename).getFileName(); size_t pos = instrument.rfind("_"); // get rid of 'event.dat' pos = instrument.rfind("_", pos - 1); // get rid of 'neutron' pos = instrument.rfind("_", pos - 1); // get rid of the run number instrument = instrument.substr(0, pos); // do the actual work IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument"); // Now execute the Child Algorithm. Catch and log any error, but don't stop. loadInst->setPropertyValue("InstrumentName", instrument); loadInst->setProperty<MatrixWorkspace_sptr>("Workspace", localWorkspace); loadInst->setProperty("RewriteSpectraMap", false); loadInst->executeAsChildAlg(); // Populate the instrument parameters in this workspace - this works around a // bug localWorkspace->populateInstrumentParameters(); }
void DiffractionEventCalibrateDetectors::movedetector(double x, double y, double z, double rotx, double roty, double rotz, std::string detname, MatrixWorkspace_sptr inputW) { IAlgorithm_sptr alg1 = createSubAlgorithm("MoveInstrumentComponent"); alg1->setProperty<MatrixWorkspace_sptr>("Workspace", inputW); alg1->setPropertyValue("ComponentName", detname); //Move in cm for small shifts alg1->setProperty("X", x*0.01); alg1->setProperty("Y", y*0.01); alg1->setProperty("Z", z*0.01); alg1->setPropertyValue("RelativePosition", "1"); alg1->executeAsSubAlg(); IAlgorithm_sptr algx = createSubAlgorithm("RotateInstrumentComponent"); algx->setProperty<MatrixWorkspace_sptr>("Workspace", inputW); algx->setPropertyValue("ComponentName", detname); algx->setProperty("X", 1.0); algx->setProperty("Y", 0.0); algx->setProperty("Z", 0.0); algx->setProperty("Angle", rotx); algx->setPropertyValue("RelativeRotation", "1"); algx->executeAsSubAlg(); IAlgorithm_sptr algy = createSubAlgorithm("RotateInstrumentComponent"); algy->setProperty<MatrixWorkspace_sptr>("Workspace", inputW); algy->setPropertyValue("ComponentName", detname); algy->setProperty("X", 0.0); algy->setProperty("Y", 1.0); algy->setProperty("Z", 0.0); algy->setProperty("Angle", roty); algy->setPropertyValue("RelativeRotation", "1"); algy->executeAsSubAlg(); IAlgorithm_sptr algz = createSubAlgorithm("RotateInstrumentComponent"); algz->setProperty<MatrixWorkspace_sptr>("Workspace", inputW); algz->setPropertyValue("ComponentName", detname); algz->setProperty("X", 0.0); algz->setProperty("Y", 0.0); algz->setProperty("Z", 1.0); algz->setProperty("Angle", rotz); algz->setPropertyValue("RelativeRotation", "1"); algz->executeAsSubAlg(); }
/** Load logs from Nexus file. Logs are expected to be in * /raw_data_1/runlog group of the file. Call to this method must be done * within /raw_data_1 group. * @param ws :: The workspace to load the logs to. * @param entry :: Nexus entry */ void LoadISISNexus2::loadLogs(DataObjects::Workspace2D_sptr ws, NXEntry & entry) { IAlgorithm_sptr alg = createChildAlgorithm("LoadNexusLogs", 0.0, 0.5); alg->setPropertyValue("Filename", this->getProperty("Filename")); alg->setProperty<MatrixWorkspace_sptr>("Workspace", ws); try { alg->executeAsChildAlg(); } catch(std::runtime_error&) { g_log.warning() << "Unable to load run logs. There will be no log " << "data associated with this workspace\n"; return; } // For ISIS Nexus only, fabricate an addtional log containing an array of proton charge information from the periods group. try { NXClass protonChargeClass = entry.openNXGroup("periods"); NXFloat periodsCharge = protonChargeClass.openNXFloat("proton_charge"); periodsCharge.load(); size_t nperiods = periodsCharge.dim0(); std::vector<double> chargesVector(nperiods); std::copy(periodsCharge(), periodsCharge() + nperiods, chargesVector.begin()); ArrayProperty<double>* protonLogData = new ArrayProperty<double>("proton_charge_by_period", chargesVector); ws->mutableRun().addProperty(protonLogData); } catch(std::runtime_error&) { this->g_log.debug("Cannot read periods information from the nexus file. This group may be absent."); } // Populate the instrument parameters. ws->populateInstrumentParameters(); // Make log creator object and add the run status log m_logCreator.reset(new ISISRunLogs(ws->run(), m_numberOfPeriods)); m_logCreator->addStatusLog(ws->mutableRun()); }
/// Run the Child Algorithm LoadInstrument (or LoadInstrumentFromRaw) void LoadRaw::runLoadInstrument(DataObjects::Workspace2D_sptr localWorkspace) { // instrument ID const std::string::size_type stripPath = m_filename.find_last_of("\\/"); std::string instrumentID = m_filename.substr(stripPath+1,3); // get the 1st 3 letters of filename part IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument"); // Now execute the Child Algorithm. Catch and log any error, but don't stop. bool executionSuccessful(true); try { loadInst->setPropertyValue("InstrumentName", instrumentID); loadInst->setProperty<MatrixWorkspace_sptr> ("Workspace", localWorkspace); loadInst->setProperty("RewriteSpectraMap", false); loadInst->execute(); } catch( std::invalid_argument&) { g_log.information("Invalid argument to LoadInstrument Child Algorithm"); executionSuccessful = false; } catch (std::runtime_error&) { g_log.information("Unable to successfully run LoadInstrument Child Algorithm"); executionSuccessful = false; } // If loading instrument definition file fails, run LoadInstrumentFromRaw instead if( !executionSuccessful ) { g_log.information() << "Instrument definition file " << " not found. Attempt to load information about \n" << "the instrument from raw data file.\n"; runLoadInstrumentFromRaw(localWorkspace); } }
void ALCDataLoadingPresenter::load() { m_view->setWaitingCursor(); try { IAlgorithm_sptr alg = AlgorithmManager::Instance().create("PlotAsymmetryByLogValue"); alg->setChild(true); // Don't want workspaces in the ADS alg->setProperty("FirstRun", m_view->firstRun()); alg->setProperty("LastRun", m_view->lastRun()); alg->setProperty("LogValue", m_view->log()); alg->setProperty("Type", m_view->calculationType()); // If time limiting requested, set min/max times if (auto timeRange = m_view->timeRange()) { alg->setProperty("TimeMin", timeRange->first); alg->setProperty("TimeMax", timeRange->second); } alg->setPropertyValue("OutputWorkspace", "__NotUsed"); alg->execute(); m_loadedData = alg->getProperty("OutputWorkspace"); assert(m_loadedData); // If errors are properly caught, shouldn't happen assert(m_loadedData->getNumberHistograms() == 1); // PlotAsymmetryByLogValue guarantees that m_view->setDataCurve(*(ALCHelper::curveDataFromWs(m_loadedData, 0))); } catch(std::exception& e) { m_view->displayError(e.what()); } m_view->restoreCursor(); }
/// Run the Child Algorithm LoadInstrument (or LoadInstrumentFromRaw) API::MatrixWorkspace_sptr LoadEmptyInstrument::runLoadInstrument() { const std::string filename = getPropertyValue("Filename"); // Determine the search directory for XML instrument definition files (IDFs) std::string directoryName = Kernel::ConfigService::Instance().getInstrumentDirectory(); const std::string::size_type stripPath = filename.find_last_of("\\/"); std::string fullPathIDF; if (stripPath != std::string::npos) { fullPathIDF = filename; // since if path already provided don't modify m_filename } else { //std::string instrumentID = m_filename.substr(stripPath+1); fullPathIDF = directoryName + "/" + filename; } IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument",0,1); loadInst->setPropertyValue("Filename", fullPathIDF); MatrixWorkspace_sptr ws = WorkspaceFactory::Instance().create("Workspace2D",1,2,1); loadInst->setProperty<MatrixWorkspace_sptr>("Workspace",ws); // Now execute the Child Algorithm. Catch and log any error and stop, // because there is no point in continuing without a valid instrument. try { loadInst->execute(); } catch (std::runtime_error& ) { g_log.error("Unable to successfully run LoadInstrument Child Algorithm"); throw std::runtime_error("Unable to obtain valid instrument."); } return ws; }
/** Executes the algorithm * * @throw Exception::FileError If the grouping file cannot be opened or read successfully */ void GetDetOffsetsMultiPeaks::exec() { // Process input information processProperties(); // Create information workspaces createInformationWorkspaces(); // Calculate offset of each detector calculateDetectorsOffsets(); // Return the output setProperty("OutputWorkspace",outputW); setProperty("NumberPeaksWorkspace",outputNP); setProperty("MaskWorkspace",maskWS); setProperty("FittedResolutionWorkspace", m_resolutionWS); setProperty("SpectraFitInfoTableWorkspace", m_infoTableWS); setProperty("PeaksOffsetTableWorkspace", m_peakOffsetTableWS); // Also save to .cal file, if requested std::string filename=getProperty("GroupingFileName"); if (!filename.empty()) { progress(0.9, "Saving .cal file"); IAlgorithm_sptr childAlg = createChildAlgorithm("SaveCalFile"); childAlg->setProperty("OffsetsWorkspace", outputW); childAlg->setProperty("MaskWorkspace", maskWS); childAlg->setPropertyValue("Filename", filename); childAlg->executeAsChildAlg(); } // Make summary progress(0.92, "Making summary"); makeFitSummary(); return; }
/** * Integrate each spectra to get the number of counts * @param inputWS :: The workspace to integrate * @param indexMin :: The lower bound of the spectra to integrate * @param indexMax :: The upper bound of the spectra to integrate * @param lower :: The lower bound * @param upper :: The upper bound * @param outputWorkspace2D :: set to true to output a workspace 2D even if the * input is an EventWorkspace * @returns A workspace containing the integrated counts */ MatrixWorkspace_sptr DetectorDiagnostic::integrateSpectra( MatrixWorkspace_sptr inputWS, const int indexMin, const int indexMax, const double lower, const double upper, const bool outputWorkspace2D) { g_log.debug() << "Integrating input spectra.\n"; // If the input spectra only has one bin, assume it has been integrated // already // but we need to pass it to the algorithm so that a copy of the input // workspace is // actually created to use for further calculations // get percentage completed estimates for now, t0 and when we've finished t1 double t0 = m_fracDone, t1 = advanceProgress(RTGetTotalCounts); IAlgorithm_sptr childAlg = createChildAlgorithm("Integration", t0, t1); childAlg->setProperty("InputWorkspace", inputWS); childAlg->setProperty("StartWorkspaceIndex", indexMin); childAlg->setProperty("EndWorkspaceIndex", indexMax); // pass inputed values straight to this integration trusting the checking done // there childAlg->setProperty("RangeLower", lower); childAlg->setProperty("RangeUpper", upper); childAlg->setPropertyValue("IncludePartialBins", "1"); childAlg->executeAsChildAlg(); // Convert to 2D if desired, and if the input was an EventWorkspace. MatrixWorkspace_sptr outputW = childAlg->getProperty("OutputWorkspace"); MatrixWorkspace_sptr finalOutputW = outputW; if (outputWorkspace2D && boost::dynamic_pointer_cast<EventWorkspace>(outputW)) { g_log.debug() << "Converting output Event Workspace into a Workspace2D." << std::endl; childAlg = createChildAlgorithm("ConvertToMatrixWorkspace", t0, t1); childAlg->setProperty("InputWorkspace", outputW); childAlg->executeAsChildAlg(); finalOutputW = childAlg->getProperty("OutputWorkspace"); } return finalOutputW; }
/** * Perform analysis on the given workspace using the parameters supplied * (using the MuonProcess algorithm) * @param inputWS :: [input] Workspace to analyse (previously grouped and * dead-time corrected) * @param options :: [input] Struct containing parameters for what sort of * analysis to do * @returns :: Workspace containing analysed data */ Workspace_sptr MuonAnalysisDataLoader::createAnalysisWorkspace( const Workspace_sptr inputWS, const AnalysisOptions &options) const { IAlgorithm_sptr alg = AlgorithmManager::Instance().createUnmanaged("MuonProcess"); alg->initialize(); // Set input workspace property auto inputGroup = boost::make_shared<WorkspaceGroup>(); // If is a group, will need to handle periods if (auto group = boost::dynamic_pointer_cast<WorkspaceGroup>(inputWS)) { for (int i = 0; i < group->getNumberOfEntries(); i++) { auto ws = boost::dynamic_pointer_cast<MatrixWorkspace>(group->getItem(i)); inputGroup->addWorkspace(ws); } alg->setProperty("SummedPeriodSet", options.summedPeriods); alg->setProperty("SubtractedPeriodSet", options.subtractedPeriods); } else if (auto ws = boost::dynamic_pointer_cast<MatrixWorkspace>(inputWS)) { // Put this single WS into a group and set it as the input property inputGroup->addWorkspace(ws); alg->setProperty("SummedPeriodSet", "1"); } else { throw std::runtime_error( "Cannot create analysis workspace: unsupported workspace type"); } alg->setProperty("InputWorkspace", inputGroup); // Set the rest of the algorithm properties setProcessAlgorithmProperties(alg, options); // We don't want workspace in the ADS so far alg->setChild(true); alg->setPropertyValue("OutputWorkspace", "__NotUsed"); alg->execute(); return alg->getProperty("OutputWorkspace"); }
/** * Assemble the partial workspaces from all MPI processes * @param partialWSName :: Name of the workspace to assemble * @param outputWSName :: Name of the assembled workspace (available in main * thread only) */ Workspace_sptr DataProcessorAlgorithm::assemble(const std::string &partialWSName, const std::string &outputWSName) { std::string threadOutput = partialWSName; #ifdef MPI_BUILD Workspace_sptr partialWS = AnalysisDataService::Instance().retrieve(partialWSName); IAlgorithm_sptr gatherAlg = createChildAlgorithm("GatherWorkspaces"); gatherAlg->setLogging(true); gatherAlg->setAlwaysStoreInADS(true); gatherAlg->setProperty("InputWorkspace", partialWS); gatherAlg->setProperty("PreserveEvents", true); gatherAlg->setPropertyValue("OutputWorkspace", outputWSName); gatherAlg->execute(); if (isMainThread()) threadOutput = outputWSName; #else UNUSED_ARG(outputWSName) #endif Workspace_sptr outputWS = AnalysisDataService::Instance().retrieve(threadOutput); return outputWS; }
/// Run the Child Algorithm LoadInstrument (or LoadInstrumentFromRaw) void LoadRaw2::runLoadInstrument(DataObjects::Workspace2D_sptr localWorkspace) { // get instrument ID std::string instrumentID = isisRaw->i_inst; // get the instrument name size_t i = instrumentID.find_first_of(' '); // cut trailing spaces if (i != std::string::npos) instrumentID.erase(i); IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument"); bool executionSuccessful(true); try { loadInst->setPropertyValue("InstrumentName", instrumentID); loadInst->setProperty<MatrixWorkspace_sptr> ("Workspace", localWorkspace); loadInst->setProperty("RewriteSpectraMap", false); loadInst->execute(); } catch( std::invalid_argument&) { g_log.information("Invalid argument to LoadInstrument Child Algorithm"); executionSuccessful = false; } catch (std::runtime_error&) { g_log.information("Unable to successfully run LoadInstrument Child Algorithm"); executionSuccessful = false; } // If loading instrument definition file fails, run LoadInstrumentFromRaw instead if( !executionSuccessful ) { g_log.information() << "Instrument definition file " << " not found. Attempt to load information about \n" << "the instrument from raw data file.\n"; runLoadInstrumentFromRaw(localWorkspace); } }
/** Rebins the data into common bins of wavelength. * @param workspace :: The input workspace to the rebinning * @param min :: The lower limit in X for the rebinning * @param max :: The upper limit in X for the rebinning * @param numBins :: The number of bins into which to rebin * @return A pointer to the workspace containing the rebinned data * @throw std::runtime_error If the Rebin child algorithm fails */ API::MatrixWorkspace_sptr UnwrapMonitor::rebin(const API::MatrixWorkspace_sptr &workspace, const double &min, const double &max, const int &numBins) { // Calculate the width of a bin const double step = (max - min) / numBins; // Create a Rebin child algorithm IAlgorithm_sptr childAlg = createChildAlgorithm("Rebin"); childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", workspace); childAlg->setPropertyValue("OutputWorkspace", "Anonymous"); // Construct the vector that holds the rebin parameters and set the property std::vector<double> paramArray; paramArray.push_back(min); paramArray.push_back(step); paramArray.push_back(max); childAlg->setProperty<std::vector<double>>("Params", paramArray); g_log.debug() << "Rebinning unwrapped data into " << numBins << " bins of width " << step << " Angstroms, running from " << min << " to " << max << std::endl; childAlg->executeAsChildAlg(); return childAlg->getProperty("OutputWorkspace"); }
void LoadNexus::runLoadMuonNexus() { IAlgorithm_sptr loadMuonNexus = createChildAlgorithm("LoadMuonNexus", 0., 1.); // Pass through the same input filename loadMuonNexus->setPropertyValue("Filename", m_filename); // Set the workspace property std::string outputWorkspace = "OutputWorkspace"; loadMuonNexus->setPropertyValue(outputWorkspace, m_workspace); // Get the array passed in the spectrum_list, if an empty array was passed use // the default std::vector<int> specList = getProperty("SpectrumList"); if (!specList.empty()) loadMuonNexus->setPropertyValue("SpectrumList", getPropertyValue("SpectrumList")); // int specMax = getProperty("SpectrumMax"); if (specMax != Mantid::EMPTY_INT()) { loadMuonNexus->setPropertyValue("SpectrumMax", getPropertyValue("SpectrumMax")); loadMuonNexus->setPropertyValue("SpectrumMin", getPropertyValue("SpectrumMin")); } loadMuonNexus->setPropertyValue("EntryNumber", getPropertyValue("EntryNumber")); // Now execute the Child Algorithm. Catch and log any error, but don't stop. // try // { loadMuonNexus->execute(); // } // catch (std::runtime_error&) // { // g_log.error("Unable to successfully run LoadMuonNexus Child Algorithm"); // } if (!loadMuonNexus->isExecuted()) g_log.error("Unable to successfully run LoadMuonNexus2 Child Algorithm"); setOutputWorkspace(loadMuonNexus); }
/** * Loads the .cal file if necessary. */ void AlignAndFocusPowder::loadCalFile(const std::string &calFilename, const std::string &groupFilename) { // check if the workspaces exist with their canonical names so they are not // reloaded for chunks if ((!m_groupWS) && (!calFilename.empty()) && (!groupFilename.empty())) { try { m_groupWS = AnalysisDataService::Instance().retrieveWS<GroupingWorkspace>( m_instName + "_group"); } catch (Exception::NotFoundError &) { ; // not noteworthy } } if ((!m_calibrationWS) && (!calFilename.empty())) { OffsetsWorkspace_sptr offsetsWS = getProperty("OffsetsWorkspace"); if (offsetsWS) { convertOffsetsToCal(offsetsWS); } else { try { m_calibrationWS = AnalysisDataService::Instance().retrieveWS<ITableWorkspace>( m_instName + "_cal"); } catch (Exception::NotFoundError &) { ; // not noteworthy } if (!m_calibrationWS) { try { OffsetsWorkspace_sptr offsetsWS = AnalysisDataService::Instance().retrieveWS<OffsetsWorkspace>( m_instName + "_offsets"); convertOffsetsToCal(offsetsWS); } catch (Exception::NotFoundError &) { ; // not noteworthy } } } } if ((!m_maskWS) && (!calFilename.empty())) { try { m_maskWS = AnalysisDataService::Instance().retrieveWS<MaskWorkspace>( m_instName + "_mask"); } catch (Exception::NotFoundError &) { ; // not noteworthy } } // see if everything exists to exit early if (m_groupWS && m_calibrationWS && m_maskWS) return; // see if the calfile or grouping file is specified if (calFilename.empty() && groupFilename.empty()) return; // load grouping file if it was already specified bool loadMask = !m_maskWS; if (loadMask && !groupFilename.empty()) { g_log.information() << "Loading Grouping file \"" << groupFilename << "\"\n"; IAlgorithm_sptr alg = createChildAlgorithm("LoadDetectorsGroupingFile"); alg->setProperty("InputFile", groupFilename); alg->executeAsChildAlg(); // get and rename the workspace m_groupWS = alg->getProperty("OutputWorkspace"); const std::string name = m_instName + "_group"; AnalysisDataService::Instance().addOrReplace(name, m_groupWS); this->setPropertyValue("GroupingWorkspace", name); // don't load again from the calibration file loadMask = false; } g_log.information() << "Loading Calibration file \"" << calFilename << "\"\n"; // bunch of booleans to keep track of things bool loadGrouping = !m_groupWS; bool loadCalibration = !m_calibrationWS; IAlgorithm_sptr alg = createChildAlgorithm("LoadDiffCal"); alg->setProperty("InputWorkspace", m_inputW); alg->setPropertyValue("Filename", calFilename); alg->setProperty<bool>("MakeCalWorkspace", loadCalibration); alg->setProperty<bool>("MakeGroupingWorkspace", loadGrouping); alg->setProperty<bool>("MakeMaskWorkspace", loadMask); alg->setProperty<double>("TofMin", getProperty("TMin")); alg->setProperty<double>("TofMax", getProperty("TMax")); alg->setPropertyValue("WorkspaceName", m_instName); alg->executeAsChildAlg(); // replace workspaces as appropriate if (loadGrouping) { m_groupWS = alg->getProperty("OutputGroupingWorkspace"); const std::string name = m_instName + "_group"; AnalysisDataService::Instance().addOrReplace(name, m_groupWS); this->setPropertyValue("GroupingWorkspace", name); } if (loadCalibration) { m_calibrationWS = alg->getProperty("OutputCalWorkspace"); const std::string name = m_instName + "_cal"; AnalysisDataService::Instance().addOrReplace(name, m_calibrationWS); this->setPropertyValue("CalibrationWorkspace", name); } if (loadMask) { m_maskWS = alg->getProperty("OutputMaskWorkspace"); const std::string name = m_instName + "_mask"; AnalysisDataService::Instance().addOrReplace(name, m_maskWS); this->setPropertyValue("MaskWorkspace", name); } }