/** * Sum over transmission group workspaces to produce one * workspace. * @param transGroup : The transmission group to be processed * @return A workspace pointer containing the sum of transmission workspaces. */ Mantid::API::Workspace_sptr ReflectometryReductionOneAuto::sumOverTransmissionGroup( WorkspaceGroup_sptr &transGroup) { // Handle transmission runs // we clone the first member of transmission group as to // avoid addition in place which would affect the original // workspace member. // // We used .release because clone() will return a unique_ptr. // we need to release the ownership of the pointer so that it // can be cast into a shared_ptr of type Workspace. Workspace_sptr transmissionRunSum(transGroup->getItem(0)->clone().release()); // make a variable to store the overall total of the summation MatrixWorkspace_sptr total; // set up and initialize plus algorithm. auto plusAlg = this->createChildAlgorithm("Plus"); plusAlg->setChild(true); // plusAlg->setRethrows(true); plusAlg->initialize(); // now accumalate the group members for (size_t item = 1; item < transGroup->size(); ++item) { plusAlg->setProperty("LHSWorkspace", transmissionRunSum); plusAlg->setProperty("RHSWorkspace", transGroup->getItem(item)); plusAlg->setProperty("OutputWorkspace", transmissionRunSum); plusAlg->execute(); total = plusAlg->getProperty("OutputWorkspace"); } return total; }
/** * Handles the plotting of workspace post algorithm completion */ void Stretch::plotWorkspaces() { WorkspaceGroup_sptr fitWorkspace; fitWorkspace = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( m_fitWorkspaceName); auto sigma = QString::fromStdString(fitWorkspace->getItem(0)->getName()); auto beta = QString::fromStdString(fitWorkspace->getItem(1)->getName()); // Check Sigma and Beta workspaces exist if (sigma.right(5).compare("Sigma") == 0) { if (beta.right(4).compare("Beta") == 0) { // Plot Beta workspace QString pyInput = "from mantidplot import plot2D\n"; if (m_plotType.compare("All") == 0 || m_plotType.compare("Beta") == 0) { pyInput += "importMatrixWorkspace('"; pyInput += beta; pyInput += "').plotGraph2D()\n"; } // Plot Sigma workspace if (m_plotType.compare("All") == 0 || m_plotType.compare("Sigma") == 0) { pyInput += "importMatrixWorkspace('"; pyInput += sigma; pyInput += "').plotGraph2D()\n"; } m_pythonRunner.runPythonCode(pyInput); } } else { g_log.error( "Beta and Sigma workspace were not found and could not be plotted."); } }
WorkspaceGroup_sptr PolarizationCorrectionFredrikze::execPNR(WorkspaceGroup_sptr inWS) { size_t itemIndex = 0; MatrixWorkspace_sptr Ip = boost::dynamic_pointer_cast<MatrixWorkspace>(inWS->getItem(itemIndex++)); MatrixWorkspace_sptr Ia = boost::dynamic_pointer_cast<MatrixWorkspace>(inWS->getItem(itemIndex++)); const auto rho = this->getEfficiencyWorkspace(crhoLabel); const auto pp = this->getEfficiencyWorkspace(cppLabel); const auto D = pp * (rho + 1); const auto nIp = (Ip * (rho * pp + 1.0) + Ia * (pp - 1.0)) / D; const auto nIa = (Ip * (rho * pp - 1.0) + Ia * (pp + 1.0)) / D; // Preserve the history of the inside workspaces nIp->history().addHistory(Ip->getHistory()); nIa->history().addHistory(Ia->getHistory()); WorkspaceGroup_sptr dataOut = boost::make_shared<WorkspaceGroup>(); dataOut->addWorkspace(nIp); dataOut->addWorkspace(nIa); return dataOut; }
WorkspaceGroup_sptr PolarizationCorrection::execPNR(WorkspaceGroup_sptr inWS) { size_t itemIndex = 0; MatrixWorkspace_sptr Ip = boost::dynamic_pointer_cast<MatrixWorkspace>(inWS->getItem(itemIndex++)); MatrixWorkspace_sptr Ia = boost::dynamic_pointer_cast<MatrixWorkspace>(inWS->getItem(itemIndex++)); MatrixWorkspace_sptr ones = copyShapeAndFill(Ip, 1.0); const VecDouble c_rho = getProperty(crhoLabel()); const VecDouble c_pp = getProperty(cppLabel()); const auto rho = this->execPolynomialCorrection( ones, c_rho); // Execute polynomial expression const auto pp = this->execPolynomialCorrection( ones, c_pp); // Execute polynomial expression const auto D = pp * (rho + 1); const auto nIp = (Ip * (rho * pp + 1.0) + Ia * (pp - 1.0)) / D; const auto nIa = (Ip * (rho * pp - 1.0) + Ia * (pp + 1.0)) / D; // Preserve the history of the inside workspaces nIp->history().addHistory(Ip->getHistory()); nIa->history().addHistory(Ia->getHistory()); WorkspaceGroup_sptr dataOut = boost::make_shared<WorkspaceGroup>(); dataOut->addWorkspace(nIp); dataOut->addWorkspace(nIa); return dataOut; }
/** * Handles the plotting of workspace post algorithm completion */ void Stretch::plotWorkspaces() { setPlotResultIsPlotting(true); WorkspaceGroup_sptr fitWorkspace; fitWorkspace = getADSWorkspaceGroup(m_fitWorkspaceName); auto sigma = QString::fromStdString(fitWorkspace->getItem(0)->getName()); auto beta = QString::fromStdString(fitWorkspace->getItem(1)->getName()); // Check Sigma and Beta workspaces exist if (sigma.right(5).compare("Sigma") == 0 && beta.right(4).compare("Beta") == 0) { QString pyInput = "from mantidplot import plot2D\n"; std::string const plotType = m_uiForm.cbPlot->currentText().toStdString(); if (plotType == "All" || plotType == "Beta") { pyInput += "importMatrixWorkspace('"; pyInput += beta; pyInput += "').plotGraph2D()\n"; } if (plotType == "All" || plotType == "Sigma") { pyInput += "importMatrixWorkspace('"; pyInput += sigma; pyInput += "').plotGraph2D()\n"; } m_pythonRunner.runPythonCode(pyInput); } else { g_log.error( "Beta and Sigma workspace were not found and could not be plotted."); } setPlotResultIsPlotting(false); }
void TomographyIfacePresenter::processViewImg() { std::string ip = m_view->showImagePath(); QString suf = QFileInfo(QString::fromStdString(ip)).suffix(); // This is not so great, as we check extensions and not really file // content/headers, as it should be. if ((0 == QString::compare(suf, "fit", Qt::CaseInsensitive)) || (0 == QString::compare(suf, "fits", Qt::CaseInsensitive))) { WorkspaceGroup_sptr wsg = m_model->loadFITSImage(ip); if (!wsg) return; MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast<MatrixWorkspace>(wsg->getItem(0)); if (!ws) return; m_view->showImage(ws); // clean-up container group workspace if (wsg) AnalysisDataService::Instance().remove(wsg->getName()); } else if ((0 == QString::compare(suf, "tif", Qt::CaseInsensitive)) || (0 == QString::compare(suf, "tiff", Qt::CaseInsensitive)) || (0 == QString::compare(suf, "png", Qt::CaseInsensitive))) { m_view->showImage(ip); } else { m_view->userWarning( "Failed to load image - format issue", "Could not load image because the extension of the file " + ip + ", suffix: " + suf.toStdString() + " does not correspond to FITS or TIFF files."); } }
/** * Handles completion of the algorithm. * * @param error If the algorithm failed */ void ISISDiagnostics::algorithmComplete(bool error) { disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmComplete(bool))); if (error) return; WorkspaceGroup_sptr sliceOutputGroup = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( "IndirectDiagnostics_Workspaces"); if (sliceOutputGroup->size() == 0) { g_log.warning("No result workspaces, cannot plot preview."); return; } for (size_t i = 0; i < sliceOutputGroup->size(); i++) { QString wsName = QString::fromStdString(sliceOutputGroup->getItem(i)->name()); } // Enable plot and save buttons m_uiForm.pbSave->setEnabled(true); m_uiForm.pbPlot->setEnabled(true); // Update the preview plots sliceAlgDone(false); m_batchAlgoRunner->executeBatchAsync(); }
/** * Groups together a vector of workspaces. This is done "manually", since the * workspaces being passed will be outside of the ADS and so the GroupWorkspaces * alg is not an option here. * * @param wsList :: the list of workspaces to group */ API::WorkspaceGroup_sptr Load::groupWsList(const std::vector<API::Workspace_sptr> &wsList) { auto group = boost::make_shared<WorkspaceGroup>(); for (const auto &ws : wsList) { WorkspaceGroup_sptr isGroup = boost::dynamic_pointer_cast<WorkspaceGroup>(ws); // If the ws to add is already a group, then add its children individually. if (isGroup) { std::vector<std::string> childrenNames = isGroup->getNames(); size_t count = 1; for (auto childName = childrenNames.begin(); childName != childrenNames.end(); ++childName, ++count) { Workspace_sptr childWs = isGroup->getItem(*childName); isGroup->remove(*childName); // childWs->setName(isGroup->getName() + "_" + // boost::lexical_cast<std::string>(count)); group->addWorkspace(childWs); } // Remove the old group from the ADS AnalysisDataService::Instance().remove(isGroup->getName()); } else { group->addWorkspace(ws); } } return group; }
/** * Handle completion of the algorithm. * * @param error If the algorithm failed */ void ResNorm::handleAlgorithmComplete(bool error) { if (error) return; QString outputBase = (m_uiForm.dsResolution->getCurrentDataName()).toLower(); const int indexCut = outputBase.lastIndexOf("_"); outputBase = outputBase.left(indexCut); outputBase += "_ResNorm"; std::string outputBaseStr = outputBase.toStdString(); WorkspaceGroup_sptr fitWorkspaces = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( outputBaseStr + "_Fit_Workspaces"); QString fitWsName(""); if (fitWorkspaces) fitWsName = QString::fromStdString(fitWorkspaces->getItem(m_previewSpec)->name()); // MantidPlot plotting QString plotOptions(m_uiForm.cbPlot->currentText()); if (plotOptions == "Intensity" || plotOptions == "All") plotSpectrum(QString::fromStdString(m_pythonExportWsName) + "_Intensity"); if (plotOptions == "Stretch" || plotOptions == "All") plotSpectrum(QString::fromStdString(m_pythonExportWsName) + "_Stretch"); if (plotOptions == "Fit" || plotOptions == "All") plotSpectrum(fitWsName, 0, 1); loadFile(m_uiForm.dsResolution->getFullFilePath(), m_uiForm.dsResolution->getCurrentDataName()); // Update preview plot previewSpecChanged(m_previewSpec); }
/** * 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 IqtFit::updatePlot() { if (!m_ffInputWS) { g_log.error("No workspace loaded, cannot create preview plot."); return; } int specNo = m_uiForm.spPlotSpectrum->value(); m_uiForm.ppPlot->clear(); m_uiForm.ppPlot->addSpectrum("Sample", m_ffInputWS, specNo); try { const QPair<double, double> curveRange = m_uiForm.ppPlot->getCurveRange("Sample"); const std::pair<double, double> range(curveRange.first, curveRange.second); m_uiForm.ppPlot->getRangeSelector("FuryFitRange") ->setRange(range.first, range.second); m_ffRangeManager->setRange(m_properties["StartX"], range.first, range.second); m_ffRangeManager->setRange(m_properties["EndX"], range.first, range.second); setDefaultParameters("Exponential1"); setDefaultParameters("Exponential2"); setDefaultParameters("StretchedExp"); m_uiForm.ppPlot->resizeX(); m_uiForm.ppPlot->setAxisRange(qMakePair(0.0, 1.0), QwtPlot::yLeft); } catch (std::invalid_argument &exc) { showMessageBox(exc.what()); } // If there is a result plot then plot it if (AnalysisDataService::Instance().doesExist(m_pythonExportWsName)) { WorkspaceGroup_sptr outputGroup = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( m_pythonExportWsName); if (specNo >= static_cast<int>(outputGroup->size())) return; MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast<MatrixWorkspace>( outputGroup->getItem(specNo)); if (ws) { if (m_uiForm.ckPlotGuess->isChecked()) { m_uiForm.ppPlot->removeSpectrum("Guess"); } m_uiForm.ppPlot->addSpectrum("Fit", ws, 1, Qt::red); m_uiForm.ppPlot->addSpectrum("Diff", ws, 2, Qt::blue); } } }
/** * Sum transmission workspaces that belong to a workspace group * @param transGroup : The transmission group containing the transmission runs * @return :: A workspace pointer containing the sum of transmission workspaces */ MatrixWorkspace_sptr ReflectometryReductionOneAuto2::sumTransmissionWorkspaces( WorkspaceGroup_sptr &transGroup) { const std::string transSum = "trans_sum"; Workspace_sptr sumWS = transGroup->getItem(0)->clone(); /// For this step to appear in the history of the output workspaces I need to /// set child to false and work with the ADS auto plusAlg = createChildAlgorithm("Plus"); plusAlg->setChild(false); plusAlg->initialize(); for (size_t item = 1; item < transGroup->size(); item++) { plusAlg->setProperty("LHSWorkspace", sumWS); plusAlg->setProperty("RHSWorkspace", transGroup->getItem(item)); plusAlg->setProperty("OutputWorkspace", transSum); plusAlg->execute(); sumWS = AnalysisDataService::Instance().retrieve(transSum); } MatrixWorkspace_sptr result = boost::dynamic_pointer_cast<MatrixWorkspace>(sumWS); AnalysisDataService::Instance().remove(transSum); return result; }
/** * Handles completion of the correction algorithm. * * @param error True of the algorithm failed */ void CalculatePaalmanPings::absCorComplete(bool error) { disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(absCorComplete(bool))); if (error) { emit showMessageBox("Absorption correction calculation failed.\nSee " "Results Log for more details."); return; } // Convert the spectrum axis of correction factors to Q const auto sampleWsName = m_uiForm.dsSample->getCurrentDataName().toStdString(); MatrixWorkspace_sptr sampleWs = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(sampleWsName); WorkspaceGroup_sptr corrections = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( m_pythonExportWsName); for (size_t i = 0; i < corrections->size(); i++) { MatrixWorkspace_sptr factorWs = boost::dynamic_pointer_cast<MatrixWorkspace>(corrections->getItem(i)); if (!factorWs || !sampleWs) continue; if (getEMode(sampleWs) == "Indirect") { API::BatchAlgorithmRunner::AlgorithmRuntimeProps convertSpecProps; IAlgorithm_sptr convertSpecAlgo = AlgorithmManager::Instance().create("ConvertSpectrumAxis"); convertSpecAlgo->initialize(); convertSpecAlgo->setProperty("InputWorkspace", factorWs); convertSpecAlgo->setProperty("OutputWorkspace", factorWs->getName()); convertSpecAlgo->setProperty("Target", "ElasticQ"); convertSpecAlgo->setProperty("EMode", "Indirect"); try { convertSpecAlgo->setProperty("EFixed", getEFixed(factorWs)); } catch (std::runtime_error &) { } m_batchAlgoRunner->addAlgorithm(convertSpecAlgo); } } // Run algorithm queue connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(postProcessComplete(bool))); m_batchAlgoRunner->executeBatchAsync(); }
/** * Returns a workspace for the first period as specified using FirstPeriod * property. * @param group :: Loaded group of workspaces to use * @return Workspace for the period */ MatrixWorkspace_sptr MuonLoad::getFirstPeriodWS(WorkspaceGroup_sptr group) { int firstPeriod = getProperty("FirstPeriod"); MatrixWorkspace_sptr resultWS; if (firstPeriod < 0 || firstPeriod >= static_cast<int>(group->size())) throw std::invalid_argument( "Workspace doesn't contain specified first period"); resultWS = boost::dynamic_pointer_cast<MatrixWorkspace>(group->getItem(firstPeriod)); if (!resultWS) throw std::invalid_argument( "First period workspace is not a MatrixWorkspace"); return resultWS; }
/** * Run instead of exec when operating on groups */ bool SaveNXTomo::processGroups() { try { std::string name = getPropertyValue("InputWorkspaces"); WorkspaceGroup_sptr groupWS = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(name); for (int i = 0; i < groupWS->getNumberOfEntries(); ++i) { m_workspaces.push_back( boost::dynamic_pointer_cast<Workspace2D>(groupWS->getItem(i))); } } catch (...) { } if (m_workspaces.size() != 0) processAll(); return true; }
/** * Remove a workspace group and all its members from the ADS. * @param name :: A group to remove. */ void AnalysisDataServiceImpl::deepRemoveGroup(const std::string &name) { WorkspaceGroup_sptr group = retrieveWS<WorkspaceGroup>(name); if (!group) { throw std::runtime_error("Workspace " + name + " is not a workspace group."); } group->observeADSNotifications(false); for (size_t i = 0; i < group->size(); ++i) { auto ws = group->getItem(i); WorkspaceGroup_sptr gws = boost::dynamic_pointer_cast<WorkspaceGroup>(ws); if (gws) { // if a member is a group remove its items as well deepRemoveGroup(gws->name()); } else { remove(ws->name()); } } remove(name); }
/** * Returns a workspace for the second period as specified using SecondPeriod * property. * @param group :: Loaded group of workspaces to use * @return Workspace for the period */ MatrixWorkspace_sptr MuonLoad::getSecondPeriodWS(WorkspaceGroup_sptr group) { int secondPeriod = getProperty("SecondPeriod"); MatrixWorkspace_sptr resultWS; if (secondPeriod != EMPTY_INT()) { if (secondPeriod < 0 || secondPeriod >= static_cast<int>(group->size())) throw std::invalid_argument( "Workspace doesn't contain specified second period"); resultWS = boost::dynamic_pointer_cast<MatrixWorkspace>( group->getItem(secondPeriod)); if (!resultWS) throw std::invalid_argument( "Second period workspace is not a MatrixWorkspace"); } return resultWS; }
void SmoothNeighboursDialog::inputWorkspaceChanged(const QString& pName) { UNUSED_ARG(pName); m_propertiesWidget->m_groupWidgets[RECTANGULAR_GROUP]->setVisible(false); m_propertiesWidget->m_groupWidgets[NON_UNIFORM_GROUP]->setVisible(false); std::string inWsName = INPUT_WORKSPACE.toStdString(); // Workspace should have been set by PropertyWidget before emitting valueChanged MatrixWorkspace_sptr inWs = this->getAlgorithm()->getProperty(inWsName); if(!inWs) { // Workspace groups are NOT returned by IWP->getWorkspace(), as they are not MatrixWorkspace, // so check the ADS for the GroupWorkspace with the same name std::string inWsValue = this->getAlgorithm()->getPointerToProperty(inWsName)->value(); // If it really doesn't exist, don't do anything if(!AnalysisDataService::Instance().doesExist(inWsValue)) return; WorkspaceGroup_sptr inGroupWs = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(inWsValue); if(inGroupWs) // If is a group workspace, use the first workspace to determine the instrument type, // as most of the times it will be the same for all the workspaces inWs = boost::dynamic_pointer_cast<MatrixWorkspace>(inGroupWs->getItem(0)); else // If is not a GroupWorkspace as well, do nothing return; } Instrument::ContainsState containsRectDetectors = inWs->getInstrument()->containsRectDetectors(); if(containsRectDetectors == Instrument::ContainsState::Full) m_propertiesWidget->m_groupWidgets[RECTANGULAR_GROUP]->setVisible(true); else m_propertiesWidget->m_groupWidgets[NON_UNIFORM_GROUP]->setVisible(true); }
/** * Updates the preview plot when the algorithm is complete. * * @param error True if the algorithm was stopped due to error, false otherwise */ void ISISDiagnostics::sliceAlgDone(bool error) { disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(sliceAlgDone(bool))); if (error) return; QStringList filenames = m_uiForm.dsInputFiles->getFilenames(); if (filenames.size() < 1) return; WorkspaceGroup_sptr sliceOutputGroup = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( "IndirectDiagnostics_Workspaces"); if (sliceOutputGroup->size() == 0) { g_log.warning("No result workspaces, cannot plot preview."); return; } MatrixWorkspace_sptr sliceWs = boost::dynamic_pointer_cast<MatrixWorkspace>( sliceOutputGroup->getItem(0)); if (!sliceWs) { g_log.warning("No result workspaces, cannot plot preview."); return; } // Set workspace for Python export as the first result workspace m_pythonExportWsName = sliceWs->getName(); // Plot result spectrum m_uiForm.ppSlicePreview->clear(); m_uiForm.ppSlicePreview->addSpectrum("Slice", sliceWs, 0); m_uiForm.ppSlicePreview->resizeX(); // Ungroup the output workspace sliceOutputGroup->removeAll(); AnalysisDataService::Instance().remove("IndirectDiagnostics_Workspaces"); }
/** * Updates the preview plot when the algorithm is complete. * * @param error True if the algorithm was stopped due to error, false otherwise */ void IndirectDiagnostics::sliceAlgDone(bool error) { if(error) return; QStringList filenames = m_uiForm.dsInputFiles->getFilenames(); if(filenames.size() < 1) return; WorkspaceGroup_sptr sliceOutputGroup = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>("IndirectDiagnostics_Workspaces"); if(sliceOutputGroup->size() == 0) { g_log.warning("No result workspaces, cannot plot preview."); return; } MatrixWorkspace_sptr sliceWs = boost::dynamic_pointer_cast<MatrixWorkspace>(sliceOutputGroup->getItem(0)); if(!sliceWs) { g_log.warning("No result workspaces, cannot plot preview."); return; } // Set workspace for Python export as the first result workspace m_pythonExportWsName = sliceWs->getName(); // Plot result spectrum plotMiniPlot(sliceWs, 0, "SlicePreviewPlot", "SlicePreviewCurve"); // Set X range to data range setXAxisToCurve("SlicePreviewPlot", "SlicePreviewCurve"); m_plots["SlicePreviewPlot"]->replot(); // Ungroup the output workspace sliceOutputGroup->removeAll(); AnalysisDataService::Instance().remove("IndirectDiagnostics_Workspaces"); }
/** * Sets a new preview spectrum for the mini plot. * * @param value workspace index */ void ResNorm::previewSpecChanged(int value) { m_previewSpec = value; // Update vanadium plot if (m_uiForm.dsVanadium->isValid()) m_uiForm.ppPlot->addSpectrum( "Vanadium", m_uiForm.dsVanadium->getCurrentDataName(), m_previewSpec); // Update fit plot std::string fitWsGroupName(m_pythonExportWsName + "_Fit_Workspaces"); std::string fitParamsName(m_pythonExportWsName + "_Fit"); if (AnalysisDataService::Instance().doesExist(fitWsGroupName)) { WorkspaceGroup_sptr fitWorkspaces = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( fitWsGroupName); ITableWorkspace_sptr fitParams = AnalysisDataService::Instance().retrieveWS<ITableWorkspace>( fitParamsName); if (fitWorkspaces && fitParams) { Column_const_sptr scaleFactors = fitParams->getColumn("Scaling"); std::string fitWsName(fitWorkspaces->getItem(m_previewSpec)->name()); MatrixWorkspace_const_sptr fitWs = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( fitWsName); MatrixWorkspace_sptr fit = WorkspaceFactory::Instance().create(fitWs, 1); fit->setX(0, fitWs->readX(1)); fit->getSpectrum(0)->setData(fitWs->readY(1), fitWs->readE(1)); for (size_t i = 0; i < fit->blocksize(); i++) fit->dataY(0)[i] /= scaleFactors->cell<double>(m_previewSpec); m_uiForm.ppPlot->addSpectrum("Fit", fit, 0, Qt::red); } } }
/** * Validate the multiperiods workspace groups. Gives the opportunity to exit * processing if things don't look right. * @param vecMultiPeriodGroups : vector of multiperiod groups. */ void MultiPeriodGroupWorker::validateMultiPeriodGroupInputs( const VecWSGroupType &vecMultiPeriodGroups) const { const size_t multiPeriodGroupsSize = vecMultiPeriodGroups.size(); if (multiPeriodGroupsSize > 0) { const size_t benchMarkGroupSize = vecMultiPeriodGroups[0]->size(); for (size_t i = 0; i < multiPeriodGroupsSize; ++i) { WorkspaceGroup_sptr currentGroup = vecMultiPeriodGroups[i]; if (currentGroup->size() != benchMarkGroupSize) { throw std::runtime_error("Not all the input Multi-period-group input " "workspaces are the same size."); } for (size_t j = 0; j < currentGroup->size(); ++j) { MatrixWorkspace_const_sptr currentNestedWS = boost::dynamic_pointer_cast<const MatrixWorkspace>( currentGroup->getItem(j)); Property *nPeriodsProperty = currentNestedWS->run().getLogData("nperiods"); size_t nPeriods = std::stoul(nPeriodsProperty->value()); if (nPeriods != benchMarkGroupSize) { throw std::runtime_error("Missmatch between nperiods log and the " "number of workspaces in the input group: " + vecMultiPeriodGroups[i]->getName()); } Property *currentPeriodProperty = currentNestedWS->run().getLogData("current_period"); size_t currentPeriod = std::stoul(currentPeriodProperty->value()); if (currentPeriod != (j + 1)) { throw std::runtime_error("Multiperiod group workspaces must be " "ordered by current_period. Correct: " + currentNestedWS->getName()); } } } } }
/** * Handle completion of the algorithm. * * @param error If the algorithm failed */ void ResNorm::handleAlgorithmComplete(bool error) { if (error) return; WorkspaceGroup_sptr fitWorkspaces = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( m_pythonExportWsName + "_Fit_Workspaces"); QString fitWsName(""); if (fitWorkspaces) fitWsName = QString::fromStdString(fitWorkspaces->getItem(m_previewSpec)->name()); // MantidPlot plotting QString plotOptions(m_uiForm.cbPlot->currentText()); if (plotOptions == "Intensity" || plotOptions == "All") plotSpectrum(QString::fromStdString(m_pythonExportWsName) + "_Intensity"); if (plotOptions == "Stretch" || plotOptions == "All") plotSpectrum(QString::fromStdString(m_pythonExportWsName) + "_Stretch"); if (plotOptions == "Fit" || plotOptions == "All") plotSpectrum(fitWsName, 0, 1); // Update preview plot previewSpecChanged(m_previewSpec); }
bool ReflectometryReductionOneAuto::processGroups() { auto group = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( getPropertyValue("InputWorkspace")); const std::string outputIvsQ = this->getPropertyValue("OutputWorkspace"); const std::string outputIvsLam = this->getPropertyValue("OutputWorkspaceWavelength"); // Create a copy of ourselves Algorithm_sptr alg = this->createChildAlgorithm( this->name(), -1, -1, this->isLogging(), this->version()); alg->setChild(false); alg->setRethrows(true); // Copy all the non-workspace properties over std::vector<Property *> props = this->getProperties(); for (auto prop = props.begin(); prop != props.end(); ++prop) { if (*prop) { IWorkspaceProperty *wsProp = dynamic_cast<IWorkspaceProperty *>(*prop); if (!wsProp) alg->setPropertyValue((*prop)->name(), (*prop)->value()); } } // Check if the transmission runs are groups or not const std::string firstTrans = this->getPropertyValue("FirstTransmissionRun"); WorkspaceGroup_sptr firstTransG; if (!firstTrans.empty()) { auto firstTransWS = AnalysisDataService::Instance().retrieveWS<Workspace>(firstTrans); firstTransG = boost::dynamic_pointer_cast<WorkspaceGroup>(firstTransWS); if (!firstTransG) alg->setProperty("FirstTransmissionRun", firstTrans); else if (group->size() != firstTransG->size()) throw std::runtime_error("FirstTransmissionRun WorkspaceGroup must be " "the same size as the InputWorkspace " "WorkspaceGroup"); } const std::string secondTrans = this->getPropertyValue("SecondTransmissionRun"); WorkspaceGroup_sptr secondTransG; if (!secondTrans.empty()) { auto secondTransWS = AnalysisDataService::Instance().retrieveWS<Workspace>(secondTrans); secondTransG = boost::dynamic_pointer_cast<WorkspaceGroup>(secondTransWS); if (!secondTransG) alg->setProperty("SecondTransmissionRun", secondTrans); else if (group->size() != secondTransG->size()) throw std::runtime_error("SecondTransmissionRun WorkspaceGroup must be " "the same size as the InputWorkspace " "WorkspaceGroup"); } std::vector<std::string> IvsQGroup, IvsLamGroup; // Execute algorithm over each group member (or period, if this is // multiperiod) size_t numMembers = group->size(); for (size_t i = 0; i < numMembers; ++i) { const std::string IvsQName = outputIvsQ + "_" + boost::lexical_cast<std::string>(i + 1); const std::string IvsLamName = outputIvsLam + "_" + boost::lexical_cast<std::string>(i + 1); alg->setProperty("InputWorkspace", group->getItem(i)->name()); alg->setProperty("OutputWorkspace", IvsQName); alg->setProperty("OutputWorkspaceWavelength", IvsLamName); // Handle transmission runs if (firstTransG) alg->setProperty("FirstTransmissionRun", firstTransG->getItem(i)->name()); if (secondTransG) alg->setProperty("SecondTransmissionRun", secondTransG->getItem(i)->name()); alg->execute(); IvsQGroup.push_back(IvsQName); IvsLamGroup.push_back(IvsLamName); // We use the first group member for our thetaout value if (i == 0) this->setPropertyValue("ThetaOut", alg->getPropertyValue("ThetaOut")); } // Group the IvsQ and IvsLam workspaces Algorithm_sptr groupAlg = this->createChildAlgorithm("GroupWorkspaces"); groupAlg->setChild(false); groupAlg->setRethrows(true); groupAlg->setProperty("InputWorkspaces", IvsLamGroup); groupAlg->setProperty("OutputWorkspace", outputIvsLam); groupAlg->execute(); groupAlg->setProperty("InputWorkspaces", IvsQGroup); groupAlg->setProperty("OutputWorkspace", outputIvsQ); groupAlg->execute(); // If this is a multiperiod workspace and we have polarization corrections // enabled if (this->getPropertyValue("PolarizationAnalysis") != noPolarizationCorrectionMode()) { if (group->isMultiperiod()) { // Perform polarization correction over the IvsLam group Algorithm_sptr polAlg = this->createChildAlgorithm("PolarizationCorrection"); polAlg->setChild(false); polAlg->setRethrows(true); polAlg->setProperty("InputWorkspace", outputIvsLam); polAlg->setProperty("OutputWorkspace", outputIvsLam); polAlg->setProperty("PolarizationAnalysis", this->getPropertyValue("PolarizationAnalysis")); polAlg->setProperty("CPp", this->getPropertyValue(cppLabel())); polAlg->setProperty("CRho", this->getPropertyValue(crhoLabel())); polAlg->setProperty("CAp", this->getPropertyValue(cApLabel())); polAlg->setProperty("CAlpha", this->getPropertyValue(cAlphaLabel())); polAlg->execute(); // Now we've overwritten the IvsLam workspaces, we'll need to recalculate // the IvsQ ones alg->setProperty("FirstTransmissionRun", ""); alg->setProperty("SecondTransmissionRun", ""); for (size_t i = 0; i < numMembers; ++i) { const std::string IvsQName = outputIvsQ + "_" + boost::lexical_cast<std::string>(i + 1); const std::string IvsLamName = outputIvsLam + "_" + boost::lexical_cast<std::string>(i + 1); alg->setProperty("InputWorkspace", IvsLamName); alg->setProperty("OutputWorkspace", IvsQName); alg->setProperty("OutputWorkspaceWavelength", IvsLamName); alg->execute(); } } else { g_log.warning("Polarization corrections can only be performed on " "multiperiod workspaces."); } } // We finished successfully this->setPropertyValue("OutputWorkspace", outputIvsQ); this->setPropertyValue("OutputWorkspaceWavelength", outputIvsLam); setExecuted(true); notificationCenter().postNotification( new FinishedNotification(this, isExecuted())); return true; }
/** Performs asymmetry analysis on a loaded workspace * @param loadedWs :: [input] Workspace to apply analysis to * @param index :: [input] Vector index where results will be stored */ void PlotAsymmetryByLogValue::doAnalysis(Workspace_sptr loadedWs, size_t index) { // Check if workspace is a workspace group WorkspaceGroup_sptr group = boost::dynamic_pointer_cast<WorkspaceGroup>(loadedWs); // If it is not, we only have 'red' data if (!group) { MatrixWorkspace_sptr ws_red = boost::dynamic_pointer_cast<MatrixWorkspace>(loadedWs); double Y, E; calcIntAsymmetry(ws_red, Y, E); m_logValue[index] = getLogValue(*ws_red); m_redY[index] = Y; m_redE[index] = E; } else { // It is a group // Process red data MatrixWorkspace_sptr ws_red; try { ws_red = boost::dynamic_pointer_cast<MatrixWorkspace>( group->getItem(m_red - 1)); } catch (std::out_of_range &) { throw std::out_of_range("Red period out of range"); } double YR, ER; calcIntAsymmetry(ws_red, YR, ER); double logValue = getLogValue(*ws_red); m_logValue[index] = logValue; m_redY[index] = YR; m_redE[index] = ER; if (m_green != EMPTY_INT()) { // Process green period if supplied by user MatrixWorkspace_sptr ws_green; try { ws_green = boost::dynamic_pointer_cast<MatrixWorkspace>( group->getItem(m_green - 1)); } catch (std::out_of_range &) { throw std::out_of_range("Green period out of range"); } double YG, EG; calcIntAsymmetry(ws_green, YG, EG); // Red data m_redY[index] = YR; m_redE[index] = ER; // Green data m_greenY[index] = YG; m_greenE[index] = EG; // Sum m_sumY[index] = YR + YG; m_sumE[index] = sqrt(ER * ER + EG * EG); // Diff calcIntAsymmetry(ws_red, ws_green, YR, ER); m_diffY[index] = YR; m_diffE[index] = ER; } } // else loadedGroup }
bool ReflectometryReductionOneAuto::processGroups() { // isPolarizationCorrectionOn is used to decide whether // we should process our Transmission WorkspaceGroup members // as individuals (not multiperiod) when PolarizationCorrection is off, // or sum over all of the workspaces in the group // and used that sum as our TransmissionWorkspace when PolarizationCorrection // is on. const bool isPolarizationCorrectionOn = this->getPropertyValue("PolarizationAnalysis") != noPolarizationCorrectionMode(); // Get our input workspace group auto group = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( getPropertyValue("InputWorkspace")); // Get name of IvsQ workspace const std::string outputIvsQ = this->getPropertyValue("OutputWorkspace"); // Get name of IvsLam workspace const std::string outputIvsLam = this->getPropertyValue("OutputWorkspaceWavelength"); // Create a copy of ourselves Algorithm_sptr alg = this->createChildAlgorithm( this->name(), -1, -1, this->isLogging(), this->version()); alg->setChild(false); alg->setRethrows(true); // Copy all the non-workspace properties over std::vector<Property *> props = this->getProperties(); for (auto &prop : props) { if (prop) { IWorkspaceProperty *wsProp = dynamic_cast<IWorkspaceProperty *>(prop); if (!wsProp) alg->setPropertyValue(prop->name(), prop->value()); } } // Check if the transmission runs are groups or not const std::string firstTrans = this->getPropertyValue("FirstTransmissionRun"); WorkspaceGroup_sptr firstTransG; if (!firstTrans.empty()) { auto firstTransWS = AnalysisDataService::Instance().retrieveWS<Workspace>(firstTrans); firstTransG = boost::dynamic_pointer_cast<WorkspaceGroup>(firstTransWS); if (!firstTransG) { // we only have one transmission workspace, so we use it as it is. alg->setProperty("FirstTransmissionRun", firstTrans); } else if (group->size() != firstTransG->size() && !isPolarizationCorrectionOn) { // if they are not the same size then we cannot associate a transmission // group workspace member with every input group workpspace member. throw std::runtime_error("FirstTransmissionRun WorkspaceGroup must be " "the same size as the InputWorkspace " "WorkspaceGroup"); } } const std::string secondTrans = this->getPropertyValue("SecondTransmissionRun"); WorkspaceGroup_sptr secondTransG; if (!secondTrans.empty()) { auto secondTransWS = AnalysisDataService::Instance().retrieveWS<Workspace>(secondTrans); secondTransG = boost::dynamic_pointer_cast<WorkspaceGroup>(secondTransWS); if (!secondTransG) // we only have one transmission workspace, so we use it as it is. alg->setProperty("SecondTransmissionRun", secondTrans); else if (group->size() != secondTransG->size() && !isPolarizationCorrectionOn) { // if they are not the same size then we cannot associate a transmission // group workspace member with every input group workpspace member. throw std::runtime_error("SecondTransmissionRun WorkspaceGroup must be " "the same size as the InputWorkspace " "WorkspaceGroup"); } } std::vector<std::string> IvsQGroup, IvsLamGroup; // Execute algorithm over each group member (or period, if this is // multiperiod) size_t numMembers = group->size(); for (size_t i = 0; i < numMembers; ++i) { const std::string IvsQName = outputIvsQ + "_" + boost::lexical_cast<std::string>(i + 1); const std::string IvsLamName = outputIvsLam + "_" + boost::lexical_cast<std::string>(i + 1); // If our transmission run is a group and PolarizationCorrection is on // then we sum our transmission group members. // // This is done inside of the for loop to avoid the wrong workspace being // used when these arguments are passed through to the exec() method. // If this is not set in the loop, exec() will fetch the first workspace // from the specified Transmission Group workspace that the user entered. if (firstTransG && isPolarizationCorrectionOn) { auto firstTransmissionSum = sumOverTransmissionGroup(firstTransG); alg->setProperty("FirstTransmissionRun", firstTransmissionSum); } if (secondTransG && isPolarizationCorrectionOn) { auto secondTransmissionSum = sumOverTransmissionGroup(secondTransG); alg->setProperty("SecondTransmissionRun", secondTransmissionSum); } // Otherwise, if polarization correction is off, we process them // using one transmission group member at a time. if (firstTransG && !isPolarizationCorrectionOn) // polarization off alg->setProperty("FirstTransmissionRun", firstTransG->getItem(i)->name()); if (secondTransG && !isPolarizationCorrectionOn) // polarization off alg->setProperty("SecondTransmissionRun", secondTransG->getItem(i)->name()); alg->setProperty("InputWorkspace", group->getItem(i)->name()); alg->setProperty("OutputWorkspace", IvsQName); alg->setProperty("OutputWorkspaceWavelength", IvsLamName); alg->execute(); MatrixWorkspace_sptr tempFirstTransWS = alg->getProperty("FirstTransmissionRun"); IvsQGroup.push_back(IvsQName); IvsLamGroup.push_back(IvsLamName); // We use the first group member for our thetaout value if (i == 0) this->setPropertyValue("ThetaOut", alg->getPropertyValue("ThetaOut")); } // Group the IvsQ and IvsLam workspaces Algorithm_sptr groupAlg = this->createChildAlgorithm("GroupWorkspaces"); groupAlg->setChild(false); groupAlg->setRethrows(true); groupAlg->setProperty("InputWorkspaces", IvsLamGroup); groupAlg->setProperty("OutputWorkspace", outputIvsLam); groupAlg->execute(); groupAlg->setProperty("InputWorkspaces", IvsQGroup); groupAlg->setProperty("OutputWorkspace", outputIvsQ); groupAlg->execute(); // If this is a multiperiod workspace and we have polarization corrections // enabled if (isPolarizationCorrectionOn) { if (group->isMultiperiod()) { // Perform polarization correction over the IvsLam group Algorithm_sptr polAlg = this->createChildAlgorithm("PolarizationCorrection"); polAlg->setChild(false); polAlg->setRethrows(true); polAlg->setProperty("InputWorkspace", outputIvsLam); polAlg->setProperty("OutputWorkspace", outputIvsLam); polAlg->setProperty("PolarizationAnalysis", this->getPropertyValue("PolarizationAnalysis")); polAlg->setProperty("CPp", this->getPropertyValue(cppLabel())); polAlg->setProperty("CRho", this->getPropertyValue(crhoLabel())); polAlg->setProperty("CAp", this->getPropertyValue(cApLabel())); polAlg->setProperty("CAlpha", this->getPropertyValue(cAlphaLabel())); polAlg->execute(); // Now we've overwritten the IvsLam workspaces, we'll need to recalculate // the IvsQ ones alg->setProperty("FirstTransmissionRun", ""); alg->setProperty("SecondTransmissionRun", ""); for (size_t i = 0; i < numMembers; ++i) { const std::string IvsQName = outputIvsQ + "_" + boost::lexical_cast<std::string>(i + 1); const std::string IvsLamName = outputIvsLam + "_" + boost::lexical_cast<std::string>(i + 1); alg->setProperty("InputWorkspace", IvsLamName); alg->setProperty("OutputWorkspace", IvsQName); alg->setProperty("CorrectionAlgorithm", "None"); alg->setProperty("OutputWorkspaceWavelength", IvsLamName); alg->execute(); } } else { g_log.warning("Polarization corrections can only be performed on " "multiperiod workspaces."); } } // We finished successfully this->setPropertyValue("OutputWorkspace", outputIvsQ); this->setPropertyValue("OutputWorkspaceWavelength", outputIvsLam); setExecuted(true); notificationCenter().postNotification( new FinishedNotification(this, isExecuted())); return true; }
/** Process groups. Groups are processed differently depending on transmission * runs and polarization analysis. If transmission run is a matrix workspace, it * will be applied to each of the members in the input workspace group. If * transmission run is a workspace group, the behaviour is different depending * on polarization analysis. If polarization analysis is off (i.e. * 'PolarizationAnalysis' is set to 'None') each item in the transmission group * is associated with the corresponding item in the input workspace group. If * polarization analysis is on (i.e. 'PolarizationAnalysis' is 'PA' or 'PNR') * items in the transmission group will be summed to produce a matrix workspace * that will be applied to each of the items in the input workspace group. See * documentation of this algorithm for more details. */ bool ReflectometryReductionOneAuto2::processGroups() { // this algorithm effectively behaves as MultiPeriodGroupAlgorithm m_usingBaseProcessGroups = true; // Get our input workspace group auto group = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( getPropertyValue("InputWorkspace")); // Get name of IvsQ workspace (native binning) const std::string outputIvsQ = getPropertyValue("OutputWorkspace"); // Get name of IvsQ (native binning) workspace const std::string outputIvsQBinned = getPropertyValue("OutputWorkspaceBinned"); // Get name of IvsLam workspace const std::string outputIvsLam = getPropertyValue("OutputWorkspaceWavelength"); // Create a copy of ourselves Algorithm_sptr alg = createChildAlgorithm(name(), -1, -1, isLogging(), version()); alg->setChild(false); alg->setRethrows(true); // Copy all the non-workspace properties over const std::vector<Property *> props = getProperties(); for (auto &prop : props) { if (prop) { IWorkspaceProperty *wsProp = dynamic_cast<IWorkspaceProperty *>(prop); if (!wsProp) alg->setPropertyValue(prop->name(), prop->value()); } } const bool polarizationAnalysisOn = getPropertyValue("PolarizationAnalysis") != "None"; // Check if the transmission runs are groups or not const std::string firstTrans = getPropertyValue("FirstTransmissionRun"); WorkspaceGroup_sptr firstTransG; MatrixWorkspace_sptr firstTransSum; if (!firstTrans.empty()) { auto firstTransWS = AnalysisDataService::Instance().retrieveWS<Workspace>(firstTrans); firstTransG = boost::dynamic_pointer_cast<WorkspaceGroup>(firstTransWS); if (!firstTransG) { alg->setProperty("FirstTransmissionRun", firstTrans); } else if (polarizationAnalysisOn) { firstTransSum = sumTransmissionWorkspaces(firstTransG); } } const std::string secondTrans = getPropertyValue("SecondTransmissionRun"); WorkspaceGroup_sptr secondTransG; MatrixWorkspace_sptr secondTransSum; if (!secondTrans.empty()) { auto secondTransWS = AnalysisDataService::Instance().retrieveWS<Workspace>(secondTrans); secondTransG = boost::dynamic_pointer_cast<WorkspaceGroup>(secondTransWS); if (!secondTransG) { alg->setProperty("SecondTransmissionRun", secondTrans); } else if (polarizationAnalysisOn) { secondTransSum = sumTransmissionWorkspaces(secondTransG); } } std::vector<std::string> IvsQGroup, IvsQUnbinnedGroup, IvsLamGroup; // Execute algorithm over each group member for (size_t i = 0; i < group->size(); ++i) { const std::string IvsQName = outputIvsQ + "_" + std::to_string(i + 1); const std::string IvsQBinnedName = outputIvsQBinned + "_" + std::to_string(i + 1); const std::string IvsLamName = outputIvsLam + "_" + std::to_string(i + 1); if (firstTransG) { if (!polarizationAnalysisOn) alg->setProperty("FirstTransmissionRun", firstTransG->getItem(i)->getName()); else alg->setProperty("FirstTransmissionRun", firstTransSum); } if (secondTransG) { if (!polarizationAnalysisOn) alg->setProperty("SecondTransmissionRun", secondTransG->getItem(i)->getName()); else alg->setProperty("SecondTransmissionRun", secondTransSum); } alg->setProperty("InputWorkspace", group->getItem(i)->getName()); alg->setProperty("OutputWorkspace", IvsQName); alg->setProperty("OutputWorkspaceBinned", IvsQBinnedName); alg->setProperty("OutputWorkspaceWavelength", IvsLamName); alg->execute(); IvsQGroup.push_back(IvsQName); IvsQUnbinnedGroup.push_back(IvsQBinnedName); IvsLamGroup.push_back(IvsLamName); } // Group the IvsQ and IvsLam workspaces Algorithm_sptr groupAlg = createChildAlgorithm("GroupWorkspaces"); groupAlg->setChild(false); groupAlg->setRethrows(true); groupAlg->setProperty("InputWorkspaces", IvsLamGroup); groupAlg->setProperty("OutputWorkspace", outputIvsLam); groupAlg->execute(); groupAlg->setProperty("InputWorkspaces", IvsQGroup); groupAlg->setProperty("OutputWorkspace", outputIvsQ); groupAlg->execute(); groupAlg->setProperty("InputWorkspaces", IvsQUnbinnedGroup); groupAlg->setProperty("OutputWorkspace", outputIvsQBinned); groupAlg->execute(); // Set other properties so they can be updated in the Reflectometry interface setPropertyValue("ThetaIn", alg->getPropertyValue("ThetaIn")); setPropertyValue("MomentumTransferMin", alg->getPropertyValue("MomentumTransferMin")); setPropertyValue("MomentumTransferMax", alg->getPropertyValue("MomentumTransferMax")); setPropertyValue("MomentumTransferStep", alg->getPropertyValue("MomentumTransferStep")); setPropertyValue("ScaleFactor", alg->getPropertyValue("ScaleFactor")); if (!polarizationAnalysisOn) { // No polarization analysis. Reduction stops here setPropertyValue("OutputWorkspace", outputIvsQ); setPropertyValue("OutputWorkspaceBinned", outputIvsQBinned); setPropertyValue("OutputWorkspaceWavelength", outputIvsLam); return true; } if (!group->isMultiperiod()) { g_log.warning("Polarization corrections can only be performed on " "multiperiod workspaces."); setPropertyValue("OutputWorkspace", outputIvsQ); setPropertyValue("OutputWorkspaceBinned", outputIvsQBinned); setPropertyValue("OutputWorkspaceWavelength", outputIvsLam); return true; } Algorithm_sptr polAlg = createChildAlgorithm("PolarizationCorrection"); polAlg->setChild(false); polAlg->setRethrows(true); polAlg->setProperty("InputWorkspace", outputIvsLam); polAlg->setProperty("OutputWorkspace", outputIvsLam); polAlg->setProperty("PolarizationAnalysis", getPropertyValue("PolarizationAnalysis")); polAlg->setProperty("CPp", getPropertyValue("CPp")); polAlg->setProperty("CRho", getPropertyValue("CRho")); polAlg->setProperty("CAp", getPropertyValue("CAp")); polAlg->setProperty("CAlpha", getPropertyValue("CAlpha")); polAlg->execute(); // Now we've overwritten the IvsLam workspaces, we'll need to recalculate // the IvsQ ones alg->setProperty("FirstTransmissionRun", ""); alg->setProperty("SecondTransmissionRun", ""); alg->setProperty("CorrectionAlgorithm", "None"); alg->setProperty("ThetaIn", Mantid::EMPTY_DBL()); alg->setProperty("ProcessingInstructions", "0"); for (size_t i = 0; i < group->size(); ++i) { const std::string IvsQName = outputIvsQ + "_" + std::to_string(i + 1); const std::string IvsQBinnedName = outputIvsQBinned + "_" + std::to_string(i + 1); const std::string IvsLamName = outputIvsLam + "_" + std::to_string(i + 1); alg->setProperty("InputWorkspace", IvsLamName); alg->setProperty("OutputWorkspace", IvsQName); alg->setProperty("OutputWorkspaceBinned", IvsQBinnedName); alg->setProperty("OutputWorkspaceWavelength", IvsLamName); alg->execute(); } setPropertyValue("OutputWorkspace", outputIvsQ); setPropertyValue("OutputWorkspaceBinned", outputIvsQBinned); setPropertyValue("OutputWorkspaceWavelength", outputIvsLam); return true; }
WorkspaceGroup_sptr PolarizationCorrection::execPA(WorkspaceGroup_sptr inWS) { if (isPropertyDefault(cAlphaLabel())) { throw std::invalid_argument("Must provide as input for PA: " + cAlphaLabel()); } if (isPropertyDefault(cApLabel())) { throw std::invalid_argument("Must provide as input for PA: " + cApLabel()); } size_t itemIndex = 0; MatrixWorkspace_sptr Ipp = boost::dynamic_pointer_cast<MatrixWorkspace>(inWS->getItem(itemIndex++)); MatrixWorkspace_sptr Ipa = boost::dynamic_pointer_cast<MatrixWorkspace>(inWS->getItem(itemIndex++)); MatrixWorkspace_sptr Iap = boost::dynamic_pointer_cast<MatrixWorkspace>(inWS->getItem(itemIndex++)); MatrixWorkspace_sptr Iaa = boost::dynamic_pointer_cast<MatrixWorkspace>(inWS->getItem(itemIndex++)); Ipp->setTitle("Ipp"); Iaa->setTitle("Iaa"); Ipa->setTitle("Ipa"); Iap->setTitle("Iap"); auto cropAlg = this->createChildAlgorithm("CropWorkspace"); cropAlg->initialize(); cropAlg->setProperty("InputWorkspace", Ipp); cropAlg->setProperty("EndWorkspaceIndex", 0); cropAlg->execute(); MatrixWorkspace_sptr croppedIpp = cropAlg->getProperty("OutputWorkspace"); MatrixWorkspace_sptr ones = copyShapeAndFill(croppedIpp, 1.0); // The ones workspace is now identical to the input workspaces in x, but has 1 // as y values. It can therefore be used to build real polynomial functions. const VecDouble c_rho = getProperty(crhoLabel()); const VecDouble c_alpha = getProperty(cAlphaLabel()); const VecDouble c_pp = getProperty(cppLabel()); const VecDouble c_ap = getProperty(cApLabel()); const auto rho = this->execPolynomialCorrection( ones, c_rho); // Execute polynomial expression const auto pp = this->execPolynomialCorrection( ones, c_pp); // Execute polynomial expression const auto alpha = this->execPolynomialCorrection( ones, c_alpha); // Execute polynomial expression const auto ap = this->execPolynomialCorrection( ones, c_ap); // Execute polynomial expression const auto A0 = (Iaa * pp * ap) + (ap * Ipa * rho * pp) + (ap * Iap * alpha * pp) + (Ipp * ap * alpha * rho * pp); const auto A1 = pp * Iaa; const auto A2 = pp * Iap; const auto A3 = ap * Iaa; const auto A4 = ap * Ipa; const auto A5 = ap * alpha * Ipp; const auto A6 = ap * alpha * Iap; const auto A7 = pp * rho * Ipp; const auto A8 = pp * rho * Ipa; const auto D = pp * ap * (rho + alpha + 1.0 + (rho * alpha)); const auto nIpp = (A0 - A1 + A2 - A3 + A4 + A5 - A6 + A7 - A8 + Ipp + Iaa - Ipa - Iap) / D; const auto nIaa = (A0 + A1 - A2 + A3 - A4 - A5 + A6 - A7 + A8 + Ipp + Iaa - Ipa - Iap) / D; const auto nIpa = (A0 - A1 + A2 + A3 - A4 - A5 + A6 + A7 - A8 - Ipp - Iaa + Ipa + Iap) / D; const auto nIap = (A0 + A1 - A2 - A3 + A4 + A5 - A6 - A7 + A8 - Ipp - Iaa + Ipa + Iap) / D; WorkspaceGroup_sptr dataOut = boost::make_shared<WorkspaceGroup>(); dataOut->addWorkspace(nIpp); dataOut->addWorkspace(nIpa); dataOut->addWorkspace(nIap); dataOut->addWorkspace(nIaa); size_t totalGroupEntries(dataOut->getNumberOfEntries()); for (size_t i = 1; i < totalGroupEntries; i++) { auto alg = this->createChildAlgorithm("ReplaceSpecialValues"); alg->setProperty("InputWorkspace", dataOut->getItem(i)); alg->setProperty("OutputWorkspace", "dataOut_" + std::to_string(i)); alg->setProperty("NaNValue", 0.0); alg->setProperty("NaNError", 0.0); alg->setProperty("InfinityValue", 0.0); alg->setProperty("InfinityError", 0.0); alg->execute(); } // Preserve the history of the inside workspaces nIpp->history().addHistory(Ipp->getHistory()); nIaa->history().addHistory(Iaa->getHistory()); nIpa->history().addHistory(Ipa->getHistory()); nIap->history().addHistory(Iap->getHistory()); return dataOut; }
bool ApplyPaalmanPings::validate() { UserInputValidator uiv; uiv.checkDataSelectorIsValid("Sample", m_uiForm.dsSample); MatrixWorkspace_sptr sampleWs; bool useCan = m_uiForm.ckUseCan->isChecked(); bool useCorrections = m_uiForm.ckUseCorrections->isChecked(); if (!(useCan || useCorrections)) uiv.addErrorMessage("Must use either container subtraction or corrections"); if (useCan) { uiv.checkDataSelectorIsValid("Container", m_uiForm.dsContainer); // Check can and sample workspaces are the same "type" (reduced or S(Q, w)) QString sample = m_uiForm.dsSample->getCurrentDataName(); QString sampleType = sample.right(sample.length() - sample.lastIndexOf("_")); QString container = m_uiForm.dsContainer->getCurrentDataName(); QString containerType = container.right(container.length() - container.lastIndexOf("_")); g_log.debug() << "Sample type is: " << sampleType.toStdString() << '\n'; g_log.debug() << "Can type is: " << containerType.toStdString() << '\n'; if (containerType != sampleType) uiv.addErrorMessage( "Sample and can workspaces must contain the same type of data."); } if (useCorrections) { if (m_uiForm.dsCorrections->getCurrentDataName().compare("") == 0) { uiv.addErrorMessage( "Use Correction must contain a corrections file or workspace."); } else { QString correctionsWsName = m_uiForm.dsCorrections->getCurrentDataName(); WorkspaceGroup_sptr corrections = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( correctionsWsName.toStdString()); for (size_t i = 0; i < corrections->size(); i++) { // Check it is a MatrixWorkspace MatrixWorkspace_sptr factorWs = boost::dynamic_pointer_cast<MatrixWorkspace>( corrections->getItem(i)); if (!factorWs) { QString msg = "Correction factor workspace " + QString::number(i) + " is not a MatrixWorkspace"; uiv.addErrorMessage(msg); continue; } // Check X unit is wavelength Mantid::Kernel::Unit_sptr xUnit = factorWs->getAxis(0)->unit(); if (xUnit->caption() != "Wavelength") { QString msg = "Correction factor workspace " + QString::fromStdString(factorWs->name()) + " is not in wavelength"; uiv.addErrorMessage(msg); } } } } // Show errors if there are any if (!uiv.isAllInputValid()) emit showMessageBox(uiv.generateErrorMessage()); return uiv.isAllInputValid(); }
void ApplyPaalmanPings::run() { // Create / Initialize algorithm API::BatchAlgorithmRunner::AlgorithmRuntimeProps absCorProps; IAlgorithm_sptr applyCorrAlg = AlgorithmManager::Instance().create("ApplyPaalmanPingsCorrection"); applyCorrAlg->initialize(); // get Sample Workspace MatrixWorkspace_sptr sampleWs = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( m_sampleWorkspaceName); m_originalSampleUnits = sampleWs->getAxis(0)->unit()->unitID(); // If not in wavelength then do conversion if (m_originalSampleUnits != "Wavelength") { g_log.information( "Sample workspace not in wavelength, need to convert to continue."); absCorProps["SampleWorkspace"] = addConvertUnitsStep(sampleWs, "Wavelength"); } else { absCorProps["SampleWorkspace"] = m_sampleWorkspaceName; } const bool useCan = m_uiForm.ckUseCan->isChecked(); const bool useCorrections = m_uiForm.ckUseCorrections->isChecked(); // Get Can and Clone MatrixWorkspace_sptr canClone; if (useCan) { const auto canName = m_uiForm.dsContainer->getCurrentDataName().toStdString(); const auto cloneName = "__algorithm_can"; IAlgorithm_sptr clone = AlgorithmManager::Instance().create("CloneWorkspace"); clone->initialize(); clone->setProperty("InputWorkspace", canName); clone->setProperty("Outputworkspace", cloneName); clone->execute(); const bool useShift = m_uiForm.ckShiftCan->isChecked(); if (useShift) { IAlgorithm_sptr scaleX = AlgorithmManager::Instance().create("ScaleX"); scaleX->initialize(); scaleX->setLogging(false); scaleX->setProperty("InputWorkspace", cloneName); scaleX->setProperty("OutputWorkspace", cloneName); scaleX->setProperty("Factor", m_uiForm.spCanShift->value()); scaleX->setProperty("Operation", "Add"); scaleX->execute(); IAlgorithm_sptr rebin = AlgorithmManager::Instance().create("RebinToWorkspace"); rebin->initialize(); rebin->setLogging(false); rebin->setProperty("WorkspaceToRebin", cloneName); rebin->setProperty("WorkspaceToMatch", m_sampleWorkspaceName); rebin->setProperty("OutputWorkspace", cloneName); rebin->execute(); } canClone = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(cloneName); // Check for same binning across sample and container if (!checkWorkspaceBinningMatches(sampleWs, canClone)) { const char *text = "Binning on sample and container does not match." "Would you like to rebin the container to match the sample?"; int result = QMessageBox::question(NULL, tr("Rebin sample?"), tr(text), QMessageBox::Yes, QMessageBox::No, QMessageBox::NoButton); if (result == QMessageBox::Yes) { addRebinStep(QString::fromStdString(canName), QString::fromStdString(m_sampleWorkspaceName)); } else { m_batchAlgoRunner->clearQueue(); g_log.error("Cannot apply absorption corrections " "using a sample and " "container with different binning."); return; } } // If not in wavelength then do conversion std::string originalCanUnits = canClone->getAxis(0)->unit()->unitID(); if (originalCanUnits != "Wavelength") { g_log.information("Container workspace not in wavelength, need to " "convert to continue."); absCorProps["CanWorkspace"] = addConvertUnitsStep(canClone, "Wavelength"); } else { absCorProps["CanWorkspace"] = cloneName; } const bool useCanScale = m_uiForm.ckScaleCan->isChecked(); if (useCanScale) { const double canScaleFactor = m_uiForm.spCanScale->value(); applyCorrAlg->setProperty("CanScaleFactor", canScaleFactor); } } if (useCorrections) { QString correctionsWsName = m_uiForm.dsCorrections->getCurrentDataName(); WorkspaceGroup_sptr corrections = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( correctionsWsName.toStdString()); bool interpolateAll = false; for (size_t i = 0; i < corrections->size(); i++) { MatrixWorkspace_sptr factorWs = boost::dynamic_pointer_cast<MatrixWorkspace>(corrections->getItem(i)); // Check for matching binning if (sampleWs && (sampleWs->blocksize() != factorWs->blocksize())) { int result; if (interpolateAll) { result = QMessageBox::Yes; } else { std::string text = "Number of bins on sample and " + factorWs->name() + " workspace does not match.\n" + "Would you like to interpolate this workspace to " "match the sample?"; result = QMessageBox::question( NULL, tr("Interpolate corrections?"), tr(text.c_str()), QMessageBox::YesToAll, QMessageBox::Yes, QMessageBox::No); } switch (result) { case QMessageBox::YesToAll: interpolateAll = true; // fall through case QMessageBox::Yes: addInterpolationStep(factorWs, absCorProps["SampleWorkspace"]); break; default: m_batchAlgoRunner->clearQueue(); g_log.error("ApplyPaalmanPings cannot run with corrections that do " "not match sample binning."); return; } } } applyCorrAlg->setProperty("CorrectionsWorkspace", correctionsWsName.toStdString()); } // Generate output workspace name auto QStrSampleWsName = QString::fromStdString(m_sampleWorkspaceName); int nameCutIndex = QStrSampleWsName.lastIndexOf("_"); if (nameCutIndex == -1) nameCutIndex = QStrSampleWsName.length(); QString correctionType; switch (m_uiForm.cbGeometry->currentIndex()) { case 0: correctionType = "flt"; break; case 1: correctionType = "cyl"; break; case 2: correctionType = "anl"; break; } QString outputWsName = QStrSampleWsName.left(nameCutIndex); // Using corrections if (m_uiForm.ckUseCorrections->isChecked()) { outputWsName += "_" + correctionType + "_Corrected"; } else { outputWsName += "_Subtracted"; } // Using container if (m_uiForm.ckUseCan->isChecked()) { const auto canName = m_uiForm.dsContainer->getCurrentDataName().toStdString(); MatrixWorkspace_sptr containerWs = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(canName); auto run = containerWs->run(); if (run.hasProperty("run_number")) { outputWsName += "_" + QString::fromStdString(run.getProperty("run_number")->value()); } else { auto canCutIndex = QString::fromStdString(canName).indexOf("_"); outputWsName += "_" + QString::fromStdString(canName).left(canCutIndex); } } outputWsName += "_red"; applyCorrAlg->setProperty("OutputWorkspace", outputWsName.toStdString()); // Add corrections algorithm to queue m_batchAlgoRunner->addAlgorithm(applyCorrAlg, absCorProps); // Run algorithm queue connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(absCorComplete(bool))); m_batchAlgoRunner->executeBatchAsync(); // Set the result workspace for Python script export m_pythonExportWsName = outputWsName.toStdString(); // m_containerWorkspaceName = m_uiForm.dsContainer->getCurrentDataName(); // updateContainer(); }