id
stringlengths
27
29
content
stringlengths
226
3.24k
codereview_new_cpp_data_13020
void ALFInstrumentModel::setData(ALFData const &dataType, MatrixWorkspace_sptr c switch (dataType) { case ALFData::SAMPLE: setSample(workspace); - return; case ALFData::VANADIUM: setVanadium(workspace); - return; } - throw std::invalid_argument("ALFData must be one of { SAMPLE, VANADIUM }"); } void ALFInstrumentModel::setSample(MatrixWorkspace_sptr const &sample) { Would it be nicer to use the switch case's `default` case to throw the error? https://www.tutorialspoint.com/cplusplus/cpp_switch_statement.htm void ALFInstrumentModel::setData(ALFData const &dataType, MatrixWorkspace_sptr c switch (dataType) { case ALFData::SAMPLE: setSample(workspace); + break; case ALFData::VANADIUM: setVanadium(workspace); + break; + default: + throw std::invalid_argument("ALFData must be one of { SAMPLE, VANADIUM }"); } } void ALFInstrumentModel::setSample(MatrixWorkspace_sptr const &sample) {
codereview_new_cpp_data_13021
void update(std::string const &property, boost::optional<double> const &value, I } void update(std::string const &property, MatrixWorkspace_sptr const &workspace, IAlgorithmRuntimeProps &properties) { - if (workspace) { - properties.setProperty(property, workspace); - } } void updateFromMap(IAlgorithmRuntimeProps &properties, std::map<std::string, std::string> const &parameterMap) { Do you need this `if (workspace)`? It was perhaps present in the preceding function because the `value` parameter was a `boost::optional` void update(std::string const &property, boost::optional<double> const &value, I } void update(std::string const &property, MatrixWorkspace_sptr const &workspace, IAlgorithmRuntimeProps &properties) { + properties.setProperty(property, workspace); } void updateFromMap(IAlgorithmRuntimeProps &properties, std::map<std::string, std::string> const &parameterMap) {
codereview_new_cpp_data_13023
TimeSplitter::TimeSplitter(const Mantid::API::MatrixWorkspace_sptr &ws, const Da "Size of x values must be one more than size of y values to construct TimeSplitter from MatrixWorkspace."); } - int64_t offset_ns{offset.totalNanoseconds()}; for (size_t i = 1; i < X.size(); i++) { - auto timeStart = Types::Core::DateAndTime((X[i - 1]), 0.0) += offset_ns; - auto timeEnd = Types::Core::DateAndTime((X[i]), 0.0) += offset_ns; auto index = static_cast<int>(Y[i - 1]); this->addROI(timeStart, timeEnd, index); } @gecage952 I've never seen `+=` used as this before. Is its purpose to avoid a call to the copy constructor? TimeSplitter::TimeSplitter(const Mantid::API::MatrixWorkspace_sptr &ws, const Da "Size of x values must be one more than size of y values to construct TimeSplitter from MatrixWorkspace."); } for (size_t i = 1; i < X.size(); i++) { + auto timeStart = Types::Core::DateAndTime(static_cast<int64_t>((X[i - 1])), offset.totalNanoseconds()); + auto timeEnd = Types::Core::DateAndTime(static_cast<int64_t>(X[i]), offset.totalNanoseconds()); auto index = static_cast<int>(Y[i - 1]); this->addROI(timeStart, timeEnd, index); }
codereview_new_cpp_data_13024
TimeSplitter::TimeSplitter(const Mantid::API::MatrixWorkspace_sptr &ws, const Da auto timeEnd = Types::Core::DateAndTime(X[i], 0.0) + offset_ns; auto index = static_cast<int>(Y[i - 1]); if ((index != IGNORE_VALUE) && (valueAtTime(timeStart) != IGNORE_VALUE || valueAtTime(timeEnd) != IGNORE_VALUE)) { - g_log.warning() << "Workspace row " << i - 1 << " may be overwritten in conversion to TimeSplitter" << '\n'; } this->addROI(timeStart, timeEnd, index); } Since in the `MatrixWorkspace` case, we don't have rows, the warning will be a little more tricky. I think you might just say that the time interval between `<< timeStart << " and " << timeEnd <<` may be overwritten. TimeSplitter::TimeSplitter(const Mantid::API::MatrixWorkspace_sptr &ws, const Da auto timeEnd = Types::Core::DateAndTime(X[i], 0.0) + offset_ns; auto index = static_cast<int>(Y[i - 1]); if ((index != IGNORE_VALUE) && (valueAtTime(timeStart) != IGNORE_VALUE || valueAtTime(timeEnd) != IGNORE_VALUE)) { + g_log.warning() << "Values between " << timeStart.second() << "(s) and " << timeEnd.second() + << "(s) may be overwritten in conversion to TimeSplitter" << '\n'; } this->addROI(timeStart, timeEnd, index); }
codereview_new_cpp_data_13025
void EventList::filterByTimeAtSample(Types::Core::DateAndTime start, Types::Core /** Filter this EventList into an output EventList, using TimeROI * keeping only events within the >= start and < end pulse times. * Detector IDs and the X axis are copied as well. * * @param timeRoi :: reference to TimeROI to be used for filtering * @param output :: reference to an event list that will be output. * @throws std::invalid_argument If output is a reference to this EventList */ -void EventList::filterByTimeROI(Kernel::TimeROI *timeRoi, EventList &output) const { if (this == &output) { throw std::invalid_argument("In-place filtering is not allowed"); } - sort(this->order); // Clear the output output.clear(); // Has to match the given type Since a `TimeROI` object may contain more than one time interval, the function is keeping events with pulse times within any of the ROI time intervals and discarding events within any of the masked time intervals. Can you insert this or a similar sentence in the docstring? void EventList::filterByTimeAtSample(Types::Core::DateAndTime start, Types::Core /** Filter this EventList into an output EventList, using TimeROI * keeping only events within the >= start and < end pulse times. + * Since a TimeROI object may contain more than one time interval, + * the function is keeping events with pulse times within any of + * the ROI time intervals and discarding events within any of the + * masked time intervals. * Detector IDs and the X axis are copied as well. * * @param timeRoi :: reference to TimeROI to be used for filtering * @param output :: reference to an event list that will be output. * @throws std::invalid_argument If output is a reference to this EventList */ +void EventList::filterByPulseTime(Kernel::TimeROI *timeRoi, EventList &output) const { if (this == &output) { throw std::invalid_argument("In-place filtering is not allowed"); } // Clear the output output.clear(); // Has to match the given type
codereview_new_cpp_data_13026
void EventList::filterByTimeAtSample(Types::Core::DateAndTime start, Types::Core /** Filter this EventList into an output EventList, using TimeROI * keeping only events within the >= start and < end pulse times. * Detector IDs and the X axis are copied as well. * * @param timeRoi :: reference to TimeROI to be used for filtering * @param output :: reference to an event list that will be output. * @throws std::invalid_argument If output is a reference to this EventList */ -void EventList::filterByTimeROI(Kernel::TimeROI *timeRoi, EventList &output) const { if (this == &output) { throw std::invalid_argument("In-place filtering is not allowed"); } - sort(this->order); // Clear the output output.clear(); // Has to match the given type This is unnecessary because you iterate over all events for each `SplittingInterval`: ```cpp std::copy_if(events.begin(), events.end(), std::back_inserter(output), [start, stop](const T &t) { return (t.m_pulsetime >= start) && (t.m_pulsetime < stop); }); ``` void EventList::filterByTimeAtSample(Types::Core::DateAndTime start, Types::Core /** Filter this EventList into an output EventList, using TimeROI * keeping only events within the >= start and < end pulse times. + * Since a TimeROI object may contain more than one time interval, + * the function is keeping events with pulse times within any of + * the ROI time intervals and discarding events within any of the + * masked time intervals. * Detector IDs and the X axis are copied as well. * * @param timeRoi :: reference to TimeROI to be used for filtering * @param output :: reference to an event list that will be output. * @throws std::invalid_argument If output is a reference to this EventList */ +void EventList::filterByPulseTime(Kernel::TimeROI *timeRoi, EventList &output) const { if (this == &output) { throw std::invalid_argument("In-place filtering is not allowed"); } // Clear the output output.clear(); // Has to match the given type
codereview_new_cpp_data_13027
bool SplittersWorkspace::removeSplitter(size_t index) { return removed; } Kernel::TimeSplitter SplittersWorkspace::convertToTimeSplitter() { Kernel::TimeSplitter splitter; - for (int i = 0; i < this->rowCount(); i++) { Kernel::SplittingInterval interval = this->getSplitter(i); splitter.addROI(interval.begin(), interval.end(), interval.index()); } Please add doxygen to explain what this does and the effect that if there are overlaps, later rows will overwrite earlier rows. This is a subtle behavior that should be documented. It would be even better if this method logged a warning when there is an overlap. bool SplittersWorkspace::removeSplitter(size_t index) { return removed; } +/** + * Converts a SplitterWorkSpace to a TimeSplitter. Note: if any rows overlap, then + * later rows will overwrite earlier rows. + */ Kernel::TimeSplitter SplittersWorkspace::convertToTimeSplitter() { Kernel::TimeSplitter splitter; + for (size_t i = 0; i < this->rowCount(); i++) { Kernel::SplittingInterval interval = this->getSplitter(i); + if (splitter.valueAtTime(interval.begin()) > 0 || splitter.valueAtTime(interval.end()) > 0) { + g_log.warning() << "SplitterWorkspace row may be overwritten in conversion to TimeSplitter: " << i << '\n'; + } splitter.addROI(interval.begin(), interval.end(), interval.index()); }
codereview_new_cpp_data_13029
double TimeSeriesProperty<TYPE>::averageValueInFilter(const std::vector<Splittin // TODO: Consider logs that aren't giving starting values. // If there's just a single value in the log, return that. - if (realSize() == 1) { - return static_cast<double>(m_values.front().value()); - } if (size() == 1) { return static_cast<double>(this->firstValue()); } Assuming `m_size` is always up-to-date, `realSize() == 1` will evaluate to `true` when `size() == 1` so the previous `if` condition is redundant. Are we assuming `m_size` becomes outdated? double TimeSeriesProperty<TYPE>::averageValueInFilter(const std::vector<Splittin // TODO: Consider logs that aren't giving starting values. // If there's just a single value in the log, return that. if (size() == 1) { return static_cast<double>(this->firstValue()); }
codereview_new_cpp_data_13030
void InstrumentDisplay::updateView(bool picking) { } } -/// Return the size of the OpenGL or Qt display widget in logical pixels -QSize InstrumentDisplay::widgetDimensions() const { - auto sizeinLogicalPixels = [](const QWidget *w) -> QSize { - const auto devicePixelRatio = w->window()->devicePixelRatio(); - return QSize(w->width() * devicePixelRatio, w->height() * devicePixelRatio); - }; - - if (currentWidget() == dynamic_cast<QWidget *>(m_glDisplay.get())) - return sizeinLogicalPixels(getGLDisplay()); - else if (currentWidget() == dynamic_cast<QWidget *>(m_qtDisplay.get())) - return sizeinLogicalPixels(getQtDisplay()); - else - return QSize(0, 0); -} } // namespace MantidQt::MantidWidgets \ No newline at end of file I found that I was able to remove this implementation when I switched to the OpenGLWidget. Is this just now able to return `m_instrumentDisplay->currentWidget()->size()` too? void InstrumentDisplay::updateView(bool picking) { } } } // namespace MantidQt::MantidWidgets \ No newline at end of file
codereview_new_cpp_data_13032
std::string NotebookWriter::markdownCell(const std::string &string_text) { void NotebookWriter::headerComment() { Json::Value strings(Json::arrayValue); strings.append(Json::Value("This IPython Notebook was automatically " - "generated by Mantid Workbench, version: ")); strings.append(Json::Value(Mantid::Kernel::MantidVersion::version())); strings.append(Json::Value("\n")); strings.append(Json::Value(Mantid::Kernel::MantidVersion::releaseNotes())); As this is an algorithm in the framework can we just say Mantid here? std::string NotebookWriter::markdownCell(const std::string &string_text) { void NotebookWriter::headerComment() { Json::Value strings(Json::arrayValue); strings.append(Json::Value("This IPython Notebook was automatically " + "generated by Mantid, version: ")); strings.append(Json::Value(Mantid::Kernel::MantidVersion::version())); strings.append(Json::Value("\n")); strings.append(Json::Value(Mantid::Kernel::MantidVersion::releaseNotes()));
codereview_new_cpp_data_13033
#include <QButtonGroup> #include <QCheckBox> #include <QComboBox> #include <QGridLayout> #include <QGroupBox> #include <QLabel> #include <QPushButton> #include <QVBoxLayout> FindDialog::FindDialog(ScriptEditor *editor) : FindReplaceDialog(editor) { - setWindowTitle(tr("MantidWorkbench") + " - " + tr("Find")); initLayout(); } Are there many of these? I think it would be good to replace them with calls to https://doc.qt.io/qt-5/qcoreapplication.html#applicationName-prop so we stop hardcoding the name everywhere. #include <QButtonGroup> #include <QCheckBox> #include <QComboBox> +#include <QCoreApplication> #include <QGridLayout> #include <QGroupBox> #include <QLabel> #include <QPushButton> #include <QVBoxLayout> FindDialog::FindDialog(ScriptEditor *editor) : FindReplaceDialog(editor) { + setWindowTitle(QCoreApplication::applicationName() + " - Find"); initLayout(); }
codereview_new_cpp_data_13034
void FindFilesThreadPoolManager::cancelWorker() { /** Check if a search is currently executing. * - * @returns true if the current worker object is null */ bool FindFilesThreadPoolManager::isSearchRunning() const { return poolInstance()->activeThreadCount() > 0; } Is this comment still accurate? void FindFilesThreadPoolManager::cancelWorker() { /** Check if a search is currently executing. * + * @returns true if no worker threads are active */ bool FindFilesThreadPoolManager::isSearchRunning() const { return poolInstance()->activeThreadCount() > 0; }
codereview_new_cpp_data_13035
void LoadDialog::enableNameSuggestion(const bool on) { */ void LoadDialog::accept() { // If the LoadDialog is already loading data, or is populating, then ignore the accept - if (!m_form.fileWidget->isSearching() && !m_populating) { - m_userAccept = true; - m_form.fileWidget->findFiles(); } } void LoadDialog::resultInspectionFinished() { This is just a readability thing, and is maybe a little up for debate, but would this be a bit clearer what it's doing? I think it then removes the need for the inline comment. ```suggestion if (m_form.fileWidget->isSearching() || m_populating) { return; } m_userAccept = true; m_form.fileWidget->findFiles(); } ``` void LoadDialog::enableNameSuggestion(const bool on) { */ void LoadDialog::accept() { // If the LoadDialog is already loading data, or is populating, then ignore the accept + if (m_form.fileWidget->isSearching() || m_populating) { + return; } + m_userAccept = true; + m_form.fileWidget->findFiles(); } void LoadDialog::resultInspectionFinished() {
codereview_new_cpp_data_13036
void FindFilesThreadPoolManager::cancelWorker() { /** Check if a search is currently executing. * - * @returns true if no worker threads are active */ bool FindFilesThreadPoolManager::isSearchRunning() const { return poolInstance()->activeThreadCount() > 0; } Doesn't this code return true when there are 1 or more worker threads active? void FindFilesThreadPoolManager::cancelWorker() { /** Check if a search is currently executing. * + * @returns true if at least one worker thread is active */ bool FindFilesThreadPoolManager::isSearchRunning() const { return poolInstance()->activeThreadCount() > 0; }
codereview_new_cpp_data_13039
std::vector<std::shared_ptr<FitPeaksAlgorithm::PeakFitResult>> FitPeaks::fitPeak PARALLEL_CHECK_INTERRUPT_REGION if (all_spectra_peaks_not_enough_datapoints > 0) - g_log.notice() << all_spectra_peaks_not_enough_datapoints << " peaks rejected: not enough X(Y) datapoints." - << std::endl; return fit_result_vector; } This is a minor performance thing. Using `std::endl` forces the logging system to flush buffers which incurs a performance hit. Changing it to us `"\n"` instead lets logging sort itself out. It is a bigger deal in other things, but to be consistent this should be ```suggestion g_log.notice() << all_spectra_peaks_not_enough_datapoints << " peaks rejected: not enough X(Y) datapoints.\n"; ``` std::vector<std::shared_ptr<FitPeaksAlgorithm::PeakFitResult>> FitPeaks::fitPeak PARALLEL_CHECK_INTERRUPT_REGION if (all_spectra_peaks_not_enough_datapoints > 0) + g_log.notice() << all_spectra_peaks_not_enough_datapoints << " peaks rejected: not enough X(Y) datapoints.\n"; return fit_result_vector; }
codereview_new_cpp_data_13040
void LoadNXSPE::exec() { file.openData("psi"); file.getData(temporary); psi = temporary.at(0); - if (std::isnan(psi)) psi = 0.; file.closeData(); } I would be tempted to say we should post a warning about this. That way we are being transparent that we have not read from the file exactly as it was written. void LoadNXSPE::exec() { file.openData("psi"); file.getData(temporary); psi = temporary.at(0); + if (std::isnan(psi)) { psi = 0.; + g_log.warning("Entry for PSI is empty, will use default of 0.0 instead."); + } file.closeData(); }
codereview_new_cpp_data_13041
void ALFAnalysisModel::openExternalPlot() const { MatrixWorkspace_sptr ALFAnalysisModel::plottedWorkspace() const { if (m_fitWorkspace) { return m_fitWorkspace; - } else if (m_extractedWorkspace) { return m_extractedWorkspace; - } else { - return nullptr; } } std::vector<int> ALFAnalysisModel::plottedWorkspaceIndices() const { ```suggestion if (m_fitWorkspace) { return m_fitWorkspace; } if (m_extractedWorkspace) { return m_extractedWorkspace; } return nullptr; ``` You don't need `else if`s if we're returning anyway. void ALFAnalysisModel::openExternalPlot() const { MatrixWorkspace_sptr ALFAnalysisModel::plottedWorkspace() const { if (m_fitWorkspace) { return m_fitWorkspace; + } + if (m_extractedWorkspace) { return m_extractedWorkspace; } + return nullptr; } std::vector<int> ALFAnalysisModel::plottedWorkspaceIndices() const {
codereview_new_cpp_data_13042
void FitPropertyBrowser::stringChanged(QtProperty *prop) { tie->set(exp.toStdString()); h->addTie(parName + "=" + exp); } catch (...) { - std::string msg = "Failed to update tie on " + parName.toStdString() + ". Expression " + exp.toStdString() + " is invalid."; QMessageBox::critical(this, "Mantid - Error", msg.c_str()); ```suggestion const auto msg = ``` void FitPropertyBrowser::stringChanged(QtProperty *prop) { tie->set(exp.toStdString()); h->addTie(parName + "=" + exp); } catch (...) { + const auto msg = "Failed to update tie on " + parName.toStdString() + ". Expression " + exp.toStdString() + " is invalid."; QMessageBox::critical(this, "Mantid - Error", msg.c_str());
codereview_new_cpp_data_13049
void IndirectDataManipulation::instrumentLoadingDone(bool error) { if (error) { g_log.warning("Instument loading failed! This instrument (or " "analyser/reflection configuration) may not be supported by " - "the interface."); return; } } ```suggestion "this interface."); ``` void IndirectDataManipulation::instrumentLoadingDone(bool error) { if (error) { g_log.warning("Instument loading failed! This instrument (or " "analyser/reflection configuration) may not be supported by " + "this interface."); return; } }
codereview_new_cpp_data_13050
using namespace DataObjects; void Q1DWeighted::init() { auto wsValidator = std::make_shared<CompositeValidator>(CompositeRelation::OR); auto monoValidator = std::make_shared<CompositeValidator>(CompositeRelation::AND); auto tofValidator = std::make_shared<CompositeValidator>(CompositeRelation::AND); - monoValidator->add<WorkspaceUnitValidator>("Label"); monoValidator->add<HistogramValidator>(false); monoValidator->add<InstrumentValidator>(); Could you add a comment and perhaps a note about this change in the validation? Is it actually relevant for the execution what unit is there? Could we have both `Empty` and `Label`? using namespace DataObjects; void Q1DWeighted::init() { auto wsValidator = std::make_shared<CompositeValidator>(CompositeRelation::OR); auto monoValidator = std::make_shared<CompositeValidator>(CompositeRelation::AND); + auto monoUnitValidator = std::make_shared<CompositeValidator>(CompositeRelation::OR); auto tofValidator = std::make_shared<CompositeValidator>(CompositeRelation::AND); + monoUnitValidator->add<WorkspaceUnitValidator>("Label"); // case for D16 omega scan, which has unit "Omega scan" + monoUnitValidator->add<WorkspaceUnitValidator>("Empty"); // case for kinetic data + + monoValidator->add(monoUnitValidator); monoValidator->add<HistogramValidator>(false); monoValidator->add<InstrumentValidator>();
codereview_new_cpp_data_13053
void IndirectSymmetrise::setFileExtensionsByName(bool filter) { void IndirectSymmetrise::handleValueChanged(QtProperty *prop, double value) { if (prop->propertyName() == "Spectrum No") { m_view->replotNewSpectrum(value); - } - if (prop->propertyName() == "EMin") { m_view->verifyERange(prop, value); m_model->setEMin(m_view->getEMin()); - } - if (prop->propertyName() == "EMax") { m_view->verifyERange(prop, value); m_model->setEMax(m_view->getEMax()); } could these be `else if`? void IndirectSymmetrise::setFileExtensionsByName(bool filter) { void IndirectSymmetrise::handleValueChanged(QtProperty *prop, double value) { if (prop->propertyName() == "Spectrum No") { m_view->replotNewSpectrum(value); + } else if (prop->propertyName() == "EMin") { m_view->verifyERange(prop, value); m_model->setEMin(m_view->getEMin()); + } else if (prop->propertyName() == "EMax") { m_view->verifyERange(prop, value); m_model->setEMax(m_view->getEMax()); }
codereview_new_cpp_data_13063
void IFunction::sortTies() { std::list<TieNode> orderedTieNodes; for (size_t i = 0; i < nParams(); ++i) { auto const tie = getTie(i); - if (!tie) { - continue; - } - // Ignore height ties for Gaussian peaks as component of a CrystalFieldFunction - if (this->name() == "CrystalFieldFunction" && tie->ownerFunction()->name() == "Gaussian" && - tie->parameterName() == "Height" && tie->asString().find("/Sigma") != std::string::npos) { continue; } Could I ask if there would be a different way to solve this that doesn't required quite detailed knowledge of the function/tie specifics in the base class? Maybe an `bool IFunction::ignoreTie(const Tie&)` that a function could override that by default returned `false`? void IFunction::sortTies() { std::list<TieNode> orderedTieNodes; for (size_t i = 0; i < nParams(); ++i) { auto const tie = getTie(i); + if (!tie || ignoreTie(*tie)) { continue; }
codereview_new_cpp_data_13066
#include <Poco/Path.h> #include <boost/algorithm/string/case_conv.hpp> #include <boost/algorithm/string/predicate.hpp> -#include <boost/range/algorithm/transform.hpp> namespace Mantid::DataHandling { I don't think you need this include. Might be a feature from the original PR for this change but compiles for me without it #include <Poco/Path.h> #include <boost/algorithm/string/case_conv.hpp> #include <boost/algorithm/string/predicate.hpp> namespace Mantid::DataHandling {
codereview_new_cpp_data_13067
void GetDetectorOffsets::exec() { PARALLEL_CRITICAL(GetDetectorOffsets_setValue) { // Use the same offset for all detectors from this pixel for (const auto &det : dets) { const auto mapEntry = pixel_to_wi.find(det); if (mapEntry == pixel_to_wi.end()) continue; - outputW->setValue(det, offset); const size_t workspaceIndex = mapEntry->second; if (mask == 1.) { // Being masked why has this moved? void GetDetectorOffsets::exec() { PARALLEL_CRITICAL(GetDetectorOffsets_setValue) { // Use the same offset for all detectors from this pixel for (const auto &det : dets) { + outputW->setValue(det, offset); const auto mapEntry = pixel_to_wi.find(det); if (mapEntry == pixel_to_wi.end()) continue; const size_t workspaceIndex = mapEntry->second; if (mask == 1.) { // Being masked
codereview_new_cpp_data_13068
void Fit::initConcrete() { std::map<std::string, std::string> Fit::validateInputs() { std::map<std::string, std::string> issues; - const auto possibleOperators = Mantid::API::Expression::DEFAULT_OPS_STR; std::string constraints = getPropertyValue("Constraints"); if (constraints.size() > 0) { auto operatorPresent = false; - for (auto op : possibleOperators) { const auto it = constraints.find_first_of(op); if (it <= constraints.size()) { operatorPresent = true; I think this is a copy? Can we do ```cpp const auto& possibleOperators = Mantid::API::Expression::DEFAULT_OPS_STR ``` void Fit::initConcrete() { std::map<std::string, std::string> Fit::validateInputs() { std::map<std::string, std::string> issues; + const auto &possibleOperators = Mantid::API::Expression::DEFAULT_OPS_STR; std::string constraints = getPropertyValue("Constraints"); if (constraints.size() > 0) { auto operatorPresent = false; + for (const auto &op : possibleOperators) { const auto it = constraints.find_first_of(op); if (it <= constraints.size()) { operatorPresent = true;
codereview_new_cpp_data_13069
void Fit::initConcrete() { std::map<std::string, std::string> Fit::validateInputs() { std::map<std::string, std::string> issues; - const auto possibleOperators = Mantid::API::Expression::DEFAULT_OPS_STR; std::string constraints = getPropertyValue("Constraints"); if (constraints.size() > 0) { auto operatorPresent = false; - for (auto op : possibleOperators) { const auto it = constraints.find_first_of(op); if (it <= constraints.size()) { operatorPresent = true; ```suggestion for (const auto & op : possibleOperators) { ``` void Fit::initConcrete() { std::map<std::string, std::string> Fit::validateInputs() { std::map<std::string, std::string> issues; + const auto &possibleOperators = Mantid::API::Expression::DEFAULT_OPS_STR; std::string constraints = getPropertyValue("Constraints"); if (constraints.size() > 0) { auto operatorPresent = false; + for (const auto &op : possibleOperators) { const auto it = constraints.find_first_of(op); if (it <= constraints.size()) { operatorPresent = true;
codereview_new_cpp_data_13070
ProcessingInstructions PreviewModel::getProcessingInstructions() const { } void PreviewModel::setSelectedRegion(Selection const &selection) { - // TODO We will need to allow for more complex selections, but for now the selection just consists two y indices if (selection.size() % 2 != 0) { throw std::runtime_error("Program error: unexpected selection size; must be multiple of 2; got " + std::to_string(selection.size())); ```suggestion // TODO We will need to allow for more complex selections, but for now the selection just consists two y indices per rectangle selection ``` ProcessingInstructions PreviewModel::getProcessingInstructions() const { } void PreviewModel::setSelectedRegion(Selection const &selection) { + // TODO We will need to allow for more complex selections, but for now the selection just consists two y indices per + // TODO rectangle selection if (selection.size() % 2 != 0) { throw std::runtime_error("Program error: unexpected selection size; must be multiple of 2; got " + std::to_string(selection.size()));
codereview_new_cpp_data_13072
std::string ConvFunctionModel::buildFickFunctionString() const { std::string ConvFunctionModel::buildChudleyElliotString() const { return "name=ChudleyElliotSQE, Height=1, Tau=1.25, Centre=0, L=1.0, " - "constraints=(Height>0, Tau>0)"; } std::string ConvFunctionModel::buildHallRossString() const { return "name=HallRossSQE, Height=1, Tau=1.25, Centre=0, L=1.0, " - "constraints=(Height>0, Tau>0)"; } std::string ConvFunctionModel::buildStretchExpFTFunctionString() const { Probably it would make sense to set constraints on "L" to be positive, as well. std::string ConvFunctionModel::buildFickFunctionString() const { std::string ConvFunctionModel::buildChudleyElliotString() const { return "name=ChudleyElliotSQE, Height=1, Tau=1.25, Centre=0, L=1.0, " + "constraints=(Height>0, Tau>0, L>0)"; } std::string ConvFunctionModel::buildHallRossString() const { return "name=HallRossSQE, Height=1, Tau=1.25, Centre=0, L=1.0, " + "constraints=(Height>0, Tau>0, L>0)"; } std::string ConvFunctionModel::buildStretchExpFTFunctionString() const {
codereview_new_cpp_data_13073
ExperimentInfo::ExperimentInfo() : m_parmap(new ParameterMap()), sptr_instrument * unlocked. * @param source The source object from which to initialize */ -ExperimentInfo::ExperimentInfo(const ExperimentInfo &source) { - this->copyExperimentInfoFrom(&source); - setSpectrumDefinitions(source.spectrumInfo().sharedSpectrumDefinitions()); -} /** * Implements the copy assignment operator May I suggest that we use the ["copy-and-swap"](https://stackoverflow.com/a/3652138) idiom to implement the copy constructor/assignment operator pair here? It is a nice idiom for reducing code duplication and providing exception guarantees at the same time. ExperimentInfo::ExperimentInfo() : m_parmap(new ParameterMap()), sptr_instrument * unlocked. * @param source The source object from which to initialize */ +ExperimentInfo::ExperimentInfo(const ExperimentInfo &source) { *this = source; } /** * Implements the copy assignment operator
codereview_new_cpp_data_13074
namespace { * @returns true if there is exactly one string, else false. */ bool isSingleFile(const std::vector<std::vector<std::string>> &fileNames) { - return fileNames.size() == 1 ? fileNames[0u].size() == 1 : false; } /** Would `return fileNames.size() == 1 && fileNames[0].size() == 1` be slightly easier to read? namespace { * @returns true if there is exactly one string, else false. */ bool isSingleFile(const std::vector<std::vector<std::string>> &fileNames) { + return fileNames.size() == 1 && fileNames[0u].size() == 1; } /**
codereview_new_cpp_data_13075
void LoadPSIMuonBin::readInTemperatureFileHeader(const std::string &contents) { std::string line = ""; for (const auto charecter : contents) { if (charecter == '\n') { - if (!line.empty() && line[0] == '!' && lineNo > uselessLines) { - processHeaderLine(line); - } else if (line.empty() || line[0] != '!') { return; } ++lineNo; line = ""; Would this read more easily if we did the `empty` check first & once then continued? void LoadPSIMuonBin::readInTemperatureFileHeader(const std::string &contents) { std::string line = ""; for (const auto charecter : contents) { if (charecter == '\n') { + if (line.empty() || line[0] != '!') { return; + } else if (lineNo > uselessLines) { + processHeaderLine(line); } ++lineNo; line = "";
codereview_new_cpp_data_13076
AffineMatrixParameter &AffineMatrixParameter::operator=(const AffineMatrixParame if (this != &other) { this->m_affineMatrix = other.m_affineMatrix; this->m_isValid = other.m_isValid; - size_t nx = m_affineMatrix.numRows(); - size_t ny = m_affineMatrix.numCols(); - m_rawMem = new coord_t[nx * ny]; - m_rawMatrix = new coord_t *[nx]; - for (size_t i = 0; i < nx; i++) - m_rawMatrix[i] = m_rawMem + (i * ny); copyRawMatrix(); } return *this; Just noting down what was discussed in person. We shouldn't need to reallocate here as the lhs/rhs are the same size. We can leave the cppcheck warning as a false positive in this case. AffineMatrixParameter &AffineMatrixParameter::operator=(const AffineMatrixParame if (this != &other) { this->m_affineMatrix = other.m_affineMatrix; this->m_isValid = other.m_isValid; copyRawMatrix(); } return *this;
codereview_new_cpp_data_13077
void LoadSQW::readDNDDimensions(std::vector<Mantid::Geometry::MDHistoDimensionBu // TODO: how to use it in our framework? -> it is B^-1 matrix possibly // re-scaled - // std::vector<double> u_to_Rlu(4 * 4); // the matrix transforming from lab to crystal frame with scaling i0 += 4 * 4; // [data.u_to_rlu, count, ok, mess] = fread_catch(fid,[4,4],'float32'); if // ~all(ok); return; end; size_t ic = 0; for (size_t i = 0; i < 4; i++) { for (size_t j = 0; j < 4; j++) { - // u_to_Rlu[ic] = static_cast<double>(interpretAs<float>(buf, i0 + 4 * (i * 4 + j))); ic++; } } i0 += ic * 4; - // Mantid::Kernel::DblMatrix UEmat(u_to_Rlu); - // Mantid::Kernel::DblMatrix Rot(3, 3); - // for (int i = 0; i < 3; i++) { - // for (int j = 0; j < 3; j++) { - // Rot[i][j] = UEmat[i][j]; - // } - //} - // dscrptn.setRotationMatrix(Rot); // axis labels size i0 += 4 * 4; Can we remove the commented out code? void LoadSQW::readDNDDimensions(std::vector<Mantid::Geometry::MDHistoDimensionBu // TODO: how to use it in our framework? -> it is B^-1 matrix possibly // re-scaled i0 += 4 * 4; // [data.u_to_rlu, count, ok, mess] = fread_catch(fid,[4,4],'float32'); if // ~all(ok); return; end; size_t ic = 0; for (size_t i = 0; i < 4; i++) { for (size_t j = 0; j < 4; j++) { ic++; } } i0 += ic * 4; // axis labels size i0 += 4 * 4;
codereview_new_cpp_data_13078
void IqtFunctionModel::estimateExpParameters() { auto const &x = m_estimationData[i].x; auto const &y = m_estimationData[i].y; auto lifeTime = (x[1] - x[0]) / (log(y[0]) - log(y[1])); - if (lifeTime <= 0 || isnan(lifeTime)) lifeTime = 1.0; auto const height = y[0] * exp(x[0] / lifeTime); setLocalParameterValue(*heightName1, i, height); since any comparison between a NaN and a double should always be false we can simplify this instead with this. ```suggestion if (!lifeTime > 0) ``` void IqtFunctionModel::estimateExpParameters() { auto const &x = m_estimationData[i].x; auto const &y = m_estimationData[i].y; auto lifeTime = (x[1] - x[0]) / (log(y[0]) - log(y[1])); + if (!(lifeTime > 0)) lifeTime = 1.0; auto const height = y[0] * exp(x[0] / lifeTime); setLocalParameterValue(*heightName1, i, height);
codereview_new_cpp_data_13079
void MuonPairingAsymmetry::validateGroupsWorkspaces(std::map<std::string, std::s Workspace_sptr ws2 = this->getProperty("InputWorkspace2"); if (!ws1) { errors["InputWorkspace1"] = "The InputWorkspace1 must be a Workspace."; - return; } if (!ws2) { errors["InputWorkspace2"] = "The InputWorkspace2 must be a Workspace."; return; } if (ws1->isGroup() && !ws2->isGroup()) { This early return means the second workspace error is not displayed. Could we populate both errors before returning? void MuonPairingAsymmetry::validateGroupsWorkspaces(std::map<std::string, std::s Workspace_sptr ws2 = this->getProperty("InputWorkspace2"); if (!ws1) { errors["InputWorkspace1"] = "The InputWorkspace1 must be a Workspace."; } if (!ws2) { errors["InputWorkspace2"] = "The InputWorkspace2 must be a Workspace."; + } + if (errors.count("InputWorkspace1") == 1 || errors.count("InputWorkspace2") == 1) { return; } if (ws1->isGroup() && !ws2->isGroup()) {
codereview_new_cpp_data_13085
void ConvertCWPDMDToSpectra::binMD(const API::IMDEventWorkspace_const_sptr &mdws } if (xindex >= static_cast<int>(vecy.size())) { g_log.warning() << "Case unexpected: Event X = " << outx << ", Boundary = " << vecx[xindex] << "\n"; } } Please add a warning for the case that xindex < 0 that prints something like Boundary X Index is less than zero void ConvertCWPDMDToSpectra::binMD(const API::IMDEventWorkspace_const_sptr &mdws } if (xindex >= static_cast<int>(vecy.size())) { g_log.warning() << "Case unexpected: Event X = " << outx << ", Boundary = " << vecx[xindex] << "\n"; + } else if (xindex < 0) { + g_log.warning() << "Case unexpected: Event X = " << outx << ", Boundary index is out of vector range.\n"; } }
codereview_new_cpp_data_13086
void StepScan::generateCurve(const QString &var) { MatrixWorkspace_sptr top = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(m_plotWSName); MatrixWorkspace_sptr bottom = norm->getProperty("OutputWorkspace"); top /= bottom; - AnalysisDataService::Instance().addOrReplace(m_plotWSName, top); } plotCurve(); I've thought about whether adding an explicit call to divide is worth it or not. Sadly the OutputWorkspace name from norm (`bottom->getName()`) returns an empty string and the bottom workspace is not in the ADS. So I think I'm happy with this addOrReplace call as it's in a relatively niche part of the codebase. void StepScan::generateCurve(const QString &var) { MatrixWorkspace_sptr top = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(m_plotWSName); MatrixWorkspace_sptr bottom = norm->getProperty("OutputWorkspace"); top /= bottom; } plotCurve();
codereview_new_cpp_data_13088
size_t SpectrumInfo::size() const { /// Return count of all detectors used within spectrum size_t SpectrumInfo::detectorCount() const { - return std::accumulate(m_spectrumDefinition->begin(), m_spectrumDefinition->end(), size_t(), - [](auto x, const Mantid::SpectrumDefinition &spec) { return x + spec.size(); }); } /// Returns a const reference to the SpectrumDefinition of the spectrum. I think this would be easier to read: ```c++ return std::accumulate(m_spectrumDefinition->begin(), m_spectrumDefinition->end(), 0, [](size_t x, const Mantid::SpectrumDefinition &spec) { return x + spec.size(); }); ``` size_t SpectrumInfo::size() const { /// Return count of all detectors used within spectrum size_t SpectrumInfo::detectorCount() const { + return std::accumulate(m_spectrumDefinition->begin(), m_spectrumDefinition->end(), 0, + [](size_t x, const Mantid::SpectrumDefinition &spec) { return x + spec.size(); }); } /// Returns a const reference to the SpectrumDefinition of the spectrum.
codereview_new_cpp_data_13089
void LoadEventPreNexus2::procEvents(DataObjects::EventWorkspace_sptr &workspace) } // determine maximum pixel id - detid_max = *(std::max_element(detIDs.cbegin(), detIDs.cend())); // For slight speed up loadOnlySomeSpectra = (!this->spectra_list.empty()); Not safe if `detIDs` can be empty. void LoadEventPreNexus2::procEvents(DataObjects::EventWorkspace_sptr &workspace) } // determine maximum pixel id + const auto it = std::max_element(detIDs.cbegin(), detIDs.cend()); + detid_max = it == detIDs.cend() ? 0 : *it; // For slight speed up loadOnlySomeSpectra = (!this->spectra_list.empty());
codereview_new_cpp_data_13090
void LoadHFIRSANS::setBeamTrapRunProperty() { std::vector<double> trapDiametersInUse; trapDiametersInUse.reserve(trapIndexInUse.size()); std::transform(trapIndexInUse.cbegin(), trapIndexInUse.cend(), std::back_inserter(trapDiametersInUse), - [trapDiameters](auto index) { return trapDiameters[index]; }); g_log.debug() << "trapDiametersInUse length:" << trapDiametersInUse.size() << "\n"; You can capture `trapDiameters` by reference here. void LoadHFIRSANS::setBeamTrapRunProperty() { std::vector<double> trapDiametersInUse; trapDiametersInUse.reserve(trapIndexInUse.size()); std::transform(trapIndexInUse.cbegin(), trapIndexInUse.cend(), std::back_inserter(trapDiametersInUse), + [&trapDiameters](auto index) { return trapDiameters[index]; }); g_log.debug() << "trapDiametersInUse length:" << trapDiametersInUse.size() << "\n";
codereview_new_cpp_data_13091
void Workspace2D::init(const HistogramData::Histogram &histogram) { Histogram1D spec(initializedHistogram.xMode(), initializedHistogram.yMode()); spec.setHistogram(initializedHistogram); std::transform(data.begin(), data.end(), data.begin(), - [spec](const auto &) { return std::move(std::make_unique<Histogram1D>(spec)); }); // Add axes that reference the data m_axes.resize(2); Capture `spec` by reference. void Workspace2D::init(const HistogramData::Histogram &histogram) { Histogram1D spec(initializedHistogram.xMode(), initializedHistogram.yMode()); spec.setHistogram(initializedHistogram); std::transform(data.begin(), data.end(), data.begin(), + [&spec](const auto &) { return std::move(std::make_unique<Histogram1D>(spec)); }); // Add axes that reference the data m_axes.resize(2);
codereview_new_cpp_data_13092
std::string CompositeImplicitFunction::toXMLString() const { AutoPtr<Element> parameterListElement = pDoc->createElement("ParameterList"); functionElement->appendChild(parameterListElement); - // this temporary object and following lines are to be replaced by std::transform_reduce, when available - std::vector<std::string> tmpVec; - tmpVec.reserve(m_Functions.size()); - std::transform(m_Functions.cbegin(), m_Functions.cend(), std::back_inserter(tmpVec), - [](const auto &function) { return function->toXMLString(); }); - std::string functionXML = std::accumulate(tmpVec.cbegin(), tmpVec.cend(), std::string()); AutoPtr<Text> functionFormatText = pDoc->createTextNode("%s"); functionElement->appendChild(functionFormatText); You should be able to use `std::accumulate` only. std::string CompositeImplicitFunction::toXMLString() const { AutoPtr<Element> parameterListElement = pDoc->createElement("ParameterList"); functionElement->appendChild(parameterListElement); + std::string functionXML = + std::accumulate(m_Functions.cbegin(), m_Functions.cend(), std::string(), + [](const auto &lhs, const auto &function) { return lhs + function->toXMLString(); }); AutoPtr<Text> functionFormatText = pDoc->createTextNode("%s"); functionElement->appendChild(functionFormatText);
codereview_new_cpp_data_13093
std::vector<Mantid::detid_t> notInTubes(const std::vector<detail::TubeBuilder> & std::vector<Mantid::detid_t> detIDs) { std::vector<Mantid::detid_t> used; std::for_each(tubes.cbegin(), tubes.cend(), [&used](const auto &tube) { - std::transform((tube.detIDs()).cbegin(), (tube.detIDs()).cend(), std::back_inserter(used), - [](const auto id) { return id; }); }); std::vector<Mantid::detid_t> diff; std::sort(detIDs.begin(), detIDs.end()); You can use `std::copy` instead of `std::transform` with a lambda. std::vector<Mantid::detid_t> notInTubes(const std::vector<detail::TubeBuilder> & std::vector<Mantid::detid_t> detIDs) { std::vector<Mantid::detid_t> used; std::for_each(tubes.cbegin(), tubes.cend(), [&used](const auto &tube) { + std::copy((tube.detIDs()).cbegin(), (tube.detIDs()).cend(), std::back_inserter(used)); }); std::vector<Mantid::detid_t> diff; std::sort(detIDs.begin(), detIDs.end());
codereview_new_cpp_data_13094
bool BatchJobManager::hasSelectedRowsRequiringProcessing(Group const &group) { // If the group itself is selected, consider its rows to also be selected auto processAllRowsInGroup = (m_processAll || isSelected(group)); - const auto it = - std::find_if((group.rows()).cbegin(), (group.rows()).cend(), [this, &processAllRowsInGroup](const auto &row) { - return (row && (processAllRowsInGroup || isSelected(row.get())) && row->requiresProcessing(m_reprocessFailed)); - }); - return it != (group.rows()).cend(); } /** Get algorithms and related properties for processing a batch of rows and You could use `return std::any_of(...` bool BatchJobManager::hasSelectedRowsRequiringProcessing(Group const &group) { // If the group itself is selected, consider its rows to also be selected auto processAllRowsInGroup = (m_processAll || isSelected(group)); + return std::any_of((group.rows()).cbegin(), (group.rows()).cend(), [this, &processAllRowsInGroup](const auto &row) { + return (row && (processAllRowsInGroup || isSelected(row.get())) && row->requiresProcessing(m_reprocessFailed)); + }); } /** Get algorithms and related properties for processing a batch of rows and
codereview_new_cpp_data_13095
std::vector<std::vector<std::string>> MuonPeriodInfo::makeCorrections(std::vecto // Find max size of logs and assume to be the correct size const auto it = std::max_element(logs.cbegin(), logs.cend(), [](const auto &log1, const auto &log2) { return log1.size() < log2.size(); }); - size_t maxSize = (*it).size(); // Check size of each log and make corrections where needed for (size_t i = 0; i < logs.size(); ++i) { if (logs[i].empty()) { ```suggestion size_t maxSize = it == logs.cend() ? 0 : (*it).size(); ``` std::vector<std::vector<std::string>> MuonPeriodInfo::makeCorrections(std::vecto // Find max size of logs and assume to be the correct size const auto it = std::max_element(logs.cbegin(), logs.cend(), [](const auto &log1, const auto &log2) { return log1.size() < log2.size(); }); + size_t maxSize = it == logs.cend() ? 0 : (*it).size(); // Check size of each log and make corrections where needed for (size_t i = 0; i < logs.size(); ++i) { if (logs[i].empty()) {
codereview_new_cpp_data_13274
Author: Hans Dembinski */ -#include <math.h> #include "_rcont.h" #include "logfactorial.h" // helper function to access a 1D array like a C-style 2D array tab_t *ptr(tab_t *m, int nr, int nc, int ir, int ic) ```suggestion ``` Apparently, this include causes problems for, I guess, `Python.h` and hence the warnings. Do the warnings go away on your side when you remove this @HDembinski? If it does, feel free to commit this and we can check if CI also passes. Author: Hans Dembinski */ #include "_rcont.h" #include "logfactorial.h" +#include <math.h> // helper function to access a 1D array like a C-style 2D array tab_t *ptr(tab_t *m, int nr, int nc, int ir, int ic)
codereview_new_cpp_data_13275
Author: Hans Dembinski */ -#include <math.h> #include "_rcont.h" #include "logfactorial.h" // helper function to access a 1D array like a C-style 2D array tab_t *ptr(tab_t *m, int nr, int nc, int ir, int ic) ```suggestion #include "logfactorial.h" #include <math.h> ``` Author: Hans Dembinski */ #include "_rcont.h" #include "logfactorial.h" +#include <math.h> // helper function to access a 1D array like a C-style 2D array tab_t *ptr(tab_t *m, int nr, int nc, int ir, int ic)