/** * Loads an empty instrument and returns a pointer to the workspace. * * Optionally loads an IPF if a reflection was provided. * * @param instrumentName Name of an inelastic indiretc instrument (IRIS, OSIRIN, *TOSCA, VESUVIO) * @param reflection Reflection mode to load parameters for (diffspec or *diffonly) */ MatrixWorkspace_sptr IndirectDiffractionReduction::loadInstrument(std::string instrumentName, std::string reflection) { std::string idfPath = Mantid::Kernel::ConfigService::Instance().getString( "instrumentDefinition.directory"); std::string parameterFilename = idfPath + instrumentName + "_Definition.xml"; IAlgorithm_sptr loadAlg = AlgorithmManager::Instance().create("LoadEmptyInstrument"); loadAlg->setChild(true); loadAlg->initialize(); loadAlg->setProperty("Filename", parameterFilename); loadAlg->setProperty("OutputWorkspace", "__InDiff_Inst"); loadAlg->execute(); MatrixWorkspace_sptr instWorkspace = loadAlg->getProperty("OutputWorkspace"); // Load parameter file if a reflection was given if (!reflection.empty()) { std::string ipfFilename = idfPath + instrumentName + "_diffraction_" + reflection + "_Parameters.xml"; IAlgorithm_sptr loadParamAlg = AlgorithmManager::Instance().create("LoadParameterFile"); loadParamAlg->setChild(true); loadParamAlg->initialize(); loadParamAlg->setProperty("Filename", ipfFilename); loadParamAlg->setProperty("Workspace", instWorkspace); loadParamAlg->execute(); } return instWorkspace; }
void ApplyPaalmanPings::updateContainer() { const auto canName = m_uiForm.dsContainer->getCurrentDataName(); const auto canValid = m_uiForm.dsContainer->isValid(); const auto useCan = m_uiForm.ckUseCan->isChecked(); if (canValid && useCan) { auto shift = m_uiForm.spCanShift->value(); if (!m_uiForm.ckShiftCan->isChecked()) shift = 0.0; auto scale = m_uiForm.spCanScale->value(); if (!m_uiForm.ckScaleCan->isChecked()) scale = 1.0; IAlgorithm_sptr scaleXAlg = AlgorithmManager::Instance().create("ScaleX"); scaleXAlg->initialize(); scaleXAlg->setLogging(false); scaleXAlg->setProperty("InputWorkspace", canName.toStdString()); scaleXAlg->setProperty("OutputWorkspace", m_containerWorkspaceName); scaleXAlg->setProperty("Factor", shift); scaleXAlg->setProperty("Operation", "Add"); scaleXAlg->execute(); IAlgorithm_sptr scaleAlg = AlgorithmManager::Instance().create("Scale"); scaleAlg->initialize(); scaleAlg->setLogging(false); scaleAlg->setProperty("InputWorkspace", m_containerWorkspaceName); scaleAlg->setProperty("OutputWorkspace", m_containerWorkspaceName); scaleAlg->setProperty("Factor", scale); scaleAlg->setProperty("Operation", "Multiply"); scaleAlg->execute(); const auto sampleValid = m_uiForm.dsSample->isValid(); if (sampleValid) { IAlgorithm_sptr rebin = AlgorithmManager::Instance().create("RebinToWorkspace"); rebin->initialize(); rebin->setLogging(false); rebin->setProperty("WorkspaceToRebin", m_containerWorkspaceName); rebin->setProperty("WorkspaceToMatch", m_sampleWorkspaceName); rebin->setProperty("OutputWorkspace", m_containerWorkspaceName); rebin->execute(); } else { // Sample was not valid so do not rebin m_uiForm.ppPreview->removeSpectrum("Container"); return; } } else { // Can was not valid so do not replot m_uiForm.ppPreview->removeSpectrum("Container"); return; } plotPreview(m_uiForm.spPreviewSpec->value()); }
/** * Handles saving the reductions from the generic algorithm. */ void IndirectDiffractionReduction::saveGenericReductions() { for (auto it = m_plotWorkspaces.begin(); it != m_plotWorkspaces.end(); ++it) { std::string wsName = *it; if (m_uiForm.ckGSS->isChecked()) { std::string tofWsName = wsName + "_tof"; // Convert to TOF for GSS IAlgorithm_sptr convertUnits = AlgorithmManager::Instance().create("ConvertUnits"); convertUnits->initialize(); convertUnits->setProperty("InputWorkspace", wsName); convertUnits->setProperty("OutputWorkspace", tofWsName); convertUnits->setProperty("Target", "TOF"); m_batchAlgoRunner->addAlgorithm(convertUnits); BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromConvUnitsProps; inputFromConvUnitsProps["InputWorkspace"] = tofWsName; // Save GSS std::string gssFilename = wsName + ".gss"; IAlgorithm_sptr saveGSS = AlgorithmManager::Instance().create("SaveGSS"); saveGSS->initialize(); saveGSS->setProperty("Filename", gssFilename); m_batchAlgoRunner->addAlgorithm(saveGSS, inputFromConvUnitsProps); } if (m_uiForm.ckNexus->isChecked()) { // Save NEXus using SaveNexusProcessed std::string nexusFilename = wsName + ".nxs"; IAlgorithm_sptr saveNexus = AlgorithmManager::Instance().create("SaveNexusProcessed"); saveNexus->initialize(); saveNexus->setProperty("InputWorkspace", wsName); saveNexus->setProperty("Filename", nexusFilename); m_batchAlgoRunner->addAlgorithm(saveNexus); } if (m_uiForm.ckAscii->isChecked()) { // Save ASCII using SaveAscii version 1 std::string asciiFilename = wsName + ".dat"; IAlgorithm_sptr saveASCII = AlgorithmManager::Instance().create("SaveAscii", 1); saveASCII->initialize(); saveASCII->setProperty("InputWorkspace", wsName); saveASCII->setProperty("Filename", asciiFilename); m_batchAlgoRunner->addAlgorithm(saveASCII); } } m_batchAlgoRunner->executeBatchAsync(); }
/** Load SPICE data to Matrix workspace * @brief ConvertCWSDExpToMomentum::loadSpiceData * @param filename * @param loaded * @param errmsg * @return */ API::MatrixWorkspace_sptr ConvertCWSDExpToMomentum::loadSpiceData(const std::string &filename, bool &loaded, std::string &errmsg) { // Init output API::MatrixWorkspace_sptr dataws; errmsg = ""; // Load SPICE file try { IAlgorithm_sptr loader = createChildAlgorithm("LoadSpiceXML2DDet"); loader->initialize(); loader->setProperty("Filename", filename); std::vector<size_t> sizelist(2); sizelist[0] = 256; sizelist[1] = 256; loader->setProperty("DetectorGeometry", sizelist); loader->setProperty("LoadInstrument", true); loader->execute(); dataws = loader->getProperty("OutputWorkspace"); loaded = static_cast<bool>(dataws); } catch (std::runtime_error &runerror) { loaded = false; errmsg = runerror.what(); } return dataws; }
/** Set goniometer to matrix workspace and get its rotation matrix R (from * Q-sample to Q-lab * and output 1/R * @brief ConvertCWSDExpToMomentum::setupTransferMatrix * @param dataws :: matrix workspace containing sample rotation angles * @param rotationMatrix :: output as matrix 1/R to convert from Q-lab to * Q-sample */ void ConvertCWSDExpToMomentum::setupTransferMatrix( API::MatrixWorkspace_sptr dataws, Kernel::DblMatrix &rotationMatrix) { // Check sample logs if (!dataws->run().hasProperty("_omega") || !dataws->run().hasProperty("_chi") || !dataws->run().hasProperty("_phi")) throw std::runtime_error( "Data workspace does not have sample log _phi, _chi or _omega. " "Unable to set goniometer and calcualte roation matrix R."); // Call algorithm SetGoniometer IAlgorithm_sptr setalg = createChildAlgorithm("SetGoniometer"); setalg->initialize(); setalg->setProperty("Workspace", dataws); setalg->setProperty("Axis0", "_omega,0,1,0,-1"); setalg->setProperty("Axis1", "_chi,0,0,1,-1"); setalg->setProperty("Axis2", "_phi,0,1,0,-1"); setalg->execute(); if (setalg->isExecuted()) { rotationMatrix = dataws->run().getGoniometer().getR(); g_log.debug() << "Ratation matrix: " << rotationMatrix.str() << "\n"; rotationMatrix.Invert(); g_log.debug() << "Ratation matrix: " << rotationMatrix.str() << "\n"; } else throw std::runtime_error("Unable to set Goniometer."); return; }
/* Executes the underlying algorithm to create the MVP model. @param factory : visualisation factory to use. @param loadingProgressUpdate : Handler for GUI updates while algorithm progresses. @param drawingProgressUpdate : Handler for GUI updates while vtkDataSetFactory::create occurs. */ vtkDataSet* MDEWEventNexusLoadingPresenter::execute(vtkDataSetFactory* factory, ProgressAction& loadingProgressUpdate, ProgressAction& drawingProgressUpdate) { using namespace Mantid::API; using namespace Mantid::Geometry; if(this->shouldLoad()) { Poco::NObserver<ProgressAction, Mantid::API::Algorithm::ProgressNotification> observer(loadingProgressUpdate, &ProgressAction::handler); AnalysisDataService::Instance().remove("MD_EVENT_WS_ID"); IAlgorithm_sptr alg = AlgorithmManager::Instance().create("LoadMD"); alg->initialize(); alg->setPropertyValue("Filename", this->m_filename); alg->setPropertyValue("OutputWorkspace", "MD_EVENT_WS_ID"); alg->setProperty("FileBackEnd", !this->m_view->getLoadInMemory()); //Load from file by default. alg->addObserver(observer); alg->execute(); alg->removeObserver(observer); } Workspace_sptr result=AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID"); Mantid::API::IMDEventWorkspace_sptr eventWs = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(result); factory->setRecursionDepth(this->m_view->getRecursionDepth()); //Create visualisation in one-shot. vtkDataSet* visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate); /*extractMetaData needs to be re-run here because the first execution of this from ::executeLoadMetadata will not have ensured that all dimensions have proper range extents set. */ this->extractMetadata(eventWs); this->appendMetadata(visualDataSet, eventWs->getName()); return visualDataSet; }
/** Call MaskBins * @param dataws :: MatrixWorkspace to mask bins for */ void MaskBinsFromTable::maskBins(API::MatrixWorkspace_sptr dataws) { bool firstloop = true; API::MatrixWorkspace_sptr outputws; size_t numcalls = m_xminVec.size(); g_log.debug() << "There will be " << numcalls << " calls to MaskBins" << "\n"; for (size_t ib = 0; ib < numcalls; ++ib) { // Construct algorithm IAlgorithm_sptr maskbins = this->createChildAlgorithm("MaskBins", 0, 0.3, true); maskbins->initialize(); // Set properties g_log.debug() << "Input to MaskBins: SpetraList = '" << m_spectraVec[ib] << "'; Xmin = " << m_xminVec[ib] << ", Xmax = " << m_xmaxVec[ib] << ".\n"; if (firstloop) { maskbins->setProperty("InputWorkspace", dataws); firstloop = false; } else { if (!outputws) throw runtime_error("Programming logic error."); maskbins->setProperty("InputWorkspace", outputws); } maskbins->setProperty("OutputWorkspace", this->getPropertyValue("OutputWorkspace")); maskbins->setPropertyValue("SpectraList", m_spectraVec[ib]); maskbins->setProperty("XMin", m_xminVec[ib]); maskbins->setProperty("XMax", m_xmaxVec[ib]); bool isexec = maskbins->execute(); if (!isexec) { stringstream errmsg; errmsg << "MaskBins() is not executed for row " << ib << "\n"; g_log.error(errmsg.str()); throw std::runtime_error(errmsg.str()); } else { g_log.debug("MaskBins() is executed successfully."); } outputws = maskbins->getProperty("OutputWorkspace"); if (!outputws) { stringstream errmsg; errmsg << "OutputWorkspace cannot be obtained from algorithm row " << ib << ". "; g_log.error(errmsg.str()); throw std::runtime_error(errmsg.str()); } } // g_log.debug() << "About to set to output." << "\n"; setProperty("OutputWorkspace", outputws); return; }
/** * This function creates the mapping/grouping file for the data analysis. * @param groupType :: Type of grouping (All, Group, Indiviual) * @return path to mapping file, or an empty string if file could not be created. */ QString IndirectConvertToEnergy::createMapFile(const QString& groupType) { QString specRange = m_uiForm.spSpectraMin->text() + "," + m_uiForm.spSpectraMax->text(); if(groupType == "File") { QString groupFile = m_uiForm.dsMapFile->getFirstFilename(); if(groupFile == "") { emit showMessageBox("You must enter a path to the .map file."); } return groupFile; } else if(groupType == "Groups") { QString groupWS = "__Grouping"; IAlgorithm_sptr groupingAlg = AlgorithmManager::Instance().create("CreateGroupingWorkspace"); groupingAlg->initialize(); groupingAlg->setProperty("FixedGroupCount", m_uiForm.spNumberGroups->value()); groupingAlg->setProperty("InstrumentName", getInstrumentConfiguration()->getInstrumentName().toStdString()); groupingAlg->setProperty("ComponentName", getInstrumentConfiguration()->getAnalyserName().toStdString()); groupingAlg->setProperty("OutputWorkspace", groupWS.toStdString()); m_batchAlgoRunner->addAlgorithm(groupingAlg); return groupWS; } else { // Catch All and Individual return groupType; } }
/** * Runs the moments algorithm with preview properties. */ void IndirectMoments::updatePreviewPlot(QString workspaceName) { if(workspaceName.isEmpty()) workspaceName = m_uiForm.dsInput->getCurrentDataName(); QString outputName = workspaceName.left(workspaceName.length() - 4); double scale = m_uiForm.spScale->value(); double eMin = m_dblManager->value(m_properties["EMin"]); double eMax = m_dblManager->value(m_properties["EMax"]); std::string outputWorkspaceName = outputName.toStdString() + "_Moments"; IAlgorithm_sptr momentsAlg = AlgorithmManager::Instance().create("SofQWMoments"); momentsAlg->initialize(); momentsAlg->setProperty("Sample", workspaceName.toStdString()); momentsAlg->setProperty("EnergyMin", eMin); momentsAlg->setProperty("EnergyMax", eMax); momentsAlg->setProperty("Plot", false); momentsAlg->setProperty("Save", false); momentsAlg->setProperty("OutputWorkspace", outputWorkspaceName); if(m_uiForm.ckScale->isChecked()) momentsAlg->setProperty("Scale", scale); // Make sure there are no other algorithms in the queue. // It seems to be possible to have the selctionChangedLazy signal fire multiple times // if the renage selector is moved in a certain way. if(m_batchAlgoRunner->queueLength() == 0) runAlgorithm(momentsAlg); }
/** * Correct loaded data for dead times (if present) and group * @param loadedData :: [input] Load result * @param grouping :: [input] Grouping to use * @returns :: Workspace containing processed data */ Workspace_sptr MuonAnalysisDataLoader::correctAndGroup( const Muon::LoadResult &loadedData, const Mantid::API::Grouping &grouping) const { ITableWorkspace_sptr deadTimes; try { // to get the dead time correction deadTimes = getDeadTimesTable(loadedData); } catch (const std::exception &e) { // If dead correction wasn't applied we can still continue, though should // make user aware of that g_log.warning() << "No dead time correction applied: " << e.what() << "\n"; } // Now apply DTC, if used, and grouping Workspace_sptr correctedGroupedWS; IAlgorithm_sptr alg = AlgorithmManager::Instance().createUnmanaged("MuonProcess"); alg->initialize(); alg->setProperty("InputWorkspace", loadedData.loadedWorkspace); alg->setProperty("Mode", "CorrectAndGroup"); if (deadTimes) { alg->setProperty("ApplyDeadTimeCorrection", true); alg->setProperty("DeadTimeTable", deadTimes); } alg->setProperty("LoadedTimeZero", loadedData.timeZero); alg->setProperty("DetectorGroupingTable", grouping.toTable()); alg->setChild(true); alg->setPropertyValue("OutputWorkspace", "__NotUsed"); alg->execute(); correctedGroupedWS = alg->getProperty("OutputWorkspace"); return correctedGroupedWS; }
/** * Handles a new file being selected by the browser. */ void DensityOfStates::handleFileChange() { QString filename = m_uiForm.mwInputFile->getFirstFilename(); // Check if we have a .phonon file QFileInfo fileInfo(filename); bool isPhononFile = fileInfo.suffix() == "phonon"; std::string filePropName("CASTEPFile"); if (isPhononFile) filePropName = "PHONONFile"; // Need a .phonon file for ion contributions if (isPhononFile) { // Load the ion table to populate the list of ions IAlgorithm_sptr ionTableAlgo = AlgorithmManager::Instance().create("SimulatedDensityOfStates"); ionTableAlgo->initialize(); ionTableAlgo->setProperty(filePropName, filename.toStdString()); ionTableAlgo->setProperty("SpectrumType", "IonTable"); ionTableAlgo->setProperty("OutputWorkspace", "__dos_ions"); m_batchAlgoRunner->addAlgorithm(ionTableAlgo); connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(ionLoadComplete(bool))); m_batchAlgoRunner->executeBatchAsync(); } else {
void AlgorithmHistoryWindow::writeToScriptFile() { QString prevDir = MantidQt::API::AlgorithmInputHistory::Instance().getPreviousDirectory(); QString scriptDir(""); // Default script directory if(prevDir.isEmpty()) { scriptDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("pythonscripts.directory")); } else { scriptDir = prevDir; } QString filePath = QFileDialog::getSaveFileName(this,tr("Save Script As "),scriptDir,tr("Script files (*.py)")); // An empty string indicates they clicked cancel if( filePath.isEmpty() ) return; IAlgorithm_sptr genPyScript = AlgorithmManager::Instance().createUnmanaged("GeneratePythonScript"); genPyScript->initialize(); genPyScript->setChild(true); // Use as utility genPyScript->setRethrows(true); // Make it throw to catch errors messages and display them in a more obvious place for this window genPyScript->setPropertyValue("InputWorkspace",m_wsName.toStdString()); genPyScript->setPropertyValue("Filename",filePath.toStdString()); try { genPyScript->execute(); } catch(std::exception &) { QMessageBox::information(this, "Generate Python Script", "Unable to generate script, see log window for details."); } MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(QFileInfo(filePath).absoluteDir().path()); }
/** Run any algorithm with a variable number of parameters * * @param algorithmName * @param count :: number of arguments given. * @return the algorithm created */ IAlgorithm_sptr FrameworkManagerImpl::exec(const std::string &algorithmName, int count, ...) { if (count % 2 == 1) { throw std::runtime_error( "Must have an even number of parameter/value string arguments"); } // Create the algorithm IAlgorithm_sptr alg = AlgorithmManager::Instance().createUnmanaged(algorithmName, -1); alg->initialize(); if (!alg->isInitialized()) throw std::runtime_error(algorithmName + " was not initialized."); va_list Params; va_start(Params, count); for (int i = 0; i < count; i += 2) { std::string paramName = va_arg(Params, const char *); std::string paramValue = va_arg(Params, const char *); alg->setPropertyValue(paramName, paramValue); } va_end(Params); alg->execute(); return alg; }
/** * Handles completion of the unit conversion and saving algorithm. * * @param error True if algorithm failed. */ void ApplyPaalmanPings::postProcessComplete(bool error) { disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(postProcessComplete(bool))); if (error) { emit showMessageBox("Unable to process corrected workspace.\nSee Results " "Log for more details."); return; } // Handle preview plot plotPreview(m_uiForm.spPreviewSpec->value()); // Handle Mantid plotting QString plotType = m_uiForm.cbPlotOutput->currentText(); if (plotType == "Spectra" || plotType == "Both") plotSpectrum(QString::fromStdString(m_pythonExportWsName)); if (plotType == "Contour" || plotType == "Both") plot2D(QString::fromStdString(m_pythonExportWsName)); // Clean up unwanted workspaces IAlgorithm_sptr deleteAlg = AlgorithmManager::Instance().create("DeleteWorkspace"); deleteAlg->initialize(); deleteAlg->setProperty("Workspace", "__algorithm_can"); deleteAlg->execute(); const auto conv = AnalysisDataService::Instance().doesExist("__algorithm_can_Wavelength"); if (conv) { deleteAlg->setProperty("Workspace", "__algorithm_can_Wavelength"); deleteAlg->execute(); } }
/** * Handles the Plot Input button * * Creates a colour 2D plot of the data */ void IndirectSqw::plotContour() { if(m_uiForm.dsSampleInput->isValid()) { QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName(); QString convertedWsName = sampleWsName.left(sampleWsName.length() - 4) + "_rqw"; IAlgorithm_sptr convertSpecAlg = AlgorithmManager::Instance().create("ConvertSpectrumAxis"); convertSpecAlg->initialize(); convertSpecAlg->setProperty("InputWorkspace", sampleWsName.toStdString()); convertSpecAlg->setProperty("OutputWorkspace", convertedWsName.toStdString()); convertSpecAlg->setProperty("Target", "ElasticQ"); convertSpecAlg->setProperty("EMode", "Indirect"); convertSpecAlg->execute(); QString pyInput = "plot2D('" + convertedWsName + "')\n"; m_pythonRunner.runPythonCode(pyInput); } else { emit showMessageBox("Invalid filename."); } }
/** * Handles a request to preview the symmetrise. * * Runs Symmetrise on the current spectrum and plots in preview mini plot. * * @see IndirectSymmetrise::previewAlgDone() */ void IndirectSymmetrise::preview() { // Handle algorithm completion signal connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(previewAlgDone(bool))); // Do nothing if no data has been laoded QString workspaceName = m_uiForm.dsInput->getCurrentDataName(); if (workspaceName.isEmpty()) return; double e_min = m_dblManager->value(m_properties["EMin"]); double e_max = m_dblManager->value(m_properties["EMax"]); long spectrumNumber = static_cast<long>(m_dblManager->value(m_properties["PreviewSpec"])); std::vector<long> spectraRange(2, spectrumNumber); // Run the algorithm on the preview spectrum only IAlgorithm_sptr symmetriseAlg = AlgorithmManager::Instance().create("Symmetrise", -1); symmetriseAlg->initialize(); symmetriseAlg->setProperty("InputWorkspace", workspaceName.toStdString()); symmetriseAlg->setProperty("XMin", e_min); symmetriseAlg->setProperty("XMax", e_max); symmetriseAlg->setProperty("SpectraRange", spectraRange); symmetriseAlg->setProperty("OutputWorkspace", "__Symmetrise_temp"); symmetriseAlg->setProperty("OutputPropertiesTable", "__SymmetriseProps_temp"); runAlgorithm(symmetriseAlg); }
/** Rebins the distributions and sets error values. */ MatrixWorkspace_sptr VesuvioL1ThetaResolution::processDistribution(MatrixWorkspace_sptr ws, const double binWidth) { const size_t numHist = ws->getNumberHistograms(); double xMin(DBL_MAX); double xMax(DBL_MIN); for (size_t i = 0; i < numHist; i++) { auto &x = ws->x(i); xMin = std::min(xMin, x.front()); xMax = std::max(xMax, x.back()); } std::stringstream binParams; binParams << xMin << "," << binWidth << "," << xMax; IAlgorithm_sptr rebin = AlgorithmManager::Instance().create("Rebin"); rebin->initialize(); rebin->setChild(true); rebin->setLogging(false); rebin->setProperty("InputWorkspace", ws); rebin->setProperty("OutputWorkspace", "__rebin"); rebin->setProperty("Params", binParams.str()); rebin->execute(); ws = rebin->getProperty("OutputWorkspace"); for (size_t i = 0; i < numHist; i++) { auto &y = ws->y(i); auto &e = ws->mutableE(i); std::transform(y.begin(), y.end(), e.begin(), [](double x) { return sqrt(x); }); } return ws; }
/** * Replots the energy mini plot */ void ISISCalibration::calPlotEnergy() { if ( ! m_uiForm.leRunNo->isValid() ) { emit showMessageBox("Run number not valid."); return; } QString files = m_uiForm.leRunNo->getFilenames().join(","); QFileInfo fi(m_uiForm.leRunNo->getFirstFilename()); QString detRange = QString::number(m_dblManager->value(m_properties["ResSpecMin"])) + "," + QString::number(m_dblManager->value(m_properties["ResSpecMax"])); IAlgorithm_sptr reductionAlg = AlgorithmManager::Instance().create("ISISIndirectEnergyTransfer"); reductionAlg->initialize(); reductionAlg->setProperty("Instrument", getInstrumentConfiguration()->getInstrumentName().toStdString()); reductionAlg->setProperty("Analyser", getInstrumentConfiguration()->getAnalyserName().toStdString()); reductionAlg->setProperty("Reflection", getInstrumentConfiguration()->getReflectionName().toStdString()); reductionAlg->setProperty("InputFiles", files.toStdString()); reductionAlg->setProperty("OutputWorkspace", "__IndirectCalibration_reduction"); reductionAlg->setProperty("SpectraRange", detRange.toStdString()); reductionAlg->execute(); if(!reductionAlg->isExecuted()) { g_log.warning("Could not generate energy preview plot."); return; } WorkspaceGroup_sptr reductionOutputGroup = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>("__IndirectCalibration_reduction"); if(reductionOutputGroup->size() == 0) { g_log.warning("No result workspaces, cannot plot energy preview."); return; } MatrixWorkspace_sptr energyWs = boost::dynamic_pointer_cast<MatrixWorkspace>(reductionOutputGroup->getItem(0)); if(!energyWs) { g_log.warning("No result workspaces, cannot plot energy preview."); return; } const Mantid::MantidVec & dataX = energyWs->readX(0); QPair<double, double> range(dataX.front(), dataX.back()); auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground"); setPlotPropertyRange(resBackground, m_properties["ResStart"], m_properties["ResEnd"], range); m_uiForm.ppResolution->clear(); m_uiForm.ppResolution->addSpectrum("Energy", energyWs, 0); m_uiForm.ppResolution->resizeX(); calSetDefaultResolution(energyWs); m_uiForm.ppResolution->replot(); }
void ILLEnergyTransfer::run() { QMap<QString, QString> instDetails = getInstrumentDetails(); IAlgorithm_sptr reductionAlg = AlgorithmManager::Instance().create("IndirectILLReduction"); reductionAlg->initialize(); reductionAlg->setProperty("Analyser", instDetails["analyser"].toStdString()); reductionAlg->setProperty("Reflection", instDetails["reflection"].toStdString()); // Handle input files QString runFilename = m_uiForm.rfInput->getFirstFilename(); reductionAlg->setProperty("Run", runFilename.toStdString()); // Handle calibration bool useCalibration = m_uiForm.ckUseCalibration->isChecked(); if(useCalibration) { QString calibrationWsName = m_uiForm.dsCalibration->getCurrentDataName(); reductionAlg->setProperty("CalibrationWorkspace", calibrationWsName.toStdString()); } // Handle mapping file bool useMapFile = m_uiForm.cbGroupingType->currentText() == "File"; if(useMapFile) { QString mapFilename = m_uiForm.rfMapFile->getFirstFilename(); reductionAlg->setProperty("MapFile", mapFilename.toStdString()); } // Set mirror mode option bool mirrorMode = m_uiForm.ckMirrorMode->isChecked(); reductionAlg->setProperty("MirrorMode", mirrorMode); // Get the name format for output files QFileInfo runFileInfo(runFilename); QString outputFilenameBase = runFileInfo.baseName() + "_" + instDetails["analyser"] + "_" + instDetails["reflection"]; std::string outputFilenameBaseStd = outputFilenameBase.toStdString(); // Set left and right workspaces when using mirror mode if(mirrorMode) { reductionAlg->setProperty("LeftWorkspace", outputFilenameBaseStd + "_left"); reductionAlg->setProperty("RightWorkspace", outputFilenameBaseStd + "_right"); } // Set output workspace properties reductionAlg->setProperty("RawWorkspace", outputFilenameBaseStd + "_raw"); reductionAlg->setProperty("ReducedWorkspace", outputFilenameBaseStd + "_red"); // Set output options reductionAlg->setProperty("Plot", m_uiForm.ckPlot->isChecked()); reductionAlg->setProperty("Save", m_uiForm.ckSave->isChecked()); m_batchAlgoRunner->addAlgorithm(reductionAlg); m_batchAlgoRunner->executeBatchAsync(); }
/** * Updates the analyser and reflection names in the UI when an instrument is selected. * * @param instrumentName Nmae of instrument */ void IndirectInstrumentConfig::updateInstrumentConfigurations(const QString & instrumentName) { if(instrumentName.isEmpty()) return; g_log.debug() << "Loading configuration for instrument: " << instrumentName.toStdString() << std::endl; bool analyserPreviousBlocking = m_uiForm.cbAnalyser->signalsBlocked(); m_uiForm.cbAnalyser->blockSignals(true); m_uiForm.cbAnalyser->clear(); IAlgorithm_sptr loadInstAlg = AlgorithmManager::Instance().create("CreateSimulationWorkspace"); loadInstAlg->initialize(); loadInstAlg->setChild(true); loadInstAlg->setProperty("Instrument", instrumentName.toStdString()); loadInstAlg->setProperty("BinParams", "0,0.5,1"); loadInstAlg->setProperty("OutputWorkspace", "__empty_instrument_workspace"); loadInstAlg->execute(); MatrixWorkspace_sptr instWorkspace = loadInstAlg->getProperty("OutputWorkspace"); QList<QPair<QString, QString>> instrumentModes; Instrument_const_sptr instrument = instWorkspace->getInstrument(); std::vector<std::string> ipfAnalysers = instrument->getStringParameter("analysers"); if(ipfAnalysers.size() == 0) return; QStringList analysers = QString::fromStdString(ipfAnalysers[0]).split(","); for(auto it = analysers.begin(); it != analysers.end(); ++it) { QString analyser = *it; std::string ipfReflections = instrument->getStringParameter("refl-" + analyser.toStdString())[0]; QStringList reflections = QString::fromStdString(ipfReflections).split(","); if(m_removeDiffraction && analyser == "diffraction") continue; if(m_forceDiffraction && analyser != "diffraction") continue; if(reflections.size() > 0) { QVariant data = QVariant(reflections); m_uiForm.cbAnalyser->addItem(analyser, data); } else { m_uiForm.cbAnalyser->addItem(analyser); } } int index = m_uiForm.cbAnalyser->currentIndex(); updateReflectionsList(index); m_uiForm.cbAnalyser->blockSignals(analyserPreviousBlocking); }
/** * Calculates binning parameters. */ void Iqt::calculateBinning() { using namespace Mantid::API; disconnect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this, SLOT(updatePropertyValues(QtProperty *, double))); QString wsName = m_uiForm.dsInput->getCurrentDataName(); QString resName = m_uiForm.dsResolution->getCurrentDataName(); if (wsName.isEmpty() || resName.isEmpty()) return; double energyMin = m_dblManager->value(m_properties["ELow"]); double energyMax = m_dblManager->value(m_properties["EHigh"]); double numBins = m_dblManager->value(m_properties["SampleBinning"]); if (numBins == 0) return; IAlgorithm_sptr furyAlg = AlgorithmManager::Instance().create("TransformToIqt"); furyAlg->initialize(); furyAlg->setProperty("SampleWorkspace", wsName.toStdString()); furyAlg->setProperty("ResolutionWorkspace", resName.toStdString()); furyAlg->setProperty("ParameterWorkspace", "__FuryProperties_temp"); furyAlg->setProperty("EnergyMin", energyMin); furyAlg->setProperty("EnergyMax", energyMax); furyAlg->setProperty("BinReductionFactor", numBins); furyAlg->setProperty("DryRun", true); furyAlg->execute(); // Get property table from algorithm ITableWorkspace_sptr propsTable = AnalysisDataService::Instance().retrieveWS<ITableWorkspace>( "__FuryProperties_temp"); // Get data from property table double energyWidth = propsTable->getColumn("EnergyWidth")->cell<float>(0); int sampleBins = propsTable->getColumn("SampleOutputBins")->cell<int>(0); int resolutionBins = propsTable->getColumn("ResolutionBins")->cell<int>(0); // Update data in property editor m_dblManager->setValue(m_properties["EWidth"], energyWidth); m_dblManager->setValue(m_properties["ResolutionBins"], resolutionBins); m_dblManager->setValue(m_properties["SampleBins"], sampleBins); connect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this, SLOT(updatePropertyValues(QtProperty *, double))); // Warn for low number of resolution bins int numResolutionBins = static_cast<int>(m_dblManager->value(m_properties["ResolutionBins"])); if (numResolutionBins < 5) showMessageBox("Number of resolution bins is less than 5.\nResults may be " "inaccurate."); }
/** * Setup output workspace * @param inputWorkspace: the input workspace * @returns a copy of the input workspace */ MatrixWorkspace_sptr TOFSANSResolutionByPixel::setupOutputWorkspace( MatrixWorkspace_sptr inputWorkspace) { IAlgorithm_sptr duplicate = createChildAlgorithm("CloneWorkspace"); duplicate->initialize(); duplicate->setProperty<Workspace_sptr>("InputWorkspace", inputWorkspace); duplicate->execute(); Workspace_sptr temp = duplicate->getProperty("OutputWorkspace"); return boost::dynamic_pointer_cast<MatrixWorkspace>(temp); }
MatrixWorkspace_sptr CalculateIqt::integration(MatrixWorkspace_sptr workspace) { IAlgorithm_sptr integrationAlgorithm = this->createChildAlgorithm("Integration"); integrationAlgorithm->initialize(); integrationAlgorithm->setProperty("InputWorkspace", workspace); integrationAlgorithm->setProperty("OutputWorkspace", "_"); integrationAlgorithm->execute(); return integrationAlgorithm->getProperty("OutputWorkspace"); }
/** * Loads an empty instrument into a workspace and returns a pointer to it. * * If an analyser and reflection are supplied then the corresponding IPF is also *loaded. * The workspace is not stored in ADS. * * @param instrumentName Name of the instrument to load * @param analyser Analyser being used (optional) * @param reflection Relection being used (optional) * @returns Pointer to instrument workspace */ Mantid::API::MatrixWorkspace_sptr IndirectDataReduction::loadInstrumentIfNotExist(std::string instrumentName, std::string analyser, std::string reflection) { std::string idfDirectory = Mantid::Kernel::ConfigService::Instance().getString( "instrumentDefinition.directory"); try { std::string parameterFilename = idfDirectory + instrumentName + "_Definition.xml"; IAlgorithm_sptr loadAlg = AlgorithmManager::Instance().create("LoadEmptyInstrument"); loadAlg->setChild(true); loadAlg->setLogging(false); loadAlg->initialize(); loadAlg->setProperty("Filename", parameterFilename); loadAlg->setProperty("OutputWorkspace", "__IDR_Inst"); loadAlg->execute(); MatrixWorkspace_sptr instWorkspace = loadAlg->getProperty("OutputWorkspace"); // Load the IPF if given an analyser and reflection if (!analyser.empty() && !reflection.empty()) { std::string ipfFilename = idfDirectory + instrumentName + "_" + analyser + "_" + reflection + "_Parameters.xml"; IAlgorithm_sptr loadParamAlg = AlgorithmManager::Instance().create("LoadParameterFile"); loadParamAlg->setChild(true); loadParamAlg->setLogging(false); loadParamAlg->initialize(); loadParamAlg->setProperty("Filename", ipfFilename); loadParamAlg->setProperty("Workspace", instWorkspace); loadParamAlg->execute(); } return instWorkspace; } catch (std::exception &ex) { g_log.warning() << "Failed to load instrument with error: " << ex.what() << ". The current facility may not be fully " "supported.\n"; return MatrixWorkspace_sptr(); } }
MatrixWorkspace_sptr CalculateIqt::convertToPointData(MatrixWorkspace_sptr workspace) { IAlgorithm_sptr pointDataAlgorithm = this->createChildAlgorithm("ConvertToPointData"); pointDataAlgorithm->initialize(); pointDataAlgorithm->setProperty("InputWorkspace", workspace); pointDataAlgorithm->setProperty("OutputWorkspace", "_"); pointDataAlgorithm->execute(); return pointDataAlgorithm->getProperty("OutputWorkspace"); }
MatrixWorkspace_sptr CalculateIqt::divide(MatrixWorkspace_sptr lhsWorkspace, MatrixWorkspace_sptr rhsWorkspace) { IAlgorithm_sptr divideAlgorithm = this->createChildAlgorithm("Divide"); divideAlgorithm->initialize(); divideAlgorithm->setProperty("LHSWorkspace", lhsWorkspace); divideAlgorithm->setProperty("RHSWorkspace", rhsWorkspace); divideAlgorithm->setProperty("OutputWorkspace", "_"); divideAlgorithm->execute(); return divideAlgorithm->getProperty("OutputWorkspace"); }
MatrixWorkspace_sptr CalculateIqt::cropWorkspace(MatrixWorkspace_sptr workspace, const double xMax) { IAlgorithm_sptr cropAlgorithm = this->createChildAlgorithm("CropWorkspace"); cropAlgorithm->initialize(); cropAlgorithm->setProperty("InputWorkspace", workspace); cropAlgorithm->setProperty("OutputWorkspace", "_"); cropAlgorithm->setProperty("XMax", xMax); cropAlgorithm->execute(); return cropAlgorithm->getProperty("OutputWorkspace"); }
MatrixWorkspace_sptr CalculateIqt::rebin(MatrixWorkspace_sptr workspace, const std::string ¶ms) { IAlgorithm_sptr rebinAlgorithm = this->createChildAlgorithm("Rebin"); rebinAlgorithm->initialize(); rebinAlgorithm->setProperty("InputWorkspace", workspace); rebinAlgorithm->setProperty("OutputWorkspace", "_"); rebinAlgorithm->setProperty("Params", params); rebinAlgorithm->execute(); return rebinAlgorithm->getProperty("OutputWorkspace"); }
void AlgorithmHistoryWindow::copytoClipboard() { // We retrieve a string containing the script by outputting the result of GeneratePythonScript // to a temp file, and parsing it from there. // QTemporaryFile will not allow its files to have extensions, and the GeneratePythonScript // validator must contains a list of accepted extensions. For that reason we choose the // workaround of: // - create a temp file through QTemporaryFile; // - take its filepath and append ".py" to it; // - use the filepath to create our own temp file, which we will handle the deletion of. QTemporaryFile temp; temp.open(); temp.close(); std::string tempFilename = temp.fileName().toStdString() + ".py"; // Create and run algorithm. IAlgorithm_sptr genPyScript = AlgorithmManager::Instance().createUnmanaged("GeneratePythonScript"); genPyScript->initialize(); genPyScript->setChild(true); // Use as utility genPyScript->setRethrows(true); // Make it throw to catch errors messages and display them in a more obvious place for this window genPyScript->setPropertyValue("InputWorkspace",m_wsName.toStdString()); genPyScript->setPropertyValue("Filename",tempFilename); try { genPyScript->execute(); } catch(std::exception &) { QMessageBox::information(this, "Generate Python Script", "Unable to generate script, see log window for details."); return; } QString script; std::ifstream file(tempFilename.c_str(), std::ifstream::in); std::stringstream buffer; // Retrieve script from file. buffer << file.rdbuf(); std::string contents(buffer.str()); script.append(contents.c_str()); file.close(); remove(tempFilename.c_str()); // Send to clipboard. QClipboard *clipboard = QApplication::clipboard(); if(NULL != clipboard) { clipboard->setText(script); } }
/** Creates and initialises an instance of an algorithm. * * The algorithm gets tracked in the list of "managed" algorithms, * which is shown in GUI for cancelling, etc. * * @param algName :: The name of the algorithm required * @param version :: The version of the algorithm required, if not defined most *recent version is used -> version =-1 * @param makeProxy :: If true (default), create and return AlgorithmProxy of *the given algorithm. * DO NOT SET TO FALSE unless you are really sure of what you are doing! * @return A pointer to the created algorithm * @throw NotFoundError Thrown if algorithm requested is not registered * @throw std::runtime_error Thrown if properties string is ill-formed */ IAlgorithm_sptr AlgorithmManagerImpl::create(const std::string &algName, const int &version, bool makeProxy) { Mutex::ScopedLock _lock(this->m_managedMutex); IAlgorithm_sptr alg; try { Algorithm_sptr unmanagedAlg = AlgorithmFactory::Instance().create( algName, version); // Throws on fail: if (makeProxy) alg = IAlgorithm_sptr(new AlgorithmProxy(unmanagedAlg)); else alg = unmanagedAlg; // If this takes us beyond the maximum size, then remove the oldest one(s) while (m_managed_algs.size() >= static_cast<std::deque<IAlgorithm_sptr>::size_type>(m_max_no_algs)) { std::deque<IAlgorithm_sptr>::iterator it; it = m_managed_algs.begin(); // Look for the first (oldest) algo that is NOT running right now. while (it != m_managed_algs.end()) { if (!(*it)->isRunning()) break; ++it; } if (it == m_managed_algs.end()) { // Unusual case where ALL algorithms are running g_log.warning() << "All algorithms in the AlgorithmManager are running. " << "Cannot pop oldest algorithm. " << "You should increase your 'algorithms.retained' value. " << m_managed_algs.size() << " in queue." << std::endl; break; } else { // Normal; erase that algorithm g_log.debug() << "Popping out oldest algorithm " << (*it)->name() << std::endl; m_managed_algs.erase(it); } } // Add to list of managed ones m_managed_algs.push_back(alg); alg->initialize(); } catch (std::runtime_error &ex) { g_log.error() << "AlgorithmManager:: Unable to create algorithm " << algName << ' ' << ex.what() << std::endl; throw std::runtime_error("AlgorithmManager:: Unable to create algorithm " + algName + ' ' + ex.what()); } return alg; }