diff --git a/.clang-format b/.clang-format index 5bead5f39dd3c5841f615beb6472c4c504d407af..7e1593bdd32a0a03c4efc84bd153505c476d6be4 100644 --- a/.clang-format +++ b/.clang-format @@ -1,2 +1,7 @@ -BasedOnStyle: LLVM +--- +BasedOnStyle: LLVM +--- +Language: Cpp +ColumnLimit: 120 +... diff --git a/.cmake-format.json b/.cmake-format.json index 10669de81e4e6ef8f2a2fad66d477dc9a8e92329..f7ebd9de35b6e6d74c517edfffdd13366502fec6 100644 --- a/.cmake-format.json +++ b/.cmake-format.json @@ -92,14 +92,26 @@ "MODULE_OUTPUT_DIR": 1, "PYQT_VERSION": 1, "FOLDER": 1, - "SIP_SRCS": "+", + "SIP_SRC": 1, "HEADER_DEPS": "+", "INCLUDE_DIRS": "+", "LINK_LIBS": "+", - "INSTALL_DIRS": "+", + "INSTALL_DIR": "+", "OSX_INSTALL_RPATH": "+", "LINUX_INSTALL_RPATH": "+" } + }, + "add_python_package": { + "kwargs": { + "EGGLINKNAME": 1, + "INSTALL_LIB_DIRS": "+", + "INSTALL_BIN_DIR": 1, + "EXCLUDE_ON_INSTALL": "+" + }, + "flags": [ + "EXECUTABLE", + "GENERATE_SITECUSTOMIZE" + ] } }, "always_wrap": [], diff --git a/.flake8 b/.flake8 index e0dc187f4b1e5c9240cfc03f429fb450f56e55d0..8258ede83c4a3155c7bf2612ae1ef2f0ad1ce076 100644 --- a/.flake8 +++ b/.flake8 @@ -13,9 +13,7 @@ exclude = images, installers, instrument, - MantidPlot, qt/applications/workbench/workbench/app/resources.py, - qt/paraview_ext, qt/python/mantidqt/resources.py, qt/python/mantidqt/dialogs/errorreports/resources_qt4.py qt/python/mantidqt/dialogs/errorreports/resources_qt5.py diff --git a/.gitattributes b/.gitattributes index 57afaf19553d1f87a7c00a26e05986c5dbc93217..9ee81e29a6cdd98f1c1ebbf482506174240c0a62 100644 --- a/.gitattributes +++ b/.gitattributes @@ -11,6 +11,6 @@ *.dot !diff # Allowing gSoap generated files to be committed. -/Code/Mantid/Framework/ICat/inc/MantidICat/ICat3/GSoapGenerated/ICat3H.h hooks.MaxObjectKiB131025=2048 +/Code/Mantid/Framework/ICat/inc/MantidICat/ICat3/GSoapGenerated/ICat3H.h hooks.MaxObjectKiB131025=2048 /Code/Mantid/Framework/ICat/src/ICat3/GSoapGenerated/ICat3C.cpp hooks.MaxObjectKiB131025=5120 /Code/Mantid/Framework/ICat/src/ICat4/GSoapGenerated/ICat4C.cpp hooks.MaxObjectKiB131025=2048 diff --git a/.githooks/pre-commit b/.githooks/pre-commit deleted file mode 100755 index 3ae5c2a03a4045e13a7c805b0d0f9e9ab2e759a0..0000000000000000000000000000000000000000 --- a/.githooks/pre-commit +++ /dev/null @@ -1,334 +0,0 @@ -#!/usr/bin/env bash -#============================================================================= -# Copyright 2010-2011 Kitware, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -#============================================================================= - -die() { - echo 'pre-commit hook failure' 1>&2 - echo '-----------------------' 1>&2 - echo '' 1>&2 - echo "$@" 1>&2 - exit 1 -} - -zero='0000000000000000000000000000000000000000' - -#----------------------------------------------------------------------------- -# Check for committer identity. -advice=' -Use the commands - - git config --global user.name '\''Your Name'\'' - git config --global user.email '\''you@yourdomain.com'\'' - -to introduce yourself to Git before committing.' - -# Ensure name and email are available. -git config --get user.name > /dev/null && -git config --get user.email > /dev/null || -die 'Identity not configured!' "$advice" - -# Validate the name and email. -git config --get user.name | grep ' ' > /dev/null || -die 'Set user.name to your Real Name (with a space), not a userid.' "$advice" -git config --get user.email | grep '^[^@]*@[^@]*$' > /dev/null || -die 'Set user.email to an email address (userid@validdomain.com).' "$advice" - -#----------------------------------------------------------------------------- -# Check content that will be added by this commit. - -if git rev-parse --verify -q HEAD > /dev/null; then - against=HEAD -else - # Initial commit: diff against an empty tree object - against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 -fi - -# Merge ("git commit" after "git merge" with conflicts or --no-commit) -merge_head=$(git rev-parse -q --verify MERGE_HEAD) || merge_head='' - -# Disallow non-ascii file names. The printable range starts at the -# space character and ends with tilde. -if test "$(git diff --cached --name-only --diff-filter=A -z $against | - LC_ALL=C tr -d '[ -~]\0')"; then - die 'Non-ascii file names may not be added: -'"$(git diff --cached --name-only --diff-filter=A $against)" -fi - -#----------------------------------------------------------------------------- -# Builtin whitespace checks. -bad=$(git diff-index --check --cached $against -- --ignore-space-at-eol) || die "$bad" - -# Approximate whitespace=tab-in-indent check with Git < 1.7.2. -git --version | grep -q " \(1\.[0-6]\|1\.7\.[01]\)" && -approx_tab_in_indent=true || approx_tab_in_indent=false -check_tab() { - lines=$(git diff-index -p --cached $against -- "$1" | - grep '^+ ') && - echo "$lines" | - while read line; do - echo "$1: tab in indent." && - echo "$line" - done -} - -# Reject addition of a line without a newline at end-of-file. -check_no_lf_at_eof() { - lines=$(git diff-index -p --cached $against -- "$1" | tail -2) - if echo "$lines" | head -1 | grep -q '^+' && - echo "$lines" | tail -1 | grep -q '^\\ No newline'; then - echo "$1: No newline at end of file" - fi -} - -# Custom whitespace checks. -check_whitespace() { - ws=$(git check-attr whitespace -- "$file" | - sed 's/^[^:]*: whitespace: //') - if $approx_tab_in_indent; then - case ",$ws," in - *,tab-in-indent,*) check_tab "$1" ;; - esac - fi - case ",$ws," in - *,no-lf-at-eof,*) check_no_lf_at_eof "$1" ;; - esac -} -bad=$(git diff-index --name-only --cached $against -- | -while read file; do - check_whitespace "$file" -done) -test -z "$bad" || die "$bad" - -#----------------------------------------------------------------------------- -# Check file modes and sizes. -mode_looks_exe() { - case "$1" in - *.bat) return 0 ;; - *.cmd) return 0 ;; - *.exe) return 0 ;; - *.com) return 0 ;; - esac - git cat-file blob "$2" | head -1 | grep "^#\!/" > /dev/null -} -mode_not_exe () { - echo "The file '$file' has looks executable but does not have an executable mode." -} -mode_bad_exe () { - echo "The file '$file' has executable mode but does not look executable." -} -mode_non_file () { - echo "The path '$file' has a non-file mode." -} -check_mode() { - case "$dst_mode" in - 100755) mode_looks_exe "$file" "$dst_obj" || mode_bad_exe ;; - 100644) mode_looks_exe "$file" "$dst_obj" && mode_not_exe ;; - 160000) ;; - *) mode_non_file ;; - esac -} - -size_max_KiB=$(git config hooks.MaxObjectKiB) -test -n "$size_max_KiB" || size_max_KiB=1024 -size_too_large_once="" -size_too_large_once() { - test -z "$size_too_large_once" || return ; size_too_large_once=done - echo 'At least one file is staged for commit with size larger than the limit. -We prefer to keep large files out of the main source tree, especially -binary files that do not compress well. This hook disallows large files. - -If it is vital that this file enters the repository, speak to a dev lead. -Remember that unit tests should typically not require loading files (see -http://www.mantidproject.org/Unit_Test_Good_Practice#Using_files_in_Unit_tests). -' -# Instructions for allowing ESSENTIAL files only: -# A limit for specific files or patterns may be set in ".gitattributes" with -# the "hooks.MaxObjectKiBYYMMDD" attribute (where YYMMDD is the current date). -# For example, the line -# -# *.c hooks.MaxObjectKiB121207=2048 -# -# sets a limit of 2048 KiB for C source files, but WILL ONLY WORK on the date -# matching the entry. This avoids the previous behaviour that once set the -# hook was forever disabled if the entry was not removed afterwards. -# See "git help attributes" for details on the .gitattributes format. -} -size_too_large() { - size_too_large_once - echo "The path '$file' has size $file_KiB KiB, greater than allowed $max_KiB KiB." -} -size_validate_max_KiB() { - test "$max_KiB" -ge "0" 2>/dev/null && return 0 - echo "The path '$file' has invalid attribute \"hooks-MaxObjectKiB=$max_KiB\"." - return 1 -} -check_size() { - test "$dst_obj" != "$zero" || return - datesuffix=`date +%y%m%d` - hookname='hooks.MaxObjectKiB'$datesuffix - max_KiB=$(git check-attr $hookname -- "$file" | - sed "s/^[^:]*: ${hookname}: //") - case "$max_KiB" in - 'unset') return ;; # No maximum for this object. - 'set') max_KiB="$size_max_KiB" ;; # Use local default. - 'unspecified') max_KiB="$size_max_KiB" ;; # Use local default. - *) size_validate_max_KiB || return ;; - esac - if test "$max_KiB" -gt "0"; then - file_KiB=$(expr '(' $(git cat-file -s "$dst_obj") + 1023 ')' / 1024) - test "$file_KiB" -le "$max_KiB" || size_too_large - fi -} - -short_commit() { - git rev-parse --short "$1" 2>/dev/null || echo "$1" -} - -lookup_config_module_update() { - update=$(git config "hooks.$1.update") - - # Special-case "true" to accept any update. - test "{$update}" = "{true}" && echo '.' && return - - # Format is "aaaaaa..bbbbbb" for update aaaaaa => bbbbbb. - # Convert to regex "^aaaaaa[a-z0-9]* bbbbbb[a-z0-9]*$". - sha1ex='[a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9]*' - regex='^\('"$sha1ex"'\)\.\.\('"$sha1ex"'\)$' - echo "$update" | - sed -n "/$regex/ {s/$regex/"'^\1[a-z0-9]* \2[a-z0-9]*$/;p;}' | - grep '.' # Return false if result is empty. -} - -check_module() { - enabled=$(git config --get --bool hooks.submodule) || enabled=true - test "$enabled" = "false" && return - - # Allow merged submodule updates. - test -n "$merge_head" && - merge_obj=$(git rev-parse -q --verify "$merge_head:$file") && - test "$merge_obj" = "$dst_obj" && return - - # Allow module-only commits without extra work. - test -z "$diffs_normal" && return - - # Check if module update is allowed with other changes. - allow=$(lookup_config_module_update "$file") || allow='none' - if echo "$src_obj $dst_obj" | grep "$allow" > /dev/null; then - return - fi - src_short=$(short_commit "$src_obj") - dst_short=$(short_commit "$dst_obj") - echo 'A submodule link is staged for commit (among other changes): - - "'"$file"'" '"$src_short => $dst_short"' - -This may occur by accident so we require an extra step to commit. -If you intend to include this change in your commit, run - - git config "hooks.'"$file"'.update" '"$src_short..$dst_short"' - -to explicitly allow the change and try the commit again. Otherwise run - - git reset HEAD -- "'"$file"'" - -to unstage the change. Furthermore, if you did not intend to modify -the submodule at all, also run - - git submodule update -- "'"$file"'" - -to checkout the current version of the submodule in your work tree. -Test your changes again to see if they still work with the module. -Finally, try the commit again. -' - return 1 -} - -check_module_rewind() { - parent_name="$1" - parent_commit="$2" - base=$(GIT_DIR="$file/.git" \ - git merge-base $src_obj $dst_obj 2>/dev/null) || base='' - test "$base" != "$dst_obj" && return - parent_short=$(short_commit "$parent_commit") - src_short=$(GIT_DIR="$file/.git" short_commit "$src_obj") - dst_short=$(GIT_DIR="$file/.git" short_commit "$dst_obj") - echo 'This commit would rewind a submodule link: - - "'"$file"'" '"$src_short => $dst_short"' - -from the newer version in '"$parent_name"' ('"$parent_short"'). Run - - git reset '"$parent_name"' -- "'"$file"'" - git submodule update -- "'"$file"'" - -to checkout the newer version of the submodule in your work tree. -Then try the commit again. -' - return 1 -} - -diffs=$(git diff-index --cached $against -- | - sed -n '/^:[^:]/ {s/^://;p;}') -diffs_normal=$(echo "$diffs" | grep -v '^...... 160000') -diffs_module=$(echo "$diffs" | grep '^...... 160000') -bad=$( -test -n "$diffs_normal" && echo "$diffs_normal" | -while read src_mode dst_mode src_obj dst_obj status file; do - if test "$src_mode" != "$dst_mode" -a "$dst_mode" != "000000"; then - check_mode - fi - if test "$dst_mode" != "160000" -a "$dst_mode" != '000000'; then - check_size - fi -done -test -n "$diffs_module" && echo "$diffs_module" | -while read src_mode dst_mode src_obj dst_obj status file; do - check_module_rewind HEAD "$against" && - check_module || - break -done -) -test -z "$bad" || die "$bad" - -#----------------------------------------------------------------------------- -# Merge checks. -if test -n "$merge_head"; then - merge_diffs=$(git diff-index --cached $merge_head -- | - sed -n '/^:[^:]/ {s/^://;p;}') -else - merge_diffs='' -fi -merge_diffs_normal=$(echo "$merge_diffs" | grep -v '^...... 160000') -merge_diffs_module=$(echo "$merge_diffs" | grep '^...... 160000') -bad=$( -test -n "$merge_diffs_module" && echo "$merge_diffs_module" | -while read src_mode dst_mode src_obj dst_obj status file; do - check_module_rewind MERGE_HEAD "$merge_head" || - break -done -) -test -z "$bad" || die "$bad" - -#----------------------------------------------------------------------------- -# Style hooks. -#. "$GIT_DIR/hooks/pre-commit-style" - -#----------------------------------------------------------------------------- -# Chain to project-specific hook. -#. "$GIT_DIR/hooks/hooks-chain.bash" -#hooks_chain pre-commit "$@" - -# vim: set filetype=sh tabstop=8 softtabstop=8 shiftwidth=8 noexpandtab : diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 9a0d3e154deec8c7101f05af5bbb1b3607cda665..9137b046f4c32d7a6af3045528b83e3bb28fb81f 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -4,7 +4,7 @@ The [developer documentation](http://developer.mantidproject.org/) has informati 2. Clone the repository with the remotes `origin` pointing at your fork as `origin` and `mantidproject/mantid` as `upstream`. This is a [common setup](https://help.github.com/articles/configuring-a-remote-for-a-fork/). 3. Make changes as you see fit. Please still follow the guidelines for [running the unit tests](http://developer.mantidproject.org/RunningTheUnitTests.html) and the [build servers](http://developer.mantidproject.org/AutomatedBuildProcess.html). 4. Submit a [pull request](https://help.github.com/articles/using-pull-requests) to this branch. This is a start to the conversation. - + If you need help, you can go to the [forum](https://forum.mantidproject.org/). Hints to make the integration of your changes easy (and happen faster): diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 7aab7239acf698c0dd06dea075e6224081fb86aa..0000000000000000000000000000000000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,11 +0,0 @@ - - -### Expected behavior - -### Actual behavior - -### Steps to reproduce the behavior - -### Platforms affected diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000000000000000000000000000000000000..550ae6fcc31c9240761a4c9f6ee2da4c1213e28d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,41 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: 'Bug' +assignees: '' + +--- + + + + + +**Describe the bug** + + +**To Reproduce** + + +**Expected behavior** + + +**Screenshots** + + +**Platform/Version (please complete the following information):** + - OS: [e.g. Windows, RHEL 7, Ubuntu, macOS] + - OS Version: + - Mantid Version [e.g. 6.0.0] + +**Additional context** + diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..ec2339e315b68524cbd97ee0a81eb50b148ce9de --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: MantidProject Forum + url: https://forum.mantidproject.org + about: Please ask and answer questions here. diff --git a/.github/ISSUE_TEMPLATE/investigation.md b/.github/ISSUE_TEMPLATE/investigation.md new file mode 100644 index 0000000000000000000000000000000000000000..d003b6e63b54b34fb5fbf50405ce0fbc4417b106 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/investigation.md @@ -0,0 +1,20 @@ +--- +name: Investigation +about: Create a task to investigate options for future work +title: 'Investigate ...' +labels: 'Investigation' +assignees: '' + +--- + +**Describe the outcome that is desired.** + + +**Does the outcome relate directly to a problem? Please describe.** + + +**Describe any solutions you are considering** + + +**Additional context** + diff --git a/.github/ISSUE_TEMPLATE/maintenance.md b/.github/ISSUE_TEMPLATE/maintenance.md new file mode 100644 index 0000000000000000000000000000000000000000..8adab93b3a6af663afea944a616d1af479b19fcb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/maintenance.md @@ -0,0 +1,17 @@ +--- +name: Maintenance +about: Create a task for maintenance of the codebase +title: 'Investigate ...' +labels: 'Maintenance' +assignees: '' + +--- + +**Describe the outcome that is desired.** + + +**Describe any solutions you are considering** + + +**Additional context** + diff --git a/.github/ISSUE_TEMPLATE/new_feature.md b/.github/ISSUE_TEMPLATE/new_feature.md new file mode 100644 index 0000000000000000000000000000000000000000..91fd532bfb9db9513b5b81c437188a04bc206535 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/new_feature.md @@ -0,0 +1,20 @@ +--- +name: New Feature +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** + + +**Describe the solution you'd like** + + +**Describe alternatives you've considered** + + +**Additional context** + diff --git a/.github/stale.yml b/.github/stale.yml index 9a8e94e104772719ab90316c1b76140e5fb8c385..907945b95f87af15bbdce64b3a3c6cc9e3625aa7 100644 --- a/.github/stale.yml +++ b/.github/stale.yml @@ -4,19 +4,28 @@ daysUntilStale: 180 daysUntilClose: 7 # Issues with these labels will never be considered stale exemptLabels: - - Never Stale + - Induction + - Roadmap # Label to use when marking an issue as stale staleLabel: Stale # Comment to post when marking an issue as stale. Set to `false` to disable markComment: > This issue has been automatically marked as stale because it has not had - recent activity. It will be closed in 7 days if no further activity occurs. - If you feel this is incorrect please comment to keep it alive, with a reason - why. - - To prevent closure, e.g. for long-term planning issues, - add the "Never Stale" label. + activity in 6 months. It will be closed in 7 days if no further activity occurs. + + Allowing issues to close as stale helps us filter out issues which can wait + for future development time. All issues closed by stale bot act like normal issues; they can be searched for, commented on or reopened at any point. + + If you'd like a closed stale issue to be considered, + feel free to either re-open the issue directly or contact a developer. + + To extend the lifetime of an issue please comment below, + it helps us see that this is still affecting you and you want + it fixed in the near-future. Extending the lifetime of an issue + may cause the development team to prioritise it over other issues, + which may be closed as stale instead. + # Comment to post when closing a stale issue. Set to `false` to disable closeComment: > This issue has been closed automatically. If this still affects you please - re-open this issue with a comment so we can look into resolving it. + re-open this issue with a comment or contact us so we can look into resolving it. diff --git a/.gitignore b/.gitignore index b0e8351e9f4d3a0d5af476c8eee8a1ba1a4ddc86..3deea1c8b6a1d2d43cc047516654e34b08ebf62c 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,9 @@ cmake_install.cmake install_manifest.txt compile_commands.json +# Ignore CMakeUserPresets +CMakeUserPresets.json + # Compiled Object files *.slo @@ -28,8 +31,9 @@ compile_commands.json *.la *.a -# Compiled python files -*.py[co] +# Byte-compiled / optimized files +__pycache__/ +*.py[cod] # Eclipse-generated files *.pydevproject @@ -76,6 +80,9 @@ local.properties #Test results *.log +#Coverage results +*.gcov + # Build results build/ /[Rr]elease/ @@ -99,11 +106,8 @@ build/ .builds *.egg-info/ Framework/Kernel/inc/MantidKernel/GitHubApiHelper.h -Vates/VatesSimpleGui/ViewWidgets/inc/MantidVatesSimpleGuiViewWidgets/LibHelper.h qt/python/mantidqt/resources.py qt/applications/workbench/workbench/app/resources.py -qt/applications/workbench/setup.py -qt/python/setup.py # Visual C++ cache files ipch/ @@ -164,11 +168,13 @@ Thumbs.db # Folder config file Desktop.ini -# PyCharm IDE +# CLion and PyCharm IDE .idea/ +cmake-build-*/ # VSCode .vscode/ +.cache/ .clangd/ XDG_CACHE_HOME/ # The file that contains metadata for VSCode Workspace @@ -187,3 +193,10 @@ Third_Party/ win64/ dbg/ rel/ + +# NFS files +*.nfs* + +# in source installed conda +mambaforge/ +miniconda3/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..31462fc2b499e296c48b11a817b757a68e71c39e --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,33 @@ +default_language_version: + python: python3 + +exclude: ^$|instrument/ + +repos: + + # Run fast code improvement/checks before running PR specific helpers. + - repo: https://github.com/pre-commit/pre-commit-hooks.git + rev: 2618198e9658cccb4a53f04af0f7d642109f3b54 + hooks: + - id: trailing-whitespace + args: [--markdown-linebreak-ext=md] + exclude: .patch$ + - id: check-added-large-files + args: ['--maxkb=4096'] + - id: check-xml + - id: check-yaml + args: [--allow-multiple-documents] + + - repo: https://github.com/mantidproject/pre-commit-hooks.git + rev: 8809bbab4c8b9609f559e2428e6255e9407c3efe + hooks: + - id: clang-format + exclude: Testing/Tools/cxxtest|tools + + - repo: https://gitlab.com/pycqa/flake8.git + rev: 3.7.9 + hooks: + - id: flake8 + # Have to manually copy this from the .flake8 as flake8 will just ignore the config if the file is passed + exclude: Framework/PythonInterface/test|qt/applications/workbench/workbench/app/resources.py|qt/python/mantidqt/resources.py|qt/python/mantidqt/dialogs/errorreports/resources_qt4.py|qt/python/mantidqt/dialogs/errorreports/resources_qt5.py|Testing/PerformanceTests|Testing/SystemTests/lib|Testing/SystemTests/scripts|Testing/SystemTests/tests/framework/reference|scripts/ErrorReporter/ui_errorreport.py + args: ['--extend-ignore=E999,F821,E127'] diff --git a/CMakeLists.txt b/CMakeLists.txt index c93404e5b9323b6ab73bdc3ef4aa4d4cefd9ef80..093ecb3af29591cb225461148cdcef0201277a73 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,5 @@ -# CMake version check. 3.14 mimimum available from EPEL. -# 3.15 is required on Windows, but is not available in EPEL yet. -cmake_minimum_required(VERSION 3.14) +# CMake version check. +cmake_minimum_required(VERSION 3.16) # Define the project name. project(Mantid) @@ -30,14 +29,13 @@ set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/buildconfig/CMake") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin) -option(ENABLE_MANTIDPLOT "Enable Qt4-based gui & components" OFF) option(ENABLE_WORKBENCH "Enable Qt5-based gui & components" ON) -if(ENABLE_MANTIDPLOT) - message( FATAL_ERROR "MantidPlot has been removed from the source code") -endif() set(CPACK_INSTALL_CMAKE_PROJECTS "${CMAKE_BINARY_DIR}" "Mantid" "ALL" "/") +# Conda build variable +set(CONDA_BUILD FALSE CACHE BOOL "If True, proceed with a Conda build. Only relevant on Windows") + # Ensure that if we are running any sanitizers the compiler options are # known in sub targets include(Sanitizers) @@ -75,13 +73,8 @@ include(Bootstrap) # Configure Eigen early include(Eigen) - include(Span) -# Set ParaView information since later items depend on it -# VATES flag. Requires ParaView -option(MAKE_VATES "Switch for compiling the Vates project" Off) - if( MSVC ) include ( MSVCSetup ) elseif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") @@ -103,11 +96,11 @@ endif() find_package(TBB REQUIRED) # We probably don't want this to run on every build. -option(COVERALLS "Generate coveralls data" OFF) +option(COVERAGE "Generate coverage data" OFF) -if(COVERALLS) - include(Coveralls) - coveralls_turn_on_coverage() +if(COVERAGE) + include(Coverage) + coverage_turn_on() endif() if(ENABLE_WORKBENCH) @@ -137,11 +130,12 @@ set(DOCS_BUILDDIR ${CMAKE_BINARY_DIR}/docs) # Framework Build options option(CXXTEST_ADD_PERFORMANCE - "Switch to add Performance tests to the list of tests run by ctest?") + "Switch to add performance tests to the list of tests run by ctest?") add_subdirectory(Framework) include_directories(Framework/Kernel/inc) +include_directories(Framework/Json/inc) include_directories(Framework/HistogramData/inc) include_directories(Framework/Indexing/inc) include_directories(Framework/Parallel/inc) @@ -204,7 +198,7 @@ endif() # System test data target add_subdirectory(Testing/SystemTests/scripts) -if(COVERALLS) +if(COVERAGE) get_property(ALL_SRCS GLOBAL PROPERTY COVERAGE_SRCS) set(SRCS_FILE "") foreach(SRC ${ALL_SRCS}) @@ -217,7 +211,7 @@ if(COVERALLS) SRCS_FILE) set(SRCS_FILENAME "${CMAKE_CURRENT_BINARY_DIR}/sources.txt") file(WRITE ${SRCS_FILENAME} ${SRCS_FILE}) - coveralls_setup(${SRCS_FILENAME} OFF "${CMAKE_SOURCE_DIR}/buildconfig/CMake") + coverage_setup(${SRCS_FILENAME} OFF "${CMAKE_SOURCE_DIR}/buildconfig/CMake") endif() # Installation settings diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000000000000000000000000000000000000..744a54c7f7e09d3d84eb40940de9d55c4c9cd8dc --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,152 @@ +{ + "version": 1, + "cmakeMinimumRequired": { + "major": 3, + "minor": 19, + "patch": 0 + }, + "configurePresets": [ + { + "name": "osx", + "displayName": "osx", + "description": "Default build options for an OSX conda build", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build", + "cacheVariables": { + "CMAKE_FIND_FRAMEWORK": "LAST", + "CMAKE_PREFIX_PATH": "$env{CONDA_PREFIX}", + "USE_PYTHON_DYNAMIC_LIB": "OFF", + "Qt5_DIR": "$env{CONDA_PREFIX}/lib/cmake/qt5", + "HDF5_ROOT": "$env{CONDA_PREFIX}", + "OpenSSL_ROOT": "$env{CONDA_PREFIX}", + "CONDA_BUILD": true, + "CMAKE_BUILD_TYPE": "Debug" + } + }, + { + "name": "win", + "displayName": "win", + "description": "Default build options for a windows conda build", + "binaryDir": "${sourceDir}/build", + "generator": "Visual Studio 16 2019", + "cacheVariables": { + "CMAKE_PREFIX_PATH": "$env{CONDA_PREFIX}", + "CONDA_BUILD": true + } + }, + { + "name": "linux", + "displayName": "linux", + "description": "Default build options for a linux conda build", + "binaryDir": "${sourceDir}/build", + "generator": "Ninja", + "cacheVariables": { + "CMAKE_PREFIX_PATH": "$env{CONDA_PREFIX}", + "CONDA_BUILD": true, + "CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH": "FALSE", + "CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH": "FALSE", + "CMAKE_BUILD_TYPE": "Debug" + } + }, + { + "name": "linux-ci", + "displayName": "linux-ci", + "description": "To be used in the CI environment only", + "binaryDir": "${sourceDir}/build", + "generator": "Ninja", + "cacheVariables": { + "CMAKE_PREFIX_PATH": "$env{CONDA_PREFIX}", + "CONDA_BUILD": true, + "CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH": "FALSE", + "CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH": "FALSE", + "CMAKE_BUILD_TYPE": "Release", + "ENABLE_PRECOMMIT": "OFF", + "ENABLE_CPACK": "ON", + "DOCS_HTML": "ON", + "ENABLE_CONDA": "ON", + "COLORED_COMPILER_OUTPUT": "OFF" + } + }, + { + "name": "linux-ci-address-sanitiser", + "displayName": "linux-ci-address-sanitiser", + "description": "To be used for the CI environment", + "binaryDir": "${sourceDir}/build", + "generator": "Ninja", + "cacheVariables": { + "CMAKE_PREFIX_PATH": "$env{CONDA_PREFIX}", + "CONDA_BUILD": true, + "CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH": "FALSE", + "CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH": "FALSE", + "CMAKE_BUILD_TYPE": "RelWithDebInfo", + "ENABLE_PRECOMMIT": "OFF", + "ENABLE_CPACK": "ON", + "DOCS_HTML": "ON", + "ENABLE_CONDA": "ON", + "COLORED_COMPILER_OUTPUT": "OFF", + "USE_SANITIZER": "Address" + } + }, + { + "name": "linux-ci-memory-sanitiser", + "displayName": "linux-ci-memory-sanitiser", + "description": "To be used for the CI environment", + "binaryDir": "${sourceDir}/build", + "generator": "Ninja", + "cacheVariables": { + "CMAKE_PREFIX_PATH": "$env{CONDA_PREFIX}", + "CONDA_BUILD": true, + "CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH": "FALSE", + "CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH": "FALSE", + "CMAKE_BUILD_TYPE": "RelWithDebInfo", + "ENABLE_PRECOMMIT": "OFF", + "ENABLE_CPACK": "ON", + "DOCS_HTML": "ON", + "ENABLE_CONDA": "ON", + "COLORED_COMPILER_OUTPUT": "OFF", + "USE_SANITIZER": "memory" + } + }, + { + "name": "linux-ci-thread-sanitiser", + "displayName": "linux-ci-thread-sanitiser", + "description": "To be used for the CI environment", + "binaryDir": "${sourceDir}/build", + "generator": "Ninja", + "cacheVariables": { + "CMAKE_PREFIX_PATH": "$env{CONDA_PREFIX}", + "CONDA_BUILD": true, + "CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH": "FALSE", + "CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH": "FALSE", + "CMAKE_BUILD_TYPE": "RelWithDebInfo", + "ENABLE_PRECOMMIT": "OFF", + "ENABLE_CPACK": "ON", + "DOCS_HTML": "ON", + "ENABLE_CONDA": "ON", + "COLORED_COMPILER_OUTPUT": "OFF", + "USE_SANITIZER": "thread" + } + }, + { + "name": "linux-ci-coverage", + "displayName": "linux-ci-coverage", + "description": "To be used in the CI environment only", + "binaryDir": "${sourceDir}/build", + "generator": "Ninja", + "cacheVariables": { + "CMAKE_PREFIX_PATH": "$env{CONDA_PREFIX}", + "CONDA_BUILD": true, + "CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH": "FALSE", + "CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH": "FALSE", + "CMAKE_BUILD_TYPE": "Debug", + "ENABLE_PRECOMMIT": "OFF", + "ENABLE_CPACK": "ON", + "DOCS_HTML": "ON", + "ENABLE_CONDA": "ON", + "COLORED_COMPILER_OUTPUT": "OFF", + "COVERAGE": "OFF", + "TESTING_TIMEOUT": "1200" + } + } + ] +} diff --git a/DEPENDENCY_LICENSES.md b/DEPENDENCY_LICENSES.md index caa17a01d31364b95949ec32aaff7559c1600946..9225edae032272526d2ccd5c1fac8b53b48bd455 100644 --- a/DEPENDENCY_LICENSES.md +++ b/DEPENDENCY_LICENSES.md @@ -36,7 +36,6 @@ | toml | x | | x | MIT | https://github.com/toml-lang/toml/blob/master/LICENSE | | Google Flatbuffers | x | | | Apache | https://github.com/google/flatbuffers/blob/master/LICENSE.txt | | kafka | x | | | apache-2.0 | http://www.apache.org/licenses/ | -| Paraview | x | x | | BSD | https://www.paraview.org/paraview-license/ | | PeriodicTable.py | | x | x | Public Domain | https://pypi.org/project/periodictable/ | | Eigen | x | | | Mozilla Public License | http://eigen.tuxfamily.org/index.php?title=Main_Page#License | | muparser | x | x | | MIT | https://beltoforion.de/article.php?a=muparser | diff --git a/Framework/API/CMakeLists.txt b/Framework/API/CMakeLists.txt index 1b8b3eca9c7c71a7e50c8045611f4164fe48aaae..d4536e0869695c7c484dcd5c0259289fbd7b0596 100644 --- a/Framework/API/CMakeLists.txt +++ b/Framework/API/CMakeLists.txt @@ -499,7 +499,7 @@ set(GMOCK_TEST_FILES MatrixWorkspaceTest.h ) -if(COVERALLS) +if(COVERAGE) foreach(loop_var ${SRC_FILES} ${INC_FILES}) set_property( GLOBAL APPEND PROPERTY COVERAGE_SRCS @@ -523,6 +523,12 @@ endif() enable_precompiled_headers(inc/MantidAPI/PrecompiledHeader.h SRC_FILES) # Add the target for this directory add_library(API ${SRC_FILES} ${INC_FILES}) +add_library(Mantid::API ALIAS API) + +target_include_directories(API PUBLIC + $ + $ +) # Set the name of the generated library set_target_properties( API PROPERTIES OUTPUT_NAME MantidAPI COMPILE_DEFINITIONS IN_MANTID_API @@ -540,27 +546,37 @@ endif() # Add to the 'Framework' group in VS set_property(TARGET API PROPERTY FOLDER "MantidFramework") -target_include_directories( - API SYSTEM PUBLIC ${NEXUS_INCLUDE_DIR} ${Boost_INCLUDE_DIRS} -) target_link_libraries( API - LINK_PRIVATE - ${JSONCPP_LIBRARIES} - ${MANTIDLIBS} - ${GSL_LIBRARIES} - ${NEXUS_LIBRARIES} + PUBLIC + Mantid::HistogramData + Mantid::Types + Mantid::Kernel + Mantid::Geometry + Mantid::Indexing + Mantid::Parallel + Nexus::nexus + PRIVATE ${WINSOCK} ${BCRYPT} + Mantid::Beamline + Mantid::Json ) # Add the unit tests directory add_subdirectory(test) # Auto-generate exports header -target_include_directories(API PUBLIC ${CMAKE_BINARY_DIR}/Framework/API) +target_include_directories(API PUBLIC + $ + $ +) generate_mantid_export_header(API TRUE) # Installation settings - +if (CONDA_BUILD) +set(TARGET_EXPORT_NAME "MantidAPITargets") +mtd_install_framework_lib(TARGETS API INSTALL_EXPORT_FILE EXPORT_NAME ${TARGET_EXPORT_NAME}) +else() mtd_install_targets(TARGETS API INSTALL_DIRS ${LIB_DIR} ${WORKBENCH_LIB_DIR}) +endif() \ No newline at end of file diff --git a/Framework/API/inc/MantidAPI/ADSValidator.h b/Framework/API/inc/MantidAPI/ADSValidator.h index dd76d4f022dc6b3ac980df1a9ce48d56c0703fa9..a9c6eb3083fca86ff28dc7c05d9bfe1297a7e96f 100644 --- a/Framework/API/inc/MantidAPI/ADSValidator.h +++ b/Framework/API/inc/MantidAPI/ADSValidator.h @@ -18,12 +18,10 @@ namespace API { /** ADSValidator : a validator that requires the value of a property to be present in the ADS. The type must be std::string */ -class MANTID_API_DLL ADSValidator - : public Kernel::TypedValidator> { +class MANTID_API_DLL ADSValidator : public Kernel::TypedValidator> { public: /// Default constructor. Sets up an empty list of valid values. - ADSValidator(const bool allowMultiSelection = true, - const bool isOptional = false); + ADSValidator(const bool allowMultiSelection = true, const bool isOptional = false); /// Clone the validator Kernel::IValidator_sptr clone() const override; @@ -45,8 +43,7 @@ protected: * @return "" if the value is on the list, or "The workspace is not in the * workspace list" */ - std::string - checkValidity(const std::vector &value) const override; + std::string checkValidity(const std::vector &value) const override; private: /// if the validator should allow multiple selection diff --git a/Framework/API/inc/MantidAPI/AlgoTimeRegister.h b/Framework/API/inc/MantidAPI/AlgoTimeRegister.h index bcea2a9af3f598e30c8d3bedda415df7788f1247..52b93606dd94ad7ddfda162f202b3ae2910d28be 100644 --- a/Framework/API/inc/MantidAPI/AlgoTimeRegister.h +++ b/Framework/API/inc/MantidAPI/AlgoTimeRegister.h @@ -30,8 +30,7 @@ public: timespec m_begin; timespec m_end; - Info(const std::string &nm, const std::thread::id &id, const timespec &be, - const timespec &en) + Info(const std::string &nm, const std::thread::id &id, const timespec &be, const timespec &en) : m_name(nm), m_threadId(id), m_begin(be), m_end(en) {} }; diff --git a/Framework/API/inc/MantidAPI/Algorithm.h b/Framework/API/inc/MantidAPI/Algorithm.h index 34e8ed2caee59159252149fc67bf59b8dbaf5e9d..ad9a2670f91cd418cdebc0f9adeb7cd233ae9bb3 100644 --- a/Framework/API/inc/MantidAPI/Algorithm.h +++ b/Framework/API/inc/MantidAPI/Algorithm.h @@ -53,6 +53,9 @@ namespace API { class AlgorithmHistory; class WorkspaceHistory; +/// Typedef for a shared pointer to an Algorithm +using Algorithm_sptr = std::shared_ptr; + /** Base class from which all concrete algorithm classes should be derived. In order for a concrete algorithm class to do anything @@ -75,8 +78,7 @@ Gaudi user guide). http://proj-gaudi.web.cern.ch/proj-gaudi/) @date 12/09/2007 */ -class MANTID_API_DLL Algorithm : public IAlgorithm, - public Kernel::PropertyManagerOwner { +class MANTID_API_DLL Algorithm : public IAlgorithm { public: /// Base class for algorithm notifications class MANTID_API_DLL AlgorithmNotification : public Poco::Notification { @@ -109,8 +111,7 @@ public: class MANTID_API_DLL ProgressNotification : public AlgorithmNotification { public: /// Constructor - ProgressNotification(const Algorithm *const alg, double p, - const std::string &msg, double estimatedTime, + ProgressNotification(const Algorithm *const alg, double p, const std::string &msg, double estimatedTime, int progressPrecision); std::string name() const override; double progress; ///< Current progress. Value must be between 0 and 1. @@ -179,30 +180,21 @@ public: /// Override if the algorithm is not part of the Mantid distribution. const std::string helpURL() const override { return ""; } - template ::value>::type> - std::tuple, Indexing::SpectrumIndexSet> - getWorkspaceAndIndices(const std::string &name) const; + template ::value>::type> + std::tuple, Indexing::SpectrumIndexSet> getWorkspaceAndIndices(const std::string &name) const; template ::value>::type, - typename = typename std::enable_if< - std::is_convertible::value || - std::is_convertible *>::value>::type> - void setWorkspaceInputProperties(const std::string &name, - const std::shared_ptr &wksp, - IndexType type, const T2 &list); + typename = typename std::enable_if::value>::type, + typename = typename std::enable_if::value || + std::is_convertible *>::value>::type> + void setWorkspaceInputProperties(const std::string &name, const std::shared_ptr &wksp, IndexType type, + const T2 &list); template ::value>::type, - typename = typename std::enable_if< - std::is_convertible::value || - std::is_convertible *>::value>::type> - void setWorkspaceInputProperties(const std::string &name, - const std::string &wsName, IndexType type, - const T2 &list); + typename = typename std::enable_if::value>::type, + typename = typename std::enable_if::value || + std::is_convertible *>::value>::type> + void setWorkspaceInputProperties(const std::string &name, const std::string &wsName, IndexType type, const T2 &list); const std::string workspaceMethodName() const override; const std::vector workspaceMethodOn() const override; @@ -227,8 +219,6 @@ public: bool isRunning() const override; bool isReadyForGarbageCollection() const override; - using Kernel::PropertyManagerOwner::getProperty; - bool isChild() const override; void setChild(const bool isChild) override; void enableHistoryRecordingForChild(const bool on) override; @@ -261,13 +251,9 @@ public: bool getAlgStartupLogging() const override; /// setting the child start progress - void setChildStartProgress(const double startProgress) const override { - m_startChildProgress = startProgress; - } + void setChildStartProgress(const double startProgress) const override { m_startChildProgress = startProgress; } /// setting the child end progress - void setChildEndProgress(const double endProgress) const override { - m_endChildProgress = endProgress; - } + void setChildEndProgress(const double endProgress) const override { m_endChildProgress = endProgress; } /** @name Serialization functions */ //@{ @@ -283,14 +269,11 @@ public: static IAlgorithm_sptr fromHistory(const AlgorithmHistory &history); //@} - virtual std::shared_ptr createChildAlgorithm( - const std::string &name, const double startProgress = -1., - const double endProgress = -1., const bool enableLogging = true, - const int &version = -1); - void setupAsChildAlgorithm(const std::shared_ptr &algorithm, - const double startProgress = -1., - const double endProgress = -1., - const bool enableLogging = true); + virtual std::shared_ptr createChildAlgorithm(const std::string &name, const double startProgress = -1., + const double endProgress = -1., + const bool enableLogging = true, const int &version = -1); + void setupAsChildAlgorithm(const Algorithm_sptr &algorithm, const double startProgress = -1., + const double endProgress = -1., const bool enableLogging = true); /// set whether we wish to track the child algorithm's history and pass it the /// parent object to fill. @@ -298,8 +281,7 @@ public: using WorkspaceVector = std::vector>; - void findWorkspaces(WorkspaceVector &workspaces, unsigned int direction, - bool checkADS = false) const; + void findWorkspaces(WorkspaceVector &workspaces, unsigned int direction, bool checkADS = false) const; // ------------------ For WorkspaceGroups ------------------------------------ virtual bool checkGroups(); @@ -311,6 +293,80 @@ public: const Parallel::Communicator &communicator() const; void setCommunicator(const Parallel::Communicator &communicator); + // Function to declare properties (i.e. store them) + void declareProperty(std::unique_ptr p, const std::string &doc = "") override; + + // Function to declare properties (i.e. store them) + void declareOrReplaceProperty(std::unique_ptr p, const std::string &doc = "") override; + void resetProperties() override; + using IPropertyManager::declareProperty; + // Sets all the declared properties from + void setProperties(const std::string &propertiesJson, + const std::unordered_set &ignoreProperties = std::unordered_set(), + bool createMissing = false) override; + + // Sets all the declared properties from a json object + void setProperties(const ::Json::Value &jsonValue, + const std::unordered_set &ignoreProperties = std::unordered_set(), + bool createMissing = false) override; + + // sets all the declared properties using a simple string format + void setPropertiesWithString( + const std::string &propertiesString, + const std::unordered_set &ignoreProperties = std::unordered_set()) override; + + void setPropertyValue(const std::string &name, const std::string &value) override; + void setPropertyValueFromJson(const std::string &name, const Json::Value &value) override; + void setPropertyOrdinal(const int &index, const std::string &value) override; + + /// Make m_properties point to the same PropertyManager as alg.m_properties. + virtual void copyPropertiesFrom(const Algorithm &alg) { m_properties.copyPropertiesFrom(alg.m_properties); } + + bool existsProperty(const std::string &name) const override; + bool validateProperties() const override; + size_t propertyCount() const override; + + std::string getPropertyValue(const std::string &name) const override; + const std::vector &getProperties() const override; + + /// Get the value of a property + TypedValue getProperty(const std::string &name) const override; + + /// Return the property manager serialized as a string. + std::string asString(bool withDefaultValues = false) const override; + + /// Return the property manager serialized as a json object. + ::Json::Value asJson(bool withDefaultValues = false) const override; + + bool isDefault(const std::string &name) const; + + /// Removes the property from management + void removeProperty(const std::string &name, const bool delproperty = true) override; + /// Removes the property from management and returns a pointer to it + std::unique_ptr takeProperty(const size_t index) override; + + /// Clears all properties under management + void clear() override; + /// Override this method to perform a custom action right after a property was + /// set. + /// The argument is the property name. Default - do nothing. + void afterPropertySet(const std::string &) override; + + void filterByTime(const Types::Core::DateAndTime & /*start*/, const Types::Core::DateAndTime & /*stop*/) override { + throw(std::runtime_error("Not yet implmented")); + } + void splitByTime(std::vector & /*splitter*/, + std::vector /* outputs*/) const override { + throw(std::runtime_error("Not yet implmented")); + } + + void filterByProperty(const Kernel::TimeSeriesProperty & /*filter*/, const std::vector & + /* excludedFromFiltering */) override { + throw(std::runtime_error("Not yet implmented")); + } + Kernel::Property *getPointerToProperty(const std::string &name) const override; + Kernel::Property *getPointerToPropertyOrdinal(const int &index) const override; + protected: /// Virtual method - must be overridden by concrete algorithm virtual void init() = 0; @@ -321,8 +377,8 @@ protected: virtual void execDistributed(); virtual void execMasterOnly(); - virtual Parallel::ExecutionMode getParallelExecutionMode( - const std::map &storageModes) const; + virtual Parallel::ExecutionMode + getParallelExecutionMode(const std::map &storageModes) const; /// Returns a semi-colon separated list of workspace types to attach this /// algorithm @@ -331,17 +387,14 @@ protected: void cacheWorkspaceProperties(); void cacheInputWorkspaceHistories(); - void setExecutionState( - const ExecutionState state); ///< Sets the current execution state - void - setResultState(const ResultState state); ///< Sets the result execution state + void setExecutionState(const ExecutionState state); ///< Sets the current execution state + void setResultState(const ResultState state); ///< Sets the result execution state void store(); /** @name Progress Reporting functions */ friend class Progress; - void progress(double p, const std::string &msg = "", - double estimatedTime = 0.0, int progressPrecision = 0); + void progress(double p, const std::string &msg = "", double estimatedTime = 0.0, int progressPrecision = 0); void interruption_point(); /// Return a reference to the algorithm's notification dispatcher @@ -349,8 +402,7 @@ protected: /// Observation slot for child algorithm progress notification messages, these /// are scaled and then signalled for this algorithm. - void handleChildProgressNotification( - const Poco::AutoPtr &pNf); + void handleChildProgressNotification(const Poco::AutoPtr &pNf); /// Return a reference to the algorithm's object that is reporting progress const Poco::AbstractObserver &progressObserver() const; @@ -374,12 +426,9 @@ protected: friend class WorkspaceHistory; // Allow workspace history loading to adjust // g_execCount - static size_t - g_execCount; ///< Counter to keep track of algorithm execution order + static size_t g_execCount; ///< Counter to keep track of algorithm execution order - virtual void setOtherProperties(IAlgorithm *alg, - const std::string &propertyName, - const std::string &propertyValue, + virtual void setOtherProperties(IAlgorithm *alg, const std::string &propertyName, const std::string &propertyValue, int periodNum); /// All the WorkspaceProperties that are Input or InOut. Set in execute() @@ -403,18 +452,15 @@ protected: /// versions bool m_usingBaseProcessGroups = false; - template (IndexType::WorkspaceIndex), typename... WSPropArgs, - typename = typename std::enable_if< - std::is_convertible::value>::type> - void declareWorkspaceInputProperties(const std::string &propertyName, - const std::string &doc, - WSPropArgs &&... wsPropArgs); + typename = typename std::enable_if::value>::type> + void declareWorkspaceInputProperties(const std::string &propertyName, const std::string &doc, + WSPropArgs &&...wsPropArgs); private: template - void doSetInputProperties(const std::string &name, const T1 &wksp, - IndexType type, const T2 &list); + void doSetInputProperties(const std::string &name, const T1 &wksp, IndexType type, const T2 &list); void lockWorkspaces(); void unlockWorkspaces(); @@ -434,48 +480,43 @@ private: void fillHistory(const std::vector &outputWorkspaces); // Report that the algorithm has completed. - void reportCompleted(const double &duration, - const bool groupProcessing = false); + void reportCompleted(const double &duration, const bool groupProcessing = false); void registerFeatureUsage() const; Parallel::ExecutionMode getExecutionMode() const; - std::map - getInputWorkspaceStorageModes() const; + std::map getInputWorkspaceStorageModes() const; void setupSkipValidationMasterOnly(); bool isCompoundProperty(const std::string &name) const; // --------------------- Private Members ----------------------------------- /// Poco::ActiveMethod used to implement asynchronous execution. - std::unique_ptr>> - m_executeAsync; + std::unique_ptr>> m_executeAsync; /// Sends notifications to observers. Observers can subscribe to /// notificationCenter /// using Poco::NotificationCenter::addObserver(...); mutable std::unique_ptr m_notificationCenter; /// Child algorithm progress observer - mutable std::unique_ptr> - m_progressObserver; - - std::atomic m_executionState; ///< the current execution state - std::atomic m_resultState; ///< the current result State - bool m_isChildAlgorithm; ///< Algorithm is a child algorithm - bool m_recordHistoryForChild; ///< Flag to indicate whether history should be - /// recorded. Applicable to child algs only - bool m_alwaysStoreInADS; ///< Always store in the ADS, even for child algos - bool m_runningAsync; ///< Algorithm is running asynchronously - bool m_rethrow; ///< Algorithm should rethrow exceptions while executing - bool m_isAlgStartupLoggingEnabled; /// Whether to log alg startup and - /// closedown messages from the base class - /// (default = true) - mutable double m_startChildProgress; ///< Keeps value for algorithm's progress - /// at start of an Child Algorithm - mutable double m_endChildProgress; ///< Keeps value for algorithm's progress - /// at Child Algorithm's finish - AlgorithmID m_algorithmID; ///< Algorithm ID for managed algorithms + mutable std::unique_ptr> m_progressObserver; + + std::atomic m_executionState; ///< the current execution state + std::atomic m_resultState; ///< the current result State + bool m_isChildAlgorithm; ///< Algorithm is a child algorithm + bool m_recordHistoryForChild; ///< Flag to indicate whether history should be + /// recorded. Applicable to child algs only + bool m_alwaysStoreInADS; ///< Always store in the ADS, even for child algos + bool m_runningAsync; ///< Algorithm is running asynchronously + bool m_rethrow; ///< Algorithm should rethrow exceptions while executing + bool m_isAlgStartupLoggingEnabled; /// Whether to log alg startup and + /// closedown messages from the base class + /// (default = true) + mutable double m_startChildProgress; ///< Keeps value for algorithm's progress + /// at start of an Child Algorithm + mutable double m_endChildProgress; ///< Keeps value for algorithm's progress + /// at Child Algorithm's finish + AlgorithmID m_algorithmID; ///< Algorithm ID for managed algorithms std::vector> m_ChildAlgorithms; ///< A list of /// weak pointers /// to any child @@ -510,10 +551,9 @@ private: /// The earliest this class should be considered for garbage collection Mantid::Types::Core::DateAndTime m_gcTime; -}; -/// Typedef for a shared pointer to an Algorithm -using Algorithm_sptr = std::shared_ptr; + Mantid::Kernel::PropertyManagerOwner m_properties; +}; } // namespace API } // namespace Mantid @@ -523,8 +563,8 @@ using Algorithm_sptr = std::shared_ptr; * is used in the call to its constructor to effect a call to the factory's * subscribe method. */ -#define DECLARE_ALGORITHM(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper register_alg_##classname(( \ - (Mantid::API::AlgorithmFactory::Instance().subscribe()), 0)); \ +#define DECLARE_ALGORITHM(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper \ + register_alg_##classname(((Mantid::API::AlgorithmFactory::Instance().subscribe()), 0)); \ } diff --git a/Framework/API/inc/MantidAPI/Algorithm.tcc b/Framework/API/inc/MantidAPI/Algorithm.tcc index 78efb0cccbe334d4b3c37ad50e2569a370c0f649..d8a8e028aa69accad2f6b5e489a204c8c1b40dd4 100644 --- a/Framework/API/inc/MantidAPI/Algorithm.tcc +++ b/Framework/API/inc/MantidAPI/Algorithm.tcc @@ -16,14 +16,12 @@ namespace { template -void setWorkspaceProperty(Mantid::API::WorkspaceProperty *wsProp, - const T2 &wksp, const std::true_type &) { +void setWorkspaceProperty(Mantid::API::WorkspaceProperty *wsProp, const T2 &wksp, const std::true_type &) { *wsProp = wksp; } template -void setWorkspaceProperty(Mantid::API::WorkspaceProperty *wsProp, - const T2 &wksp, const std::false_type &) { +void setWorkspaceProperty(Mantid::API::WorkspaceProperty *wsProp, const T2 &wksp, const std::false_type &) { wsProp->setValue(wksp); } } // namespace @@ -40,30 +38,23 @@ IndexType::WorkspaceIndex Can contain PropertyMode, LockMode, and validators. @param doc Property documentation string. */ -template -void Algorithm::declareWorkspaceInputProperties(const std::string &propertyName, - const std::string &doc, - WSPropArgs &&... wsPropArgs) { - auto wsProp = std::make_unique>( - propertyName, "", Kernel::Direction::Input, - std::forward(wsPropArgs)...); +template +void Algorithm::declareWorkspaceInputProperties(const std::string &propertyName, const std::string &doc, + WSPropArgs &&...wsPropArgs) { + auto wsProp = std::make_unique>(propertyName, "", Kernel::Direction::Input, + std::forward(wsPropArgs)...); const auto &wsPropRef = *wsProp; declareProperty(std::move(wsProp), doc); - auto indexTypePropName = - IndexTypeProperty::generatePropertyName(propertyName); - auto indexTypeProp = - std::make_unique(indexTypePropName, AllowedIndexTypes); + auto indexTypePropName = IndexTypeProperty::generatePropertyName(propertyName); + auto indexTypeProp = std::make_unique(indexTypePropName, AllowedIndexTypes); const auto &indexTypePropRef = *indexTypeProp; - declareProperty(std::move(indexTypeProp), - "The type of indices in the optional index set; For optimal " - "performance WorkspaceIndex should be preferred;"); + declareProperty(std::move(indexTypeProp), "The type of indices in the optional index set; For optimal " + "performance WorkspaceIndex should be preferred;"); auto indexPropName = IndexProperty::generatePropertyName(propertyName); - declareProperty(std::make_unique(indexPropName, wsPropRef, - indexTypePropRef), + declareProperty(std::make_unique(indexPropName, wsPropRef, indexTypePropRef), "An optional set of spectra that will be processed by the " "algorithm; If not set, all spectra will be processed; The " "indices in this list can be workspace indices or possibly " @@ -77,23 +68,18 @@ void Algorithm::declareWorkspaceInputProperties(const std::string &propertyName, } template -void Algorithm::doSetInputProperties(const std::string &name, const T1 &wksp, - IndexType type, const T2 &list) { +void Algorithm::doSetInputProperties(const std::string &name, const T1 &wksp, IndexType type, const T2 &list) { if (!isCompoundProperty(name)) - throw std::runtime_error( - "Algorithm::setWorkspaceInputProperties can only be used " - "with properties declared using " - "declareWorkspaceInputProperties."); + throw std::runtime_error("Algorithm::setWorkspaceInputProperties can only be used " + "with properties declared using " + "declareWorkspaceInputProperties."); - auto *wsProp = - dynamic_cast *>(getPointerToProperty(name)); - auto *indexTypeProp = dynamic_cast( - getPointerToProperty(IndexTypeProperty::generatePropertyName(name))); - auto *indexProp = dynamic_cast( - getPointerToProperty(IndexProperty::generatePropertyName(name))); + auto *wsProp = dynamic_cast *>(getPointerToProperty(name)); + auto *indexTypeProp = + dynamic_cast(getPointerToProperty(IndexTypeProperty::generatePropertyName(name))); + auto *indexProp = dynamic_cast(getPointerToProperty(IndexProperty::generatePropertyName(name))); - setWorkspaceProperty( - wsProp, wksp, std::is_convertible>()); + setWorkspaceProperty(wsProp, wksp, std::is_convertible>()); *indexTypeProp = type; @@ -110,9 +96,8 @@ void Algorithm::doSetInputProperties(const std::string &name, const T1 &wksp, @param list List of indices to be used. */ template -void Algorithm::setWorkspaceInputProperties(const std::string &name, - const std::shared_ptr &wksp, - IndexType type, const T2 &list) { +void Algorithm::setWorkspaceInputProperties(const std::string &name, const std::shared_ptr &wksp, IndexType type, + const T2 &list) { doSetInputProperties, T2, T1>(name, wksp, type, list); } @@ -126,9 +111,8 @@ void Algorithm::setWorkspaceInputProperties(const std::string &name, @param list List of indices to be used. */ template -void Algorithm::setWorkspaceInputProperties(const std::string &name, - const std::string &wsName, - IndexType type, const T2 &list) { +void Algorithm::setWorkspaceInputProperties(const std::string &name, const std::string &wsName, IndexType type, + const T2 &list) { doSetInputProperties(name, wsName, type, list); } @@ -142,10 +126,9 @@ template std::tuple, Indexing::SpectrumIndexSet> Algorithm::getWorkspaceAndIndices(const std::string &name) const { if (!isCompoundProperty(name)) - throw std::runtime_error( - "Algorithm::getWorkspacesAndIndices can only be used " - "with properties declared using " - "declareWorkspaceInputProperties."); + throw std::runtime_error("Algorithm::getWorkspacesAndIndices can only be used " + "with properties declared using " + "declareWorkspaceInputProperties."); std::shared_ptr ws = getProperty(name); @@ -156,8 +139,7 @@ Algorithm::getWorkspaceAndIndices(const std::string &name) const { // problems related to the property mechanism in the future: // https://github.com/mantidproject/mantid/issues/20092 - auto indexProp = dynamic_cast( - getPointerToProperty(IndexProperty::generatePropertyName(name))); + auto indexProp = dynamic_cast(getPointerToProperty(IndexProperty::generatePropertyName(name))); Indexing::SpectrumIndexSet indexSet = *indexProp; return std::make_tuple(ws, indexSet); diff --git a/Framework/API/inc/MantidAPI/AlgorithmFactory.h b/Framework/API/inc/MantidAPI/AlgorithmFactory.h index fac49622ac453706125eb4ea8e65c71876845b43..9ad584c597ef45d0ec2a7f1369034493b4bd9553 100644 --- a/Framework/API/inc/MantidAPI/AlgorithmFactory.h +++ b/Framework/API/inc/MantidAPI/AlgorithmFactory.h @@ -45,8 +45,7 @@ class Algorithm; @author Russell Taylor, Tessella Support Services plc @date 21/09/2007 */ -class MANTID_API_DLL AlgorithmFactoryImpl final - : public Kernel::DynamicFactory { +class MANTID_API_DLL AlgorithmFactoryImpl final : public Kernel::DynamicFactory { public: AlgorithmFactoryImpl(const AlgorithmFactoryImpl &) = delete; AlgorithmFactoryImpl &operator=(const AlgorithmFactoryImpl &) = delete; @@ -72,9 +71,8 @@ public: * @returns The classname that was registered */ template - std::pair - subscribe(std::unique_ptr> instantiator, - const SubscribeAction replaceExisting = ErrorIfExists) { + std::pair subscribe(std::unique_ptr> instantiator, + const SubscribeAction replaceExisting = ErrorIfExists) { const auto tempAlg = instantiator->createInstance(); const int version = extractAlgVersion(tempAlg); const std::string className = extractAlgName(tempAlg); @@ -87,16 +85,14 @@ public: } else { if (version == it->second && replaceExisting == ErrorIfExists) { std::ostringstream os; - os << "Cannot register algorithm " << className - << " twice with the same version\n"; + os << "Cannot register algorithm " << className << " twice with the same version\n"; throw std::runtime_error(os.str()); } if (version > it->second) { m_vmap[className] = version; } } - Kernel::DynamicFactory::subscribe(key, std::move(instantiator), - replaceExisting); + Kernel::DynamicFactory::subscribe(key, std::move(instantiator), replaceExisting); } else { throw std::invalid_argument("Cannot register empty algorithm name"); } @@ -116,22 +112,19 @@ public: const std::vector getKeys(bool includeHidden) const; /// Get an algorithms name from the alias map - boost::optional - getRealNameFromAlias(const std::string &alias) const noexcept; + boost::optional getRealNameFromAlias(const std::string &alias) const noexcept; /// Returns the highest version of the algorithm currently registered int highestVersion(const std::string &algorithmName) const; /// Get the algorithm categories - const std::unordered_set - getCategories(bool includeHidden = false) const; + const std::unordered_set getCategories(bool includeHidden = false) const; /// Get the algorithm categories const std::map getCategoriesWithState() const; /// Returns algorithm descriptors. - std::vector - getDescriptors(bool includeHidden = false, bool includeAliases = false) const; + std::vector getDescriptors(bool includeHidden = false, bool includeAliases = false) const; /// unmangles the names used as keys into the name and version std::pair decodeName(const std::string &mangledName) const; @@ -140,17 +133,14 @@ private: friend struct Mantid::Kernel::CreateUsingNew; /// Extract the name of an algorithm - const std::string - extractAlgName(const std::shared_ptr &alg) const; + const std::string extractAlgName(const std::shared_ptr &alg) const; /// Extract the version of an algorithm int extractAlgVersion(const std::shared_ptr &alg) const; /// Extract the alias of an algorithm - const std::string - extractAlgAlias(const std::shared_ptr &alg) const; + const std::string extractAlgAlias(const std::shared_ptr &alg) const; /// Create an algorithm object with the specified name - std::shared_ptr createAlgorithm(const std::string &name, - const int version) const; + std::shared_ptr createAlgorithm(const std::string &name, const int version) const; /// Private Constructor for singleton class AlgorithmFactoryImpl(); @@ -174,17 +164,15 @@ private: using AlgorithmFactory = Mantid::Kernel::SingletonHolder; /// Convenient typedef for an UpdateNotification -using AlgorithmFactoryUpdateNotification = - Mantid::Kernel::DynamicFactory::UpdateNotification; -using AlgorithmFactoryUpdateNotification_ptr = const Poco::AutoPtr< - Mantid::Kernel::DynamicFactory::UpdateNotification> &; +using AlgorithmFactoryUpdateNotification = Mantid::Kernel::DynamicFactory::UpdateNotification; +using AlgorithmFactoryUpdateNotification_ptr = + const Poco::AutoPtr::UpdateNotification> &; } // namespace API } // namespace Mantid namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/AlgorithmFactoryObserver.h b/Framework/API/inc/MantidAPI/AlgorithmFactoryObserver.h index 8a402e874fb209c52351812d07bd224370febb01..173b826f6f2583b51503e165fd27a9d00bffb78f 100644 --- a/Framework/API/inc/MantidAPI/AlgorithmFactoryObserver.h +++ b/Framework/API/inc/MantidAPI/AlgorithmFactoryObserver.h @@ -45,8 +45,7 @@ private: void _updateHandle(AlgorithmFactoryUpdateNotification_ptr pNf); /// Poco::NObserver for SubscribeNotification. - Poco::NObserver - m_updateObserver; + Poco::NObserver m_updateObserver; }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/AlgorithmHasProperty.h b/Framework/API/inc/MantidAPI/AlgorithmHasProperty.h index 82c03df6b229742c20ee549fa45331bc78851335..fe1d3ad45737938052edd4e707b7040eeea5a6f8 100644 --- a/Framework/API/inc/MantidAPI/AlgorithmHasProperty.h +++ b/Framework/API/inc/MantidAPI/AlgorithmHasProperty.h @@ -21,16 +21,14 @@ class IAlgorithm; @author Martyn Gigg, Tessella plc @date 30/03/2011 */ -class MANTID_API_DLL AlgorithmHasProperty - : public Kernel::TypedValidator> { +class MANTID_API_DLL AlgorithmHasProperty : public Kernel::TypedValidator> { public: AlgorithmHasProperty(const std::string &propName); std::string getType() const; Kernel::IValidator_sptr clone() const override; protected: - std::string - checkValidity(const std::shared_ptr &value) const override; + std::string checkValidity(const std::shared_ptr &value) const override; private: /// Store the property name diff --git a/Framework/API/inc/MantidAPI/AlgorithmHistory.h b/Framework/API/inc/MantidAPI/AlgorithmHistory.h index 482e8e064d1a119543a4825f9d839a23a2b5b4b0..4beaf916c608de820ed74e80287a39d9a9bc77b0 100644 --- a/Framework/API/inc/MantidAPI/AlgorithmHistory.h +++ b/Framework/API/inc/MantidAPI/AlgorithmHistory.h @@ -46,21 +46,17 @@ public: /// The date-and-time will be stored as the Mantid::Types::Core::DateAndTime /// type explicit AlgorithmHistory(const Algorithm *const alg, - const Types::Core::DateAndTime &start = - Types::Core::DateAndTime::getCurrentTime(), - const double &duration = -1.0, - std::size_t uexeccount = 0); + const Types::Core::DateAndTime &start = Types::Core::DateAndTime::getCurrentTime(), + const double &duration = -1.0, std::size_t uexeccount = 0); ~AlgorithmHistory(); AlgorithmHistory &operator=(const AlgorithmHistory &); AlgorithmHistory(const AlgorithmHistory &); AlgorithmHistory(const std::string &name, int vers, std::string uuid, - const Types::Core::DateAndTime &start = - Types::Core::DateAndTime::getCurrentTime(), + const Types::Core::DateAndTime &start = Types::Core::DateAndTime::getCurrentTime(), const double &duration = -1.0, std::size_t uexeccount = 0); - void addExecutionInfo(const Types::Core::DateAndTime &start, - const double &duration); - void addProperty(const std::string &name, const std::string &value, - bool isdefault, const unsigned int &direction = 99); + void addExecutionInfo(const Types::Core::DateAndTime &start, const double &duration); + void addProperty(const std::string &name, const std::string &value, bool isdefault, + const unsigned int &direction = 99); /// add a child algorithm history record to this history object void addChildHistory(const AlgorithmHistory_sptr &childHist); @@ -72,23 +68,17 @@ public: /// get execution duration double executionDuration() const { return m_executionDuration; } /// get execution date - Mantid::Types::Core::DateAndTime executionDate() const { - return m_executionDate; - } + Mantid::Types::Core::DateAndTime executionDate() const { return m_executionDate; } /// get the execution count const std::size_t &execCount() const { return m_execCount; } /// get the uuid const std::string &uuid() const { return m_uuid; } /// get parameter list of algorithm in history const - const Mantid::Kernel::PropertyHistories &getProperties() const { - return m_properties; - } + const Mantid::Kernel::PropertyHistories &getProperties() const { return m_properties; } /// get the string representation of a specified property const std::string &getPropertyValue(const std::string &name) const; /// get the child histories of this history object - const AlgorithmHistories &getChildHistories() const { - return m_childHistories; - } + const AlgorithmHistories &getChildHistories() const { return m_childHistories; } /// Retrieve a child algorithm history by index AlgorithmHistory_sptr getChildAlgorithmHistory(const size_t index) const; /// Add operator[] access @@ -96,12 +86,9 @@ public: /// Retrieve the number of child algorithms size_t childHistorySize() const; /// print contents of object - void printSelf(std::ostream &, const int indent = 0, - const size_t maxPropertyLength = 0) const; + void printSelf(std::ostream &, const int indent = 0, const size_t maxPropertyLength = 0) const; /// Less than operator - inline bool operator<(const AlgorithmHistory &other) const { - return execCount() < other.execCount(); - } + inline bool operator<(const AlgorithmHistory &other) const { return execCount() < other.execCount(); } /// Equality operator inline bool operator==(const AlgorithmHistory &other) const { return (execCount() == other.execCount() && name() == other.name()); @@ -115,9 +102,8 @@ public: // Set the execution count void setExecCount(std::size_t execCount) { m_execCount = execCount; } /// Set data on history after it is created - void fillAlgorithmHistory(const Algorithm *const alg, - const Types::Core::DateAndTime &start, - const double &duration, std::size_t uexeccount); + void fillAlgorithmHistory(const Algorithm *const alg, const Types::Core::DateAndTime &start, const double &duration, + std::size_t uexeccount); // Allow Algorithm::execute to change the exec count & duration after the // algorithm was executed friend class Algorithm; @@ -145,8 +131,7 @@ private: std::string m_uuid; }; -MANTID_API_DLL std::ostream &operator<<(std::ostream &, - const AlgorithmHistory &); +MANTID_API_DLL std::ostream &operator<<(std::ostream &, const AlgorithmHistory &); } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/AlgorithmManager.h b/Framework/API/inc/MantidAPI/AlgorithmManager.h index e9d6aa8cba4c50046cf39eefc8ad1ef7cd9d51f6..ae58f9efc4328ae3c9f1cd50017012c5c14d171d 100644 --- a/Framework/API/inc/MantidAPI/AlgorithmManager.h +++ b/Framework/API/inc/MantidAPI/AlgorithmManager.h @@ -26,8 +26,7 @@ namespace API { /// Class for when an algorithm is starting asynchronously class AlgorithmStartingNotification : public Poco::Notification { public: - AlgorithmStartingNotification(IAlgorithm_sptr alg) - : Poco::Notification(), m_alg(std::move(alg)) {} + AlgorithmStartingNotification(IAlgorithm_sptr alg) : Poco::Notification(), m_alg(std::move(alg)) {} /// Returns the algorithm that is starting IAlgorithm_sptr getAlgorithm() const { return m_alg; } @@ -44,8 +43,7 @@ public: /// Creates a managed algorithm with the option of choosing a version IAlgorithm_sptr create(const std::string &algName, const int &version = -1); /// Creates an unmanaged algorithm with the option of choosing a version - std::shared_ptr createUnmanaged(const std::string &algName, - const int &version = -1) const; + std::shared_ptr createUnmanaged(const std::string &algName, const int &version = -1) const; std::size_t size() const; @@ -53,8 +51,7 @@ public: void removeById(AlgorithmID id); std::vector runningInstances() const; - std::vector - runningInstancesOf(const std::string &algorithmName) const; + std::vector runningInstancesOf(const std::string &algorithmName) const; /// Sends notifications to observers. Observers can subscribe to /// notificationCenter @@ -81,8 +78,7 @@ private: size_t removeFinishedAlgorithms(); /// The list of managed algorithms - std::deque - m_managed_algs; ///< pointers to managed algorithms [policy???] + std::deque m_managed_algs; ///< pointers to managed algorithms [policy???] /// Mutex for modifying/accessing the m_managed_algs member. mutable std::mutex m_managedMutex; }; @@ -94,7 +90,6 @@ using AlgorithmManager = Mantid::Kernel::SingletonHolder; namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/AlgorithmObserver.h b/Framework/API/inc/MantidAPI/AlgorithmObserver.h index f6023006be58b698e8b657432ee7cb10b5dc7cb5..485d7a3a6aaca239069f14fe6f86adaceda51e42 100644 --- a/Framework/API/inc/MantidAPI/AlgorithmObserver.h +++ b/Framework/API/inc/MantidAPI/AlgorithmObserver.h @@ -37,9 +37,7 @@ public: void stopObserving(const Mantid::API::IAlgorithm *alg); void stopObservingManager(); - virtual void progressHandle(const IAlgorithm *alg, double p, - const std::string &msg, - const double estimatedTime, + virtual void progressHandle(const IAlgorithm *alg, double p, const std::string &msg, const double estimatedTime, const int progressPrecision); virtual void startingHandle(IAlgorithm_sptr alg); virtual void startHandle(const IAlgorithm *alg); @@ -47,31 +45,25 @@ public: virtual void errorHandle(const IAlgorithm *alg, const std::string &what); private: - void - _progressHandle(const Poco::AutoPtr &pNf); + void _progressHandle(const Poco::AutoPtr &pNf); /// Poco::NObserver for Algorithm::ProgressNotification. - Poco::NObserver - m_progressObserver; + Poco::NObserver m_progressObserver; void _startHandle(const Poco::AutoPtr &pNf); /// Poco::NObserver for Algorithm::StartedNotification. - Poco::NObserver - m_startObserver; + Poco::NObserver m_startObserver; void _finishHandle(const Poco::AutoPtr &pNf); /// Poco::NObserver for Algorithm::FinishedNotification. - Poco::NObserver - m_finishObserver; + Poco::NObserver m_finishObserver; void _errorHandle(const Poco::AutoPtr &pNf); /// Poco::NObserver for Algorithm::ErrorNotification. - Poco::NObserver - m_errorObserver; + Poco::NObserver m_errorObserver; void _startingHandle(const Poco::AutoPtr &pNf); /// Poco::NObserver for API::AlgorithmStartingNotification - Poco::NObserver - m_startingObserver; + Poco::NObserver m_startingObserver; }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/AlgorithmProperty.h b/Framework/API/inc/MantidAPI/AlgorithmProperty.h index 61eba66900e016f5569137a7c8ece40caa29078e..bb926e3d99d526532ced9991707440de3382b135 100644 --- a/Framework/API/inc/MantidAPI/AlgorithmProperty.h +++ b/Framework/API/inc/MantidAPI/AlgorithmProperty.h @@ -35,16 +35,14 @@ API::IAlgorithm interface. @author Martyn Gigg, Tessella Plc @date 24/03/2011 */ -class MANTID_API_DLL AlgorithmProperty - : public Kernel::PropertyWithValue> { +class MANTID_API_DLL AlgorithmProperty : public Kernel::PropertyWithValue> { public: /// Typedef the held type using HeldType = std::shared_ptr; /// Constructor AlgorithmProperty(const std::string &propName, - Kernel::IValidator_sptr validator = - Kernel::IValidator_sptr(new Kernel::NullValidator), + Kernel::IValidator_sptr validator = Kernel::IValidator_sptr(new Kernel::NullValidator), unsigned int direction = Kernel::Direction::Input); AlgorithmProperty(const AlgorithmProperty &) = default; @@ -53,14 +51,11 @@ public: using Kernel::PropertyWithValue::operator=; /// 'Virtual copy constructor' - inline AlgorithmProperty *clone() const override { - return new AlgorithmProperty(*this); - } + inline AlgorithmProperty *clone() const override { return new AlgorithmProperty(*this); } /// Add the value of another property. Doesn't make sense here. AlgorithmProperty &operator+=(Kernel::Property const *) override { - throw Kernel::Exception::NotImplementedError( - "+= operator is not implemented for AlgorithmProperty."); + throw Kernel::Exception::NotImplementedError("+= operator is not implemented for AlgorithmProperty."); return *this; } /// Return the algorithm as string @@ -82,8 +77,7 @@ private: }; #ifdef _WIN32 -#pragma warning( \ - pop) // Re-enable the warning about multiple assignment operators +#pragma warning(pop) // Re-enable the warning about multiple assignment operators #endif } // namespace API diff --git a/Framework/API/inc/MantidAPI/AnalysisDataService.h b/Framework/API/inc/MantidAPI/AnalysisDataService.h index 7729a772cdba220a79082ff9dabfb69caf92d0b8..5d8af186a02c2cb74788df19d0e50931ed8305b0 100644 --- a/Framework/API/inc/MantidAPI/AnalysisDataService.h +++ b/Framework/API/inc/MantidAPI/AnalysisDataService.h @@ -40,8 +40,7 @@ class WorkspaceGroup; Modified to inherit from DataService */ -class MANTID_API_DLL AnalysisDataServiceImpl final - : public Kernel::DataService { +class MANTID_API_DLL AnalysisDataServiceImpl final : public Kernel::DataService { public: /** @name Extra notifications only applicable to the ADS */ //@{ @@ -50,12 +49,9 @@ public: public: /// Constructor GroupWorkspacesNotification(const std::vector &wsnames) - : DataServiceNotification("", std::shared_ptr()), - m_wsnames(wsnames) {} + : DataServiceNotification("", std::shared_ptr()), m_wsnames(wsnames) {} /// returns the workspace names - const std::vector &inputworkspacenames() const { - return m_wsnames; - } + const std::vector &inputworkspacenames() const { return m_wsnames; } private: std::vector m_wsnames; ///< cache of ws names @@ -66,8 +62,7 @@ public: class UnGroupingWorkspaceNotification : public DataServiceNotification { public: /// Constructor - UnGroupingWorkspaceNotification(const std::string &name, - const std::shared_ptr &obj) + UnGroupingWorkspaceNotification(const std::string &name, const std::shared_ptr &obj) : DataServiceNotification(name, obj) {} }; @@ -95,12 +90,10 @@ public: const std::string isValid(const std::string &name) const; /// Overridden add member to attach the name to the workspace when a /// workspace object is added to the service - void add(const std::string &name, - const std::shared_ptr &workspace) override; + void add(const std::string &name, const std::shared_ptr &workspace) override; /// Overridden addOrReplace member to attach the name to the workspace when /// a workspace object is added to the service - void addOrReplace(const std::string &name, - const std::shared_ptr &workspace) override; + void addOrReplace(const std::string &name, const std::shared_ptr &workspace) override; /// Overridden rename member to attach the new name to the workspace when a /// workspace object is renamed virtual void rename(const std::string &oldName, const std::string &newName); @@ -114,22 +107,19 @@ public: * Workspace * @return a shared pointer of WSTYPE */ - template - std::shared_ptr retrieveWS(const std::string &name) const { + template std::shared_ptr retrieveWS(const std::string &name) const { // Get as a bare workspace try { // Cast to the desired type and return that. - return std::dynamic_pointer_cast( - Kernel::DataService::retrieve(name)); + return std::dynamic_pointer_cast(Kernel::DataService::retrieve(name)); } catch (Kernel::Exception::NotFoundError &) { throw; } } - std::vector - retrieveWorkspaces(const std::vector &names, - bool unrollGroups = false) const; + std::vector retrieveWorkspaces(const std::vector &names, + bool unrollGroups = false) const; /** @name Methods to work with workspace groups */ //@{ @@ -145,8 +135,7 @@ public: private: /// Checks the name is valid, throwing if not - void verifyName(const std::string &name, - const std::shared_ptr &workspace); + void verifyName(const std::string &name, const std::shared_ptr &workspace); friend struct Mantid::Kernel::CreateUsingNew; /// Constructor @@ -162,69 +151,52 @@ private: std::string m_illegalChars; }; -using AnalysisDataService = - Mantid::Kernel::SingletonHolder; +using AnalysisDataService = Mantid::Kernel::SingletonHolder; -using WorkspaceAddNotification = - Mantid::Kernel::DataService::AddNotification; -using WorkspaceAddNotification_ptr = const Poco::AutoPtr< - Mantid::Kernel::DataService::AddNotification> &; +using WorkspaceAddNotification = Mantid::Kernel::DataService::AddNotification; +using WorkspaceAddNotification_ptr = + const Poco::AutoPtr::AddNotification> &; -using WorkspaceBeforeReplaceNotification = Mantid::Kernel::DataService< - Mantid::API::Workspace>::BeforeReplaceNotification; +using WorkspaceBeforeReplaceNotification = + Mantid::Kernel::DataService::BeforeReplaceNotification; using WorkspaceBeforeReplaceNotification_ptr = - const Poco::AutoPtr::BeforeReplaceNotification> &; + const Poco::AutoPtr::BeforeReplaceNotification> &; -using WorkspaceAfterReplaceNotification = Mantid::Kernel::DataService< - Mantid::API::Workspace>::AfterReplaceNotification; +using WorkspaceAfterReplaceNotification = Mantid::Kernel::DataService::AfterReplaceNotification; using WorkspaceAfterReplaceNotification_ptr = - const Poco::AutoPtr::AfterReplaceNotification> &; - -using WorkspacePreDeleteNotification = - Mantid::Kernel::DataService::PreDeleteNotification; -using WorkspacePreDeleteNotification_ptr = const Poco::AutoPtr< - Mantid::Kernel::DataService::PreDeleteNotification> - &; - -using WorkspacePostDeleteNotification = - Mantid::Kernel::DataService::PostDeleteNotification; -using WorkspacePostDeleteNotification_ptr = const Poco::AutoPtr< - Mantid::Kernel::DataService::PostDeleteNotification> - &; - -using ClearADSNotification = - Mantid::Kernel::DataService::ClearNotification; -using ClearADSNotification_ptr = const Poco::AutoPtr< - Mantid::Kernel::DataService::ClearNotification> &; - -using WorkspaceRenameNotification = - Mantid::Kernel::DataService::RenameNotification; -using WorkspaceRenameNotification_ptr = const Poco::AutoPtr< - Mantid::Kernel::DataService::RenameNotification> &; - -using WorkspacesGroupedNotification = - AnalysisDataServiceImpl::GroupWorkspacesNotification; -using WorkspacesGroupedNotification_ptr = - const Poco::AutoPtr &; - -using WorkspaceUnGroupingNotification = - AnalysisDataServiceImpl::UnGroupingWorkspaceNotification; -using WorkspaceUnGroupingNotification_ptr = const Poco::AutoPtr< - AnalysisDataServiceImpl::UnGroupingWorkspaceNotification> &; - -using GroupUpdatedNotification = - AnalysisDataServiceImpl::GroupUpdatedNotification; -using GroupUpdatedNotification_ptr = - const Poco::AutoPtr &; + const Poco::AutoPtr::AfterReplaceNotification> &; + +using WorkspacePreDeleteNotification = Mantid::Kernel::DataService::PreDeleteNotification; +using WorkspacePreDeleteNotification_ptr = + const Poco::AutoPtr::PreDeleteNotification> &; + +using WorkspacePostDeleteNotification = Mantid::Kernel::DataService::PostDeleteNotification; +using WorkspacePostDeleteNotification_ptr = + const Poco::AutoPtr::PostDeleteNotification> &; + +using ClearADSNotification = Mantid::Kernel::DataService::ClearNotification; +using ClearADSNotification_ptr = + const Poco::AutoPtr::ClearNotification> &; + +using WorkspaceRenameNotification = Mantid::Kernel::DataService::RenameNotification; +using WorkspaceRenameNotification_ptr = + const Poco::AutoPtr::RenameNotification> &; + +using WorkspacesGroupedNotification = AnalysisDataServiceImpl::GroupWorkspacesNotification; +using WorkspacesGroupedNotification_ptr = const Poco::AutoPtr &; + +using WorkspaceUnGroupingNotification = AnalysisDataServiceImpl::UnGroupingWorkspaceNotification; +using WorkspaceUnGroupingNotification_ptr = + const Poco::AutoPtr &; + +using GroupUpdatedNotification = AnalysisDataServiceImpl::GroupUpdatedNotification; +using GroupUpdatedNotification_ptr = const Poco::AutoPtr &; } // Namespace API } // Namespace Mantid namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/AnalysisDataServiceObserver.h b/Framework/API/inc/MantidAPI/AnalysisDataServiceObserver.h index cfb8b7f1f40246de7c59fab832ab38ae1039dda7..a2d131e14f5f2de8fac1d2622cc1c3bec93c5f9c 100644 --- a/Framework/API/inc/MantidAPI/AnalysisDataServiceObserver.h +++ b/Framework/API/inc/MantidAPI/AnalysisDataServiceObserver.h @@ -52,84 +52,51 @@ public: virtual void anyChangeHandle(); virtual void addHandle(const std::string &wsName, const Workspace_sptr &ws); - virtual void replaceHandle(const std::string &wsName, - const Workspace_sptr &ws); - virtual void deleteHandle(const std::string &wsName, - const Workspace_sptr &ws); + virtual void replaceHandle(const std::string &wsName, const Workspace_sptr &ws); + virtual void deleteHandle(const std::string &wsName, const Workspace_sptr &ws); virtual void clearHandle(); - virtual void renameHandle(const std::string &wsName, - const std::string &newName); + virtual void renameHandle(const std::string &wsName, const std::string &newName); virtual void groupHandle(const std::string &wsName, const Workspace_sptr &ws); - virtual void unGroupHandle(const std::string &wsName, - const Workspace_sptr &ws); - virtual void groupUpdateHandle(const std::string &wsName, - const Workspace_sptr &ws); + virtual void unGroupHandle(const std::string &wsName, const Workspace_sptr &ws); + virtual void groupUpdateHandle(const std::string &wsName, const Workspace_sptr &ws); private: - bool m_observingAdd{false}, m_observingReplace{false}, - m_observingDelete{false}, m_observingClear{false}, - m_observingRename{false}, m_observingGroup{false}, - m_observingUnGroup{false}, m_observingGroupUpdate{false}; - - void _addHandle( - const Poco::AutoPtr &pNf); - void _replaceHandle( - const Poco::AutoPtr - &pNf); - void _deleteHandle( - const Poco::AutoPtr &pNf); - void _clearHandle( - const Poco::AutoPtr &pNf); - void _renameHandle( - const Poco::AutoPtr &pNf); - void _groupHandle( - const Poco::AutoPtr - &pNf); - void _unGroupHandle( - const Poco::AutoPtr< - AnalysisDataServiceImpl::UnGroupingWorkspaceNotification> &pNf); - void _groupUpdateHandle( - const Poco::AutoPtr - &pNf); + bool m_observingAdd{false}, m_observingReplace{false}, m_observingDelete{false}, m_observingClear{false}, + m_observingRename{false}, m_observingGroup{false}, m_observingUnGroup{false}, m_observingGroupUpdate{false}; + + void _addHandle(const Poco::AutoPtr &pNf); + void _replaceHandle(const Poco::AutoPtr &pNf); + void _deleteHandle(const Poco::AutoPtr &pNf); + void _clearHandle(const Poco::AutoPtr &pNf); + void _renameHandle(const Poco::AutoPtr &pNf); + void _groupHandle(const Poco::AutoPtr &pNf); + void _unGroupHandle(const Poco::AutoPtr &pNf); + void _groupUpdateHandle(const Poco::AutoPtr &pNf); /// Poco::NObserver for AddNotification. - Poco::NObserver - m_addObserver; + Poco::NObserver m_addObserver; /// Poco::NObserver for ReplaceNotification. - Poco::NObserver - m_replaceObserver; + Poco::NObserver m_replaceObserver; /// Poco::NObserver for DeleteNotification. - Poco::NObserver - m_deleteObserver; + Poco::NObserver m_deleteObserver; /// Poco::NObserver for ClearNotification - Poco::NObserver - m_clearObserver; + Poco::NObserver m_clearObserver; /// Poco::NObserver for RenameNotification - Poco::NObserver - m_renameObserver; + Poco::NObserver m_renameObserver; /// Poco::NObserver for GroupNotification - Poco::NObserver - m_groupObserver; + Poco::NObserver m_groupObserver; /// Poco::NObserver for UnGroupNotification - Poco::NObserver + Poco::NObserver m_unGroupObserver; /// Poco::NObserver for GroupUpdateNotification - Poco::NObserver + Poco::NObserver m_groupUpdatedObserver; }; diff --git a/Framework/API/inc/MantidAPI/ArchiveSearchFactory.h b/Framework/API/inc/MantidAPI/ArchiveSearchFactory.h index d96ec4f0a59e0c5af72ff3ddf4458f1e2266f1da..687eb75aece1f32a2d1a3efa5174045b7f389e1f 100644 --- a/Framework/API/inc/MantidAPI/ArchiveSearchFactory.h +++ b/Framework/API/inc/MantidAPI/ArchiveSearchFactory.h @@ -24,12 +24,10 @@ Creates instances of IArchiveSearch @author Roman Tolchenov, Tessella plc @date 27/07/2010 */ -class MANTID_API_DLL ArchiveSearchFactoryImpl - : public Kernel::DynamicFactory { +class MANTID_API_DLL ArchiveSearchFactoryImpl : public Kernel::DynamicFactory { public: ArchiveSearchFactoryImpl(const ArchiveSearchFactoryImpl &) = delete; - ArchiveSearchFactoryImpl & - operator=(const ArchiveSearchFactoryImpl &) = delete; + ArchiveSearchFactoryImpl &operator=(const ArchiveSearchFactoryImpl &) = delete; private: friend struct Mantid::Kernel::CreateUsingNew; @@ -40,14 +38,12 @@ private: ~ArchiveSearchFactoryImpl() override = default; }; -using ArchiveSearchFactory = - Mantid::Kernel::SingletonHolder; +using ArchiveSearchFactory = Mantid::Kernel::SingletonHolder; } // namespace API } // namespace Mantid namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/Axis.h b/Framework/API/inc/MantidAPI/Axis.h index f963686451375bc6a2851409c565b6bf60400aa5..83b6710aff7b14bf7907d4706fc6f737fa367d22 100644 --- a/Framework/API/inc/MantidAPI/Axis.h +++ b/Framework/API/inc/MantidAPI/Axis.h @@ -35,8 +35,7 @@ public: /// Virtual constructor virtual Axis *clone(const MatrixWorkspace *const parentWorkspace) = 0; /// Virtual constructor for axis of different length - virtual Axis *clone(const std::size_t length, - const MatrixWorkspace *const parentWorkspace) = 0; + virtual Axis *clone(const std::size_t length, const MatrixWorkspace *const parentWorkspace) = 0; const std::string &title() const; std::string &title(); @@ -45,8 +44,7 @@ public: std::shared_ptr &unit(); /// Set the unit on the Axis - virtual const std::shared_ptr & - setUnit(const std::string &unitName); + virtual const std::shared_ptr &setUnit(const std::string &unitName); /// Returns true is the axis is a Spectra axis virtual bool isSpectra() const { return false; } @@ -58,12 +56,10 @@ public: /// Returns the value at a specified index /// @param index :: the index /// @param verticalIndex :: The verticalIndex - virtual double operator()(const std::size_t &index, - const std::size_t &verticalIndex = 0) const = 0; + virtual double operator()(const std::size_t &index, const std::size_t &verticalIndex = 0) const = 0; /// Gets the value at the specified index. Just calls operator() but is easier /// to use with Axis pointers - double getValue(const std::size_t &index, - const std::size_t &verticalIndex = 0) const; + double getValue(const std::size_t &index, const std::size_t &verticalIndex = 0) const; /// returns min value defined on axis virtual double getMin() const = 0; /// returns max value defined on axis @@ -86,6 +82,8 @@ public: virtual bool operator==(const Axis &) const = 0; /// Returns a text label of for a value + /// Note that the index here is not the index of a value, but the effective + /// index of the bin virtual std::string label(const std::size_t &index) const = 0; protected: diff --git a/Framework/API/inc/MantidAPI/BinEdgeAxis.h b/Framework/API/inc/MantidAPI/BinEdgeAxis.h index a41a5fa6993ead24cc7822116a87cfdbb6aa7afe..5b038172fb05c00d02af7f66ea194828c4917fc6 100644 --- a/Framework/API/inc/MantidAPI/BinEdgeAxis.h +++ b/Framework/API/inc/MantidAPI/BinEdgeAxis.h @@ -23,12 +23,12 @@ public: BinEdgeAxis(const std::vector &edges); Axis *clone(const MatrixWorkspace *const parentWorkspace) override; - Axis *clone(const std::size_t length, - const MatrixWorkspace *const parentWorkspace) override; + Axis *clone(const std::size_t length, const MatrixWorkspace *const parentWorkspace) override; std::vector createBinBoundaries() const override; void setValue(const std::size_t &index, const double &value) override; size_t indexOfValue(const double value) const override; + std::string label(const std::size_t &index) const override; }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/BoostOptionalToAlgorithmProperty.h b/Framework/API/inc/MantidAPI/BoostOptionalToAlgorithmProperty.h index 39af124f01c44922a82a2e0068345fbab9dced95..808f1f41e44215e702d78fe7ffc4b0376906b202 100644 --- a/Framework/API/inc/MantidAPI/BoostOptionalToAlgorithmProperty.h +++ b/Framework/API/inc/MantidAPI/BoostOptionalToAlgorithmProperty.h @@ -35,10 +35,9 @@ value of type boost::optional will be returned. * */ template -T checkForMandatoryInstrumentDefault( - Mantid::API::Algorithm *const alg, const std::string &propName, - const Mantid::Geometry::Instrument_const_sptr &instrument, - const std::string &idf_name) { +T checkForMandatoryInstrumentDefault(Mantid::API::Algorithm *const alg, const std::string &propName, + const Mantid::Geometry::Instrument_const_sptr &instrument, + const std::string &idf_name) { auto algProperty = alg->getPointerToProperty(propName); if (algProperty->isDefault()) { auto defaults = instrument->getNumberParameter(idf_name); @@ -49,8 +48,7 @@ T checkForMandatoryInstrumentDefault( } return static_cast(defaults[0]); } else { - return static_cast( - boost::lexical_cast(algProperty->value())); + return static_cast(boost::lexical_cast(algProperty->value())); } } @@ -68,10 +66,9 @@ T checkForMandatoryInstrumentDefault( * */ template -boost::optional checkForOptionalInstrumentDefault( - Mantid::API::Algorithm *const alg, const std::string &propName, - const Mantid::Geometry::Instrument_const_sptr &instrument, - const std::string &idf_name) { +boost::optional checkForOptionalInstrumentDefault(Mantid::API::Algorithm *const alg, const std::string &propName, + const Mantid::Geometry::Instrument_const_sptr &instrument, + const std::string &idf_name) { auto algProperty = alg->getPointerToProperty(propName); if (algProperty->isDefault()) { auto defaults = instrument->getNumberParameter(idf_name); @@ -81,8 +78,7 @@ boost::optional checkForOptionalInstrumentDefault( return boost::optional(); } } else { - double value = - boost::lexical_cast(algProperty->value()); + double value = boost::lexical_cast(algProperty->value()); return boost::optional(static_cast(value)); } } @@ -91,15 +87,15 @@ boost::optional checkForOptionalInstrumentDefault( * Specializations for std::string */ template <> -MANTID_API_DLL std::string checkForMandatoryInstrumentDefault( - Mantid::API::Algorithm *const alg, const std::string &propName, - const Mantid::Geometry::Instrument_const_sptr &instrument, - const std::string &idf_name); +MANTID_API_DLL std::string checkForMandatoryInstrumentDefault(Mantid::API::Algorithm *const alg, + const std::string &propName, + const Mantid::Geometry::Instrument_const_sptr &instrument, + const std::string &idf_name); template <> -MANTID_API_DLL boost::optional checkForOptionalInstrumentDefault( - Mantid::API::Algorithm *const alg, const std::string &propName, - const Mantid::Geometry::Instrument_const_sptr &instrument, - const std::string &idf_name); +MANTID_API_DLL boost::optional +checkForOptionalInstrumentDefault(Mantid::API::Algorithm *const alg, const std::string &propName, + const Mantid::Geometry::Instrument_const_sptr &instrument, + const std::string &idf_name); } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/BoxController.h b/Framework/API/inc/MantidAPI/BoxController.h index 2c4c77a74db3acd8612eb72cf7caab858819d4a5..8ce321eae888c3d932df08a01caca23481c731d9 100644 --- a/Framework/API/inc/MantidAPI/BoxController.h +++ b/Framework/API/inc/MantidAPI/BoxController.h @@ -39,16 +39,14 @@ public: * @return BoxController instance */ BoxController(size_t nd) - : nd(nd), m_maxId(0), m_SplitThreshold(1024), m_splitTopInto(boost::none), - m_numSplit(1), m_numTopSplit(1), + : nd(nd), m_maxId(0), m_SplitThreshold(1024), m_splitTopInto(boost::none), m_numSplit(1), m_numTopSplit(1), m_fileIO(std::shared_ptr()) { // TODO: Smarter ways to determine all of these values m_maxDepth = 5; m_numEventsAtMax = 0; m_addingEvents_eventsPerTask = 1000; m_significantEventsNumber = 10000000; - m_addingEvents_numTasksPerBlock = - Kernel::ThreadPool::getNumPhysicalCores() * 5; + m_addingEvents_numTasksPerBlock = Kernel::ThreadPool::getNumPhysicalCores() * 5; m_splitInto.resize(this->nd, 1); resetNumBoxes(); } @@ -179,9 +177,8 @@ public: */ void setSplitTopInto(size_t dim, size_t num) { if (dim >= nd) - throw std::invalid_argument( - "BoxController::setSplitTopInto() called with " - "too high of a dimension index."); + throw std::invalid_argument("BoxController::setSplitTopInto() called with " + "too high of a dimension index."); // If the vector is not created, then create it if (!m_splitTopInto) { m_splitTopInto = std::vector(nd, 1); @@ -199,23 +196,18 @@ public: this->m_addingEvents_eventsPerTask = m_addingEvents_eventsPerTask; } /// @return When adding events, how many events per task should be done? - size_t getAddingEvents_eventsPerTask() const { - return m_addingEvents_eventsPerTask; - } + size_t getAddingEvents_eventsPerTask() const { return m_addingEvents_eventsPerTask; } /** When adding events, how many events tasks per block should be done? * * @param m_addingEvents_numTasksPerBlock :: tasks/block */ - void - setAddingEvents_numTasksPerBlock(size_t m_addingEvents_numTasksPerBlock) { + void setAddingEvents_numTasksPerBlock(size_t m_addingEvents_numTasksPerBlock) { this->m_addingEvents_numTasksPerBlock = m_addingEvents_numTasksPerBlock; } /// @return When adding events, how many tasks per block should be done? - size_t getAddingEvents_numTasksPerBlock() const { - return m_addingEvents_numTasksPerBlock; - } + size_t getAddingEvents_numTasksPerBlock() const { return m_addingEvents_numTasksPerBlock; } //----------------------------------------------------------------------------------- /** Get parameters for adding events to a MDGridBox, trying to optimize @@ -231,8 +223,7 @@ public: *will * help the CPU be used fully. */ - void getAddingEventsParameters(size_t &eventsPerTask, - size_t &numTasksPerBlock) const { + void getAddingEventsParameters(size_t &eventsPerTask, size_t &numTasksPerBlock) const { // TODO: Smarter values here depending on nd, etc. eventsPerTask = m_addingEvents_eventsPerTask; numTasksPerBlock = m_addingEvents_numTasksPerBlock; @@ -252,9 +243,7 @@ public: } /// The number of events that triggers box splitting - size_t getSignificantEventsNumber() const { - return m_significantEventsNumber; - } + size_t getSignificantEventsNumber() const { return m_significantEventsNumber; } //----------------------------------------------------------------------------------- /** Determine when would be a good time to split MDBoxes into MDGridBoxes. @@ -269,8 +258,7 @@ public: *the workspace * @return true if the boxes should get split. */ - bool shouldSplitBoxes(size_t nEventsInOutput, size_t eventsAdded, - size_t numMDBoxes) const { + bool shouldSplitBoxes(size_t nEventsInOutput, size_t eventsAdded, size_t numMDBoxes) const { // Avoid divide by zero if (numMDBoxes == 0) return false; @@ -279,8 +267,7 @@ public: // Split when adding 1/16^th as many events as are already in the output, // (because when the workspace gets very large you should split less often) // But no more often than every 10 million events. - const size_t comparisonPoint = - std::max(nEventsInOutput / 16, m_significantEventsNumber); + const size_t comparisonPoint = std::max(nEventsInOutput / 16, m_significantEventsNumber); if (eventsAdded > comparisonPoint) return true; @@ -330,8 +317,7 @@ public: const auto &splitTopInto = m_splitTopInto.get(); size_t numSplitTop = - std::accumulate(splitTopInto.cbegin(), splitTopInto.cend(), size_t{1}, - std::multiplies()); + std::accumulate(splitTopInto.cbegin(), splitTopInto.cend(), size_t{1}, std::multiplies()); m_numMDBoxes[depth + 1] += numSplitTop; } else { m_numMDBoxes[depth + 1] += m_numSplit; @@ -343,26 +329,20 @@ public: /** Return the vector giving the number of MD Grid Boxes as a function of * depth */ - const std::vector &getNumMDGridBoxes() const { - return m_numMDGridBoxes; - } + const std::vector &getNumMDGridBoxes() const { return m_numMDGridBoxes; } /** Return the vector giving the MAXIMUM number of MD Boxes as a function of * depth */ - const std::vector &getMaxNumMDBoxes() const { - return m_maxNumMDBoxes; - } + const std::vector &getMaxNumMDBoxes() const { return m_maxNumMDBoxes; } /** Return the total number of MD Boxes, irrespective of depth */ size_t getTotalNumMDBoxes() const { - return std::accumulate(m_numMDBoxes.cbegin(), m_numMDBoxes.cend(), - size_t{0}, std::plus()); + return std::accumulate(m_numMDBoxes.cbegin(), m_numMDBoxes.cend(), size_t{0}, std::plus()); } /** Return the total number of MDGridBox'es, irrespective of depth */ size_t getTotalNumMDGridBoxes() const { - return std::accumulate(m_numMDGridBoxes.cbegin(), m_numMDGridBoxes.cend(), - size_t{0}, std::plus()); + return std::accumulate(m_numMDGridBoxes.cbegin(), m_numMDGridBoxes.cend(), size_t{0}, std::plus()); } /** Return the average recursion depth of gridding. @@ -375,8 +355,7 @@ public: // units of the volume of the finest possible box. // I.e. a box at level 1 is 100 x bigger than a box at level 2, so it // counts 100x more. - total += double(depth * m_numMDBoxes[depth]) * - (maxNumberOfFinestBoxes / m_maxNumMDBoxes[depth]); + total += double(depth * m_numMDBoxes[depth]) * (maxNumberOfFinestBoxes / m_maxNumMDBoxes[depth]); } return total / maxNumberOfFinestBoxes; } @@ -399,8 +378,7 @@ public: IBoxControllerIO *getFileIO() { return m_fileIO.get(); } /// makes box controller file based by providing class, responsible for /// fileIO. - void setFileBacked(const std::shared_ptr &newFileIO, - const std::string &fileName = ""); + void setFileBacked(const std::shared_ptr &newFileIO, const std::string &fileName = ""); void clearFileBacked(); //----------------------------------------------------------------------------------- // BoxCtrlChangesInterface *getChangesList(){return m_ChangesList;} @@ -449,11 +427,9 @@ private: m_maxNumMDBoxes[0] = 1; for (size_t depth = 1; depth < m_maxNumMDBoxes.size(); depth++) { if (depth == 1 && m_splitTopInto) { - m_maxNumMDBoxes[depth] = - m_maxNumMDBoxes[depth - 1] * double(m_numTopSplit); + m_maxNumMDBoxes[depth] = m_maxNumMDBoxes[depth - 1] * double(m_numTopSplit); } else { - m_maxNumMDBoxes[depth] = - m_maxNumMDBoxes[depth - 1] * double(m_numSplit); + m_maxNumMDBoxes[depth] = m_maxNumMDBoxes[depth - 1] * double(m_numSplit); } } } diff --git a/Framework/API/inc/MantidAPI/BoxControllerSettingsAlgorithm.h b/Framework/API/inc/MantidAPI/BoxControllerSettingsAlgorithm.h index ddaa2348bd1465fd525816eaf8cae4881b5f8958..48268aa374bd26389d73eb1e11172458464e9cef 100644 --- a/Framework/API/inc/MantidAPI/BoxControllerSettingsAlgorithm.h +++ b/Framework/API/inc/MantidAPI/BoxControllerSettingsAlgorithm.h @@ -26,23 +26,18 @@ class DLLExport BoxControllerSettingsAlgorithm : public API::Algorithm { public: protected: /// Initialise the properties - void initBoxControllerProps(const std::string &SplitInto = "5", - int SplitThreshold = 1000, - int MaxRecursionDepth = 5); + void initBoxControllerProps(const std::string &SplitInto = "5", int SplitThreshold = 1000, int MaxRecursionDepth = 5); /// Set the settings in the given box controller - void - setBoxController(const Mantid::API::BoxController_sptr &bc, - const Mantid::Geometry::Instrument_const_sptr &instrument); + void setBoxController(const Mantid::API::BoxController_sptr &bc, + const Mantid::Geometry::Instrument_const_sptr &instrument); /// Set the settings in the given box controller void setBoxController(const Mantid::API::BoxController_sptr &bc); std::string getBoxSettingsGroupName() { return "Box Splitting Settings"; } /// Take the defaults for the box splitting from the instrument parameters. - void takeDefaultsFromInstrument( - const Mantid::Geometry::Instrument_const_sptr &instrument, - const size_t ndims); + void takeDefaultsFromInstrument(const Mantid::Geometry::Instrument_const_sptr &instrument, const size_t ndims); private: }; diff --git a/Framework/API/inc/MantidAPI/CatalogFactory.h b/Framework/API/inc/MantidAPI/CatalogFactory.h index 36d0c8416705e049305773105d5c6cdbe5af06b4..9d4c10f723be804a613e78d9add1a0c400edca08 100644 --- a/Framework/API/inc/MantidAPI/CatalogFactory.h +++ b/Framework/API/inc/MantidAPI/CatalogFactory.h @@ -15,12 +15,10 @@ * The second operation that this macro performs is to provide the definition * of the CatalogID method for the concrete Catalog. */ -#define DECLARE_CATALOG(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper \ - register_alg_##classname(((Mantid::API::CatalogFactory::Instance() \ - .subscribe(#classname)), \ - 0)); \ +#define DECLARE_CATALOG(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper \ + register_alg_##classname(((Mantid::API::CatalogFactory::Instance().subscribe(#classname)), 0)); \ } //---------------------------------------------------------------------- @@ -44,8 +42,7 @@ class ICatalog; @author Sofia Antony, ISIS Rutherford Appleton Laboratory @date 01/10/2010 */ -class MANTID_API_DLL CatalogFactoryImpl - : public Kernel::DynamicFactory { +class MANTID_API_DLL CatalogFactoryImpl : public Kernel::DynamicFactory { public: CatalogFactoryImpl(const CatalogFactoryImpl &) = delete; CatalogFactoryImpl &operator=(const CatalogFactoryImpl &) = delete; @@ -70,7 +67,6 @@ using CatalogFactory = Mantid::Kernel::SingletonHolder; namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/CatalogManager.h b/Framework/API/inc/MantidAPI/CatalogManager.h index 914fc2f508600583cdc2a1adc2e617a1f2484afc..57a6b4c67db486d05257f1bcf1c7c74511de4970 100644 --- a/Framework/API/inc/MantidAPI/CatalogManager.h +++ b/Framework/API/inc/MantidAPI/CatalogManager.h @@ -27,9 +27,7 @@ public: CatalogManagerImpl &operator=(const CatalogManagerImpl &) = delete; /// Creates a new catalog and session, and adds it to the activeCatalogs /// container. - CatalogSession_sptr login(const std::string &username, - const std::string &password, - const std::string &endpoint, + CatalogSession_sptr login(const std::string &username, const std::string &password, const std::string &endpoint, const std::string &facility); /// Get a specific catalog using the sessionID. ICatalog_sptr getCatalog(const std::string &sessionID); @@ -58,7 +56,6 @@ using CatalogManager = Kernel::SingletonHolder; namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/CatalogSession.h b/Framework/API/inc/MantidAPI/CatalogSession.h index 16dc083580cb5fec763a850025d9cc41e77ff672..0f9155590254723f7ac356ff4fdaab975861dea3 100644 --- a/Framework/API/inc/MantidAPI/CatalogSession.h +++ b/Framework/API/inc/MantidAPI/CatalogSession.h @@ -21,8 +21,7 @@ namespace API { */ class MANTID_API_DLL CatalogSession { public: - CatalogSession(const std::string &sessionID, const std::string &facility, - const std::string &endpoint); + CatalogSession(const std::string &sessionID, const std::string &facility, const std::string &endpoint); std::string getSessionId() const; void setSessionId(const std::string &sessionID); const std::string &getSoapEndpoint() const; diff --git a/Framework/API/inc/MantidAPI/Citation.h b/Framework/API/inc/MantidAPI/Citation.h index 19d85c95bda4e3d0a7bb1817c3707a257ab69234..7c85172dd77c7847b32797f3b8186414d9dd9ebe 100644 --- a/Framework/API/inc/MantidAPI/Citation.h +++ b/Framework/API/inc/MantidAPI/Citation.h @@ -45,9 +45,8 @@ public: * @param url - The website url for which the citation refers * @param description - The description of the thing that is being cited */ - Citation(const std::string &doi = "", const std::string &bibtex = "", - const std::string &endnote = "", const std::string &url = "", - const std::string &description = ""); + Citation(const std::string &doi = "", const std::string &bibtex = "", const std::string &endnote = "", + const std::string &url = "", const std::string &description = ""); // Needed for future Set constructiom bool operator==(const Citation &rhs) const; diff --git a/Framework/API/inc/MantidAPI/Column.h b/Framework/API/inc/MantidAPI/Column.h index 39b48c720c4017bb2312e2c9dc8969335a4d1cd3..f02603e9134c1eef2e366417a6d645d8b9f864b5 100644 --- a/Framework/API/inc/MantidAPI/Column.h +++ b/Framework/API/inc/MantidAPI/Column.h @@ -117,29 +117,21 @@ public: /// cell(indexVec[p.end-1]). /// If equalRanges is empty then there are no equal velues in this /// column. - virtual void - sortIndex(bool ascending, size_t start, size_t end, - std::vector &indexVec, - std::vector> &equalRanges) const; + virtual void sortIndex(bool ascending, size_t start, size_t end, std::vector &indexVec, + std::vector> &equalRanges) const; /// Re-arrange values in this column according to indices in indexVec virtual void sortValues(const std::vector &indexVec); /// Templated method for returning a value. No type checks are done. - template T &cell(size_t index) { - return *static_cast(void_pointer(index)); - } + template T &cell(size_t index) { return *static_cast(void_pointer(index)); } /// Templated method for returning a value (const version). No type checks are /// done. - template const T &cell(size_t index) const { - return *static_cast(void_pointer(index)); - } + template const T &cell(size_t index) const { return *static_cast(void_pointer(index)); } /// Type check. - template bool isType() const { - return !std::strcmp(get_type_info().name(), typeid(T).name()); - } + template bool isType() const { return !std::strcmp(get_type_info().name(), typeid(T).name()); } /// get plot type /// @return See description of setPlotType() for the interpretation of the @@ -157,9 +149,7 @@ public: * Fills a std vector with values from the column if the types are compatible. * @param maxSize :: Set size to less than the full column. */ - template - std::vector - numeric_fill(size_t maxSize = std::numeric_limits::max()) const { + template std::vector numeric_fill(size_t maxSize = std::numeric_limits::max()) const { std::vector vec(std::min(size(), maxSize)); for (size_t i = 0; i < vec.size(); ++i) { vec[i] = static_cast(toDouble(i)); @@ -167,13 +157,9 @@ public: return vec; } - virtual bool equals(const Column &, double) const { - throw std::runtime_error("equals not implemented"); - }; + virtual bool equals(const Column &, double) const { throw std::runtime_error("equals not implemented"); }; - virtual bool equalsRelErr(const Column &, double) const { - throw std::runtime_error("equals not implemented"); - }; + virtual bool equalsRelErr(const Column &, double) const { throw std::runtime_error("equals not implemented"); }; protected: /// Sets the new column size. diff --git a/Framework/API/inc/MantidAPI/ColumnFactory.h b/Framework/API/inc/MantidAPI/ColumnFactory.h index 8a708955b2fb32daa663fa5293fff64ec26cdb19..1acc02aa8c2423de6f8b56cee97071548dedb8ce 100644 --- a/Framework/API/inc/MantidAPI/ColumnFactory.h +++ b/Framework/API/inc/MantidAPI/ColumnFactory.h @@ -55,7 +55,6 @@ using ColumnFactory = Mantid::Kernel::SingletonHolder; namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/CompositeCatalog.h b/Framework/API/inc/MantidAPI/CompositeCatalog.h index b4ebf7022f981e57079ddab9bd6167edba3713b9..f8c94d29c0c349b5866488b0e861d08c60f823bd 100644 --- a/Framework/API/inc/MantidAPI/CompositeCatalog.h +++ b/Framework/API/inc/MantidAPI/CompositeCatalog.h @@ -27,27 +27,21 @@ public: /// Adds a catalog to the list of catalogs (m_catalogs) void add(const ICatalog_sptr &catalog); /// Log the user into the catalog system. - CatalogSession_sptr login(const std::string &username, - const std::string &password, - const std::string &endpoint, + CatalogSession_sptr login(const std::string &username, const std::string &password, const std::string &endpoint, const std::string &facility) override; /// Log the user out of the catalog system. void logout() override; /// Search the catalog for data. - void search(const ICat::CatalogSearchParam &inputs, - ITableWorkspace_sptr &outputws, const int &offset, + void search(const ICat::CatalogSearchParam &inputs, ITableWorkspace_sptr &outputws, const int &offset, const int &limit) override; /// Obtain the number of results returned by the search method. - int64_t - getNumberOfSearchResults(const ICat::CatalogSearchParam &inputs) override; + int64_t getNumberOfSearchResults(const ICat::CatalogSearchParam &inputs) override; /// Show the logged in user's investigations search results. void myData(ITableWorkspace_sptr &outputws) override; /// Get datasets. - void getDataSets(const std::string &investigationId, - ITableWorkspace_sptr &outputws) override; + void getDataSets(const std::string &investigationId, ITableWorkspace_sptr &outputws) override; /// Get datafiles - void getDataFiles(const std::string &investigationId, - ITableWorkspace_sptr &outputws) override; + void getDataFiles(const std::string &investigationId, ITableWorkspace_sptr &outputws) override; /// Get instruments list void listInstruments(std::vector &instruments) override; /// Get investigationtypes list diff --git a/Framework/API/inc/MantidAPI/CompositeDomainMD.h b/Framework/API/inc/MantidAPI/CompositeDomainMD.h index 0ef223294d2acd1febee0f5a92ee25abe798d1be..c6a102ff573b831a07de770cd64034ebbc3a55e3 100644 --- a/Framework/API/inc/MantidAPI/CompositeDomainMD.h +++ b/Framework/API/inc/MantidAPI/CompositeDomainMD.h @@ -37,10 +37,9 @@ public: const FunctionDomain &getDomain(size_t i) const override; protected: - mutable std::unique_ptr m_iterator; ///< IMDIterator - size_t m_totalSize; ///< The total size of the domain - mutable std::vector> - m_domains; ///< smaller parts of the domain + mutable std::unique_ptr m_iterator; ///< IMDIterator + size_t m_totalSize; ///< The total size of the domain + mutable std::vector> m_domains; ///< smaller parts of the domain }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/CompositeFunction.h b/Framework/API/inc/MantidAPI/CompositeFunction.h index 859532d1ae25c09ec6832c063bacf1bee1f1ab52..0cfb8806e1ca29b2aa5d619f5b9ac55780198c59 100644 --- a/Framework/API/inc/MantidAPI/CompositeFunction.h +++ b/Framework/API/inc/MantidAPI/CompositeFunction.h @@ -53,28 +53,26 @@ public: /// Sets the workspace for each member function void setWorkspace(std::shared_ptr ws) override; /// Set matrix workspace - void setMatrixWorkspace(std::shared_ptr workspace, - size_t wi, double startX, double endX) override; + void setMatrixWorkspace(std::shared_ptr workspace, size_t wi, double startX, + double endX) override; /// Function you want to fit to. - void function(const FunctionDomain &domain, - FunctionValues &values) const override; + void function(const FunctionDomain &domain, FunctionValues &values) const override; /// Derivatives of function with respect to active parameters void functionDeriv(const FunctionDomain &domain, Jacobian &jacobian) override; /// Set i-th parameter - void setParameter(size_t, const double &value, - bool explicitlySet = true) override; + void setParameter(size_t, const double &value, bool explicitlySet = true) override; /// Set i-th parameter description void setParameterDescription(size_t, const std::string &description) override; /// Get i-th parameter [[nodiscard]] double getParameter(size_t i) const override; + /// Get parameter from i-th function, j-th local parameter index + [[nodiscard]] double getParameter(size_t i, size_t j) const; /// Set parameter by name. - void setParameter(const std::string &name, const double &value, - bool explicitlySet = true) override; + void setParameter(const std::string &name, const double &value, bool explicitlySet = true) override; /// Set description of parameter by name. - void setParameterDescription(const std::string &name, - const std::string &description) override; + void setParameterDescription(const std::string &name, const std::string &description) override; /// Get parameter by name. [[nodiscard]] double getParameter(const std::string &name) const override; /// Check if function has a parameter with this name. @@ -84,21 +82,21 @@ public: /// Return a value of attribute attName [[nodiscard]] Attribute getAttribute(const std::string &name) const override; // Set an attribute value - void setAttribute(const std::string &name, - const API::IFunction::Attribute &value) override; + void setAttribute(const std::string &name, const API::IFunction::Attribute &value) override; + // Register the functions usage + void registerFunctionUsage(bool internal) override; /// Total number of parameters [[nodiscard]] size_t nParams() const override; // Total number of attributes, which includes global and local function // attributes [[nodiscard]] size_t nAttributes() const override; // Total number of global attributes, defined at the composite function level - [[nodiscard]] size_t nGlobalAttributes() const noexcept { - return IFunction::nAttributes(); - } + [[nodiscard]] size_t nGlobalAttributes() const noexcept { return IFunction::nAttributes(); } /// Returns the index of parameter name [[nodiscard]] size_t parameterIndex(const std::string &name) const override; /// Returns the name of parameter i [[nodiscard]] std::string parameterName(size_t i) const override; + [[nodiscard]] std::string parameterName(size_t i, size_t j) const; /// Returns the name of attribute i [[nodiscard]] std::string attributeName(size_t i) const override; /// Returns the description of parameter i @@ -107,6 +105,8 @@ public: [[nodiscard]] bool isExplicitlySet(size_t i) const override; /// Get the fitting error for a parameter [[nodiscard]] double getError(size_t i) const override; + /// Get the fitting error for i-th function's j-th parameter + [[nodiscard]] double getError(size_t i, size_t j) const; /// Get the fitting error for a parameter by name [[nodiscard]] double getError(const std::string &name) const override; /// Set the fitting error for a parameter @@ -127,11 +127,9 @@ public: [[nodiscard]] std::string descriptionOfActive(size_t i) const override; /// Return parameter index from a parameter reference. - [[nodiscard]] size_t - getParameterIndex(const ParameterReference &ref) const override; + [[nodiscard]] size_t getParameterIndex(const ParameterReference &ref) const override; /// Get the containing function - [[nodiscard]] IFunction_sptr - getContainingFunction(const ParameterReference &ref) const; + [[nodiscard]] IFunction_sptr getContainingFunction(const ParameterReference &ref) const; /// Apply the ties void applyTies() override; @@ -154,14 +152,13 @@ public: /// Get number of domains required by this function [[nodiscard]] size_t getNumberDomains() const override; /// Split this function (if needed) into a list of independent functions. - [[nodiscard]] std::vector> - createEquivalentFunctions() const override; + [[nodiscard]] std::vector> createEquivalentFunctions() const override; + /// Returns true if the composite has at least one of this function. + [[nodiscard]] bool hasFunction(const std::string &functionName) const; /// Returns the pointer to i-th function [[nodiscard]] IFunction_sptr getFunction(std::size_t i) const override; /// Number of functions - [[nodiscard]] std::size_t nFunctions() const override { - return m_functions.size(); - } + [[nodiscard]] std::size_t nFunctions() const override { return m_functions.size(); } /* CompositeFunction own methods */ @@ -172,17 +169,16 @@ public: /// Replace a function void replaceFunction(size_t functionIndex, const IFunction_sptr &f); /// Replace a function - void replaceFunctionPtr(const IFunction_sptr &f_old, - const IFunction_sptr &f_new); + void replaceFunctionPtr(const IFunction_sptr &f_old, const IFunction_sptr &f_new); + /// Get the first function index with a matching function name + [[nodiscard]] std::size_t functionIndex(const std::string &functionName) const; /// Get the function index [[nodiscard]] std::size_t functionIndex(std::size_t i) const; [[nodiscard]] std::size_t attributeFunctionIndex(std::size_t i) const; /// Returns the index of parameter i as it declared in its function - [[nodiscard]] size_t parameterLocalIndex(size_t i, - bool recursive = false) const; + [[nodiscard]] size_t parameterLocalIndex(size_t i, bool recursive = false) const; /// Returns the name of parameter i as it declared in its function - [[nodiscard]] std::string parameterLocalName(size_t i, - bool recursive = false) const; + [[nodiscard]] std::string parameterLocalName(size_t i, bool recursive = false) const; /// Check the function. void checkFunction(); /// Remove all member functions @@ -190,58 +186,46 @@ public: /// Returns the number of attributes associated with the function virtual size_t nLocalAttributes() const { return 0; } /// Returns a list of attribute names - virtual std::vector getLocalAttributeNames() const { - return std::vector(); - } + virtual std::vector getLocalAttributeNames() const { return std::vector(); } /// Return a value of attribute attName - virtual Attribute getLocalAttribute(size_t i, - const std::string &attName) const { + virtual Attribute getLocalAttribute(size_t i, const std::string &attName) const { (void)i; - throw std::invalid_argument("Attribute " + attName + - " not found in function " + this->name()); + throw std::invalid_argument("Attribute " + attName + " not found in function " + this->name()); } /// Set a value to attribute attName - virtual void setLocalAttribute(size_t i, const std::string &attName, - const Attribute &) { + virtual void setLocalAttribute(size_t i, const std::string &attName, const Attribute &) { (void)i; - throw std::invalid_argument("Attribute " + attName + - " not found in function " + this->name()); + throw std::invalid_argument("Attribute " + attName + " not found in function " + this->name()); } /// Check if attribute attName exists virtual bool hasLocalAttribute(const std::string &) const { return false; } - template - void setLocalAttributeValue(size_t i, const std::string &attName, - const T &value) { + template void setLocalAttributeValue(size_t i, const std::string &attName, const T &value) { setLocalAttribute(i, attName, Attribute(value)); } - void setLocalAttributeValue(size_t i, const std::string &attName, - const char *value) { + void setLocalAttributeValue(size_t i, const std::string &attName, const char *value) { setLocalAttribute(i, attName, Attribute(std::string(value))); } /// Change status of parameter void setParameterStatus(size_t i, ParameterStatus status) override; /// Get status of parameter ParameterStatus getParameterStatus(size_t i) const override; + /// Extract function index and parameter name from a variable name + static std::pair parseName(const std::string &varName); protected: /// Function initialization. Declare function parameters in this method. void init() override; /// Declare a new parameter - void declareParameter(const std::string &name, double initValue = 0, - const std::string &description = "") override; + void declareParameter(const std::string &name, double initValue = 0, const std::string &description = "") override; /// Declare a single attribute - void declareAttribute(const std::string &name, - const API::IFunction::Attribute &defaultValue); + void declareAttribute(const std::string &name, const API::IFunction::Attribute &defaultValue); /// Writes itself into a string - std::string writeToString( - const std::string &parentLocalAttributesStr = "") const override; + std::string writeToString(const std::string &parentLocalAttributesStr = "") const override; size_t paramOffset(size_t i) const { return m_paramOffsets[i]; } private: - /// Extract function index and parameter name from a variable name - static std::pair parseName(const std::string &varName); // get attribute offset from attribute index size_t getAttributeOffset(size_t attributeIndex) const; /// Pointers to the included functions @@ -296,38 +280,30 @@ public: * @param iY0 :: The data index offset for a particular function * @param iP0 :: The parameter index offset for a particular function */ - PartialJacobian(Jacobian *J, size_t iY0, size_t iP0) - : m_J(J), m_iY0(iY0), m_iP0(iP0) {} + PartialJacobian(Jacobian *J, size_t iY0, size_t iP0) : m_J(J), m_iY0(iY0), m_iP0(iP0) {} /** * Overridden Jacobian::set(...). * @param iY :: The index of the data point * @param iP :: The parameter index of an individual function. * @param value :: The derivative value */ - void set(size_t iY, size_t iP, double value) override { - m_J->set(m_iY0 + iY, m_iP0 + iP, value); - } + void set(size_t iY, size_t iP, double value) override { m_J->set(m_iY0 + iY, m_iP0 + iP, value); } /** * Overridden Jacobian::get(...). * @param iY :: The index of the data point * @param iP :: The parameter index of an individual function. */ - double get(size_t iY, size_t iP) override { - return m_J->get(m_iY0 + iY, m_iP0 + iP); - } + double get(size_t iY, size_t iP) override { return m_J->get(m_iY0 + iY, m_iP0 + iP); } /** Zero all matrix elements. */ void zero() override { - throw Kernel::Exception::NotImplementedError( - "zero() is not implemented for PartialJacobian"); + throw Kernel::Exception::NotImplementedError("zero() is not implemented for PartialJacobian"); } /** Add number to all iY (data) Jacobian elements for a given iP (parameter) * @param value :: Value to add * @param iP :: The index of an active parameter. */ - void addNumberToColumn(const double &value, const size_t &iP) override { - m_J->addNumberToColumn(value, m_iP0 + iP); - } + void addNumberToColumn(const double &value, const size_t &iP) override { m_J->addNumberToColumn(value, m_iP0 + iP); } }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/ConstraintFactory.h b/Framework/API/inc/MantidAPI/ConstraintFactory.h index 576b9744e3a73717741012c60c5e0cf3e24e4395..933bcbe628fdf40c9058ac56d4998ef1979d9084 100644 --- a/Framework/API/inc/MantidAPI/ConstraintFactory.h +++ b/Framework/API/inc/MantidAPI/ConstraintFactory.h @@ -36,17 +36,14 @@ class Expression; @date 4/02/2010 */ -class MANTID_API_DLL ConstraintFactoryImpl final - : public Kernel::DynamicFactory { +class MANTID_API_DLL ConstraintFactoryImpl final : public Kernel::DynamicFactory { public: ConstraintFactoryImpl(const ConstraintFactoryImpl &) = delete; ConstraintFactoryImpl &operator=(const ConstraintFactoryImpl &) = delete; /// Creates an instance of a Constraint - IConstraint *createInitialized(IFunction *fun, const std::string &input, - bool isDefault = false) const; + IConstraint *createInitialized(IFunction *fun, const std::string &input, bool isDefault = false) const; /// Creates an instance of a Constraint - IConstraint *createInitialized(IFunction *fun, const Expression &expr, - bool isDefault = false) const; + IConstraint *createInitialized(IFunction *fun, const Expression &expr, bool isDefault = false) const; private: friend struct Mantid::Kernel::CreateUsingNew; @@ -57,16 +54,14 @@ private: ~ConstraintFactoryImpl() override = default; }; -using ConstraintFactory = - Mantid::Kernel::SingletonHolder; +using ConstraintFactory = Mantid::Kernel::SingletonHolder; } // namespace API } // namespace Mantid namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid @@ -74,10 +69,8 @@ EXTERN_MANTID_API template class MANTID_API_DLL * Macro for declaring a new type of function to be used with the * FunctionFactory */ -#define DECLARE_CONSTRAINT(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper register_constraint_##classname( \ - ((Mantid::API::ConstraintFactory::Instance().subscribe( \ - #classname)), \ - 0)); \ +#define DECLARE_CONSTRAINT(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper register_constraint_##classname( \ + ((Mantid::API::ConstraintFactory::Instance().subscribe(#classname)), 0)); \ } diff --git a/Framework/API/inc/MantidAPI/CostFunctionFactory.h b/Framework/API/inc/MantidAPI/CostFunctionFactory.h index 4d51afafef4a786a31780b237fc856f18a836c65..cfc380023d87bf430342eef1a2b97c2c7d43b755 100644 --- a/Framework/API/inc/MantidAPI/CostFunctionFactory.h +++ b/Framework/API/inc/MantidAPI/CostFunctionFactory.h @@ -33,8 +33,7 @@ class ICostFunction; @date 20/05/2010 */ -class MANTID_API_DLL CostFunctionFactoryImpl - : public Kernel::DynamicFactory { +class MANTID_API_DLL CostFunctionFactoryImpl : public Kernel::DynamicFactory { public: /**Creates an instance of a cost function * @param type :: The function's type @@ -48,15 +47,13 @@ private: CostFunctionFactoryImpl(); }; -using CostFunctionFactory = - Mantid::Kernel::SingletonHolder; +using CostFunctionFactory = Mantid::Kernel::SingletonHolder; } // namespace API } // namespace Mantid namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/DataProcessorAlgorithm.h b/Framework/API/inc/MantidAPI/DataProcessorAlgorithm.h index 446323fedab1dc40d30837d81e249e25c6086eea..fbb29a2687b7e5ff30d03b6ed7a4fec56414383e 100644 --- a/Framework/API/inc/MantidAPI/DataProcessorAlgorithm.h +++ b/Framework/API/inc/MantidAPI/DataProcessorAlgorithm.h @@ -26,76 +26,60 @@ namespace API { @date 2012-04-04 */ -template -class MANTID_API_DLL GenericDataProcessorAlgorithm : public Base { +template class MANTID_API_DLL GenericDataProcessorAlgorithm : public Base { public: GenericDataProcessorAlgorithm(); std::string getPropertyValue(const std::string &name) const override; - Kernel::PropertyManagerOwner::TypedValue - getProperty(const std::string &name) const override; + Kernel::IPropertyManager::TypedValue getProperty(const std::string &name) const override; protected: - std::shared_ptr createChildAlgorithm( - const std::string &name, const double startProgress = -1., - const double endProgress = -1., const bool enableLogging = true, - const int &version = -1) override; + std::shared_ptr createChildAlgorithm(const std::string &name, const double startProgress = -1., + const double endProgress = -1., const bool enableLogging = true, + const int &version = -1) override; void setLoadAlg(const std::string &alg); void setLoadAlgFileProp(const std::string &filePropName); void setAccumAlg(const std::string &alg); void setPropManagerPropName(const std::string &propName); - void mapPropertyName(const std::string &nameInProp, - const std::string &nameInPropManager); + void mapPropertyName(const std::string &nameInProp, const std::string &nameInPropManager); void copyProperty(const API::Algorithm_sptr &alg, const std::string &name); virtual ITableWorkspace_sptr determineChunk(const std::string &filename); virtual MatrixWorkspace_sptr loadChunk(const size_t rowIndex); - Workspace_sptr load(const std::string &inputData, - const bool loadQuiet = false); + Workspace_sptr load(const std::string &inputData, const bool loadQuiet = false); std::vector splitInput(const std::string &input); void forwardProperties(); - std::shared_ptr getProcessProperties( - const std::string &propertyManager = std::string()) const; + std::shared_ptr + getProcessProperties(const std::string &propertyManager = std::string()) const; /// MPI option. If false, we will use one job event if MPI is available bool m_useMPI; Workspace_sptr assemble(Workspace_sptr partialWS); - Workspace_sptr assemble(const std::string &partialWSName, - const std::string &outputWSName); - void saveNexus(const std::string &outputWSName, - const std::string &outputFile); + Workspace_sptr assemble(const std::string &partialWSName, [[maybe_unused]] const std::string &outputWSName); + void saveNexus(const std::string &outputWSName, const std::string &outputFile); bool isMainThread(); int getNThreads(); /// Divide a matrix workspace by another matrix workspace - MatrixWorkspace_sptr divide(const MatrixWorkspace_sptr lhs, - const MatrixWorkspace_sptr rhs); + MatrixWorkspace_sptr divide(const MatrixWorkspace_sptr lhs, const MatrixWorkspace_sptr rhs); /// Divide a matrix workspace by a single value - MatrixWorkspace_sptr divide(const MatrixWorkspace_sptr lhs, - const double &rhsValue); + MatrixWorkspace_sptr divide(const MatrixWorkspace_sptr lhs, const double &rhsValue); /// Multiply a matrix workspace by another matrix workspace - MatrixWorkspace_sptr multiply(const MatrixWorkspace_sptr lhs, - const MatrixWorkspace_sptr rhs); + MatrixWorkspace_sptr multiply(const MatrixWorkspace_sptr lhs, const MatrixWorkspace_sptr rhs); /// Multiply a matrix workspace by a single value - MatrixWorkspace_sptr multiply(const MatrixWorkspace_sptr lhs, - const double &rhsValue); + MatrixWorkspace_sptr multiply(const MatrixWorkspace_sptr lhs, const double &rhsValue); /// Add a matrix workspace to another matrix workspace - MatrixWorkspace_sptr plus(const MatrixWorkspace_sptr lhs, - const MatrixWorkspace_sptr rhs); + MatrixWorkspace_sptr plus(const MatrixWorkspace_sptr lhs, const MatrixWorkspace_sptr rhs); /// Add a single value to a matrix workspace - MatrixWorkspace_sptr plus(const MatrixWorkspace_sptr lhs, - const double &rhsValue); + MatrixWorkspace_sptr plus(const MatrixWorkspace_sptr lhs, const double &rhsValue); /// Subract a matrix workspace by another matrix workspace - MatrixWorkspace_sptr minus(const MatrixWorkspace_sptr lhs, - const MatrixWorkspace_sptr rhs); + MatrixWorkspace_sptr minus(const MatrixWorkspace_sptr lhs, const MatrixWorkspace_sptr rhs); /// Subract a single value from a matrix workspace - MatrixWorkspace_sptr minus(const MatrixWorkspace_sptr lhs, - const double &rhsValue); + MatrixWorkspace_sptr minus(const MatrixWorkspace_sptr lhs, const double &rhsValue); private: template - ResultType executeBinaryAlgorithm(const std::string &algorithmName, - const LHSType lhs, const RHSType rhs) { + ResultType executeBinaryAlgorithm(const std::string &algorithmName, const LHSType lhs, const RHSType rhs) { auto alg = createChildAlgorithm(algorithmName); alg->initialize(); @@ -136,17 +120,12 @@ private: void visualStudioC4661Workaround(); }; -template <> -MANTID_API_DLL void -GenericDataProcessorAlgorithm::visualStudioC4661Workaround(); +template <> MANTID_API_DLL void GenericDataProcessorAlgorithm::visualStudioC4661Workaround(); using DataProcessorAlgorithm = GenericDataProcessorAlgorithm; -using SerialDataProcessorAlgorithm = - GenericDataProcessorAlgorithm; -using ParallelDataProcessorAlgorithm = - GenericDataProcessorAlgorithm; -using DistributedDataProcessorAlgorithm = - GenericDataProcessorAlgorithm; +using SerialDataProcessorAlgorithm = GenericDataProcessorAlgorithm; +using ParallelDataProcessorAlgorithm = GenericDataProcessorAlgorithm; +using DistributedDataProcessorAlgorithm = GenericDataProcessorAlgorithm; } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/DeclareUserAlg.h b/Framework/API/inc/MantidAPI/DeclareUserAlg.h index 5c452425b9ec35799d5f43def3dc6c07d7b28e6b..cec7d925cf6f8ff3d8a731439dd522dd1612ea21 100644 --- a/Framework/API/inc/MantidAPI/DeclareUserAlg.h +++ b/Framework/API/inc/MantidAPI/DeclareUserAlg.h @@ -6,7 +6,7 @@ // SPDX - License - Identifier: GPL - 3.0 + #pragma once -#define DECLARE_USER_ALG(x) \ - Algorithm *x##_create() { return new x; } \ - \ +#define DECLARE_USER_ALG(x) \ + Algorithm *x##_create() { return new x; } \ + \ void x##_destroy(Algorithm *p) { delete p; } diff --git a/Framework/API/inc/MantidAPI/DetectorSearcher.h b/Framework/API/inc/MantidAPI/DetectorSearcher.h index 27c4a4f7b2c328c5b5c80250f8fccac67b62a8bc..e66dd7fac8c4df65e5641e9de12e13e0a8be8891 100644 --- a/Framework/API/inc/MantidAPI/DetectorSearcher.h +++ b/Framework/API/inc/MantidAPI/DetectorSearcher.h @@ -43,8 +43,7 @@ public: using DetectorSearchResult = std::tuple; /// Create a new DetectorSearcher with the given instrument & detectors - DetectorSearcher(const Geometry::Instrument_const_sptr &instrument, - const Geometry::DetectorInfo &detInfo); + DetectorSearcher(const Geometry::Instrument_const_sptr &instrument, const Geometry::DetectorInfo &detInfo); /// Find a detector that intsects with the given Qlab vector DetectorSearchResult findDetectorIndex(const Kernel::V3D &q); @@ -55,18 +54,16 @@ private: DetectorSearchResult searchUsingNearestNeighbours(const Kernel::V3D &q); /// Check whether the given direction in detector space intercepts with a /// detector - std::tuple checkInteceptWithNeighbours( - const Kernel::V3D &direction, - const Kernel::NearestNeighbours<3>::NearestNeighbourResults &neighbours) - const; + std::tuple + checkInteceptWithNeighbours(const Kernel::V3D &direction, + const Kernel::NearestNeighbours<3>::NearestNeighbourResults &neighbours) const; /// Helper function to build the nearest neighbour tree void createDetectorCache(); /// Helper function to convert a Qlab vector to a direction in detector space Kernel::V3D convertQtoDirection(const Kernel::V3D &q) const; /// Helper function to handle the tube gap parameter in tube instruments - DetectorSearchResult handleTubeGap( - const Kernel::V3D &detectorDir, - const Kernel::NearestNeighbours<3>::NearestNeighbourResults &neighbours); + DetectorSearchResult handleTubeGap(const Kernel::V3D &detectorDir, + const Kernel::NearestNeighbours<3>::NearestNeighbourResults &neighbours); // Instance variables diff --git a/Framework/API/inc/MantidAPI/DistributedAlgorithm.h b/Framework/API/inc/MantidAPI/DistributedAlgorithm.h index 04caacc3abcbab458376c6135f1cfd61ef966248..a8e967aa19087d94b5f2f7a14d1bd01e6731e44d 100644 --- a/Framework/API/inc/MantidAPI/DistributedAlgorithm.h +++ b/Framework/API/inc/MantidAPI/DistributedAlgorithm.h @@ -36,9 +36,8 @@ namespace API { */ class MANTID_API_DLL DistributedAlgorithm : public Algorithm { protected: - Parallel::ExecutionMode getParallelExecutionMode( - const std::map &storageModes) - const override; + Parallel::ExecutionMode + getParallelExecutionMode(const std::map &storageModes) const override; }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/DomainCreatorFactory.h b/Framework/API/inc/MantidAPI/DomainCreatorFactory.h index 67621d4788dc607ff26471a3a12d6042b5f3fac6..d2bde7070f44ac8fcf137ee9ffe091973ff95661 100644 --- a/Framework/API/inc/MantidAPI/DomainCreatorFactory.h +++ b/Framework/API/inc/MantidAPI/DomainCreatorFactory.h @@ -27,14 +27,11 @@ class IDomainCreator; Constructs a DomainCreator object from a string */ -class MANTID_API_DLL DomainCreatorFactoryImpl - : public Kernel::DynamicFactory { +class MANTID_API_DLL DomainCreatorFactoryImpl : public Kernel::DynamicFactory { public: /// Returns an initialized domain creator - IDomainCreator *createDomainCreator(const std::string &id, - Kernel::IPropertyManager *pm, - const std::string &workspacePropertyName, - const unsigned int domainType) const; + IDomainCreator *createDomainCreator(const std::string &id, Kernel::IPropertyManager *pm, + const std::string &workspacePropertyName, const unsigned int domainType) const; private: friend struct Mantid::Kernel::CreateUsingNew; @@ -46,8 +43,7 @@ private: DomainCreatorFactoryImpl(const DomainCreatorFactoryImpl &) = delete; /// No copying - DomainCreatorFactoryImpl & - operator=(const DomainCreatorFactoryImpl &) = delete; + DomainCreatorFactoryImpl &operator=(const DomainCreatorFactoryImpl &) = delete; /// Private Destructor for singleton ~DomainCreatorFactoryImpl() override = default; @@ -57,15 +53,13 @@ private: using Kernel::DynamicFactory::createUnwrapped; }; -using DomainCreatorFactory = - Mantid::Kernel::SingletonHolder; +using DomainCreatorFactory = Mantid::Kernel::SingletonHolder; } // namespace API } // namespace Mantid namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/EnabledWhenWorkspaceIsType.h b/Framework/API/inc/MantidAPI/EnabledWhenWorkspaceIsType.h index 6875bb6d31331b139c8a7ce567f20406240a5ebb..de09c745fc14b3bd5c7591037f70ae7158a7ed59 100644 --- a/Framework/API/inc/MantidAPI/EnabledWhenWorkspaceIsType.h +++ b/Framework/API/inc/MantidAPI/EnabledWhenWorkspaceIsType.h @@ -26,8 +26,7 @@ namespace API { @author Janik Zikovsky @date 2011-09-21 */ -template -class DLLExport EnabledWhenWorkspaceIsType : public Kernel::IPropertySettings { +template class DLLExport EnabledWhenWorkspaceIsType : public Kernel::IPropertySettings { public: //-------------------------------------------------------------------------------------------- /** Constructor @@ -35,10 +34,8 @@ public: * @param enabledSetting :: Set Enabled on this property to this value when * the workspace is of type T. Default true. */ - EnabledWhenWorkspaceIsType(std::string otherPropName, - bool enabledSetting = true) - : IPropertySettings(), m_otherPropName(std::move(otherPropName)), - m_enabledSetting(enabledSetting) {} + EnabledWhenWorkspaceIsType(std::string otherPropName, bool enabledSetting = true) + : IPropertySettings(), m_otherPropName(std::move(otherPropName)), m_enabledSetting(enabledSetting) {} //-------------------------------------------------------------------------------------------- /** Does the validator fulfill the criterion based on the @@ -81,15 +78,11 @@ public: //-------------------------------------------------------------------------------------------- /// Return true/false based on whether the other property satisfies the /// criterion - bool isEnabled(const Kernel::IPropertyManager *algo) const override { - return checkCriterion(algo); - } + bool isEnabled(const Kernel::IPropertyManager *algo) const override { return checkCriterion(algo); } //-------------------------------------------------------------------------------------------- /// Return true always - bool isVisible(const Kernel::IPropertyManager *) const override { - return true; - } + bool isVisible(const Kernel::IPropertyManager *) const override { return true; } //-------------------------------------------------------------------------------------------- /// Make a copy of the present type of validator diff --git a/Framework/API/inc/MantidAPI/ExperimentInfo.h b/Framework/API/inc/MantidAPI/ExperimentInfo.h index 663416ad2dbb3c991c0ec63c2ff7b8d6c2de782f..8e1e74e19445b3abd521d20f507a4b3684aaeb14 100644 --- a/Framework/API/inc/MantidAPI/ExperimentInfo.h +++ b/Framework/API/inc/MantidAPI/ExperimentInfo.h @@ -12,6 +12,7 @@ #include "MantidGeometry/Instrument_fwd.h" #include "MantidKernel/DeltaEMode.h" +#include "MantidKernel/Unit.h" #include "MantidKernel/V3D.h" #include "MantidKernel/cow_ptr.h" @@ -80,8 +81,7 @@ public: void populateInstrumentParameters(); void setNumberOfDetectorGroups(const size_t count) const; - void setDetectorGrouping(const size_t index, - const std::set &detIDs) const; + void setDetectorGrouping(const size_t index, const std::set &detIDs) const; /// Sample accessors const Sample &sample() const; @@ -108,30 +108,27 @@ public: double getEFixed(const detid_t detID) const; /// Easy access to the efixed value for this run & optional detector double getEFixed(const std::shared_ptr &detector = - std::shared_ptr{ - nullptr}) const; + std::shared_ptr{nullptr}) const; + double getEFixedGivenEMode(const std::shared_ptr &detector, + const Kernel::DeltaEMode::Type emode) const; + double getEFixedForIndirect(const std::shared_ptr &detector, + const std::vector ¶meterNames) const; /// Set the efixed value for a given detector ID void setEFixed(const detid_t detID, const double value); /// Saves this experiment description to the open NeXus file - void saveExperimentInfoNexus(::NeXus::File *file, - bool saveLegacyInstrument = true) const; + void saveExperimentInfoNexus(::NeXus::File *file, bool saveLegacyInstrument = true) const; /// Saves this experiment description to the open NeXus file - void saveExperimentInfoNexus(::NeXus::File *file, bool saveInstrument, - bool saveSample, bool saveLogs) const; + void saveExperimentInfoNexus(::NeXus::File *file, bool saveInstrument, bool saveSample, bool saveLogs) const; /// Loads an experiment description from the open NeXus file - void loadExperimentInfoNexus(const std::string &nxFilename, - ::NeXus::File *file, std::string ¶meterStr); + void loadExperimentInfoNexus(const std::string &nxFilename, ::NeXus::File *file, std::string ¶meterStr); /// Load the instrument from an open NeXus file. - void loadInstrumentInfoNexus(const std::string &nxFilename, - ::NeXus::File *file, std::string ¶meterStr); + void loadInstrumentInfoNexus(const std::string &nxFilename, ::NeXus::File *file, std::string ¶meterStr); /// Load the instrument from an open NeXus file without reading any parameters - void loadInstrumentInfoNexus(const std::string &nxFilename, - ::NeXus::File *file); + void loadInstrumentInfoNexus(const std::string &nxFilename, ::NeXus::File *file); /// Load instrument parameters from an open Nexus file in Instument group if /// found there - void loadInstrumentParametersNexus(::NeXus::File *file, - std::string ¶meterStr); + void loadInstrumentParametersNexus(::NeXus::File *file, std::string ¶meterStr); /// Load the sample and log info from an open NeXus file. void loadSampleAndLogInfoNexus(::NeXus::File *file); @@ -164,8 +161,7 @@ protected: /// Called as the first operation of most public methods. virtual void populateIfNotLoaded() const; - void setSpectrumDefinitions( - Kernel::cow_ptr> spectrumDefinitions); + void setSpectrumDefinitions(Kernel::cow_ptr> spectrumDefinitions); virtual void updateCachedDetectorGrouping(const size_t index) const; /// Parameters modifying the base instrument @@ -175,23 +171,17 @@ protected: private: /// Fill with given instrument parameter - void populateWithParameter(Geometry::ParameterMap ¶mMap, - Geometry::ParameterMap ¶mMapForPosAndRot, - const std::string &name, - const Geometry::XMLInstrumentParameter ¶mInfo, + void populateWithParameter(Geometry::ParameterMap ¶mMap, Geometry::ParameterMap ¶mMapForPosAndRot, + const std::string &name, const Geometry::XMLInstrumentParameter ¶mInfo, const Run &runData); /// Attempt to load instrument embedded in Nexus file. *file must have /// instrument group open. - void loadEmbeddedInstrumentInfoNexus(::NeXus::File *file, - std::string &instrumentName, - std::string &instrumentXml); + void loadEmbeddedInstrumentInfoNexus(::NeXus::File *file, std::string &instrumentName, std::string &instrumentXml); /// Set the instrument given the name and XML leading from IDF file if XML /// string is empty - void setInstumentFromXML(const std::string &nxFilename, - std::string &instrumentName, - std::string &instrumentXml); + void setInstumentFromXML(const std::string &nxFilename, std::string &instrumentName, std::string &instrumentXml); // Loads the xml from an instrument file with some basic error handling std::string loadInstrumentXML(const std::string &filename); diff --git a/Framework/API/inc/MantidAPI/Expression.h b/Framework/API/inc/MantidAPI/Expression.h index 83ce0b367d6e1fd557baa3bf68f4c50a8ecc5473..55c8ccca0ac9aee2196074b83b2157545a2242c9 100644 --- a/Framework/API/inc/MantidAPI/Expression.h +++ b/Framework/API/inc/MantidAPI/Expression.h @@ -47,8 +47,7 @@ public: /// contructor Expression(const std::vector &ops); /// contructor - Expression(const std::vector &binary, - const std::unordered_set &unary); + Expression(const std::vector &binary, const std::unordered_set &unary); /// copy contructor Expression(const Expression &expr); /// Assignment operator @@ -138,8 +137,7 @@ private: * this one. * @param p :: The precedence of the connecting operator. */ - Token(size_t i, size_t j, size_t k, size_t p) - : is(i), ie(j), is1(k), prec(p) {} + Token(size_t i, size_t j, size_t k, size_t p) : is(i), ie(j), is1(k), prec(p) {} size_t is; ///< The index of the first symbol of the token. size_t ie; ///< The index of the last symbol of the token. size_t is1; ///< The index of the first symbol of the next token. @@ -169,23 +167,19 @@ private: Tokens m_tokens; ///< The container for the token markers std::string m_expr; ///< Saved expression string - std::string m_funct; ///< Function name - std::string - m_op; ///< Operator connecting this expression to its sibling on the left + std::string m_funct; ///< Function name + std::string m_op; ///< Operator connecting this expression to its sibling on the left std::vector m_terms; ///< Child expressions (function arguments) /** * Keeps operator that can be used in an expression */ struct Operators { - std::vector - binary; ///< Binary operators in reverse precedence order - std::unordered_set unary; ///< Unary operators - std::map - precedence; ///< Map of the operator precedence order - std::unordered_set - symbols; ///< All the symbols that are used in the binary operators - std::map op_number; ///< map of operators + std::vector binary; ///< Binary operators in reverse precedence order + std::unordered_set unary; ///< Unary operators + std::map precedence; ///< Map of the operator precedence order + std::unordered_set symbols; ///< All the symbols that are used in the binary operators + std::map op_number; ///< map of operators }; /** diff --git a/Framework/API/inc/MantidAPI/FileBackedExperimentInfo.h b/Framework/API/inc/MantidAPI/FileBackedExperimentInfo.h index b6cc8922538682ae2facd3810da88404f85b9d9d..7e567bfcc01572e8ca77173eab62752d5fefe8e8 100644 --- a/Framework/API/inc/MantidAPI/FileBackedExperimentInfo.h +++ b/Framework/API/inc/MantidAPI/FileBackedExperimentInfo.h @@ -18,8 +18,7 @@ namespace API { */ class MANTID_API_DLL FileBackedExperimentInfo : public ExperimentInfo { public: - FileBackedExperimentInfo(const std::string &filename, - const std::string &nxpath); + FileBackedExperimentInfo(const std::string &filename, const std::string &nxpath); ExperimentInfo *cloneExperimentInfo() const override; private: diff --git a/Framework/API/inc/MantidAPI/FileFinder.h b/Framework/API/inc/MantidAPI/FileFinder.h index 86b8c7a2281ff25cb0aed2e099b2b613270fc69c..bbc088af1d9dd1411d7e6e8131076aaa430b210f 100644 --- a/Framework/API/inc/MantidAPI/FileFinder.h +++ b/Framework/API/inc/MantidAPI/FileFinder.h @@ -35,31 +35,23 @@ number */ class MANTID_API_DLL FileFinderImpl { public: - std::string getFullPath(const std::string &filename, - const bool ignoreDirs = false) const; - std::string getPath(const std::vector &archs, - const std::set &filenames, + std::string getFullPath(const std::string &filename, const bool ignoreDirs = false) const; + std::string getPath(const std::vector &archs, const std::set &filenames, const std::vector &exts) const; /// DO NOT USE! MADE PUBLIC FOR TESTING ONLY. - std::string makeFileName(const std::string &hint, - const Kernel::InstrumentInfo &instrument) const; + std::string makeFileName(const std::string &hint, const Kernel::InstrumentInfo &instrument) const; void setCaseSensitive(const bool cs); bool getCaseSensitive() const; - std::vector - getArchiveSearch(const Kernel::FacilityInfo &facility) const; - std::string findRun(const std::string &hintstr, - const std::vector &exts = {}, + std::vector getArchiveSearch(const Kernel::FacilityInfo &facility) const; + std::string findRun(const std::string &hintstr, const std::vector &exts = {}, const bool useExtsOnly = false) const; - std::vector findRuns(const std::string &hintstr, - const std::vector &exts = {}, + std::vector findRuns(const std::string &hintstr, const std::vector &exts = {}, const bool useExtsOnly = false) const; /// DO NOT USE! MADE PUBLIC FOR TESTING ONLY. const Kernel::InstrumentInfo getInstrument(const std::string &hint) const; /// DO NOT USE! MADE PUBLIC FOR TESTING ONLY. - std::string getExtension(const std::string &filename, - const std::vector &exts) const; - void getUniqueExtensions(const std::vector &extensionsToAdd, - std::vector &uniqueExts) const; + std::string getExtension(const std::string &filename, const std::vector &exts) const; + void getUniqueExtensions(const std::vector &extensionsToAdd, std::vector &uniqueExts) const; private: friend struct Mantid::Kernel::CreateUsingNew; @@ -72,11 +64,11 @@ private: FileFinderImpl(const FileFinderImpl &); /// Assignment operator FileFinderImpl &operator=(const FileFinderImpl &); + /// A method that returns error messages if the provided runs are invalid + std::string validateRuns(const std::string &searchText) const; std::string extractAllowedSuffix(std::string &userString) const; - std::pair - toInstrumentAndNumber(const std::string &hint) const; - std::string getArchivePath(const std::vector &archs, - const std::set &filenames, + std::pair toInstrumentAndNumber(const std::string &hint) const; + std::string getArchivePath(const std::vector &archs, const std::set &filenames, const std::vector &exts) const; std::string toUpper(const std::string &src) const; /// glob option - set to case sensitive or insensitive @@ -89,7 +81,6 @@ using FileFinder = Mantid::Kernel::SingletonHolder; namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/FileLoaderRegistry.h b/Framework/API/inc/MantidAPI/FileLoaderRegistry.h index e12cb3f550ad6761be0d512d481f1406d58aa387..2eb466367a4fc385e7fb04bb4ca1e5e206e54165 100644 --- a/Framework/API/inc/MantidAPI/FileLoaderRegistry.h +++ b/Framework/API/inc/MantidAPI/FileLoaderRegistry.h @@ -65,19 +65,16 @@ public: // If the factory didn't throw then the name is valid m_names[format].insert(nameVersion); m_totalSize += 1; - m_log.debug() << "Registered '" << nameVersion.first << "' version '" - << nameVersion.second << "' as file loader\n"; + m_log.debug() << "Registered '" << nameVersion.first << "' version '" << nameVersion.second << "' as file loader\n"; } /// Unsubscribe a named algorithm and version from the loader registration void unsubscribe(const std::string &name, const int version = -1); /// Returns the name of an Algorithm that can load the given filename - const std::shared_ptr - chooseLoader(const std::string &filename) const; + const std::shared_ptr chooseLoader(const std::string &filename) const; /// Checks whether the given algorithm can load the file - bool canLoad(const std::string &algorithmName, - const std::string &filename) const; + bool canLoad(const std::string &algorithmName, const std::string &filename) const; private: /// Friend so that CreateUsingNew @@ -94,33 +91,26 @@ private: switch (format) { case Nexus: if (!std::is_base_of, T>::value) { - throw std::runtime_error( - std::string("FileLoaderRegistryImpl::subscribe - Class '") + - typeid(T).name() + - "' registered as Nexus loader but it does not " - "inherit from " - "API::IFileLoader"); + throw std::runtime_error(std::string("FileLoaderRegistryImpl::subscribe - Class '") + typeid(T).name() + + "' registered as Nexus loader but it does not " + "inherit from " + "API::IFileLoader"); } break; case NexusHDF5: - if (!std::is_base_of, - T>::value) { - throw std::runtime_error( - std::string("FileLoaderRegistryImpl::subscribe - Class '") + - typeid(T).name() + - "' registered as NexusHDF5 loader but it does not " - "inherit from " - "API::IFileLoader"); + if (!std::is_base_of, T>::value) { + throw std::runtime_error(std::string("FileLoaderRegistryImpl::subscribe - Class '") + typeid(T).name() + + "' registered as NexusHDF5 loader but it does not " + "inherit from " + "API::IFileLoader"); } break; case Generic: if (!std::is_base_of, T>::value) { - throw std::runtime_error( - std::string("FileLoaderRegistryImpl::subscribe - Class '") + - typeid(T).name() + - "' registered as Generic loader but it does " - "not inherit from " - "API::IFileLoader"); + throw std::runtime_error(std::string("FileLoaderRegistryImpl::subscribe - Class '") + typeid(T).name() + + "' registered as Generic loader but it does " + "not inherit from " + "API::IFileLoader"); } break; default: @@ -130,8 +120,7 @@ private: }; /// Remove a named algorithm & version from the given map - void removeAlgorithm(const std::string &name, const int version, - std::multimap &typedLoaders); + void removeAlgorithm(const std::string &name, const int version, std::multimap &typedLoaders); /// The list of names. The index pointed to by LoaderFormat defines a set for /// that format. The length is equal to the length of the LoaderFormat enum @@ -144,15 +133,13 @@ private: }; /// Type for the actual singleton instance -using FileLoaderRegistry = - Mantid::Kernel::SingletonHolder; +using FileLoaderRegistry = Mantid::Kernel::SingletonHolder; } // namespace API } // namespace Mantid namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/FileProperty.h b/Framework/API/inc/MantidAPI/FileProperty.h index 88f23dc69f10af907cc7fb454c341e92161651b6..1a3dc7be7f8ba90f9dc847f2ba8dcf550ecb98cc 100644 --- a/Framework/API/inc/MantidAPI/FileProperty.h +++ b/Framework/API/inc/MantidAPI/FileProperty.h @@ -39,39 +39,32 @@ namespace API { FileAction type parameter in the constructor. */ -class MANTID_API_DLL FileProperty - : public Kernel::PropertyWithValue { +class MANTID_API_DLL FileProperty : public Kernel::PropertyWithValue { public: /// An enumeration for load/save types. This is passed on to the FileValidator /// as a constructor parameter. enum FileAction { // Note that the order here ensures that the correct boolean gets passed to // the FileValidator. - Save = 0, ///< to specify a file to write to, the file may or may not exist + Save = 0, ///< to specify a file to write to, the file may or may not exist OptionalSave = 1, ///< to specify a file to write to but an empty string is /// allowed here which will be passed to the algorithm - Load = 2, ///< to specify a file to open for reading, the file must exist - OptionalLoad = - 3, ///< to specify a file to read but the file doesn't have to exist - Directory = 4, ///< to specify a directory that must exist - OptionalDirectory = - 5 ///< to specify a directory that does not have to exist + Load = 2, ///< to specify a file to open for reading, the file must exist + OptionalLoad = 3, ///< to specify a file to read but the file doesn't have to exist + Directory = 4, ///< to specify a directory that must exist + OptionalDirectory = 5 ///< to specify a directory that does not have to exist }; /// Constructor taking a list of extensions as a vector - FileProperty( - const std::string &name, const std::string &defaultValue, - unsigned int action, - const std::vector &exts = std::vector(), - unsigned int direction = Kernel::Direction::Input); + FileProperty(const std::string &name, const std::string &defaultValue, unsigned int action, + const std::vector &exts = std::vector(), + unsigned int direction = Kernel::Direction::Input); /// Constructor taking a single extension as a string - FileProperty(const std::string &name, const std::string &default_value, - unsigned int action, const std::string &ext, + FileProperty(const std::string &name, const std::string &default_value, unsigned int action, const std::string &ext, unsigned int direction = Kernel::Direction::Input); /// Constructor taking a list of extensions as an initializer_list - FileProperty(const std::string &name, const std::string &default_value, - unsigned int action, std::initializer_list exts, - unsigned int direction = Kernel::Direction::Input); + FileProperty(const std::string &name, const std::string &default_value, unsigned int action, + std::initializer_list exts, unsigned int direction = Kernel::Direction::Input); FileProperty(const FileProperty &) = default; FileProperty &operator=(const FileProperty &) = default; @@ -123,8 +116,7 @@ private: }; #ifdef _WIN32 -#pragma warning( \ - pop) // Re-enable the warning about multiple assignment operators +#pragma warning(pop) // Re-enable the warning about multiple assignment operators #endif } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/FrameworkManager.h b/Framework/API/inc/MantidAPI/FrameworkManager.h index c4b10908fbe63b8cf15dfcd6456d572987be5876..d79cb99aaea620999e7eb31d905c24c37b2a259b 100644 --- a/Framework/API/inc/MantidAPI/FrameworkManager.h +++ b/Framework/API/inc/MantidAPI/FrameworkManager.h @@ -60,8 +60,7 @@ public: void clearPropertyManagers(); /// Creates an algorithm and runs it, with variadic arguments - std::shared_ptr exec(const std::string &algorithmName, int count, - ...); + std::shared_ptr exec(const std::string &algorithmName, int count, ...); /// Returns a shared pointer to the workspace requested Workspace *getWorkspace(const std::string &wsName); @@ -78,8 +77,7 @@ private: ~FrameworkManagerImpl() = default; /// Load a set of plugins using a key from the ConfigService - void loadPluginsUsingKey(const std::string &locationKey, - const std::string &excludeKey); + void loadPluginsUsingKey(const std::string &locationKey, const std::string &excludeKey); /// Set up the global locale void setGlobalNumericLocaleToC(); /// Silence NeXus output @@ -113,7 +111,6 @@ using FrameworkManager = Mantid::Kernel::SingletonHolder; namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/FuncMinimizerFactory.h b/Framework/API/inc/MantidAPI/FuncMinimizerFactory.h index d3b3c5b80c811388b0f6409f9af26278394f2986..6158725459060596e39480fb64de4f35de0e52c6 100644 --- a/Framework/API/inc/MantidAPI/FuncMinimizerFactory.h +++ b/Framework/API/inc/MantidAPI/FuncMinimizerFactory.h @@ -33,8 +33,7 @@ class IFuncMinimizer; @date 20/05/2010 */ -class MANTID_API_DLL FuncMinimizerFactoryImpl - : public Kernel::DynamicFactory { +class MANTID_API_DLL FuncMinimizerFactoryImpl : public Kernel::DynamicFactory { public: /// Creates an instance of a minimizer std::shared_ptr createMinimizer(const std::string &str) const; @@ -45,16 +44,14 @@ private: FuncMinimizerFactoryImpl(); }; -using FuncMinimizerFactory = - Mantid::Kernel::SingletonHolder; +using FuncMinimizerFactory = Mantid::Kernel::SingletonHolder; } // namespace API } // namespace Mantid namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid @@ -62,10 +59,8 @@ EXTERN_MANTID_API template class MANTID_API_DLL * Macro for declaring a new type of minimizers to be used with the * FuncMinimizerFactory */ -#define DECLARE_FUNCMINIMIZER(classname, username) \ - namespace { \ - Mantid::Kernel::RegistrationHelper register_funcminimizer_##classname( \ - ((Mantid::API::FuncMinimizerFactory::Instance().subscribe( \ - #username)), \ - 0)); \ +#define DECLARE_FUNCMINIMIZER(classname, username) \ + namespace { \ + Mantid::Kernel::RegistrationHelper register_funcminimizer_##classname( \ + ((Mantid::API::FuncMinimizerFactory::Instance().subscribe(#username)), 0)); \ } diff --git a/Framework/API/inc/MantidAPI/FunctionDomain1D.h b/Framework/API/inc/MantidAPI/FunctionDomain1D.h index 5362baa2cc2e5bbf2d4e3483c0f19e92f24294c4..c409b77cf04a6b4aefcab55cb1319cbb45a535dd 100644 --- a/Framework/API/inc/MantidAPI/FunctionDomain1D.h +++ b/Framework/API/inc/MantidAPI/FunctionDomain1D.h @@ -42,7 +42,7 @@ public: const double *getPointerAt(size_t i) const { return m_data + i; } /// Convert to a vector std::vector toVector() const; - /// Set a peak redius to pass to peak functions. + /// Set a peak radius to pass to peak functions. void setPeakRadius(int radius); /// Get the peak radius. int getPeakRadius() const; @@ -74,17 +74,19 @@ public: /// Constructor. FunctionDomain1DVector(const double x); /// Constructor. - FunctionDomain1DVector(const double startX, const double endX, - const size_t n); + FunctionDomain1DVector(const double startX, const double endX, const size_t n); /// Constructor. FunctionDomain1DVector(const std::vector &xvalues); + /// No-copy constructor. + FunctionDomain1DVector(std::vector &&xvalues); /// Constructor. - FunctionDomain1DVector(std::vector::const_iterator from, - std::vector::const_iterator to); + FunctionDomain1DVector(std::vector::const_iterator from, std::vector::const_iterator to); /// Copy constructor. FunctionDomain1DVector(const FunctionDomain1DVector &); /// Copy assignment operator. FunctionDomain1DVector &operator=(const FunctionDomain1DVector &); + /// Get the underlying vector + std::vector getVector() { return m_X; } protected: std::vector m_X; ///< vector of function arguments @@ -120,8 +122,7 @@ public: /// Constructor. FunctionDomain1DSpectrum(size_t wi, const std::vector &xvalues); /// Constructor. - FunctionDomain1DSpectrum(size_t wi, std::vector::const_iterator from, - std::vector::const_iterator to); + FunctionDomain1DSpectrum(size_t wi, std::vector::const_iterator from, std::vector::const_iterator to); /// Get the workspace index size_t getWorkspaceIndex() const { return m_workspaceIndex; } @@ -139,15 +140,13 @@ public: /// Constructor. FunctionDomain1DHistogram(const std::vector &bins); /// Constructor. - FunctionDomain1DHistogram(std::vector::const_iterator from, - std::vector::const_iterator to); + FunctionDomain1DHistogram(std::vector::const_iterator from, std::vector::const_iterator to); /// Disable copy operator FunctionDomain1DHistogram(const FunctionDomain1DHistogram &) = delete; /// Disable assignment operator - FunctionDomain1DHistogram & - operator=(const FunctionDomain1DHistogram &) = delete; + FunctionDomain1DHistogram &operator=(const FunctionDomain1DHistogram &) = delete; /// Get the leftmost boundary double leftBoundary() const; diff --git a/Framework/API/inc/MantidAPI/FunctionDomainMD.h b/Framework/API/inc/MantidAPI/FunctionDomainMD.h index 43ebc9efa049ac4ea93b8f8593986d6f8fa01790..b9b1d84bbf51388c762c4a9333a6560e9fd9f1f0 100644 --- a/Framework/API/inc/MantidAPI/FunctionDomainMD.h +++ b/Framework/API/inc/MantidAPI/FunctionDomainMD.h @@ -22,8 +22,7 @@ namespace API { class MANTID_API_DLL FunctionDomainMD : public FunctionDomain { public: /// Constructor. - FunctionDomainMD(const IMDWorkspace_const_sptr &ws, size_t start = 0, - size_t length = 0); + FunctionDomainMD(const IMDWorkspace_const_sptr &ws, size_t start = 0, size_t length = 0); /// Destructor. ~FunctionDomainMD() override; /// Return the number of arguments in the domain diff --git a/Framework/API/inc/MantidAPI/FunctionFactory.h b/Framework/API/inc/MantidAPI/FunctionFactory.h index 27a98c69d8e6551df0fe44427f18dafe20a225b3..4a4c09166be2b1b32eca5c18224d329a5ea860d5 100644 --- a/Framework/API/inc/MantidAPI/FunctionFactory.h +++ b/Framework/API/inc/MantidAPI/FunctionFactory.h @@ -10,6 +10,7 @@ // Includes //---------------------------------------------------------------------- #include "MantidAPI/DllConfig.h" +#include "MantidAPI/IPeakFunction.h" #include "MantidKernel/DynamicFactory.h" #include "MantidKernel/SingletonHolder.h" #include @@ -39,8 +40,7 @@ class MultiDomainFunction; @date 27/10/2009 */ -class MANTID_API_DLL FunctionFactoryImpl final - : public Kernel::DynamicFactory { +class MANTID_API_DLL FunctionFactoryImpl final : public Kernel::DynamicFactory { public: FunctionFactoryImpl(const FunctionFactoryImpl &) = delete; FunctionFactoryImpl &operator=(const FunctionFactoryImpl &) = delete; @@ -55,21 +55,17 @@ public: /// Creates an instnce of an inizialised multidomain function where each /// domain has the same function. - std::shared_ptr - createInitializedMultiDomainFunction(const std::string &input, - size_t domainNumber) const; + std::shared_ptr createInitializedMultiDomainFunction(const std::string &input, + size_t domainNumber) const; /// Query available functions based on the template type - template - std::vector getFunctionNames() const; + template std::vector getFunctionNames() const; /// Get function names that can be used by generic fitting GUIs std::vector getFunctionNamesGUI() const; // Unhide the base class version (to satisfy the intel compiler) using Kernel::DynamicFactory::subscribe; - void subscribe(const std::string &className, - std::unique_ptr pAbstractFactory, - Kernel::DynamicFactory::SubscribeAction replace = - ErrorIfExists); + void subscribe(const std::string &className, std::unique_ptr pAbstractFactory, + Kernel::DynamicFactory::SubscribeAction replace = ErrorIfExists); void unsubscribe(const std::string &className); @@ -85,32 +81,26 @@ private: using Kernel::DynamicFactory::createUnwrapped; /// Create a simple function - std::shared_ptr - createSimple(const Expression &expr, - std::map &parentAttributes) const; + std::shared_ptr createSimple(const Expression &expr, + std::map &parentAttributes) const; + std::shared_ptr createPeakFunction(const Expression &expr, const std::string &name) const; /// Create a composite function - std::shared_ptr - createComposite(const Expression &expr, - std::map &parentAttributes) const; + std::shared_ptr createComposite(const Expression &expr, + std::map &parentAttributes) const; /// Throw an exception void inputError(const std::string &str = "") const; /// Add constraints to the created function - void addConstraints(const std::shared_ptr &fun, - const Expression &expr) const; + void addConstraints(const std::shared_ptr &fun, const Expression &expr) const; /// Add a single constraint to the created function - void addConstraint(const std::shared_ptr &fun, - const Expression &expr) const; + void addConstraint(const std::shared_ptr &fun, const Expression &expr) const; /// Add a single constraint to the created function with non-default penalty - void addConstraint(const std::shared_ptr &fun, - const Expression &constraint_expr, + void addConstraint(const std::shared_ptr &fun, const Expression &constraint_expr, const Expression &penalty_expr) const; /// Add ties to the created function - void addTies(const std::shared_ptr &fun, - const Expression &expr) const; + void addTies(const std::shared_ptr &fun, const Expression &expr) const; /// Add a tie to the created function - void addTie(const std::shared_ptr &fun, - const Expression &expr) const; + void addTie(const std::shared_ptr &fun, const Expression &expr) const; mutable std::map> m_cachedFunctionNames; mutable std::mutex m_mutex; @@ -121,8 +111,7 @@ private: * @tparam FunctionType :: The type of the functions to list * @returns A vector of the names of the functions matching the template type */ -template -std::vector FunctionFactoryImpl::getFunctionNames() const { +template std::vector FunctionFactoryImpl::getFunctionNames() const { std::lock_guard _lock(m_mutex); const std::string soughtType(typeid(FunctionType).name()); @@ -133,29 +122,25 @@ std::vector FunctionFactoryImpl::getFunctionNames() const { // Create the entry in the cache and work with it directly std::vector &typeNames = m_cachedFunctionNames[soughtType]; const std::vector names = this->getKeys(); - std::copy_if(names.cbegin(), names.cend(), std::back_inserter(typeNames), - [this](const std::string &name) { - std::shared_ptr func = this->createFunction(name); - return std::dynamic_pointer_cast(func); - }); + std::copy_if(names.cbegin(), names.cend(), std::back_inserter(typeNames), [this](const std::string &name) { + std::shared_ptr func = this->createFunction(name); + return std::dynamic_pointer_cast(func); + }); return typeNames; } using FunctionFactory = Mantid::Kernel::SingletonHolder; /// Convenient typedef for an UpdateNotification -using FunctionFactoryUpdateNotification = - FunctionFactoryImpl::UpdateNotification; +using FunctionFactoryUpdateNotification = FunctionFactoryImpl::UpdateNotification; /// Convenient typedef for an UpdateNotification AutoPtr -using FunctionFactoryUpdateNotification_ptr = - const Poco::AutoPtr &; +using FunctionFactoryUpdateNotification_ptr = const Poco::AutoPtr &; } // namespace API } // namespace Mantid namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid @@ -163,10 +148,8 @@ EXTERN_MANTID_API template class MANTID_API_DLL * Macro for declaring a new type of function to be used with the * FunctionFactory */ -#define DECLARE_FUNCTION(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper \ - register_function_##classname(((Mantid::API::FunctionFactory::Instance() \ - .subscribe(#classname)), \ - 0)); \ +#define DECLARE_FUNCTION(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper \ + register_function_##classname(((Mantid::API::FunctionFactory::Instance().subscribe(#classname)), 0)); \ } diff --git a/Framework/API/inc/MantidAPI/FunctionGenerator.h b/Framework/API/inc/MantidAPI/FunctionGenerator.h index c1ca9fb218260ed8c10dd274a3ebf85667fcd69e..407eb22a8b555e1eb43cb7a703c811c026b3cb6d 100644 --- a/Framework/API/inc/MantidAPI/FunctionGenerator.h +++ b/Framework/API/inc/MantidAPI/FunctionGenerator.h @@ -37,18 +37,15 @@ public: /// m_source and m_target. //@{ /// Set i-th parameter - void setParameter(size_t, const double &value, - bool explicitlySet = true) override; + void setParameter(size_t, const double &value, bool explicitlySet = true) override; /// Set i-th parameter description void setParameterDescription(size_t, const std::string &description) override; /// Get i-th parameter double getParameter(size_t i) const override; /// Set parameter by name. - void setParameter(const std::string &name, const double &value, - bool explicitlySet = true) override; + void setParameter(const std::string &name, const double &value, bool explicitlySet = true) override; /// Set description of parameter by name. - void setParameterDescription(const std::string &name, - const std::string &description) override; + void setParameterDescription(const std::string &name, const std::string &description) override; /// Get parameter by name. double getParameter(const std::string &name) const override; /// Check if function has a parameter with this name. @@ -86,8 +83,7 @@ public: protected: /// Declare a new parameter - void declareParameter(const std::string &name, double initValue = 0, - const std::string &description = "") override; + void declareParameter(const std::string &name, double initValue = 0, const std::string &description = "") override; /// Change status of parameter void setParameterStatus(size_t i, ParameterStatus status) override; /// Get status of parameter @@ -113,8 +109,7 @@ public: //@} /// Evaluate the function - void function(const FunctionDomain &domain, - FunctionValues &values) const override; + void function(const FunctionDomain &domain, FunctionValues &values) const override; protected: /// overwrite IFunction base class method, which declare function parameters diff --git a/Framework/API/inc/MantidAPI/FunctionParameterDecorator.h b/Framework/API/inc/MantidAPI/FunctionParameterDecorator.h index 0037863168b65485cdf227490cead04c717a9722..6bb15b02475192408925ede4870e91b0c84e9341 100644 --- a/Framework/API/inc/MantidAPI/FunctionParameterDecorator.h +++ b/Framework/API/inc/MantidAPI/FunctionParameterDecorator.h @@ -36,23 +36,19 @@ public: IFunction_sptr clone() const override; void setWorkspace(std::shared_ptr ws) override; - void setMatrixWorkspace(std::shared_ptr workspace, - size_t wi, double startX, double endX) override; + void setMatrixWorkspace(std::shared_ptr workspace, size_t wi, double startX, + double endX) override; /// Set i-th parameter of decorated function. - void setParameter(size_t i, const double &value, - bool explicitlySet = true) override; + void setParameter(size_t i, const double &value, bool explicitlySet = true) override; /// Set i-th parameter description of decorated function. - void setParameterDescription(size_t i, - const std::string &description) override; + void setParameterDescription(size_t i, const std::string &description) override; /// Get i-th parameter of decorated function. double getParameter(size_t i) const override; /// Set parameter of decorated function by name. - void setParameter(const std::string &name, const double &value, - bool explicitlySet = true) override; + void setParameter(const std::string &name, const double &value, bool explicitlySet = true) override; /// Set description of parameter of decorated function by name. - void setParameterDescription(const std::string &name, - const std::string &description) override; + void setParameterDescription(const std::string &name, const std::string &description) override; /// Value of i-th active parameter of the decorated function. double activeParameter(size_t i) const override; @@ -93,14 +89,12 @@ public: /// Return a value of attribute attName of decorated function- IFunction::Attribute getAttribute(const std::string &attName) const override; /// Set a value to attribute attName of decorated function. - void setAttribute(const std::string &attName, - const IFunction::Attribute &attValue) override; + void setAttribute(const std::string &attName, const IFunction::Attribute &attValue) override; /// Check if attribute attName exists in decorated function bool hasAttribute(const std::string &attName) const override; /// Tie a parameter of decorated function to other parameters (or a constant). - void tie(const std::string &parName, const std::string &expr, - bool isDefault = false) override; + void tie(const std::string &parName, const std::string &expr, bool isDefault = false) override; /// Apply the ties in decorated function. void applyTies() override; /// Remove all ties of decorated function. @@ -126,8 +120,7 @@ protected: void throwIfNoFunctionSet() const; - void declareParameter(const std::string &name, double initValue, - const std::string &description) override; + void declareParameter(const std::string &name, double initValue, const std::string &description) override; void addTie(std::unique_ptr) override; void setParameterStatus(size_t i, ParameterStatus status) override; @@ -139,8 +132,7 @@ protected: IFunction_sptr m_wrappedFunction; }; -using FunctionParameterDecorator_sptr = - std::shared_ptr; +using FunctionParameterDecorator_sptr = std::shared_ptr; } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/FunctionProperty.h b/Framework/API/inc/MantidAPI/FunctionProperty.h index f98f9be15bbae3f3d03b59b60eda569085ba1c55..fd65f81caad0be9bccd4f1e9e80f138aa1563797 100644 --- a/Framework/API/inc/MantidAPI/FunctionProperty.h +++ b/Framework/API/inc/MantidAPI/FunctionProperty.h @@ -11,6 +11,7 @@ //---------------------------------------------------------------------- #include "MantidAPI/DllConfig.h" #include "MantidAPI/IFunction.h" +#include "MantidAPI/WorkspaceProperty.h" #include "MantidKernel/Exception.h" #include "MantidKernel/PropertyWithValue.h" @@ -25,19 +26,18 @@ is the creation string accepted by the FunctionFactory. @author Roman Tolchenov, Tessella plc @date 08/02/2012 */ -class MANTID_API_DLL FunctionProperty - : public Kernel::PropertyWithValue> { +class MANTID_API_DLL FunctionProperty : public Kernel::PropertyWithValue> { public: /// Constructor. - FunctionProperty(const std::string &name, - const unsigned int direction = Kernel::Direction::Input); + FunctionProperty(const std::string &name, const unsigned int direction = Kernel::Direction::Input, + const PropertyMode::Type optional = PropertyMode::Type::Mandatory); /// Copy constructor - FunctionProperty(const FunctionProperty &right); + FunctionProperty(const FunctionProperty &right) = default; /// Copy assignment operator. Only copies the value (i.e. the pointer to the /// function) - FunctionProperty &operator=(const FunctionProperty &right); + FunctionProperty &operator=(const FunctionProperty &right) = default; /// Bring in the PropertyWithValue assignment operator explicitly (avoids /// VSC++ warning) @@ -47,9 +47,7 @@ public: FunctionProperty &operator+=(Kernel::Property const *) override; /// 'Virtual copy constructor' - FunctionProperty *clone() const override { - return new FunctionProperty(*this); - } + FunctionProperty *clone() const override { return new FunctionProperty(*this); } /// Get the function definition string std::string value() const override; @@ -76,6 +74,11 @@ public: const Kernel::PropertyHistory createHistory() const override; private: + /// Return true if the property is optional. + bool isOptional() const; + + /// A flag indicating whether the property should be considered optional. + PropertyMode::Type m_optional; /// The function definition string (as used by the FunctionFactory) std::string m_definition; }; diff --git a/Framework/API/inc/MantidAPI/GridDomain1D.h b/Framework/API/inc/MantidAPI/GridDomain1D.h index 40d2cf598b2bf10fe3a61796be35bdbf01796b1b..67a1d88636c76a163a5c420cdcde946ef6fc98e4 100644 --- a/Framework/API/inc/MantidAPI/GridDomain1D.h +++ b/Framework/API/inc/MantidAPI/GridDomain1D.h @@ -26,8 +26,7 @@ namespace API { class MANTID_API_DLL GridDomain1D : public API::GridDomain { public: /// initialize - void initialize(double &startX, double &endX, size_t &n, - const std::string &scaling); + void initialize(double &startX, double &endX, size_t &n, const std::string &scaling); /// number of grid point s size_t size() const override { return m_points.size(); } /// number of dimensions in the grid diff --git a/Framework/API/inc/MantidAPI/GroupingLoader.h b/Framework/API/inc/MantidAPI/GroupingLoader.h index 1413a85042454dfdea5634d3935fde501acac8ce..1d60cde4f4cf4ca4edb47717cce022b7f40697d0 100644 --- a/Framework/API/inc/MantidAPI/GroupingLoader.h +++ b/Framework/API/inc/MantidAPI/GroupingLoader.h @@ -44,14 +44,12 @@ public: class MANTID_API_DLL GroupingLoader { public: explicit GroupingLoader(Geometry::Instrument_const_sptr instrument); - GroupingLoader(Geometry::Instrument_const_sptr instrument, - const std::string &mainFieldDirection); + GroupingLoader(Geometry::Instrument_const_sptr instrument, const std::string &mainFieldDirection); virtual ~GroupingLoader(); /// Load the grouping from the instrument's IDF std::shared_ptr getGroupingFromIDF() const; /// Loads grouping from the XML file specified - static void loadGroupingFromXML(const std::string &filename, - Grouping &grouping); + static void loadGroupingFromXML(const std::string &filename, Grouping &grouping); /// Returns a "dummy" grouping of a single group with all the detectors in it std::shared_ptr getDummyGrouping(); diff --git a/Framework/API/inc/MantidAPI/HistoWorkspace.h b/Framework/API/inc/MantidAPI/HistoWorkspace.h index c4c3b3ab77d9ba725d73a5419b464eabaeeffe50..de7262cb8245c4a41a5d0ce0118eaa158817e20e 100644 --- a/Framework/API/inc/MantidAPI/HistoWorkspace.h +++ b/Framework/API/inc/MantidAPI/HistoWorkspace.h @@ -21,19 +21,14 @@ namespace API { */ class MANTID_API_DLL HistoWorkspace : public MatrixWorkspace { public: - HistoWorkspace( - const Parallel::StorageMode storageMode = Parallel::StorageMode::Cloned) + HistoWorkspace(const Parallel::StorageMode storageMode = Parallel::StorageMode::Cloned) : MatrixWorkspace(storageMode) {} /// Returns a clone of the workspace - std::unique_ptr clone() const { - return std::unique_ptr(doClone()); - } + std::unique_ptr clone() const { return std::unique_ptr(doClone()); } /// Returns a default-initialized clone of the workspace - std::unique_ptr cloneEmpty() const { - return std::unique_ptr(doCloneEmpty()); - } + std::unique_ptr cloneEmpty() const { return std::unique_ptr(doCloneEmpty()); } private: HistoWorkspace *doClone() const override = 0; diff --git a/Framework/API/inc/MantidAPI/HistoryItem.h b/Framework/API/inc/MantidAPI/HistoryItem.h index e450ba8247ebdff5262860b6f3956195b721483e..12f12ae5fd83200f1f4d3a090f34e6feb798ef15 100644 --- a/Framework/API/inc/MantidAPI/HistoryItem.h +++ b/Framework/API/inc/MantidAPI/HistoryItem.h @@ -30,12 +30,8 @@ public: virtual ~HistoryItem() = default; bool isUnrolled() const { return m_unrolled; } void unrolled(bool unrolled) { m_unrolled = unrolled; } - AlgorithmHistory_const_sptr getAlgorithmHistory() const { - return m_algorithmHistory; - } - size_t numberOfChildren() const { - return m_algorithmHistory->childHistorySize(); - } + AlgorithmHistory_const_sptr getAlgorithmHistory() const { return m_algorithmHistory; } + size_t numberOfChildren() const { return m_algorithmHistory->childHistorySize(); } private: AlgorithmHistory_const_sptr m_algorithmHistory; diff --git a/Framework/API/inc/MantidAPI/HistoryView.h b/Framework/API/inc/MantidAPI/HistoryView.h index ec2ab0375398fc46323bc169dd32ebd8ea12c210..dd277ba3a8210bc9913f995c62fc179920fe7bda 100644 --- a/Framework/API/inc/MantidAPI/HistoryView.h +++ b/Framework/API/inc/MantidAPI/HistoryView.h @@ -37,18 +37,14 @@ public: void unrollAll(); void roll(size_t index); void rollAll(); - void - filterBetweenExecDate(Mantid::Types::Core::DateAndTime start, - Mantid::Types::Core::DateAndTime end = - Mantid::Types::Core::DateAndTime::getCurrentTime()); + void filterBetweenExecDate(Mantid::Types::Core::DateAndTime start, + Mantid::Types::Core::DateAndTime end = Mantid::Types::Core::DateAndTime::getCurrentTime()); /** * Get the list of History Items for this view. * * @returns vector of history items for this view. */ - const std::vector &getAlgorithmsList() const { - return m_historyItems; - }; + const std::vector &getAlgorithmsList() const { return m_historyItems; }; size_t size() const { return m_historyItems.size(); } diff --git a/Framework/API/inc/MantidAPI/IArchiveSearch.h b/Framework/API/inc/MantidAPI/IArchiveSearch.h index ad5af681d9d47b654c10015ef0b7155e80516b48..ce220b68c7e1121c7a504be414be2b1c5517ab59 100644 --- a/Framework/API/inc/MantidAPI/IArchiveSearch.h +++ b/Framework/API/inc/MantidAPI/IArchiveSearch.h @@ -18,12 +18,10 @@ #include #include -#define DECLARE_ARCHIVESEARCH(classname, facility) \ - namespace { \ - Mantid::Kernel::RegistrationHelper register_archive_##facility( \ - ((Mantid::API::ArchiveSearchFactory::Instance().subscribe( \ - #facility)), \ - 0)); \ +#define DECLARE_ARCHIVESEARCH(classname, facility) \ + namespace { \ + Mantid::Kernel::RegistrationHelper register_archive_##facility( \ + ((Mantid::API::ArchiveSearchFactory::Instance().subscribe(#facility)), 0)); \ } namespace Mantid { @@ -46,9 +44,8 @@ public: * the archive * @param exts :: A list of extensions to check for in turn against each file */ - virtual std::string - getArchivePath(const std::set &filenames, - const std::vector &exts) const = 0; + virtual std::string getArchivePath(const std::set &filenames, + const std::vector &exts) const = 0; }; /// Typedef for a shared pointer to an IArchiveSearch diff --git a/Framework/API/inc/MantidAPI/IBackgroundFunction.h b/Framework/API/inc/MantidAPI/IBackgroundFunction.h index 5474fe4d3d1acfc1f1873d31417f6c042f419d70..fa9b13a48d461c92c7342b65ad95deb737ae5b67 100644 --- a/Framework/API/inc/MantidAPI/IBackgroundFunction.h +++ b/Framework/API/inc/MantidAPI/IBackgroundFunction.h @@ -24,8 +24,7 @@ public: /// Fits the function /// @param X :: a vector of x values /// @param Y :: a matching vector of Y values - virtual void fit(const std::vector &X, - const std::vector &Y) = 0; + virtual void fit(const std::vector &X, const std::vector &Y) = 0; }; using IBackgroundFunction_sptr = std::shared_ptr; diff --git a/Framework/API/inc/MantidAPI/IBoxControllerIO.h b/Framework/API/inc/MantidAPI/IBoxControllerIO.h index a71e95fc5fa19607bd3e00870cb1aa55633f63c2..f46e0c3b0a8ffc77cc0c8787772baf32e2333e2b 100644 --- a/Framework/API/inc/MantidAPI/IBoxControllerIO.h +++ b/Framework/API/inc/MantidAPI/IBoxControllerIO.h @@ -32,25 +32,20 @@ public: it is opened in read mode otherwise * @return false if the file had been already opened. Throws if problems with openeing */ - virtual bool openFile(const std::string &fileName, - const std::string &mode) = 0; + virtual bool openFile(const std::string &fileName, const std::string &mode) = 0; /**@return true if file is already opened */ virtual bool isOpened() const = 0; /**@return the full name of the used data file*/ virtual const std::string &getFileName() const = 0; /**Save a float data block in the specified file position */ - virtual void saveBlock(const std::vector & /* DataBlock */, - const uint64_t /*blockPosition*/) const = 0; + virtual void saveBlock(const std::vector & /* DataBlock */, const uint64_t /*blockPosition*/) const = 0; /**Save a double data block in the specified file position */ - virtual void saveBlock(const std::vector & /* DataBlock */, - const uint64_t /*blockPosition*/) const = 0; + virtual void saveBlock(const std::vector & /* DataBlock */, const uint64_t /*blockPosition*/) const = 0; /** load known size float data block from spefied file position */ - virtual void loadBlock(std::vector & /* Block */, - const uint64_t /*blockPosition*/, + virtual void loadBlock(std::vector & /* Block */, const uint64_t /*blockPosition*/, const size_t /*BlockSize*/) const = 0; - virtual void loadBlock(std::vector & /* Block */, - const uint64_t /*blockPosition*/, + virtual void loadBlock(std::vector & /* Block */, const uint64_t /*blockPosition*/, const size_t /*BlockSize*/) const = 0; /** flush the IO buffers */ @@ -66,8 +61,7 @@ public: * and the size of the data type in bytes (e.g. the class dependant physical * meaning of the blockSize and blockPosition used * by save/load operations */ - virtual void setDataType(const size_t blockSize, - const std::string &typeName) = 0; + virtual void setDataType(const size_t blockSize, const std::string &typeName) = 0; virtual void getDataType(size_t &blockSize, std::string &typeName) const = 0; }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/ICatalog.h b/Framework/API/inc/MantidAPI/ICatalog.h index 902588ec59074193e8aab2efe1786c8d2a704d43..d913abe863c120be15672a0f7418fd2c997b2f09 100644 --- a/Framework/API/inc/MantidAPI/ICatalog.h +++ b/Framework/API/inc/MantidAPI/ICatalog.h @@ -30,17 +30,14 @@ public: /// Virtual destructor virtual ~ICatalog() = default; /// method to login to a catalog - virtual CatalogSession_sptr login(const std::string &, const std::string &, - const std::string &, + virtual CatalogSession_sptr login(const std::string &, const std::string &, const std::string &, const std::string &) = 0; /// logout from catalog virtual void logout() = 0; /// Search investigations - virtual void search(const ICat::CatalogSearchParam &, ITableWorkspace_sptr &, - const int &, const int &) = 0; + virtual void search(const ICat::CatalogSearchParam &, ITableWorkspace_sptr &, const int &, const int &) = 0; /// Obtain the number of results returned by the search method. - virtual int64_t - getNumberOfSearchResults(const ICat::CatalogSearchParam &) = 0; + virtual int64_t getNumberOfSearchResults(const ICat::CatalogSearchParam &) = 0; /// search logged in users data virtual void myData(ITableWorkspace_sptr &) = 0; /// get datasets. diff --git a/Framework/API/inc/MantidAPI/ICatalogInfoService.h b/Framework/API/inc/MantidAPI/ICatalogInfoService.h index d95e541f1efa9c8edfcb31935f426175bc7b18e3..51a01c7165d2daf830a62ab60ff41c394579978d 100644 --- a/Framework/API/inc/MantidAPI/ICatalogInfoService.h +++ b/Framework/API/inc/MantidAPI/ICatalogInfoService.h @@ -28,16 +28,13 @@ public: /// Obtain url to download a file from. virtual const std::string getDownloadURL(const long long &) = 0; /// Obtain the url to upload a file to. - virtual const std::string getUploadURL(const std::string &, - const std::string &, - const std::string &) = 0; + virtual const std::string getUploadURL(const std::string &, const std::string &, const std::string &) = 0; /// Obtains the investigations that the user can publish to and saves related /// information to a workspace. virtual ITableWorkspace_sptr getPublishInvestigations() = 0; }; using ICatalogInfoService_sptr = std::shared_ptr; -using ICatalogInfoService_const_sptr = - std::shared_ptr; +using ICatalogInfoService_const_sptr = std::shared_ptr; } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/IConstraint.h b/Framework/API/inc/MantidAPI/IConstraint.h index 68c53278f9a6be14f735a84fee826006f729b39e..4d6543b69c55a682b946e8175486774f991b1f1e 100644 --- a/Framework/API/inc/MantidAPI/IConstraint.h +++ b/Framework/API/inc/MantidAPI/IConstraint.h @@ -26,8 +26,7 @@ class Expression; class MANTID_API_DLL IConstraint : public ParameterReference { public: /// Initialize the constraint from an expression - virtual void initialize(IFunction *fun, const Expression &expr, - bool isDefault = false) = 0; + virtual void initialize(IFunction *fun, const Expression &expr, bool isDefault = false) = 0; /// Returns a penalty number which is bigger than or equal to zero /// If zero it means that the constraint is not penalized. If larger diff --git a/Framework/API/inc/MantidAPI/ICostFunction.h b/Framework/API/inc/MantidAPI/ICostFunction.h index eb382ab7f72c02dae22e589f8fada9fbe786bc7a..6d06d7375161f7fb2499a5afc6c401a5eae729d1 100644 --- a/Framework/API/inc/MantidAPI/ICostFunction.h +++ b/Framework/API/inc/MantidAPI/ICostFunction.h @@ -63,12 +63,10 @@ using ICostFunction_sptr = std::shared_ptr; * Macro for declaring a new type of cost functions to be used with the * CostFunctionFactory */ -#define DECLARE_COSTFUNCTION(classname, username) \ - namespace { \ - Mantid::Kernel::RegistrationHelper register_costfunction_##classname( \ - ((Mantid::API::CostFunctionFactory::Instance().subscribe( \ - #username)), \ - 0)); \ +#define DECLARE_COSTFUNCTION(classname, username) \ + namespace { \ + Mantid::Kernel::RegistrationHelper register_costfunction_##classname( \ + ((Mantid::API::CostFunctionFactory::Instance().subscribe(#username)), 0)); \ } } // namespace API diff --git a/Framework/API/inc/MantidAPI/IDomainCreator.h b/Framework/API/inc/MantidAPI/IDomainCreator.h index bd103b7fbac7b2330cbcb84eb6eb3a04efeb8540..a0f4cff5f8076d0afa7493dc60b1de431a8e99ab 100644 --- a/Framework/API/inc/MantidAPI/IDomainCreator.h +++ b/Framework/API/inc/MantidAPI/IDomainCreator.h @@ -41,26 +41,22 @@ public: /// Type of domain to create. enum DomainType { Simple = 0, Sequential, Parallel }; /// Constrcutor - IDomainCreator(Kernel::IPropertyManager *manager, - const std::vector &workspacePropertyNames, + IDomainCreator(Kernel::IPropertyManager *manager, const std::vector &workspacePropertyNames, DomainType domainType = Simple); /// Virtual destructor virtual ~IDomainCreator() = default; /// Initialize - virtual void initialize(Kernel::IPropertyManager *, const std::string &, - DomainType) {} + virtual void initialize(Kernel::IPropertyManager *, const std::string &, DomainType) {} /// Toggle output of either just composite or composite + members - void separateCompositeMembersInOutput(const bool value, - const bool conv = false); + void separateCompositeMembersInOutput(const bool value, const bool conv = false); /// Declare properties that specify the dataset within the workspace to fit /// to. /// @param suffix :: A suffix to give to all new properties. /// @param addProp :: If false don't actually declare new properties but do /// other stuff if needed - virtual void declareDatasetProperties(const std::string &suffix = "", - bool addProp = true) { + virtual void declareDatasetProperties(const std::string &suffix = "", bool addProp = true) { UNUSED_ARG(suffix); UNUSED_ARG(addProp); } @@ -76,8 +72,7 @@ public: /// @param i0 :: Starting index in values for the fitting data. /// Implementations must make sure values has enough room /// for the data from index i0 to the end of the container. - virtual void createDomain(std::shared_ptr &domain, - std::shared_ptr &values, + virtual void createDomain(std::shared_ptr &domain, std::shared_ptr &values, size_t i0 = 0) = 0; /// Create an output workspace filled with data simulated with the fitting @@ -91,11 +86,10 @@ public: /// If empty do not create the property, /// just return a pointer /// @return A shared pointer to the created workspace. - virtual std::shared_ptr createOutputWorkspace( - const std::string &baseName, API::IFunction_sptr function, - std::shared_ptr domain, - std::shared_ptr values, - const std::string &outputWorkspacePropertyName = "OutputWorkspace") { + virtual std::shared_ptr + createOutputWorkspace(const std::string &baseName, API::IFunction_sptr function, + std::shared_ptr domain, std::shared_ptr values, + const std::string &outputWorkspacePropertyName = "OutputWorkspace") { UNUSED_ARG(baseName); UNUSED_ARG(function); UNUSED_ARG(domain); @@ -142,10 +136,8 @@ using IDomainCreator_sptr = std::shared_ptr; * subscribe method. * The id is the key that should be used to create the object */ -#define DECLARE_DOMAINCREATOR(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper \ - register_alg_##classname(((Mantid::API::DomainCreatorFactory::Instance() \ - .subscribe(#classname)), \ - 0)); \ +#define DECLARE_DOMAINCREATOR(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper \ + register_alg_##classname(((Mantid::API::DomainCreatorFactory::Instance().subscribe(#classname)), 0)); \ } diff --git a/Framework/API/inc/MantidAPI/IEventList.h b/Framework/API/inc/MantidAPI/IEventList.h index 98943a88414bdbdcd1c7f34492641a8e24615bb9..54a8959422c13d41b778d41fe02647fbd2fe3a1a 100644 --- a/Framework/API/inc/MantidAPI/IEventList.h +++ b/Framework/API/inc/MantidAPI/IEventList.h @@ -46,26 +46,19 @@ public: /// Get memory size of event list size_t getMemorySize() const override = 0; /// Get copy of counts and errors, rebinned using on the given X values - virtual void generateHistogram(const MantidVec &X, MantidVec &Y, MantidVec &E, - bool skipError = false) const = 0; + virtual void generateHistogram(const MantidVec &X, MantidVec &Y, MantidVec &E, bool skipError = false) const = 0; /// Get copy of counts and errors rebinned using the given X values w.r.t /// pulse time. - virtual void generateHistogramPulseTime(const MantidVec &X, MantidVec &Y, - MantidVec &E, + virtual void generateHistogramPulseTime(const MantidVec &X, MantidVec &Y, MantidVec &E, bool skipError = false) const = 0; /// Get copy of counts and errors rebinning using the given X values w.r.t /// absolute time at the sample. - virtual void generateHistogramTimeAtSample(const MantidVec &X, MantidVec &Y, - MantidVec &E, - const double &tofFactor, - const double &tofOffset, - bool skipError = false) const = 0; + virtual void generateHistogramTimeAtSample(const MantidVec &X, MantidVec &Y, MantidVec &E, const double &tofFactor, + const double &tofOffset, bool skipError = false) const = 0; /// Integrate the event list - virtual double integrate(const double minX, const double maxX, - const bool entireRange) const = 0; + virtual double integrate(const double minX, const double maxX, const bool entireRange) const = 0; /// Convert the TOF values - virtual void convertTof(std::function func, - const int sorting = 0) = 0; + virtual void convertTof(std::function func, const int sorting = 0) = 0; /// Convert the TOF values virtual void convertTof(const double factor, const double offset = 0.) = 0; /// Scale the TOF values by a constant @@ -93,8 +86,7 @@ public: /// Return the list of event weight error values virtual void getWeightErrors(std::vector &weightErrors) const = 0; /// Return the list of pulse time values - virtual std::vector - getPulseTimes() const = 0; + virtual std::vector getPulseTimes() const = 0; /// Get the minimum TOF from the list virtual double getTofMin() const = 0; /// Get the maximum TOF from the list @@ -104,13 +96,11 @@ public: /// Get the maximum pulse time from the list virtual Mantid::Types::Core::DateAndTime getPulseTimeMax() const = 0; /// Get the maximum time at sample. - virtual Mantid::Types::Core::DateAndTime - getTimeAtSampleMax(const double &tofFactor, - const double &tofOffset) const = 0; + virtual Mantid::Types::Core::DateAndTime getTimeAtSampleMax(const double &tofFactor, + const double &tofOffset) const = 0; /// Get the minimum time at sample - virtual Mantid::Types::Core::DateAndTime - getTimeAtSampleMin(const double &tofFactor, - const double &tofOffset) const = 0; + virtual Mantid::Types::Core::DateAndTime getTimeAtSampleMin(const double &tofFactor, + const double &tofOffset) const = 0; /// Set the TOFs from the given list virtual void setTofs(const MantidVec &tofs) = 0; /// Multiply event list by a constant with error @@ -118,11 +108,9 @@ public: /// Divide event list by a constant with error virtual void divide(const double value, const double error = 0.0) = 0; /// Multiply event list by a histogram - virtual void multiply(const MantidVec &X, const MantidVec &Y, - const MantidVec &E) = 0; + virtual void multiply(const MantidVec &X, const MantidVec &Y, const MantidVec &E) = 0; /// Divide event list by a histogram - virtual void divide(const MantidVec &X, const MantidVec &Y, - const MantidVec &E) = 0; + virtual void divide(const MantidVec &X, const MantidVec &Y, const MantidVec &E) = 0; }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/IEventWorkspace.h b/Framework/API/inc/MantidAPI/IEventWorkspace.h index f94cbac1ec2b67760a333de7b26ce8afaa5ce0f5..698a74f997485408441d1a902b1236d6e6e5815d 100644 --- a/Framework/API/inc/MantidAPI/IEventWorkspace.h +++ b/Framework/API/inc/MantidAPI/IEventWorkspace.h @@ -21,16 +21,13 @@ namespace API { */ class MANTID_API_DLL IEventWorkspace : public MatrixWorkspace { public: - IEventWorkspace( - const Parallel::StorageMode storageMode = Parallel::StorageMode::Cloned) + IEventWorkspace(const Parallel::StorageMode storageMode = Parallel::StorageMode::Cloned) : MatrixWorkspace(storageMode) {} IEventWorkspace &operator=(const IEventWorkspace &) = delete; /// Returns a clone of the workspace IEventWorkspace_uptr clone() const { return IEventWorkspace_uptr(doClone()); } /// Returns a default-initialized clone of the workspace - IEventWorkspace_uptr cloneEmpty() const { - return IEventWorkspace_uptr(doCloneEmpty()); - } + IEventWorkspace_uptr cloneEmpty() const { return IEventWorkspace_uptr(doCloneEmpty()); } IEventList &getSpectrum(const size_t index) override = 0; const IEventList &getSpectrum(const size_t index) const override = 0; @@ -42,13 +39,10 @@ public: virtual double getTofMax() const = 0; virtual Mantid::Types::Core::DateAndTime getPulseTimeMax() const = 0; virtual Mantid::Types::Core::DateAndTime getPulseTimeMin() const = 0; - virtual Mantid::Types::Core::DateAndTime - getTimeAtSampleMax(double tofOffset = 0) const = 0; - virtual Mantid::Types::Core::DateAndTime - getTimeAtSampleMin(double tofOffset = 0) const = 0; + virtual Mantid::Types::Core::DateAndTime getTimeAtSampleMax(double tofOffset = 0) const = 0; + virtual Mantid::Types::Core::DateAndTime getTimeAtSampleMin(double tofOffset = 0) const = 0; virtual EventType getEventType() const = 0; - void generateHistogram(const std::size_t index, const MantidVec &X, - MantidVec &Y, MantidVec &E, + void generateHistogram(const std::size_t index, const MantidVec &X, MantidVec &Y, MantidVec &E, bool skipError = false) const override = 0; virtual void setAllX(const HistogramData::BinEdges &x) = 0; diff --git a/Framework/API/inc/MantidAPI/IFileLoader.h b/Framework/API/inc/MantidAPI/IFileLoader.h index 1f5c0c2fb513b6efdd6a2585bdb68edf16ec8c03..907800a31a49b93524b00949fa2b326d5f4b63d8 100644 --- a/Framework/API/inc/MantidAPI/IFileLoader.h +++ b/Framework/API/inc/MantidAPI/IFileLoader.h @@ -16,8 +16,7 @@ Defines an interface to an algorithm that loads a file so that it can take part in the automatic selection procedure provided by the FileLoaderRegistry. */ -template -class MANTID_API_DLL IFileLoader : public ParallelAlgorithm { +template class MANTID_API_DLL IFileLoader : public ParallelAlgorithm { public: /// Returns a confidence value that this algorithm can load a file virtual int confidence(DescriptorType &descriptor) const = 0; diff --git a/Framework/API/inc/MantidAPI/IFuncMinimizer.h b/Framework/API/inc/MantidAPI/IFuncMinimizer.h index 81636f09d5f1ef3b281e037043971532b2d9252d..c14bd62d4f6191af6066dca9859a24389b0b830a 100644 --- a/Framework/API/inc/MantidAPI/IFuncMinimizer.h +++ b/Framework/API/inc/MantidAPI/IFuncMinimizer.h @@ -28,8 +28,7 @@ public: /// Initialize minimizer. /// @param function :: Function to minimize /// @param maxIterations :: Maximum number of iterations. - virtual void initialize(API::ICostFunction_sptr function, - size_t maxIterations = 1000) = 0; + virtual void initialize(API::ICostFunction_sptr function, size_t maxIterations = 1000) = 0; /// Get name of minimizer virtual std::string name() const = 0; diff --git a/Framework/API/inc/MantidAPI/IFunction.h b/Framework/API/inc/MantidAPI/IFunction.h index 18160216d5cde8107e5cfea383e4dbd5098c4b55..c60f0ba818a01e9748e58537fd71c3e27c0fd9a5 100644 --- a/Framework/API/inc/MantidAPI/IFunction.h +++ b/Framework/API/inc/MantidAPI/IFunction.h @@ -51,11 +51,8 @@ class FunctionHandler; * double attribute* * It functions by inheriting the () operator defined in each lambda */ -template struct AttributeLambdaVisitor : Ts... { - using Ts::operator()...; -}; -template -AttributeLambdaVisitor(Ts...)->AttributeLambdaVisitor; +template struct AttributeLambdaVisitor : Ts... { using Ts::operator()...; }; +template AttributeLambdaVisitor(Ts...) -> AttributeLambdaVisitor; /** This is an interface to a fitting function - a semi-abstarct class. Functions derived from IFunction can be used with the Fit algorithm. @@ -171,8 +168,7 @@ public: * implement the virtual AttributeVisitor::apply methods. See * implementation of Attribute::value() method for an example. */ - template - class DLLExport AttributeVisitor : public boost::static_visitor { + template class DLLExport AttributeVisitor : public boost::static_visitor { public: /// Virtual destructor virtual ~AttributeVisitor() = default; @@ -203,8 +199,7 @@ public: /** * Const version of AttributeVisitor. */ - template - class DLLExport ConstAttributeVisitor : public boost::static_visitor { + template class DLLExport ConstAttributeVisitor : public boost::static_visitor { public: /// Virtual destructor virtual ~ConstAttributeVisitor() = default; @@ -240,8 +235,7 @@ public: /// Create empty string attribute explicit Attribute() : m_data(std::string()), m_quoteValue(false) {} /// Create string attribute - explicit Attribute(const std::string &str, bool quoteValue = false) - : m_data(str), m_quoteValue(quoteValue) {} + explicit Attribute(const std::string &str, bool quoteValue = false) : m_data(str), m_quoteValue(quoteValue) {} /// Create int attribute explicit Attribute(const int &i) : m_data(i), m_quoteValue(false) {} /// Create double attribute @@ -249,24 +243,16 @@ public: /// Create bool attribute explicit Attribute(const bool &b) : m_data(b), m_quoteValue(false) {} /// Create string attribute - explicit Attribute(const char *c) - : m_data(std::string(c)), m_quoteValue(false) {} + explicit Attribute(const char *c) : m_data(std::string(c)), m_quoteValue(false) {} /// Create vector attribute - explicit Attribute(const std::vector &v) - : m_data(v), m_quoteValue(false) {} + explicit Attribute(const std::vector &v) : m_data(v), m_quoteValue(false) {} /// Apply an attribute visitor - template T apply(AttributeVisitor &v) { - return boost::apply_visitor(v, m_data); - } + template T apply(AttributeVisitor &v) { return boost::apply_visitor(v, m_data); } /// Apply a const attribute visitor - template T apply(ConstAttributeVisitor &v) const { - return boost::apply_visitor(v, m_data); - } + template T apply(ConstAttributeVisitor &v) const { return boost::apply_visitor(v, m_data); } /// Apply a lambda visitor - template void apply(AttributeLambdaVisitor &v) { - boost::apply_visitor(v, m_data); - } + template void apply(AttributeLambdaVisitor &v) { boost::apply_visitor(v, m_data); } /// Returns type of the attribute std::string type() const; @@ -312,38 +298,36 @@ public: private: /// The data holder as boost variant - mutable boost::variant> - m_data; + mutable boost::variant> m_data; /// Flag indicating if the string value should be returned quoted bool m_quoteValue = false; }; //---------------------------------------------------------// - /// Constructor - IFunction() : m_isParallel(false), m_handler(nullptr), m_chiSquared(0.0) {} + IFunction(); /// Virtual destructor virtual ~IFunction(); /// No copying IFunction(const IFunction &) = delete; /// No copying IFunction &operator=(const IFunction &) = delete; - /// Returns the function's name virtual std::string name() const = 0; /// Writes itself into a string std::string asString() const; /// Virtual copy constructor virtual std::shared_ptr clone() const; + + /** Registers the usage of the algorithm with the UsageService + */ + virtual void registerFunctionUsage(bool internal); /// Set the workspace. /// @param ws :: Shared pointer to a workspace - virtual void setWorkspace(std::shared_ptr ws) { - UNUSED_ARG(ws); - } + virtual void setWorkspace(std::shared_ptr ws) { UNUSED_ARG(ws); } /// Set matrix workspace - virtual void - setMatrixWorkspace(std::shared_ptr workspace, - size_t wi, double startX, double endX); + virtual void setMatrixWorkspace(std::shared_ptr workspace, size_t wi, double startX, + double endX); /// Iinialize the function virtual void initialize() { this->init(); } /// Returns an estimate of the number of progress reports a single evaluation @@ -374,8 +358,7 @@ public: /// @param domain :: Provides arguments for the function. /// @param values :: A buffer to store the function values. It must be large /// enogh to store domain.size() values. - virtual void function(const FunctionDomain &domain, - FunctionValues &values) const = 0; + virtual void function(const FunctionDomain &domain, FunctionValues &values) const = 0; /// Derivatives of function with respect to active parameters. virtual void functionDeriv(const FunctionDomain &domain, Jacobian &jacobian); @@ -389,19 +372,15 @@ public: /** @name Function parameters */ //@{ /// Set i-th parameter - virtual void setParameter(size_t, const double &value, - bool explicitlySet = true) = 0; + virtual void setParameter(size_t, const double &value, bool explicitlySet = true) = 0; /// Set i-th parameter description - virtual void setParameterDescription(size_t, - const std::string &description) = 0; + virtual void setParameterDescription(size_t, const std::string &description) = 0; /// Get i-th parameter virtual double getParameter(size_t i) const = 0; /// Set parameter by name. - virtual void setParameter(const std::string &name, const double &value, - bool explicitlySet = true) = 0; + virtual void setParameter(const std::string &name, const double &value, bool explicitlySet = true) = 0; /// Set description of parameter by name. - virtual void setParameterDescription(const std::string &name, - const std::string &description) = 0; + virtual void setParameterDescription(const std::string &name, const std::string &description) = 0; /// Get parameter by name. virtual double getParameter(const std::string &name) const = 0; /// Check if function has a parameter with this name. @@ -472,8 +451,7 @@ public: /** @name Ties */ //@{ /// Tie a parameter to other parameters (or a constant) - virtual void tie(const std::string &parName, const std::string &expr, - bool isDefault = false); + virtual void tie(const std::string &parName, const std::string &expr, bool isDefault = false); /// Add several ties virtual void addTies(const std::string &ties, bool isDefault = false); /// Apply the ties @@ -502,8 +480,7 @@ public: [[nodiscard]] virtual IConstraint *getConstraint(size_t i) const; /// Remove a constraint virtual void removeConstraint(const std::string &parName); - virtual void setConstraintPenaltyFactor(const std::string &parName, - const double &c); + virtual void setConstraintPenaltyFactor(const std::string &parName, const double &c); /// Write a parameter constraint to a string [[nodiscard]] std::string writeConstraints() const; /// Remove all constraints. @@ -525,8 +502,7 @@ public: /// Check if attribute attName exists [[nodiscard]] virtual bool hasAttribute(const std::string &name) const; /// Set an attribute value - template - void setAttributeValue(const std::string &attName, const T &value) { + template void setAttributeValue(const std::string &attName, const T &value) { // Since we can't know T and we would rather not create a universal setter // copy and replace in-place auto attr = getAttribute(attName); @@ -544,31 +520,24 @@ public: /// Set up the function for a fit. virtual void setUpForFit(); /// Get number of values for a given domain. - [[nodiscard]] virtual size_t - getValuesSize(const FunctionDomain &domain) const; + [[nodiscard]] virtual size_t getValuesSize(const FunctionDomain &domain) const; /// Get number of domains required by this function [[nodiscard]] virtual size_t getNumberDomains() const; /// Split this function (if needed) into a list of independent functions. - [[nodiscard]] virtual std::vector> - createEquivalentFunctions() const; + [[nodiscard]] virtual std::vector> createEquivalentFunctions() const; /// Calculate numerical derivatives void calNumericalDeriv(const FunctionDomain &domain, Jacobian &jacobian); /// Set the covariance matrix - void - setCovarianceMatrix(const std::shared_ptr> &covar); + void setCovarianceMatrix(const std::shared_ptr> &covar); /// Get the covariance matrix - std::shared_ptr> getCovarianceMatrix() const { - return m_covar; - } + std::shared_ptr> getCovarianceMatrix() const { return m_covar; } /// Set the reduced chi^2 void setReducedChiSquared(double chi2) { m_chiSquared = chi2; } /// Get the reduced chi^2 [[nodiscard]] double getReducedChiSquared() const { return m_chiSquared; } /// Set the parallel hint - void setParallel(bool on) { - m_isParallel = on; - } + void setParallel(bool on) { m_isParallel = on; } /// Get the parallel hint [[nodiscard]] bool isParallel() const { return m_isParallel; } @@ -583,12 +552,7 @@ public: /// FixedByDefault: Fixed by default, don't show in ties of /// the output string. /// Tied: Value depends on values of other parameters. - enum ParameterStatus { - Active, - Fixed, - FixedByDefault, - Tied - }; + enum ParameterStatus { Active, Fixed, FixedByDefault, Tied }; /// Change status of parameter virtual void setParameterStatus(size_t i, ParameterStatus status) = 0; /// Get status of parameter @@ -598,18 +562,14 @@ protected: /// Function initialization. Declare function parameters in this method. virtual void init(); /// Declare a new parameter - virtual void declareParameter(const std::string &name, double initValue = 0, - const std::string &description = "") = 0; + virtual void declareParameter(const std::string &name, double initValue = 0, const std::string &description = "") = 0; /// Convert a value from one unit (inUnit) to unit defined in workspace (ws) - [[nodiscard]] double - convertValue(double value, Kernel::Unit_sptr &outUnit, - const std::shared_ptr &ws, - size_t wsIndex) const; + [[nodiscard]] double convertValue(double value, Kernel::Unit_sptr &outUnit, + const std::shared_ptr &ws, size_t wsIndex) const; void convertValue(std::vector &values, Kernel::Unit_sptr &outUnit, - const std::shared_ptr &ws, - size_t wsIndex) const; + const std::shared_ptr &ws, size_t wsIndex) const; /// Override to declare function attributes virtual void declareAttributes() {} @@ -617,21 +577,17 @@ protected: virtual void declareParameters() {} /// Declare a single attribute - void declareAttribute(const std::string &name, - const API::IFunction::Attribute &defaultValue); + void declareAttribute(const std::string &name, const API::IFunction::Attribute &defaultValue); /// Store an attribute's value - void storeAttributeValue(const std::string &name, - const API::IFunction::Attribute &value); + void storeAttributeValue(const std::string &name, const API::IFunction::Attribute &value); /// A read-only ("mutable") attribute can be stored in a const method - void storeReadOnlyAttribute(const std::string &name, - const API::IFunction::Attribute &value) const; + void storeReadOnlyAttribute(const std::string &name, const API::IFunction::Attribute &value) const; /// Add a new tie. Derived classes must provide storage for ties virtual void addTie(std::unique_ptr tie); [[nodiscard]] bool hasOrderedTies() const; void applyOrderedTies(); /// Writes itself into a string - [[nodiscard]] virtual std::string - writeToString(const std::string &parentLocalAttributesStr = "") const; + [[nodiscard]] virtual std::string writeToString(const std::string &parentLocalAttributesStr = "") const; friend class ParameterTie; friend class CompositeFunction; @@ -660,6 +616,8 @@ private: std::vector> m_constraints; /// Ties ordered in order of correct application std::vector m_orderedTies; + /// whether the function usage has been registered + bool m_isRegistered{false}; }; /// shared pointer to the function base class diff --git a/Framework/API/inc/MantidAPI/IFunction1D.h b/Framework/API/inc/MantidAPI/IFunction1D.h index d47e22d803e1aa870c50f6dbfeade2c6fccb87f3..c7416a505cc4a58fb3ac6ea5bf80690a8b45ab9c 100644 --- a/Framework/API/inc/MantidAPI/IFunction1D.h +++ b/Framework/API/inc/MantidAPI/IFunction1D.h @@ -44,40 +44,31 @@ class MANTID_API_DLL IFunction1D : public virtual IFunction { public: /* Overidden methods */ - void function(const FunctionDomain &domain, - FunctionValues &values) const override; + void function(const FunctionDomain &domain, FunctionValues &values) const override; void functionDeriv(const FunctionDomain &domain, Jacobian &jacobian) override; - virtual void derivative(const FunctionDomain &domain, FunctionValues &values, - const size_t order = 1) const; + virtual void derivative(const FunctionDomain &domain, FunctionValues &values, const size_t order = 1) const; /// Function you want to fit to. - virtual void function1D(double *out, const double *xValues, - const size_t nData) const = 0; + virtual void function1D(double *out, const double *xValues, const size_t nData) const = 0; /// Function to calculate the derivatives of the data set - virtual void derivative1D(double *out, const double *xValues, - const size_t nData, const size_t order) const; + virtual void derivative1D(double *out, const double *xValues, const size_t nData, const size_t order) const; /// Derivatives of function with respect to active parameters - virtual void functionDeriv1D(Jacobian *jacobian, const double *xValues, - const size_t nData); + virtual void functionDeriv1D(Jacobian *jacobian, const double *xValues, const size_t nData); protected: template - using Function1DMethod = void (FunctionType::*)(double *, const double *, - const size_t) const; + using Function1DMethod = void (FunctionType::*)(double *, const double *, const size_t) const; /// Calculate a numerical derivative for the 1D data template - void calcNumericalDerivative1D(Jacobian *jacobian, EvaluationMethod func1D, - const double *xValues, const size_t nData); + void calcNumericalDerivative1D(Jacobian *jacobian, EvaluationMethod func1D, const double *xValues, + const size_t nData); /// Calculate histogram data for the given bin boundaries. - virtual void histogram1D(double *out, double left, const double *right, - const size_t nBins) const; + virtual void histogram1D(double *out, double left, const double *right, const size_t nBins) const; /// Derivatives of the histogram1D with respect to active parameters. - virtual void histogramDerivative1D(Jacobian *jacobian, double left, - const double *right, - const size_t nBins) const; + virtual void histogramDerivative1D(Jacobian *jacobian, double left, const double *right, const size_t nBins) const; /// Logger instance static Kernel::Logger g_log; diff --git a/Framework/API/inc/MantidAPI/IFunction1D.tcc b/Framework/API/inc/MantidAPI/IFunction1D.tcc index 019683040cfc04147c926c506439e7c796e00a7d..aa8275721d83a43d1c8d8c0fe3a5621427c9a820 100644 --- a/Framework/API/inc/MantidAPI/IFunction1D.tcc +++ b/Framework/API/inc/MantidAPI/IFunction1D.tcc @@ -13,9 +13,7 @@ namespace Mantid { namespace API { template -void IFunction1D::calcNumericalDerivative1D(Jacobian *jacobian, - EvaluationMethod eval1D, - const double *xValues, +void IFunction1D::calcNumericalDerivative1D(Jacobian *jacobian, EvaluationMethod eval1D, const double *xValues, const size_t nData) { /* * Uses the knowledge that this is a simple 1D domain to calculate the @@ -30,8 +28,7 @@ void IFunction1D::calcNumericalDerivative1D(Jacobian *jacobian, using std::fabs; constexpr double epsilon(std::numeric_limits::epsilon() * 100); constexpr double stepPercentage(0.001); - constexpr double cutoff = - 100.0 * std::numeric_limits::min() / stepPercentage; + constexpr double cutoff = 100.0 * std::numeric_limits::min() / stepPercentage; applyTies(); // just in case std::vector minusStep(nData), plusStep(nData); diff --git a/Framework/API/inc/MantidAPI/IFunction1DSpectrum.h b/Framework/API/inc/MantidAPI/IFunction1DSpectrum.h index c2ce53bb8968bc65e1e4af75c30e5b0b1f98ac44..c5b33ca090f1cb9f3482c42eeadb3fc58adc9f50 100644 --- a/Framework/API/inc/MantidAPI/IFunction1DSpectrum.h +++ b/Framework/API/inc/MantidAPI/IFunction1DSpectrum.h @@ -25,19 +25,16 @@ namespace API { */ class MANTID_API_DLL IFunction1DSpectrum : public virtual IFunction { public: - void function(const FunctionDomain &domain, - FunctionValues &values) const override; + void function(const FunctionDomain &domain, FunctionValues &values) const override; void functionDeriv(const FunctionDomain &domain, Jacobian &jacobian) override; /// Provide a concrete function in an implementation that operates on a /// FunctionDomain1DSpectrum. - virtual void function1DSpectrum(const FunctionDomain1DSpectrum &domain, - FunctionValues &values) const = 0; + virtual void function1DSpectrum(const FunctionDomain1DSpectrum &domain, FunctionValues &values) const = 0; /// Derivatives of the function. The base implementation calculates numerical /// derivatives. - virtual void functionDeriv1DSpectrum(const FunctionDomain1DSpectrum &domain, - Jacobian &jacobian); + virtual void functionDeriv1DSpectrum(const FunctionDomain1DSpectrum &domain, Jacobian &jacobian); protected: static Kernel::Logger g_log; diff --git a/Framework/API/inc/MantidAPI/IFunctionGeneral.h b/Framework/API/inc/MantidAPI/IFunctionGeneral.h index b87db3c691a04fc1974189b2b0f46ce40098a2a0..4f08aa3bdccbfe4fa9edb633cf3a694a2eb68aef 100644 --- a/Framework/API/inc/MantidAPI/IFunctionGeneral.h +++ b/Framework/API/inc/MantidAPI/IFunctionGeneral.h @@ -25,16 +25,14 @@ namespace API { */ class MANTID_API_DLL IFunctionGeneral : public virtual IFunction { public: - void function(const FunctionDomain &domain, - FunctionValues &values) const override; + void function(const FunctionDomain &domain, FunctionValues &values) const override; void functionDeriv(const FunctionDomain &domain, Jacobian &jacobian) override; size_t getValuesSize(const FunctionDomain &domain) const override; /// Provide a concrete function in an implementation that operates on a /// FunctionDomainGeneral. - virtual void functionGeneral(const FunctionDomainGeneral &domain, - FunctionValues &values) const = 0; + virtual void functionGeneral(const FunctionDomainGeneral &domain, FunctionValues &values) const = 0; /// Get number of columns that the domain must have. /// If consider the collection of these columns as a table diff --git a/Framework/API/inc/MantidAPI/IFunctionMD.h b/Framework/API/inc/MantidAPI/IFunctionMD.h index 9bdd92a76984ba1bd73bdef1acdc98af77d32e5a..1dfbd96f8aecfbac57000c388610da900ae6bd67 100644 --- a/Framework/API/inc/MantidAPI/IFunctionMD.h +++ b/Framework/API/inc/MantidAPI/IFunctionMD.h @@ -57,17 +57,12 @@ public: /// @param ws :: Shared pointer to a workspace void setWorkspace(std::shared_ptr ws) override; - void function(const FunctionDomain &domain, - FunctionValues &values) const override; - void functionDeriv(const FunctionDomain &domain, - Jacobian &jacobian) override { - calNumericalDeriv(domain, jacobian); - } + void function(const FunctionDomain &domain, FunctionValues &values) const override; + void functionDeriv(const FunctionDomain &domain, Jacobian &jacobian) override { calNumericalDeriv(domain, jacobian); } protected: /// Performs the function evaluations on the MD domain - void evaluateFunction(const FunctionDomainMD &domain, - FunctionValues &values) const; + void evaluateFunction(const FunctionDomainMD &domain, FunctionValues &values) const; virtual void useDimension(const std::string &id); /// Do finction initialization after useAllDimensions() was called @@ -78,8 +73,7 @@ protected: /// maps dimension id to its index in m_dimensions std::map m_dimensionIndexMap; /// dimensions used in this function in the expected order - std::vector> - m_dimensions; + std::vector> m_dimensions; private: /// Use all the dimensions in the workspace diff --git a/Framework/API/inc/MantidAPI/IFunctionMW.h b/Framework/API/inc/MantidAPI/IFunctionMW.h index 689d1d547ebdabe7f2522044b5cbb514454ae12d..6fc3b88d892a413ccef49aacc2610277c94be2b5 100644 --- a/Framework/API/inc/MantidAPI/IFunctionMW.h +++ b/Framework/API/inc/MantidAPI/IFunctionMW.h @@ -30,8 +30,8 @@ namespace API { class MANTID_API_DLL IFunctionMW : public virtual IFunction { public: /// Set MatrixWorkspace - void setMatrixWorkspace(std::shared_ptr workspace, - size_t wi, double startX, double endX) override; + void setMatrixWorkspace(std::shared_ptr workspace, size_t wi, double startX, + double endX) override; /// Get shared pointer to the workspace std::shared_ptr getMatrixWorkspace() const; /// Get the workspace index diff --git a/Framework/API/inc/MantidAPI/IFunctionWithLocation.h b/Framework/API/inc/MantidAPI/IFunctionWithLocation.h index 0a2e1c2b6d7b36573b19585e8c7af8e3028e0731..7d7d38fb0562852bfccd856096ac490ce7c0cf15 100644 --- a/Framework/API/inc/MantidAPI/IFunctionWithLocation.h +++ b/Framework/API/inc/MantidAPI/IFunctionWithLocation.h @@ -23,8 +23,7 @@ namespace API { @author Anders Markvardsen, ISIS, RAL @date 2/11/2009 */ -class MANTID_API_DLL IFunctionWithLocation : public virtual ParamFunction, - public virtual IFunction1D { +class MANTID_API_DLL IFunctionWithLocation : public virtual ParamFunction, public virtual IFunction1D { public: /// Virtual destructor /// (avoids warnings about non-trivial move assignment in virtually inheriting @@ -55,15 +54,11 @@ public: /// don't show it in ties virtual void fixCentre(bool isDefault = false) { UNUSED_ARG(isDefault); - throw std::runtime_error( - "Generic centre fixing isn't implemented for this function."); + throw std::runtime_error("Generic centre fixing isn't implemented for this function."); } /// Free the centre parameter. - virtual void unfixCentre() { - throw std::runtime_error( - "Generic centre fixing isn't implemented for this function."); - } + virtual void unfixCentre() { throw std::runtime_error("Generic centre fixing isn't implemented for this function."); } }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/IFunction_fwd.h b/Framework/API/inc/MantidAPI/IFunction_fwd.h index f3184382c7987a3d4afa845b21311c54699f16bb..b8e47218394e1614c0a0fc2d63390ec8230e7138 100644 --- a/Framework/API/inc/MantidAPI/IFunction_fwd.h +++ b/Framework/API/inc/MantidAPI/IFunction_fwd.h @@ -34,8 +34,7 @@ class MultiDomainFunction; /// Shared pointer to Mantid::API::MultiDomainFunction using MultiDomainFunction_sptr = std::shared_ptr; /// Shared pointer to Mantid::API::MultiDomainFunction (const version) -using MultiDomainFunction_const_sptr = - std::shared_ptr; +using MultiDomainFunction_const_sptr = std::shared_ptr; } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/IJournal.h b/Framework/API/inc/MantidAPI/IJournal.h index 6dd6f10f34a86339a970a948bc78f9b34ac0c829..dc5e15673a54d509862923fe83c3e195250834b4 100644 --- a/Framework/API/inc/MantidAPI/IJournal.h +++ b/Framework/API/inc/MantidAPI/IJournal.h @@ -30,9 +30,8 @@ public: /// Get the list of cycle names virtual std::vector getCycleNames() = 0; /// Get data for runs that match the given filters - virtual std::vector - getRuns(std::vector const &valuesToLookup = {}, - RunData const &filters = RunData()) = 0; + virtual std::vector getRuns(std::vector const &valuesToLookup = {}, + RunData const &filters = RunData()) = 0; }; } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/ILatticeFunction.h b/Framework/API/inc/MantidAPI/ILatticeFunction.h index 186a11ab1a2696f675ed6eb0cb3084c6a7d64015..5a1251e11d2334003daacf24288afe08d62aa4ee 100644 --- a/Framework/API/inc/MantidAPI/ILatticeFunction.h +++ b/Framework/API/inc/MantidAPI/ILatticeFunction.h @@ -27,17 +27,14 @@ class MANTID_API_DLL ILatticeFunction : public FunctionParameterDecorator { public: ILatticeFunction(); - void function(const FunctionDomain &domain, - FunctionValues &values) const override; + void function(const FunctionDomain &domain, FunctionValues &values) const override; void functionDeriv(const FunctionDomain &domain, Jacobian &jacobian) override; /// Function that should calculate d-values for the HKLs provided in the /// domain. - virtual void functionLattice(const LatticeDomain &latticeDomain, - FunctionValues &values) const = 0; + virtual void functionLattice(const LatticeDomain &latticeDomain, FunctionValues &values) const = 0; - virtual void functionDerivLattice(const LatticeDomain &latticeDomain, - Jacobian &jacobian); + virtual void functionDerivLattice(const LatticeDomain &latticeDomain, Jacobian &jacobian); /// A string that names the crystal system. virtual void setLatticeSystem(const std::string &crystalSystem) = 0; diff --git a/Framework/API/inc/MantidAPI/ILiveListener.h b/Framework/API/inc/MantidAPI/ILiveListener.h index 1da18c2128ec6306713fbc850f7c3bb651adad65..d424a283168d25b7911d37692ac3d842f893571a 100644 --- a/Framework/API/inc/MantidAPI/ILiveListener.h +++ b/Framework/API/inc/MantidAPI/ILiveListener.h @@ -65,8 +65,7 @@ public: * The value of 'start of run' is 1 second * for compatibility with the SNS live stream and ISIS Kafka live stream. */ - virtual void - start(Types::Core::DateAndTime startTime = Types::Core::DateAndTime()) = 0; + virtual void start(Types::Core::DateAndTime startTime = Types::Core::DateAndTime()) = 0; /** Get the data that's been buffered since the last call to this method * (or since start() was called). diff --git a/Framework/API/inc/MantidAPI/IMDEventWorkspace.h b/Framework/API/inc/MantidAPI/IMDEventWorkspace.h index e150a388681dc3ec4d7435f79172e9c6ff46608c..1b941f72f93adb67db1c675a9d1f5b6dd1764ec2 100644 --- a/Framework/API/inc/MantidAPI/IMDEventWorkspace.h +++ b/Framework/API/inc/MantidAPI/IMDEventWorkspace.h @@ -33,28 +33,22 @@ namespace API { * @date Dec 3, 2010 * * */ -class MANTID_API_DLL IMDEventWorkspace : public API::IMDWorkspace, - public API::MultipleExperimentInfos { +class MANTID_API_DLL IMDEventWorkspace : public API::IMDWorkspace, public API::MultipleExperimentInfos { public: IMDEventWorkspace(); /// Returns a clone of the workspace - IMDEventWorkspace_uptr clone() const { - return IMDEventWorkspace_uptr(doClone()); - } + IMDEventWorkspace_uptr clone() const { return IMDEventWorkspace_uptr(doClone()); } /// Returns a default-initialized clone of the workspace - IMDEventWorkspace_uptr cloneEmpty() const { - return IMDEventWorkspace_uptr(doCloneEmpty()); - } + IMDEventWorkspace_uptr cloneEmpty() const { return IMDEventWorkspace_uptr(doCloneEmpty()); } /// Perform initialization after dimensions (and others) have been set. virtual void initialize() = 0; IMDEventWorkspace &operator=(const IMDEventWorkspace &) = delete; /// Get the minimum extents that hold the data - virtual std::vector> - getMinimumExtents(size_t depth = 2) const = 0; + virtual std::vector> getMinimumExtents(size_t depth = 2) const = 0; /// Returns some information about the box controller, to be displayed in the /// GUI, for example @@ -63,8 +57,7 @@ public: virtual Mantid::API::BoxController_sptr getBoxController() = 0; virtual Mantid::API::BoxController_const_sptr getBoxController() const = 0; - virtual void getBoxes(std::vector &boxes, size_t maxDepth, - bool leafOnly) = 0; + virtual void getBoxes(std::vector &boxes, size_t maxDepth, bool leafOnly) = 0; /// @return true if the workspace is file-backed virtual bool isFileBacked() const = 0; @@ -95,24 +88,19 @@ public: bool threadSafe() const override; - virtual void setCoordinateSystem( - const Mantid::Kernel::SpecialCoordinateSystem coordinateSystem) = 0; + virtual void setCoordinateSystem(const Mantid::Kernel::SpecialCoordinateSystem coordinateSystem) = 0; /// Preferred visual normalizaiton method for any histo workspaces created /// from this. - virtual void setDisplayNormalizationHisto( - Mantid::API::MDNormalization preferredNormalizationHisto) = 0; + virtual void setDisplayNormalizationHisto(Mantid::API::MDNormalization preferredNormalizationHisto) = 0; Mantid::API::MDNormalization displayNormalizationHisto() const override = 0; /// Preferred visual normalization method. - virtual void setDisplayNormalization( - Mantid::API::MDNormalization preferredNormalization) = 0; + virtual void setDisplayNormalization(Mantid::API::MDNormalization preferredNormalization) = 0; Mantid::API::MDNormalization displayNormalization() const override = 0; // Check if this class has an oriented lattice on a sample object - virtual bool hasOrientedLattice() const override { - return MultipleExperimentInfos::hasOrientedLattice(); - } + virtual bool hasOrientedLattice() const override { return MultipleExperimentInfos::hasOrientedLattice(); } virtual void setBox(API::IMDNode *box) = 0; diff --git a/Framework/API/inc/MantidAPI/IMDHistoWorkspace.h b/Framework/API/inc/MantidAPI/IMDHistoWorkspace.h index de81b93115df38e281fccb1450b1b949c17d4b8a..39b42403b1329e327e60611f88f8fbf3c8ad6de1 100644 --- a/Framework/API/inc/MantidAPI/IMDHistoWorkspace.h +++ b/Framework/API/inc/MantidAPI/IMDHistoWorkspace.h @@ -19,19 +19,14 @@ namespace API { @date 2011-11-09 */ -class MANTID_API_DLL IMDHistoWorkspace : public IMDWorkspace, - public MultipleExperimentInfos { +class MANTID_API_DLL IMDHistoWorkspace : public IMDWorkspace, public MultipleExperimentInfos { public: IMDHistoWorkspace() = default; IMDHistoWorkspace &operator=(const IMDHistoWorkspace &) = delete; /// Returns a clone of the workspace - IMDHistoWorkspace_uptr clone() const { - return IMDHistoWorkspace_uptr(doClone()); - } + IMDHistoWorkspace_uptr clone() const { return IMDHistoWorkspace_uptr(doClone()); } /// Returns a default-initialized clone of the workspace - IMDHistoWorkspace_uptr cloneEmpty() const { - return IMDHistoWorkspace_uptr(doCloneEmpty()); - } + IMDHistoWorkspace_uptr cloneEmpty() const { return IMDHistoWorkspace_uptr(doCloneEmpty()); } /// See the MDHistoWorkspace definition for descriptions of these virtual coord_t getInverseVolume() const = 0; virtual const signal_t *getSignalArray() const = 0; @@ -42,62 +37,44 @@ public: virtual signal_t *mutableErrorSquaredArray() = 0; virtual signal_t *mutableNumEventsArray() = 0; - virtual void setTo(signal_t signal, signal_t errorSquared, - signal_t numEvents) = 0; + virtual void setTo(signal_t signal, signal_t errorSquared, signal_t numEvents) = 0; virtual Mantid::Kernel::VMD getCenter(size_t linearIndex) const = 0; virtual void setSignalAt(size_t index, signal_t value) = 0; virtual void setErrorSquaredAt(size_t index, signal_t value) = 0; virtual signal_t getErrorAt(size_t index) const = 0; virtual signal_t getErrorAt(size_t index1, size_t index2) const = 0; - virtual signal_t getErrorAt(size_t index1, size_t index2, - size_t index3) const = 0; - virtual signal_t getErrorAt(size_t index1, size_t index2, size_t index3, - size_t index4) const = 0; + virtual signal_t getErrorAt(size_t index1, size_t index2, size_t index3) const = 0; + virtual signal_t getErrorAt(size_t index1, size_t index2, size_t index3, size_t index4) const = 0; virtual signal_t getSignalAt(size_t index) const = 0; virtual signal_t getSignalAt(size_t index1, size_t index2) const = 0; - virtual signal_t getSignalAt(size_t index1, size_t index2, - size_t index3) const = 0; - virtual signal_t getSignalAt(size_t index1, size_t index2, size_t index3, - size_t index4) const = 0; + virtual signal_t getSignalAt(size_t index1, size_t index2, size_t index3) const = 0; + virtual signal_t getSignalAt(size_t index1, size_t index2, size_t index3, size_t index4) const = 0; virtual signal_t getSignalNormalizedAt(size_t index) const = 0; - virtual signal_t getSignalNormalizedAt(size_t index1, - size_t index2) const = 0; - virtual signal_t getSignalNormalizedAt(size_t index1, size_t index2, - size_t index3) const = 0; - virtual signal_t getSignalNormalizedAt(size_t index1, size_t index2, - size_t index3, - size_t index4) const = 0; + virtual signal_t getSignalNormalizedAt(size_t index1, size_t index2) const = 0; + virtual signal_t getSignalNormalizedAt(size_t index1, size_t index2, size_t index3) const = 0; + virtual signal_t getSignalNormalizedAt(size_t index1, size_t index2, size_t index3, size_t index4) const = 0; virtual signal_t getErrorNormalizedAt(size_t index) const = 0; virtual signal_t getErrorNormalizedAt(size_t index1, size_t index2) const = 0; - virtual signal_t getErrorNormalizedAt(size_t index1, size_t index2, - size_t index3) const = 0; - virtual signal_t getErrorNormalizedAt(size_t index1, size_t index2, - size_t index3, size_t index4) const = 0; + virtual signal_t getErrorNormalizedAt(size_t index1, size_t index2, size_t index3) const = 0; + virtual signal_t getErrorNormalizedAt(size_t index1, size_t index2, size_t index3, size_t index4) const = 0; virtual signal_t &errorSquaredAt(size_t index) = 0; virtual signal_t &signalAt(size_t index) = 0; virtual size_t getLinearIndex(size_t index1, size_t index2) const = 0; - virtual size_t getLinearIndex(size_t index1, size_t index2, - size_t index3) const = 0; - virtual size_t getLinearIndex(size_t index1, size_t index2, size_t index3, - size_t index4) const = 0; + virtual size_t getLinearIndex(size_t index1, size_t index2, size_t index3) const = 0; + virtual size_t getLinearIndex(size_t index1, size_t index2, size_t index3, size_t index4) const = 0; - virtual LinePlot - getLineData(const Mantid::Kernel::VMD &start, const Mantid::Kernel::VMD &end, - Mantid::API::MDNormalization normalize) const = 0; + virtual LinePlot getLineData(const Mantid::Kernel::VMD &start, const Mantid::Kernel::VMD &end, + Mantid::API::MDNormalization normalize) const = 0; virtual double &operator[](const size_t &index) = 0; - virtual void setCoordinateSystem( - const Kernel::SpecialCoordinateSystem coordinateSystem) = 0; + virtual void setCoordinateSystem(const Kernel::SpecialCoordinateSystem coordinateSystem) = 0; - virtual void setDisplayNormalization( - const Mantid::API::MDNormalization &preferredNormalization) = 0; + virtual void setDisplayNormalization(const Mantid::API::MDNormalization &preferredNormalization) = 0; // Check if this class has an oriented lattice on any sample object - virtual bool hasOrientedLattice() const override { - return MultipleExperimentInfos::hasOrientedLattice(); - } + virtual bool hasOrientedLattice() const override { return MultipleExperimentInfos::hasOrientedLattice(); } protected: /// Protected copy constructor. May be used by childs for cloning. diff --git a/Framework/API/inc/MantidAPI/IMDIterator.h b/Framework/API/inc/MantidAPI/IMDIterator.h index 7684fd8a1934db8908bd301cfea279ee2b1d4698..cf1d29f18cba07af607ae615b0eb14feb4988190 100644 --- a/Framework/API/inc/MantidAPI/IMDIterator.h +++ b/Framework/API/inc/MantidAPI/IMDIterator.h @@ -74,14 +74,12 @@ public: virtual signal_t getError() const = 0; /// Return a list of vertexes defining the volume pointed to - virtual std::unique_ptr - getVertexesArray(size_t &numVertices) const = 0; + virtual std::unique_ptr getVertexesArray(size_t &numVertices) const = 0; /// Return a list of vertexes defining the volume pointed to, enable masking /// of dimensions. - virtual std::unique_ptr - getVertexesArray(size_t &numVertices, const size_t outDimensions, - const bool *maskDim) const = 0; + virtual std::unique_ptr getVertexesArray(size_t &numVertices, const size_t outDimensions, + const bool *maskDim) const = 0; /// Returns the position of the center of the box pointed to. virtual Mantid::Kernel::VMD getCenter() const = 0; @@ -89,8 +87,11 @@ public: /// Returns the number of events/points contained in this box virtual size_t getNumEvents() const = 0; - /// For a given event/point in this box, return the run index - virtual uint16_t getInnerRunIndex(size_t index) const = 0; + /// For a given event/point in this box, return the associated experiment-info index + virtual uint16_t getInnerExpInfoIndex(size_t index) const = 0; + + /// For a given event/point in this box, return the goniometer index + virtual uint16_t getInnerGoniometerIndex(size_t index) const = 0; /// For a given event/point in this box, return the detector ID virtual int32_t getInnerDetectorID(size_t index) const = 0; diff --git a/Framework/API/inc/MantidAPI/IMDNode.h b/Framework/API/inc/MantidAPI/IMDNode.h index 173aa1b95f8412e0a7fa0aedde35e743d3bb02ac..bf7928a58cd7f58988857876236ffa9d7911b100 100644 --- a/Framework/API/inc/MantidAPI/IMDNode.h +++ b/Framework/API/inc/MantidAPI/IMDNode.h @@ -48,9 +48,7 @@ public: virtual Kernel::ISaveable *getISaveable() const = 0; /** initiate the structure responsible for swapping the box on HDD if out of * memory. */ - virtual void setFileBacked(const uint64_t /*fileLocation*/, - const size_t /*fileSize*/, - const bool /*markSaved*/) = 0; + virtual void setFileBacked(const uint64_t /*fileLocation*/, const size_t /*fileSize*/, const bool /*markSaved*/) = 0; /** initiate the structure responsible for swapping the box on HDD if out of * memory with default parameters (it does not know its place on HDD and was * not saved). */ @@ -65,13 +63,11 @@ public: /**Save the box at specific disk position using the class, respoinsible for * the file IO. */ - virtual void saveAt(API::IBoxControllerIO *const /*saver */, - uint64_t /*position*/) const = 0; + virtual void saveAt(API::IBoxControllerIO *const /*saver */, uint64_t /*position*/) const = 0; /**Load the additional box data of specified size from the disk location * provided using the class, respoinsible for the file IO and append them to * the box */ - virtual void loadAndAddFrom(API::IBoxControllerIO *const /*saver */, - uint64_t /*position*/, size_t /* Size */) = 0; + virtual void loadAndAddFrom(API::IBoxControllerIO *const /*saver */, uint64_t /*position*/, size_t /* Size */) = 0; /// drop event data from memory but keep averages virtual void clearDataFromMemory() = 0; //------------------------------------------------------------- @@ -116,8 +112,7 @@ public: /// Return the indexth child MDBoxBase. virtual IMDNode *getChild(size_t index) = 0; /// Sets the children from a vector of children - virtual void setChildren(const std::vector &boxes, - const size_t indexStart, const size_t indexEnd) = 0; + virtual void setChildren(const std::vector &boxes, const size_t indexStart, const size_t indexEnd) = 0; /// Return a pointer to the parent box virtual void setParent(IMDNode *parent) = 0; /// Return a pointer to the parent box @@ -128,17 +123,14 @@ public: // box-related /// Fill a vector with all the boxes who are the childred of this one up to a /// certain depth - virtual void getBoxes(std::vector &boxes, size_t maxDepth, - bool leafOnly) = 0; + virtual void getBoxes(std::vector &boxes, size_t maxDepth, bool leafOnly) = 0; /// Fill a vector with all the boxes who are the childred of this one up to a /// certain depth and selected by the function. - virtual void getBoxes(std::vector &boxes, size_t maxDepth, - bool leafOnly, + virtual void getBoxes(std::vector &boxes, size_t maxDepth, bool leafOnly, Mantid::Geometry::MDImplicitFunction *function) = 0; /// Fill a vector with all the boxes who are satisfying the condition - virtual void getBoxes(std::vector &outBoxes, - const std::function &cond) = 0; + virtual void getBoxes(std::vector &outBoxes, const std::function &cond) = 0; // -------------------------------- Events-Related // ------------------------------------------- @@ -156,8 +148,7 @@ public: * @returns coordTable -- vector of events parameters * @return nColumns -- number of parameters for each event */ - virtual void getEventsData(std::vector &coordTable, - size_t &nColumns) const = 0; + virtual void getEventsData(std::vector &coordTable, size_t &nColumns) const = 0; /** The method to convert the table of data into vector of events * Used to load events from plain binary file * @param coordTable -- vector of events data, which would be packed into @@ -166,19 +157,15 @@ public: virtual void setEventsData(const std::vector &coordTable) = 0; /// Add a single event defined by its components - virtual void buildAndAddEvent(const signal_t Signal, const signal_t errorSq, - const std::vector &point, - uint16_t runIndex, uint32_t detectorId) = 0; + virtual void buildAndAddEvent(const signal_t Signal, const signal_t errorSq, const std::vector &point, + uint16_t expInfoIndex, uint16_t goniometerIndex, uint32_t detectorId) = 0; /// Add a single event, with no mutex locking - virtual void buildAndAddEventUnsafe(const signal_t Signal, - const signal_t errorSq, - const std::vector &point, - uint16_t runIndex, - uint32_t detectorId) = 0; + virtual void buildAndAddEventUnsafe(const signal_t Signal, const signal_t errorSq, const std::vector &point, + uint16_t expInfoIndex, uint16_t goniometerIndex, uint32_t detectorId) = 0; /// Add several events from the vector of event parameters - virtual size_t buildAndAddEvents(const std::vector &sigErrSq, - const std::vector &Coord, - const std::vector &runIndex, + virtual size_t buildAndAddEvents(const std::vector &sigErrSq, const std::vector &Coord, + const std::vector &expInfoIndex, + const std::vector &goniometerIndex, const std::vector &detectorId) = 0; // ------------------------------------------------------------------------------------------- @@ -198,11 +185,9 @@ public: * @param useOnePercentBackgroundCorrection :: if one percent correction *should be applied to background. */ - virtual void integrateSphere( - Mantid::API::CoordTransform &radiusTransform, const coord_t radiusSquared, - signal_t &signal, signal_t &errorSquared, - const coord_t innerRadiusSquared = 0.0, - const bool useOnePercentBackgroundCorrection = true) const = 0; + virtual void integrateSphere(Mantid::API::CoordTransform &radiusTransform, const coord_t radiusSquared, + signal_t &signal, signal_t &errorSquared, const coord_t innerRadiusSquared = 0.0, + const bool useOnePercentBackgroundCorrection = true) const = 0; /** Find the centroid of all events contained within by doing a weighted *average * of their coordinates. @@ -214,9 +199,8 @@ public: * @param[out] centroid :: array of size [nd]; its centroid will be added * @param[out] signal :: set to the integrated signal */ - virtual void centroidSphere(Mantid::API::CoordTransform &radiusTransform, - const coord_t radiusSquared, coord_t *centroid, - signal_t &signal) const = 0; + virtual void centroidSphere(Mantid::API::CoordTransform &radiusTransform, const coord_t radiusSquared, + coord_t *centroid, signal_t &signal) const = 0; /** Cylinder (peak) integration * The CoordTransform object could be used for more cylinder * reduces the dimensions to two values. @@ -230,21 +214,18 @@ public: * @param errorSquared [out] :: set to the integrated squared error. * @param signal_fit [out] :: array of values for the fit. */ - virtual void integrateCylinder(Mantid::API::CoordTransform &radiusTransform, - const coord_t radius, const coord_t length, - signal_t &signal, signal_t &errorSquared, + virtual void integrateCylinder(Mantid::API::CoordTransform &radiusTransform, const coord_t radius, + const coord_t length, signal_t &signal, signal_t &errorSquared, std::vector &signal_fit) const = 0; /** Split sub-boxes, if this is possible and neede for this box */ - virtual void - splitAllIfNeeded(Mantid::Kernel::ThreadScheduler * /*ts*/ = nullptr) = 0; + virtual void splitAllIfNeeded(Mantid::Kernel::ThreadScheduler * /*ts*/ = nullptr) = 0; /** Recalculate signal etc. */ virtual void refreshCache(Kernel::ThreadScheduler * /*ts*/ = nullptr) = 0; /** Calculate the centroid of this box and all sub-boxes. */ virtual void calculateCentroid(coord_t * /*centroid*/) const = 0; /** Calculate the centroid of this box and all sub-boxes. */ - virtual void calculateCentroid(coord_t * /*centroid*/, - const int /*runindex*/) const = 0; + virtual void calculateCentroid(coord_t * /*centroid*/, const int /*expInfoIndex*/) const = 0; /** Get the centroid of this box and all sub-boxes. */ virtual coord_t *getCentroid() const = 0; //---------------------------------------------------------------------------------------------------------------------------------- @@ -253,8 +234,7 @@ public: virtual signal_t getError() const = 0; virtual signal_t getErrorSquared() const = 0; virtual coord_t getInverseVolume() const = 0; - virtual Mantid::Geometry::MDDimensionExtents & - getExtents(size_t dim) = 0; + virtual Mantid::Geometry::MDDimensionExtents &getExtents(size_t dim) = 0; virtual const IMDNode *getBoxAtCoord(const coord_t * /*coords*/) = 0; virtual void getCenter(coord_t *const /*boxCenter*/) const = 0; virtual uint32_t getDepth() const = 0; @@ -268,21 +248,16 @@ public: // -------------------------------- Geometry/vertexes-Related // ------------------------------------------- virtual std::vector getVertexes() const = 0; - virtual std::unique_ptr - getVertexesArray(size_t &numVertices) const = 0; - virtual std::unique_ptr - getVertexesArray(size_t &numVertices, const size_t outDimensions, - const bool *maskDim) const = 0; - virtual void transformDimensions(std::vector &scaling, - std::vector &offset) = 0; + virtual std::unique_ptr getVertexesArray(size_t &numVertices) const = 0; + virtual std::unique_ptr getVertexesArray(size_t &numVertices, const size_t outDimensions, + const bool *maskDim) const = 0; + virtual void transformDimensions(std::vector &scaling, std::vector &offset) = 0; // to avoid casting (which need also the number of dimensions) method say if // Node is a box. if not, it is gridbox virtual bool isBox() const = 0; - virtual signal_t getSignalByNEvents() const { - return this->getSignal() / static_cast(this->getNPoints()); - } + virtual signal_t getSignalByNEvents() const { return this->getSignal() / static_cast(this->getNPoints()); } // ----------------------------- Helper Methods // -------------------------------------------------------- @@ -295,8 +270,7 @@ public: * @return */ - static inline bool CompareFilePosition(const IMDNode *const a, - const IMDNode *const b) { + static inline bool CompareFilePosition(const IMDNode *const a, const IMDNode *const b) { return (a->getID() < b->getID()); } @@ -309,9 +283,7 @@ public: * * @param boxes :: ref to a vector of boxes. It will be sorted in-place. */ - static void sortObjByID(std::vector &boxes) { - std::sort(boxes.begin(), boxes.end(), CompareFilePosition); - } + static void sortObjByID(std::vector &boxes) { std::sort(boxes.begin(), boxes.end(), CompareFilePosition); } }; } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/IMDWorkspace.h b/Framework/API/inc/MantidAPI/IMDWorkspace.h index b6ef76935760734e093d213a578aa6cbb6cb7d94..7355b43fc703636b838efef9bca4df5231d6268c 100644 --- a/Framework/API/inc/MantidAPI/IMDWorkspace.h +++ b/Framework/API/inc/MantidAPI/IMDWorkspace.h @@ -39,8 +39,7 @@ static const signal_t MDMaskValue = std::numeric_limits::quiet_NaN(); class MANTID_API_DLL IMDWorkspace : public Workspace, public API::MDGeometry { public: - IMDWorkspace( - const Parallel::StorageMode storageMode = Parallel::StorageMode::Cloned); + IMDWorkspace(const Parallel::StorageMode storageMode = Parallel::StorageMode::Cloned); IMDWorkspace &operator=(const IMDWorkspace &other) = delete; /** @@ -53,14 +52,10 @@ public: }; /// Returns a clone of the workspace - std::unique_ptr clone() const { - return std::unique_ptr(doClone()); - } + std::unique_ptr clone() const { return std::unique_ptr(doClone()); } /// Returns a default-initialized clone of the workspace - std::unique_ptr cloneEmpty() const { - return std::unique_ptr(doCloneEmpty()); - } + std::unique_ptr cloneEmpty() const { return std::unique_ptr(doCloneEmpty()); } /// Get the number of points associated with the workspace. /// For MDEvenWorkspace it is the number of events contributing into the @@ -77,59 +72,48 @@ public: virtual uint64_t getNEvents() const = 0; /// Creates a new iterator pointing to the first cell in the workspace - virtual std::vector> createIterators( - size_t suggestedNumCores = 1, - Mantid::Geometry::MDImplicitFunction *function = nullptr) const = 0; + virtual std::vector> + createIterators(size_t suggestedNumCores = 1, Mantid::Geometry::MDImplicitFunction *function = nullptr) const = 0; /// Returns the (normalized) signal at a given coordinates - virtual signal_t - getSignalAtCoord(const coord_t *coords, - const Mantid::API::MDNormalization &normalization) const = 0; + virtual signal_t getSignalAtCoord(const coord_t *coords, const Mantid::API::MDNormalization &normalization) const = 0; /// Returns the (normalized) signal at a given coordinates or 0 if the value // is masked, used for plotting - virtual signal_t getSignalWithMaskAtCoord( - const coord_t *coords, - const Mantid::API::MDNormalization &normalization) const = 0; + virtual signal_t getSignalWithMaskAtCoord(const coord_t *coords, + const Mantid::API::MDNormalization &normalization) const = 0; /// Method to generate a line plot through a MD-workspace - virtual LinePlot getLinePlot(const Mantid::Kernel::VMD &start, - const Mantid::Kernel::VMD &end, + virtual LinePlot getLinePlot(const Mantid::Kernel::VMD &start, const Mantid::Kernel::VMD &end, Mantid::API::MDNormalization normalize) const; - std::unique_ptr createIterator( - Mantid::Geometry::MDImplicitFunction *function = nullptr) const; + std::unique_ptr createIterator(Mantid::Geometry::MDImplicitFunction *function = nullptr) const; std::string getConvention() const; void setConvention(std::string convention); std::string changeQConvention(); signal_t getSignalAtVMD(const Mantid::Kernel::VMD &coords, - const Mantid::API::MDNormalization &normalization = - Mantid::API::VolumeNormalization) const; + const Mantid::API::MDNormalization &normalization = Mantid::API::VolumeNormalization) const; signal_t getSignalWithMaskAtVMD(const Mantid::Kernel::VMD &coords, - const Mantid::API::MDNormalization &normalization = - Mantid::API::VolumeNormalization) const; + const Mantid::API::MDNormalization &normalization = Mantid::API::VolumeNormalization) const; /// Setter for the masking region. - virtual void setMDMasking( - std::unique_ptr maskingRegion) = 0; + virtual void setMDMasking(std::unique_ptr maskingRegion) = 0; /// Clear existing masks virtual void clearMDMasking() = 0; /// - virtual Kernel::SpecialCoordinateSystem - getSpecialCoordinateSystem() const = 0; + virtual Kernel::SpecialCoordinateSystem getSpecialCoordinateSystem() const = 0; /// if a workspace was filebacked, this should clear file-based status, delete /// file-based information and close related files. virtual void clearFileBacked(bool /* loadFileContentsToMemory*/) {} /// this is the method to build table workspace from any workspace. It does /// not have much sence and may be placed here erroneously virtual ITableWorkspace_sptr makeBoxTable(size_t /*start*/, size_t /* num*/) { - throw Kernel::Exception::NotImplementedError( - "This method is not generally implemented "); + throw Kernel::Exception::NotImplementedError("This method is not generally implemented "); } // Preferred normalization to use for display @@ -148,8 +132,7 @@ protected: /// Protected copy constructor. May be used by childs for cloning. IMDWorkspace(const IMDWorkspace &) = default; - void makeSinglePointWithNaN(std::vector &x, std::vector &y, - std::vector &e) const; + void makeSinglePointWithNaN(std::vector &x, std::vector &y, std::vector &e) const; const std::string toString() const override; diff --git a/Framework/API/inc/MantidAPI/IMaskWorkspace.h b/Framework/API/inc/MantidAPI/IMaskWorkspace.h index 3639bf4ee0c96bb48310cbceea8422d1e9fcc529..08a53120ccb5f493c73718692023d7c105a5a780 100644 --- a/Framework/API/inc/MantidAPI/IMaskWorkspace.h +++ b/Framework/API/inc/MantidAPI/IMaskWorkspace.h @@ -34,12 +34,9 @@ public: /// Set / remove mask of a detector virtual void setMasked(const detid_t detectorID, const bool mask = true) = 0; /// Set / remove masks of all detectors in a set - virtual void setMasked(const std::set &detectorIDs, - const bool mask = true) = 0; + virtual void setMasked(const std::set &detectorIDs, const bool mask = true) = 0; /// Returns a clone of the workspace - std::unique_ptr clone() const { - return std::unique_ptr(doInterfaceClone()); - } + std::unique_ptr clone() const { return std::unique_ptr(doInterfaceClone()); } protected: /// Protected copy constructor. May be used by childs for cloning. diff --git a/Framework/API/inc/MantidAPI/IPawleyFunction.h b/Framework/API/inc/MantidAPI/IPawleyFunction.h index 075baf3ecbcfc6889ceb62c862688dcdde17e45c..b856b6221bf9069d9e4c757631ca841b3d6b7a41 100644 --- a/Framework/API/inc/MantidAPI/IPawleyFunction.h +++ b/Framework/API/inc/MantidAPI/IPawleyFunction.h @@ -36,8 +36,7 @@ public: virtual void setUnitCell(const std::string &unitCellString) = 0; /// Assign several peaks with the same fwhm/height parameters. - virtual void setPeaks(const std::vector &hkls, double fwhm, - double height) = 0; + virtual void setPeaks(const std::vector &hkls, double fwhm, double height) = 0; /// Removes all peaks from the function. virtual void clearPeaks() = 0; diff --git a/Framework/API/inc/MantidAPI/IPeakFunction.h b/Framework/API/inc/MantidAPI/IPeakFunction.h index 514771ae237a442de1c336892149f9738610d7cd..93fb4b3b059a9e74602e5f2b80d7dc764d81fc68 100644 --- a/Framework/API/inc/MantidAPI/IPeakFunction.h +++ b/Framework/API/inc/MantidAPI/IPeakFunction.h @@ -10,9 +10,38 @@ // Includes //---------------------------------------------------------------------- #include "MantidAPI/IFunctionWithLocation.h" +#include "boost/shared_ptr.hpp" namespace Mantid { namespace API { + +class TempJacobian : public Jacobian { +public: + TempJacobian(size_t y, size_t p) : m_y(y), m_p(p), m_J(y * p) {} + void set(size_t iY, size_t iP, double value) override { m_J[iY * m_p + iP] = value; } + double get(size_t iY, size_t iP) override { return m_J[iY * m_p + iP]; } + size_t maxParam(size_t iY) { + double max = -DBL_MAX; + size_t maxIndex = 0; + for (size_t i = 0; i < m_p; ++i) { + double current = get(iY, i); + if (current > max) { + maxIndex = i; + max = current; + } + } + + return maxIndex; + } + void zero() override { m_J.assign(m_J.size(), 0.0); } + +protected: + size_t m_y; + size_t m_p; + std::vector m_J; +}; + +using IntegrationResultCache = std::pair; /** An interface to a peak function, which extend the interface of IFunctionWithLocation by adding methods to set and get peak width. @@ -24,8 +53,7 @@ public: /// Constructor IPeakFunction(); - void function(const FunctionDomain &domain, - FunctionValues &values) const override; + void function(const FunctionDomain &domain, FunctionValues &values) const override; /// Returns the peak FWHM virtual double fwhm() const = 0; @@ -36,27 +64,36 @@ public: /// Returns the integral intensity of the peak virtual double intensity() const; + /** + * Error in the integrated intensity of the peak due to uncertainties in the values of the fit parameters. + * @details if the peak function contains no fit-parameter uncertainties, then the integration error is set to NaN. + * Also, this function assumes no correlation between the fit parameters, so that their corresponding errors are + * summed up in quadrature. + */ + virtual double intensityError() const; + /// Sets the integral intensity of the peak virtual void setIntensity(const double newIntensity); + /// Override parent so that we may bust the cache when a parameter is set + void setParameter(const std::string &name, const double &value, bool explicitlySet = true) override; + + /// Override parent so that we may bust the cache when a parameter is set + void setParameter(size_t, const double &value, bool explicitlySet = true) override; + /// General implementation of the method for all peaks. - void function1D(double *out, const double *xValues, - const size_t nData) const override; + void function1D(double *out, const double *xValues, const size_t nData) const override; /// General implementation of the method for all peaks. - void functionDeriv1D(Jacobian *out, const double *xValues, - const size_t nData) override; + void functionDeriv1D(Jacobian *out, const double *xValues, const size_t nData) override; /// Get the interval on which the peak has all its values above a certain /// level - virtual std::pair - getDomainInterval(double level = DEFAULT_SEARCH_LEVEL) const; + virtual std::pair getDomainInterval(double level = DEFAULT_SEARCH_LEVEL) const; /// Function evaluation method to be implemented in the inherited classes - virtual void functionLocal(double *out, const double *xValues, - const size_t nData) const = 0; + virtual void functionLocal(double *out, const double *xValues, const size_t nData) const = 0; /// Derivative evaluation method. Default is to calculate numerically - virtual void functionDerivLocal(Jacobian *jacobian, const double *xValues, - const size_t nData); + virtual void functionDerivLocal(Jacobian *jacobian, const double *xValues, const size_t nData); /// Get name of parameter that is associated to centre. std::string getCentreParameterName() const; @@ -76,16 +113,17 @@ public: /// don't show it in ties virtual void fixIntensity(bool isDefault = false) { UNUSED_ARG(isDefault); - throw std::runtime_error( - "Generic intensity fixing isn't implemented for this function."); + throw std::runtime_error("Generic intensity fixing isn't implemented for this function."); } /// Free the intensity parameter. virtual void unfixIntensity() { - throw std::runtime_error( - "Generic intensity fixing isn't implemented for this function."); + throw std::runtime_error("Generic intensity fixing isn't implemented for this function."); } +protected: + virtual IntegrationResultCache integrate() const; + private: /// Set new peak radius void setPeakRadius(int r) const; @@ -94,6 +132,10 @@ private: mutable int m_peakRadius; /// The default level for searching a domain interval (getDomainInterval()) static constexpr double DEFAULT_SEARCH_LEVEL = 1e-5; + // Cache the result of a PeakFunctionIntegrator call + mutable boost::shared_ptr integrationResult = nullptr; + // Flag to dirty the cache when a param has been set + mutable bool m_parameterContextDirty = false; }; using IPeakFunction_sptr = std::shared_ptr; diff --git a/Framework/API/inc/MantidAPI/IPeaksWorkspace.h b/Framework/API/inc/MantidAPI/IPeaksWorkspace.h index 62e3f16a00a2961dcb01584658ad8d4367c4e3c6..f1755ddca1c0fcd594aafb9d61ee27cba251505e 100644 --- a/Framework/API/inc/MantidAPI/IPeaksWorkspace.h +++ b/Framework/API/inc/MantidAPI/IPeaksWorkspace.h @@ -30,8 +30,7 @@ namespace API { @author Ruth Mikkelson, SNS ORNL @date 3/10/2010 */ -class MANTID_API_DLL IPeaksWorkspace : public ITableWorkspace, - public Mantid::API::ExperimentInfo { +class MANTID_API_DLL IPeaksWorkspace : public ITableWorkspace, public Mantid::API::ExperimentInfo { public: /// Ctor IPeaksWorkspace() : ITableWorkspace(), ExperimentInfo() { @@ -70,8 +69,7 @@ public: * @param position :: V3D positon of the peak. * @param frame :: Coordinate system frame of the peak position. */ - virtual void addPeak(const Kernel::V3D &position, - const Kernel::SpecialCoordinateSystem &frame) = 0; + virtual void addPeak(const Kernel::V3D &position, const Kernel::SpecialCoordinateSystem &frame) = 0; //--------------------------------------------------------------------------------------------- /** Return a reference to the Peak @@ -92,9 +90,7 @@ public: * @param peakNum :: index of the peak to get. * @return a pointer to a Peak object. */ - Mantid::Geometry::IPeak *getPeakPtr(const int peakNum) { - return &this->getPeak(peakNum); - } + Mantid::Geometry::IPeak *getPeakPtr(const int peakNum) { return &this->getPeak(peakNum); } //--------------------------------------------------------------------------------------------- /** Create an instance of a Peak @@ -104,9 +100,8 @@ public: * detector. Calculated if not provided. * @return a pointer to a new Peak object. */ - virtual std::unique_ptr - createPeak(const Mantid::Kernel::V3D &QLabFrame, - boost::optional detectorDistance = boost::none) const = 0; + virtual std::unique_ptr createPeak(const Mantid::Kernel::V3D &QLabFrame, + boost::optional detectorDistance = boost::none) const = 0; //--------------------------------------------------------------------------------------------- /** Create an instance of a Peak @@ -115,16 +110,27 @@ public: * @return a pointer to a new Peak object. */ virtual std::unique_ptr - createPeak(const Mantid::Kernel::V3D &position, - const Mantid::Kernel::SpecialCoordinateSystem &frame) const = 0; + createPeak(const Mantid::Kernel::V3D &position, const Mantid::Kernel::SpecialCoordinateSystem &frame) const = 0; + + //--------------------------------------------------------------------------------------------- + /** Create an instance of a Peak + * @param position :: enter of the peak in the sample frame + * @return a pointer to a new Peak object. + */ + virtual std::unique_ptr createPeakQSample(const Mantid::Kernel::V3D &position) const = 0; /** * Create an instance of a peak using a V3D * @param HKL V3D * @return a pointer to a new Peak object. */ - virtual std::unique_ptr - createPeakHKL(const Mantid::Kernel::V3D &HKL) const = 0; + virtual std::unique_ptr createPeakHKL(const Mantid::Kernel::V3D &HKL) const = 0; + + /** + * Create an instance of a peak using default constructor + * @return a pointer to a new Peak object. + */ + virtual std::unique_ptr createPeak() const = 0; //--------------------------------------------------------------------------------------------- /** Determine if the workspace has been integrated using a peaks integration @@ -147,21 +153,21 @@ public: * Set the special coordinate system. * @param coordinateSystem : Special Q3D coordinate system to use. */ - virtual void setCoordinateSystem( - const Kernel::SpecialCoordinateSystem coordinateSystem) = 0; + virtual void setCoordinateSystem(const Kernel::SpecialCoordinateSystem coordinateSystem) = 0; //--------------------------------------------------------------------------------------------- /** * Get the special coordinate system. * @returns special Q3D coordinate system to use being used by this * PeaksWorkspace object. Probably the one the workspace was generated with. */ - virtual Kernel::SpecialCoordinateSystem - getSpecialCoordinateSystem() const = 0; + virtual Kernel::SpecialCoordinateSystem getSpecialCoordinateSystem() const = 0; + + virtual std::vector> peakInfo(const Kernel::V3D &QFrame, + bool labCoords) const = 0; + virtual int peakInfoNumber(const Kernel::V3D &qLabFrame, bool labCoords) const = 0; - virtual std::vector> - peakInfo(const Kernel::V3D &QFrame, bool labCoords) const = 0; - virtual int peakInfoNumber(const Kernel::V3D &qLabFrame, - bool labCoords) const = 0; + //--------------------------------------------------------------------------------------------- + virtual void saveNexus(::NeXus::File *file) const = 0; std::string convention; diff --git a/Framework/API/inc/MantidAPI/IPowderDiffPeakFunction.h b/Framework/API/inc/MantidAPI/IPowderDiffPeakFunction.h index 739d9a3af45dac056eec65f2fbb375851f3c53a5..50bd09e7d30a8dcc3016d7d49af418168360fe13 100644 --- a/Framework/API/inc/MantidAPI/IPowderDiffPeakFunction.h +++ b/Framework/API/inc/MantidAPI/IPowderDiffPeakFunction.h @@ -19,9 +19,7 @@ namespace API { @author Roman Tolchenov, Tessella Support Services plc @date 16/10/2009 */ -class MANTID_API_DLL IPowderDiffPeakFunction - : public virtual API::ParamFunction, - public virtual API::IFunction1D { +class MANTID_API_DLL IPowderDiffPeakFunction : public virtual API::ParamFunction, public virtual API::IFunction1D { public: /// Constructor and Destructor IPowderDiffPeakFunction(); @@ -57,21 +55,17 @@ public: virtual void calculateParameters(bool explicitoutput) const = 0; /// Set up the flag to show whether (from client) cell parameter value changed - virtual void setUnitCellParameterValueChangeFlag(bool changed) { - m_cellParamValueChanged = changed; - } + virtual void setUnitCellParameterValueChangeFlag(bool changed) { m_cellParamValueChanged = changed; } /// The flag to show whether the parameters set to peak function making an /// valid peak virtual bool isPhysical() { return m_parameterValid; } /// Override setting a new value to the i-th parameter - void setParameter(size_t i, const double &value, - bool explicitlySet = true) override; + void setParameter(size_t i, const double &value, bool explicitlySet = true) override; /// Override setting a new value to a parameter by name - void setParameter(const std::string &name, const double &value, - bool explicitlySet = true) override; + void setParameter(const std::string &name, const double &value, bool explicitlySet = true) override; /// Check whether a parameter is a profile parameter virtual bool hasProfileParameter(std::string paramname); @@ -81,12 +75,10 @@ public: /// Calculate function in a range using IFunction1D::function; - virtual void function(std::vector &out, - const std::vector &xValues) const = 0; + virtual void function(std::vector &out, const std::vector &xValues) const = 0; /// Get maximum value on a given set of data points - virtual double getMaximumValue(const std::vector &xValues, - size_t &indexmax) const; + virtual double getMaximumValue(const std::vector &xValues, size_t &indexmax) const; protected: /// Local function for GSL minimizer diff --git a/Framework/API/inc/MantidAPI/IRemoteJobManager.h b/Framework/API/inc/MantidAPI/IRemoteJobManager.h index 01c09e63399f654d3cfb348ea83383ad80312dee..e38cedcf15019478a6c4716e48d05b27974ea9ff 100644 --- a/Framework/API/inc/MantidAPI/IRemoteJobManager.h +++ b/Framework/API/inc/MantidAPI/IRemoteJobManager.h @@ -101,8 +101,7 @@ public: * properly. * @throws std::runtime_error If authentication fails */ - virtual void authenticate(const std::string &username, - const std::string &password) = 0; + virtual void authenticate(const std::string &username, const std::string &password) = 0; /** * Logout from the remote resource (close session). Depending on the @@ -147,10 +146,9 @@ public: * properly. * @throws std::runtime_error if job submission fails. */ - virtual std::string - submitRemoteJob(const std::string &transactionID, const std::string &runnable, - const std::string ¶m, const std::string &taskName = "", - const int numNodes = 1, const int coresPerNode = 1) = 0; + virtual std::string submitRemoteJob(const std::string &transactionID, const std::string &runnable, + const std::string ¶m, const std::string &taskName = "", + const int numNodes = 1, const int coresPerNode = 1) = 0; /** * Get/download a file from the (remote) compute resource. @@ -168,8 +166,7 @@ public: * properly. * @throws std::runtime_error If the download operation fails */ - virtual void downloadRemoteFile(const std::string &transactionID, - const std::string &remoteFileName, + virtual void downloadRemoteFile(const std::string &transactionID, const std::string &remoteFileName, const std::string &localFileName) = 0; /** @@ -197,8 +194,7 @@ public: * * @throws std::runtime_error If the query fails */ - virtual std::vector - queryRemoteFile(const std::string &transactionID) const = 0; + virtual std::vector queryRemoteFile(const std::string &transactionID) const = 0; /** * Get information (status etc.) for an (in principle) running job @@ -267,8 +263,7 @@ public: * arguments passed * @throws std::runtime_error If the upload fails */ - virtual void uploadRemoteFile(const std::string &transactionID, - const std::string &remoteFileName, + virtual void uploadRemoteFile(const std::string &transactionID, const std::string &remoteFileName, const std::string &localFileName) = 0; }; diff --git a/Framework/API/inc/MantidAPI/ISpectrum.h b/Framework/API/inc/MantidAPI/ISpectrum.h index b113217592d1e168448f1d42c4478e21467abd32..ed900a8e0ed05d0241a656ce2c8a715d0295a341 100644 --- a/Framework/API/inc/MantidAPI/ISpectrum.h +++ b/Framework/API/inc/MantidAPI/ISpectrum.h @@ -94,7 +94,7 @@ public: /// Returns the Histogram associated with this spectrum. virtual HistogramData::Histogram histogram() const { return histogramRef(); } /// Sets the Histogram associated with this spectrum. - template void setHistogram(T &&... data) { + template void setHistogram(T &&...data) { HistogramData::Histogram histogram(std::forward(data)...); // Check for the special case EventList, it only accepts histograms without // Y and E data. @@ -102,12 +102,8 @@ public: mutableHistogramRef() = std::move(histogram); } - HistogramData::Histogram::YMode yMode() const { - return histogramRef().yMode(); - } - void setYMode(HistogramData::Histogram::YMode ymode) { - mutableHistogramRef().setYMode(ymode); - } + HistogramData::Histogram::YMode yMode() const { return histogramRef().yMode(); } + void setYMode(HistogramData::Histogram::YMode ymode) { mutableHistogramRef().setYMode(ymode); } void convertToCounts() { checkIsYAndEWritable(); mutableHistogramRef().convertToCounts(); @@ -122,82 +118,63 @@ public: HistogramData::PointStandardDeviations pointStandardDeviations() const { return histogramRef().pointStandardDeviations(); } - template void setBinEdges(T &&... data) & { + template void setBinEdges(T &&...data) & { mutableHistogramRef().setBinEdges(std::forward(data)...); } - template void setPoints(T &&... data) & { + template void setPoints(T &&...data) & { // Check for the special case EventList, it only works with BinEdges. checkWorksWithPoints(); mutableHistogramRef().setPoints(std::forward(data)...); } - template void setPointVariances(T &&... data) & { + template void setPointVariances(T &&...data) & { // Note that we can set point variances even if storage mode is BinEdges, Dx // is *always* one value *per bin*. mutableHistogramRef().setPointVariances(std::forward(data)...); } - template void setPointStandardDeviations(T &&... data) & { + template void setPointStandardDeviations(T &&...data) & { mutableHistogramRef().setPointStandardDeviations(std::forward(data)...); } - virtual HistogramData::Counts counts() const { - return histogramRef().counts(); - } - virtual HistogramData::CountVariances countVariances() const { - return histogramRef().countVariances(); - } - virtual HistogramData::CountStandardDeviations - countStandardDeviations() const { + virtual HistogramData::Counts counts() const { return histogramRef().counts(); } + virtual HistogramData::CountVariances countVariances() const { return histogramRef().countVariances(); } + virtual HistogramData::CountStandardDeviations countStandardDeviations() const { return histogramRef().countStandardDeviations(); } - virtual HistogramData::Frequencies frequencies() const { - return histogramRef().frequencies(); - } - virtual HistogramData::FrequencyVariances frequencyVariances() const { - return histogramRef().frequencyVariances(); - } - virtual HistogramData::FrequencyStandardDeviations - frequencyStandardDeviations() const { + virtual HistogramData::Frequencies frequencies() const { return histogramRef().frequencies(); } + virtual HistogramData::FrequencyVariances frequencyVariances() const { return histogramRef().frequencyVariances(); } + virtual HistogramData::FrequencyStandardDeviations frequencyStandardDeviations() const { return histogramRef().frequencyStandardDeviations(); } - template void setCounts(T &&... data) & { + template void setCounts(T &&...data) & { // Check for the special case EventList, cannot set Y and E there. checkIsYAndEWritable(); mutableHistogramRef().setCounts(std::forward(data)...); } - template void setCountVariances(T &&... data) & { + template void setCountVariances(T &&...data) & { checkIsYAndEWritable(); mutableHistogramRef().setCountVariances(std::forward(data)...); } - template void setCountStandardDeviations(T &&... data) & { + template void setCountStandardDeviations(T &&...data) & { checkIsYAndEWritable(); mutableHistogramRef().setCountStandardDeviations(std::forward(data)...); } - template void setFrequencies(T &&... data) & { + template void setFrequencies(T &&...data) & { checkIsYAndEWritable(); mutableHistogramRef().setFrequencies(std::forward(data)...); } - template void setFrequencyVariances(T &&... data) & { + template void setFrequencyVariances(T &&...data) & { checkIsYAndEWritable(); mutableHistogramRef().setFrequencyVariances(std::forward(data)...); } - template void setFrequencyStandardDeviations(T &&... data) & { + template void setFrequencyStandardDeviations(T &&...data) & { checkIsYAndEWritable(); - mutableHistogramRef().setFrequencyStandardDeviations( - std::forward(data)...); + mutableHistogramRef().setFrequencyStandardDeviations(std::forward(data)...); } const HistogramData::HistogramX &x() const { return histogramRef().x(); } - virtual const HistogramData::HistogramY &y() const { - return histogramRef().y(); - } - virtual const HistogramData::HistogramE &e() const { - return histogramRef().e(); - } + virtual const HistogramData::HistogramY &y() const { return histogramRef().y(); } + virtual const HistogramData::HistogramE &e() const { return histogramRef().e(); } const HistogramData::HistogramDx &dx() const { return histogramRef().dx(); } - HistogramData::HistogramX &mutableX() & { - return mutableHistogramRef().mutableX(); - } - HistogramData::HistogramDx &mutableDx() & { - return mutableHistogramRef().mutableDx(); - } + HistogramData::HistogramX &mutableX() & { return mutableHistogramRef().mutableX(); } + HistogramData::HistogramDx &mutableDx() & { return mutableHistogramRef().mutableDx(); } HistogramData::HistogramY &mutableY() & { checkIsYAndEWritable(); return mutableHistogramRef().mutableY(); @@ -206,24 +183,12 @@ public: checkIsYAndEWritable(); return mutableHistogramRef().mutableE(); } - Kernel::cow_ptr sharedX() const { - return histogramRef().sharedX(); - } - virtual Kernel::cow_ptr sharedY() const { - return histogramRef().sharedY(); - } - virtual Kernel::cow_ptr sharedE() const { - return histogramRef().sharedE(); - } - Kernel::cow_ptr sharedDx() const { - return histogramRef().sharedDx(); - } - void setSharedX(const Kernel::cow_ptr &x) & { - mutableHistogramRef().setSharedX(x); - } - void setSharedDx(const Kernel::cow_ptr &dx) & { - mutableHistogramRef().setSharedDx(dx); - } + Kernel::cow_ptr sharedX() const { return histogramRef().sharedX(); } + virtual Kernel::cow_ptr sharedY() const { return histogramRef().sharedY(); } + virtual Kernel::cow_ptr sharedE() const { return histogramRef().sharedE(); } + Kernel::cow_ptr sharedDx() const { return histogramRef().sharedDx(); } + void setSharedX(const Kernel::cow_ptr &x) & { mutableHistogramRef().setSharedX(x); } + void setSharedDx(const Kernel::cow_ptr &dx) & { mutableHistogramRef().setSharedDx(dx); } void setSharedY(const Kernel::cow_ptr &y) & { checkIsYAndEWritable(); mutableHistogramRef().setSharedY(y); diff --git a/Framework/API/inc/MantidAPI/ISplittersWorkspace.h b/Framework/API/inc/MantidAPI/ISplittersWorkspace.h index e7c762354b1b16a45387044428f68cf213306c34..4d087dcf837822e64ad87d948d3ee686ae25e5fc 100644 --- a/Framework/API/inc/MantidAPI/ISplittersWorkspace.h +++ b/Framework/API/inc/MantidAPI/ISplittersWorkspace.h @@ -30,9 +30,7 @@ public: virtual ~ISplittersWorkspace() = default; /// Returns a clone of the workspace - std::unique_ptr clone() const { - return std::unique_ptr(doClone()); - } + std::unique_ptr clone() const { return std::unique_ptr(doClone()); } /* * Add a time splitter to table workspace @@ -66,8 +64,7 @@ private: /// Typedef for a shared pointer to \c TableWorkspace using ISplittersWorkspace_sptr = std::shared_ptr; /// Typedef for a shared pointer to \c const \c TableWorkspace -using ISplittersWorkspace_const_sptr = - std::shared_ptr; +using ISplittersWorkspace_const_sptr = std::shared_ptr; } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/ITableWorkspace.h b/Framework/API/inc/MantidAPI/ITableWorkspace.h index b14270e0817d50477423e197e6af840a36fbd203..60b4c11cc8b64a7382ef88f2e79cfbc7a5f476e2 100644 --- a/Framework/API/inc/MantidAPI/ITableWorkspace.h +++ b/Framework/API/inc/MantidAPI/ITableWorkspace.h @@ -36,8 +36,7 @@ namespace API { class TableColumnHelper { public: /// Constructor - TableColumnHelper(ITableWorkspace *tw, const std::string &name) - : m_workspace(tw), m_name(name) {} + TableColumnHelper(ITableWorkspace *tw, const std::string &name) : m_workspace(tw), m_name(name) {} ITableWorkspace *m_workspace; ///< Pointer to the TableWorkspace std::string m_name; ///< column namae }; @@ -46,8 +45,7 @@ public: class TableConstColumnHelper { public: /// Constructor - TableConstColumnHelper(const ITableWorkspace *tw, const std::string &name) - : m_workspace(tw), m_name(name) {} + TableConstColumnHelper(const ITableWorkspace *tw, const std::string &name) : m_workspace(tw), m_name(name) {} const ITableWorkspace *m_workspace; ///< Pointer to the TableWorkspace std::string m_name; ///< column namae }; @@ -56,8 +54,7 @@ public: class TableRowHelper { public: /// Constructor - TableRowHelper(ITableWorkspace *tw, size_t row) - : m_workspace(tw), m_row(row) {} + TableRowHelper(ITableWorkspace *tw, size_t row) : m_workspace(tw), m_row(row) {} ITableWorkspace *m_workspace; ///< Pointer to the TableWorkspace size_t m_row; ///< Row number }; @@ -107,17 +104,12 @@ public: ITableWorkspace() {} /// Returns a clone of the workspace - ITableWorkspace_uptr clone() const { - return std::unique_ptr(doClone()); - } + ITableWorkspace_uptr clone() const { return std::unique_ptr(doClone()); } /// Returns a default-initialized clone of the workspace - ITableWorkspace_uptr cloneEmpty() const { - return ITableWorkspace_uptr(doCloneEmpty()); - } + ITableWorkspace_uptr cloneEmpty() const { return ITableWorkspace_uptr(doCloneEmpty()); } - ITableWorkspace_uptr - cloneColumns(const std::vector &colNames) const; + ITableWorkspace_uptr cloneColumns(const std::vector &colNames) const; ITableWorkspace &operator=(const ITableWorkspace &) = delete; /// Return the workspace typeID @@ -128,11 +120,9 @@ public: * @param name :: The name to assign to the column * @return True if the column was successfully added */ - virtual Column_sptr addColumn(const std::string &type, - const std::string &name) = 0; + virtual Column_sptr addColumn(const std::string &type, const std::string &name) = 0; /// Creates n new columns of the same type. - virtual bool addColumns(const std::string &type, const std::string &name, - size_t n); + virtual bool addColumns(const std::string &type, const std::string &name, size_t n); /**Get access to shared pointer containing workspace properties */ virtual API::LogManager_sptr logs() = 0; /**Get constant access to shared pointer containing workspace properties */ @@ -201,9 +191,8 @@ public: T &getRef(const std::string &name, size_t index) { std::shared_ptr c = getColumn(name); if (!c->isType()) { - std::string str = std::string("getRef: Type mismatch. ") + - typeid(T).name() + " != " + c->get_type_info().name() + - '\n'; + std::string str = + std::string("getRef: Type mismatch. ") + typeid(T).name() + " != " + c->get_type_info().name() + '\n'; throw std::runtime_error(str); } return *(static_cast(c->void_pointer(index))); @@ -221,9 +210,7 @@ public: Column_sptr c = getColumn(col); if (!c->isType()) { std::ostringstream ostr; - ostr << "cell: Type mismatch:\n" - << typeid(T).name() << " != \n" - << c->get_type_info().name() << '\n'; + ostr << "cell: Type mismatch:\n" << typeid(T).name() << " != \n" << c->get_type_info().name() << '\n'; throw std::runtime_error(ostr.str()); } if (row >= this->rowCount()) { @@ -267,9 +254,7 @@ public: @param col :: Column number @return the reference of a requested cell if it's a string */ - std::string &String(size_t row, size_t col) { - return cell(row, col); - } + std::string &String(size_t row, size_t col) { return cell(row, col); } /** Creates a TableRow object for row \a row. @param row :: Row number @@ -294,8 +279,7 @@ public: virtual void find(std::string value, size_t &row, const size_t &col) = 0; /// find method to get the index of Mantid::Kernel::V3D cell value in a table /// workspace - virtual void find(Mantid::Kernel::V3D value, size_t &row, - const size_t &col) = 0; + virtual void find(Mantid::Kernel::V3D value, size_t &row, const size_t &col) = 0; void modified(); @@ -323,12 +307,9 @@ protected: void removeFromColumn(Column *c, size_t index) { c->remove(index); } private: - ITableWorkspace *doClone() const override { - return doCloneColumns(std::vector()); - } + ITableWorkspace *doClone() const override { return doCloneColumns(std::vector()); } ITableWorkspace *doCloneEmpty() const override = 0; - virtual ITableWorkspace * - doCloneColumns(const std::vector &colNames) const = 0; + virtual ITableWorkspace *doCloneColumns(const std::vector &colNames) const = 0; }; // ===================================================================================== @@ -340,12 +321,10 @@ private: template class ColumnVector { public: /// Constructor - ColumnVector(const TableColumnHelper &th) - : m_column(th.m_workspace->getColumn(th.m_name)) { + ColumnVector(const TableColumnHelper &th) : m_column(th.m_workspace->getColumn(th.m_name)) { if (!m_column->isType()) { std::stringstream mess; - mess << "Type mismatch when creating a ColumnVector<" << typeid(T).name() - << ">."; + mess << "Type mismatch when creating a ColumnVector<" << typeid(T).name() << ">."; throw std::runtime_error(mess.str()); } } @@ -353,8 +332,7 @@ public: ColumnVector(Column_sptr column) : m_column(std::move(column)) { if (!m_column->isType()) { std::stringstream mess; - mess << "Type mismatch when creating a ColumnVector<" << typeid(T).name() - << ">."; + mess << "Type mismatch when creating a ColumnVector<" << typeid(T).name() << ">."; throw std::runtime_error(mess.str()); } } @@ -378,12 +356,10 @@ private: template class ConstColumnVector { public: /// Constructor - ConstColumnVector(const TableConstColumnHelper &th) - : m_column(th.m_workspace->getColumn(th.m_name)) { + ConstColumnVector(const TableConstColumnHelper &th) : m_column(th.m_workspace->getColumn(th.m_name)) { if (!m_column->isType()) { std::stringstream mess; - mess << "Type mismatch when creating a ColumnVector<" << typeid(T).name() - << ">."; + mess << "Type mismatch when creating a ColumnVector<" << typeid(T).name() << ">."; throw std::runtime_error(mess.str()); } } @@ -391,8 +367,7 @@ public: ConstColumnVector(Column_const_sptr column) : m_column(std::move(column)) { if (!m_column->isType()) { std::stringstream mess; - mess << "Type mismatch when creating a ColumnVector<" << typeid(T).name() - << ">."; + mess << "Type mismatch when creating a ColumnVector<" << typeid(T).name() << ">."; throw std::runtime_error(mess.str()); } } diff --git a/Framework/API/inc/MantidAPI/ITransformScale.h b/Framework/API/inc/MantidAPI/ITransformScale.h index 4d3d24d7fb813ad5a363b69a4ada30c76d5e4b40..8877d5bccffdba4da7a29e5784e0450643d6c28e 100644 --- a/Framework/API/inc/MantidAPI/ITransformScale.h +++ b/Framework/API/inc/MantidAPI/ITransformScale.h @@ -43,10 +43,8 @@ using ITransformScale_sptr = std::shared_ptr; } // namespace API } // namespace Mantid -#define DECLARE_TRANSFORMSCALE(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper register_trs_##classname( \ - ((Mantid::API::TransformScaleFactory::Instance().subscribe( \ - #classname)), \ - 0)); \ +#define DECLARE_TRANSFORMSCALE(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper register_trs_##classname( \ + ((Mantid::API::TransformScaleFactory::Instance().subscribe(#classname)), 0)); \ } diff --git a/Framework/API/inc/MantidAPI/ImmutableCompositeFunction.h b/Framework/API/inc/MantidAPI/ImmutableCompositeFunction.h index 381b7bafd857e300be9bdf2944db99197a93c245..effa88e6865a0fd93b2f78e69a7d391481e3799e 100644 --- a/Framework/API/inc/MantidAPI/ImmutableCompositeFunction.h +++ b/Framework/API/inc/MantidAPI/ImmutableCompositeFunction.h @@ -30,25 +30,19 @@ public: /// Returns the function's name std::string name() const override { return "ImmutableCompositeFunction"; } /// Set i-th parameter - void setParameter(size_t i, const double &value, - bool explicitlySet = true) override { + void setParameter(size_t i, const double &value, bool explicitlySet = true) override { CompositeFunction::setParameter(i, value, explicitlySet); } /// Set i-th parameter description - void setParameterDescription(size_t i, - const std::string &description) override { + void setParameterDescription(size_t i, const std::string &description) override { CompositeFunction::setParameterDescription(i, description); } /// Set parameter by name. - void setParameter(const std::string &name, const double &value, - bool explicitlySet = true) override; + void setParameter(const std::string &name, const double &value, bool explicitlySet = true) override; /// Set description of parameter by name. - void setParameterDescription(const std::string &name, - const std::string &description) override; + void setParameterDescription(const std::string &name, const std::string &description) override; /// Get i-th parameter - double getParameter(size_t i) const override { - return CompositeFunction::getParameter(i); - } + double getParameter(size_t i) const override { return CompositeFunction::getParameter(i); } /// Get parameter by name. double getParameter(const std::string &name) const override; /// Returns the index of parameter name @@ -68,8 +62,7 @@ protected: /// Add default constraints void addDefaultConstraints(const std::string &constraints); /// Writes itself into a string - std::string writeToString( - const std::string &parentLocalAttributesStr = "") const override; + std::string writeToString(const std::string &parentLocalAttributesStr = "") const override; private: /// Keep paramater aliases diff --git a/Framework/API/inc/MantidAPI/ImplicitFunctionFactory.h b/Framework/API/inc/MantidAPI/ImplicitFunctionFactory.h index f3034eaf03056787a4bbee79b58901d8ac8d7bdd..3e51d30ee2b557d2fe8440601c736ad43b0975ab 100644 --- a/Framework/API/inc/MantidAPI/ImplicitFunctionFactory.h +++ b/Framework/API/inc/MantidAPI/ImplicitFunctionFactory.h @@ -24,20 +24,15 @@ ImplicitFunctions. namespace Mantid { namespace API { -class MANTID_API_DLL ImplicitFunctionFactoryImpl - : public Kernel::DynamicFactory { +class MANTID_API_DLL ImplicitFunctionFactoryImpl : public Kernel::DynamicFactory { public: ImplicitFunctionFactoryImpl(const ImplicitFunctionFactoryImpl &) = delete; - ImplicitFunctionFactoryImpl & - operator=(const ImplicitFunctionFactoryImpl &) = delete; - Mantid::Geometry::MDImplicitFunction_sptr - create(const std::string &className) const override; + ImplicitFunctionFactoryImpl &operator=(const ImplicitFunctionFactoryImpl &) = delete; + Mantid::Geometry::MDImplicitFunction_sptr create(const std::string &className) const override; - virtual Mantid::Geometry::MDImplicitFunction * - createUnwrapped(Poco::XML::Element *processXML) const; + virtual Mantid::Geometry::MDImplicitFunction *createUnwrapped(Poco::XML::Element *processXML) const; - Mantid::Geometry::MDImplicitFunction * - createUnwrapped(const std::string &processXML) const override; + Mantid::Geometry::MDImplicitFunction *createUnwrapped(const std::string &processXML) const override; friend struct Mantid::Kernel::CreateUsingNew; @@ -48,8 +43,7 @@ private: ~ImplicitFunctionFactoryImpl() override = default; }; -using ImplicitFunctionFactory = - Mantid::Kernel::SingletonHolder; +using ImplicitFunctionFactory = Mantid::Kernel::SingletonHolder; } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/ImplicitFunctionParameter.h b/Framework/API/inc/MantidAPI/ImplicitFunctionParameter.h index 89c290e496f2721015dc7a03a20ec6f86880afa8..d8376c91dc8337e2d81005a26f9371eba2d2f9f6 100644 --- a/Framework/API/inc/MantidAPI/ImplicitFunctionParameter.h +++ b/Framework/API/inc/MantidAPI/ImplicitFunctionParameter.h @@ -88,48 +88,32 @@ template struct ElementTraits {}; */ template <> struct ElementTraits { using ValueType = size_t; - static std::string formatCS(const ValueType &value) { - return boost::str(boost::format("%u,") % value); - } - static std::string format(const ValueType &value) { - return boost::str(boost::format("%u") % value); - } + static std::string formatCS(const ValueType &value) { return boost::str(boost::format("%u,") % value); } + static std::string format(const ValueType &value) { return boost::str(boost::format("%u") % value); } }; /** ElementTraits for boolean element types. */ template <> struct ElementTraits { using ValueType = bool; - static std::string formatCS(const ValueType &value) { - return boost::str(boost::format("%u,") % value); - } - static std::string format(const ValueType &value) { - return boost::str(boost::format("%u") % value); - } + static std::string formatCS(const ValueType &value) { return boost::str(boost::format("%u,") % value); } + static std::string format(const ValueType &value) { return boost::str(boost::format("%u") % value); } }; /** ElementTraits for double element types. */ template <> struct ElementTraits { using ValueType = double; - static std::string formatCS(const ValueType &value) { - return boost::str(boost::format("%.4f,") % value); - } - static std::string format(const ValueType &value) { - return boost::str(boost::format("%.4f") % value); - } + static std::string formatCS(const ValueType &value) { return boost::str(boost::format("%.4f,") % value); } + static std::string format(const ValueType &value) { return boost::str(boost::format("%.4f") % value); } }; /** ElementTraits for float element types. */ template <> struct ElementTraits { using ValueType = double; - static std::string formatCS(const ValueType &value) { - return boost::str(boost::format("%.4f,") % value); - } - static std::string format(const ValueType &value) { - return boost::str(boost::format("%.4f") % value); - } + static std::string formatCS(const ValueType &value) { return boost::str(boost::format("%.4f,") % value); } + static std::string format(const ValueType &value) { return boost::str(boost::format("%.4f") % value); } }; //------------------------------------------------------------------------------------ diff --git a/Framework/API/inc/MantidAPI/ImplicitFunctionParameterParser.h b/Framework/API/inc/MantidAPI/ImplicitFunctionParameterParser.h index 1e9f640a7be8bad6c5d7bb757859443dd1f3e352..adf7177b0e407f6ebb465b70632aba28ff634027 100644 --- a/Framework/API/inc/MantidAPI/ImplicitFunctionParameterParser.h +++ b/Framework/API/inc/MantidAPI/ImplicitFunctionParameterParser.h @@ -12,12 +12,10 @@ * subscribe method. */ //#define Parser Parser -#define DECLARE_IMPLICIT_FUNCTION_PARAMETER_PARSER(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper register_alg_##classname( \ - ((Mantid::API::ImplicitFunctionParameterParserFactory::Instance() \ - .subscribe(#classname)), \ - 0)); \ +#define DECLARE_IMPLICIT_FUNCTION_PARAMETER_PARSER(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper register_alg_##classname( \ + ((Mantid::API::ImplicitFunctionParameterParserFactory::Instance().subscribe(#classname)), 0)); \ } //---------------------------------------------------------------------- @@ -66,14 +64,11 @@ class MANTID_API_DLL ImplicitFunctionParameterParser { public: /// Successor type. Unique shared pointer with stack scoped deletion /// semantics. - using SuccessorType = boost::interprocess::unique_ptr< - ImplicitFunctionParameterParser, - DeleterPolicy>; + using SuccessorType = + boost::interprocess::unique_ptr>; - virtual ImplicitFunctionParameter * - createParameter(Poco::XML::Element *parameterElement) = 0; - virtual void - setSuccessorParser(ImplicitFunctionParameterParser *paramParser) = 0; + virtual ImplicitFunctionParameter *createParameter(Poco::XML::Element *parameterElement) = 0; + virtual void setSuccessorParser(ImplicitFunctionParameterParser *paramParser) = 0; virtual ~ImplicitFunctionParameterParser() = default; protected: diff --git a/Framework/API/inc/MantidAPI/ImplicitFunctionParameterParserFactory.h b/Framework/API/inc/MantidAPI/ImplicitFunctionParameterParserFactory.h index 14d2d1447e9006628d89cb298955708c2a051710..10350878988dedfe6880ff1c2ffb0a200f6b244b 100644 --- a/Framework/API/inc/MantidAPI/ImplicitFunctionParameterParserFactory.h +++ b/Framework/API/inc/MantidAPI/ImplicitFunctionParameterParserFactory.h @@ -26,18 +26,14 @@ namespace API { class MANTID_API_DLL ImplicitFunctionParameterParserFactoryImpl : public Kernel::DynamicFactory { public: - ImplicitFunctionParameterParserFactoryImpl( - const ImplicitFunctionParameterParserFactoryImpl &) = delete; - ImplicitFunctionParameterParserFactoryImpl & - operator=(const ImplicitFunctionParameterParserFactoryImpl &) = delete; - std::shared_ptr - create(const std::string &xmlString) const override; - ImplicitFunctionParameterParser *createImplicitFunctionParameterParserFromXML( - Poco::XML::Element *parametersElement) const; + ImplicitFunctionParameterParserFactoryImpl(const ImplicitFunctionParameterParserFactoryImpl &) = delete; + ImplicitFunctionParameterParserFactoryImpl &operator=(const ImplicitFunctionParameterParserFactoryImpl &) = delete; + std::shared_ptr create(const std::string &xmlString) const override; + ImplicitFunctionParameterParser * + createImplicitFunctionParameterParserFromXML(Poco::XML::Element *parametersElement) const; private: - friend struct Mantid::Kernel::CreateUsingNew< - ImplicitFunctionParameterParserFactoryImpl>; + friend struct Mantid::Kernel::CreateUsingNew; /// Private Constructor for singleton class ImplicitFunctionParameterParserFactoryImpl() = default; @@ -53,7 +49,7 @@ using ImplicitFunctionParameterParserFactory = namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder< - Mantid::API::ImplicitFunctionParameterParserFactoryImpl>; +EXTERN_MANTID_API template class MANTID_API_DLL + Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/ImplicitFunctionParser.h b/Framework/API/inc/MantidAPI/ImplicitFunctionParser.h index 28b7bfe13bf2b83a61f7c6c7dd92cf3e5f4dd638..9fc9cbc7b6703429455a8fa16ac3f9cd34ceef5a 100644 --- a/Framework/API/inc/MantidAPI/ImplicitFunctionParser.h +++ b/Framework/API/inc/MantidAPI/ImplicitFunctionParser.h @@ -12,12 +12,10 @@ * subscribe method. */ //#define Parser Parser -#define DECLARE_IMPLICIT_FUNCTION_PARSER(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper register_alg_##classname( \ - ((Mantid::API::ImplicitFunctionParserFactory::Instance() \ - .subscribe(#classname)), \ - 0)); \ +#define DECLARE_IMPLICIT_FUNCTION_PARSER(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper register_alg_##classname( \ + ((Mantid::API::ImplicitFunctionParserFactory::Instance().subscribe(#classname)), 0)); \ } //---------------------------------------------------------------------- @@ -52,13 +50,10 @@ namespace API { class MANTID_API_DLL ImplicitFunctionParser { public: /// Successor type. Unique pointer with stack scoped deletion semantics. - using SuccessorType = - boost::interprocess::unique_ptr>; + using SuccessorType = boost::interprocess::unique_ptr>; protected: - ImplicitFunctionParameterParser::SuccessorType - m_paramParserRoot; // Chain of responsibility + ImplicitFunctionParameterParser::SuccessorType m_paramParserRoot; // Chain of responsibility SuccessorType m_successor; @@ -75,11 +70,9 @@ protected: } public: - ImplicitFunctionParser(ImplicitFunctionParameterParser *parameterParser) - : m_paramParserRoot(parameterParser) {} + ImplicitFunctionParser(ImplicitFunctionParameterParser *parameterParser) : m_paramParserRoot(parameterParser) {} - virtual ImplicitFunctionBuilder * - createFunctionBuilder(Poco::XML::Element *functionElement) = 0; + virtual ImplicitFunctionBuilder *createFunctionBuilder(Poco::XML::Element *functionElement) = 0; virtual void setSuccessorParser(ImplicitFunctionParser *parser) = 0; virtual void setParameterParser(ImplicitFunctionParameterParser *parser) = 0; virtual ~ImplicitFunctionParser() = default; diff --git a/Framework/API/inc/MantidAPI/ImplicitFunctionParserFactory.h b/Framework/API/inc/MantidAPI/ImplicitFunctionParserFactory.h index d32f2b2ff1fdec5d169205e193bf5cd3adb177b1..0b2a71235be7f01f54c356924faa69bfaf78d1e9 100644 --- a/Framework/API/inc/MantidAPI/ImplicitFunctionParserFactory.h +++ b/Framework/API/inc/MantidAPI/ImplicitFunctionParserFactory.h @@ -24,24 +24,17 @@ namespace Mantid { namespace API { -class MANTID_API_DLL ImplicitFunctionParserFactoryImpl - : public Kernel::DynamicFactory { +class MANTID_API_DLL ImplicitFunctionParserFactoryImpl : public Kernel::DynamicFactory { public: - ImplicitFunctionParserFactoryImpl(const ImplicitFunctionParserFactoryImpl &) = - delete; - ImplicitFunctionParserFactoryImpl & - operator=(const ImplicitFunctionParserFactoryImpl &) = delete; - std::shared_ptr - create(const std::string &xmlString) const override; - ImplicitFunctionParser * - createImplicitFunctionParserFromXML(const std::string &functionXML) const; - - ImplicitFunctionParser *createImplicitFunctionParserFromXML( - Poco::XML::Element *functionElement) const; + ImplicitFunctionParserFactoryImpl(const ImplicitFunctionParserFactoryImpl &) = delete; + ImplicitFunctionParserFactoryImpl &operator=(const ImplicitFunctionParserFactoryImpl &) = delete; + std::shared_ptr create(const std::string &xmlString) const override; + ImplicitFunctionParser *createImplicitFunctionParserFromXML(const std::string &functionXML) const; + + ImplicitFunctionParser *createImplicitFunctionParserFromXML(Poco::XML::Element *functionElement) const; private: - friend struct Mantid::Kernel::CreateUsingNew< - ImplicitFunctionParserFactoryImpl>; + friend struct Mantid::Kernel::CreateUsingNew; /// Private Constructor for singleton class ImplicitFunctionParserFactoryImpl() = default; @@ -49,14 +42,13 @@ private: ~ImplicitFunctionParserFactoryImpl() override = default; }; -using ImplicitFunctionParserFactory = - Mantid::Kernel::SingletonHolder; +using ImplicitFunctionParserFactory = Mantid::Kernel::SingletonHolder; } // namespace API } // namespace Mantid namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder< - Mantid::API::ImplicitFunctionParserFactoryImpl>; +EXTERN_MANTID_API template class MANTID_API_DLL + Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/IndexProperty.h b/Framework/API/inc/MantidAPI/IndexProperty.h index e9bae459f24dd4c9431409f2d259efb1a3446a72..cbdf4f14b10f2375313d83923d781f2e0d46b6d5 100644 --- a/Framework/API/inc/MantidAPI/IndexProperty.h +++ b/Framework/API/inc/MantidAPI/IndexProperty.h @@ -29,11 +29,9 @@ namespace API { */ class MANTID_API_DLL IndexProperty : public Kernel::ArrayProperty { public: - IndexProperty(const std::string &name, - const IWorkspaceProperty &workspaceProp, + IndexProperty(const std::string &name, const IWorkspaceProperty &workspaceProp, const IndexTypeProperty &indexTypeProp, - const Kernel::IValidator_sptr &validator = - Kernel::IValidator_sptr(new Kernel::NullValidator)); + const Kernel::IValidator_sptr &validator = Kernel::IValidator_sptr(new Kernel::NullValidator)); IndexProperty(const IndexProperty &) = default; // Copy assignment is deleted since there are reference type members. diff --git a/Framework/API/inc/MantidAPI/IndexTypeProperty.h b/Framework/API/inc/MantidAPI/IndexTypeProperty.h index 7316982428256efa11c6c5215dd208be85b0c4f3..c8d919f8deb86a4711ff3fa2c807bbb0c91d8432 100644 --- a/Framework/API/inc/MantidAPI/IndexTypeProperty.h +++ b/Framework/API/inc/MantidAPI/IndexTypeProperty.h @@ -12,7 +12,7 @@ namespace Mantid { namespace API { -enum IndexType { SpectrumNum = 1, WorkspaceIndex = 2 }; +enum class IndexType { SpectrumNum = 1, WorkspaceIndex = 2 }; /** IndexTypeProperty : Implementation of a property which stores the type of input indices users require for accessing workspace data. This works in harmony @@ -21,11 +21,9 @@ with IndexProperty and is not intended for isolated use. @author Lamar Moore @date 05-05-2017 */ -class MANTID_API_DLL IndexTypeProperty - : public Kernel::PropertyWithValue { +class MANTID_API_DLL IndexTypeProperty : public Kernel::PropertyWithValue { public: - IndexTypeProperty(const std::string &name = "IndexType", - int indexType = IndexType::WorkspaceIndex); + IndexTypeProperty(const std::string &name = "IndexType", int indexType = static_cast(IndexType::WorkspaceIndex)); IndexType selectedType() const; diff --git a/Framework/API/inc/MantidAPI/InstrumentDataService.h b/Framework/API/inc/MantidAPI/InstrumentDataService.h index e773dbd452de1d50e9d06fe49b6f75696cd604f9..01539faeaef6617a6c8b7b2ec391bf577bc00286 100644 --- a/Framework/API/inc/MantidAPI/InstrumentDataService.h +++ b/Framework/API/inc/MantidAPI/InstrumentDataService.h @@ -19,8 +19,7 @@ Class to store shared_pointer to Instrument Objects. @author Laurent C Chapon, ISIS, Rutherford Appleton Laboratory @date 30/05/2008 */ -class MANTID_API_DLL InstrumentDataServiceImpl - : public Mantid::Kernel::DataService { +class MANTID_API_DLL InstrumentDataServiceImpl : public Mantid::Kernel::DataService { private: friend struct Mantid::Kernel::CreateUsingNew; /// Constructor @@ -28,19 +27,16 @@ private: /// Private, unimplemented copy constructor InstrumentDataServiceImpl(const InstrumentDataServiceImpl &) = delete; /// Private, unimplemented copy assignment operator - InstrumentDataServiceImpl & - operator=(const InstrumentDataServiceImpl &) = delete; + InstrumentDataServiceImpl &operator=(const InstrumentDataServiceImpl &) = delete; }; -using InstrumentDataService = - Mantid::Kernel::SingletonHolder; +using InstrumentDataService = Mantid::Kernel::SingletonHolder; } // Namespace API } // Namespace Mantid namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/InstrumentFileFinder.h b/Framework/API/inc/MantidAPI/InstrumentFileFinder.h index 8c7e62f7265ccdaf946892a6f4cdf6a90cc506cb..93b62b0927ec61eec3a20e3f897e0494f21857c3 100644 --- a/Framework/API/inc/MantidAPI/InstrumentFileFinder.h +++ b/Framework/API/inc/MantidAPI/InstrumentFileFinder.h @@ -17,22 +17,19 @@ class MANTID_API_DLL InstrumentFileFinder { public: /// Search instrument directories for Parameter file, /// return full path name if found, else "". - static std::string getParameterPath(const std::string &instName, - const std::string &dirHint = ""); + static std::string getParameterPath(const std::string &instName, const std::string &dirHint = ""); /// Get the IDF using the instrument name and date - static std::string getInstrumentFilename(const std::string &instrumentName, - const std::string &date = ""); + static std::string getInstrumentFilename(const std::string &instrumentName, const std::string &date = ""); /// Utility to retrieve a resource file (IDF, Parameters, ..) - static std::vector getResourceFilenames( - const std::string &prefix, const std::vector &fileFormats, - const std::vector &directoryNames, const std::string &date); + static std::vector getResourceFilenames(const std::string &prefix, + const std::vector &fileFormats, + const std::vector &directoryNames, + const std::string &date); /// Utility to retrieve the validity dates for the given IDF - static void getValidFromTo(const std::string &IDFfilename, - std::string &outValidFrom, - std::string &outValidTo); + static void getValidFromTo(const std::string &IDFfilename, std::string &outValidFrom, std::string &outValidTo); private: static std::string lookupIPF(const std::string &dir, std::string filename); diff --git a/Framework/API/inc/MantidAPI/InstrumentValidator.h b/Framework/API/inc/MantidAPI/InstrumentValidator.h index f3ef9a88d3a5b38fc6286f0ae08e16cb47c2090e..7849295516a09b3f99418dfa97e67c3201e21053 100644 --- a/Framework/API/inc/MantidAPI/InstrumentValidator.h +++ b/Framework/API/inc/MantidAPI/InstrumentValidator.h @@ -18,8 +18,7 @@ class ExperimentInfo; /** A validator which checks that a workspace has a valid instrument. */ -class MANTID_API_DLL InstrumentValidator - : public Kernel::TypedValidator> { +class MANTID_API_DLL InstrumentValidator : public Kernel::TypedValidator> { public: /// Enumeration describing requirements enum Requirements { SourcePosition = 0x1, SamplePosition = 0x2 }; @@ -28,8 +27,7 @@ public: InstrumentValidator(const unsigned int flags = SamplePosition); std::string getType() const; Kernel::IValidator_sptr clone() const override; - std::string - checkValidity(const std::shared_ptr &value) const override; + std::string checkValidity(const std::shared_ptr &value) const override; private: unsigned int m_requires; diff --git a/Framework/API/inc/MantidAPI/Jacobian.h b/Framework/API/inc/MantidAPI/Jacobian.h index f8ef3873f3870a8a173d5d42bb99cdb0bba4c8cb..e4a04983f540e98030113b3cffc2298ee5bc25aa 100644 --- a/Framework/API/inc/MantidAPI/Jacobian.h +++ b/Framework/API/inc/MantidAPI/Jacobian.h @@ -45,8 +45,7 @@ public: virtual void addNumberToColumn(const double &value, const size_t &iActiveP) { (void)value; (void)iActiveP; // Avoid compiler warning - throw Kernel::Exception::NotImplementedError( - "No addNumberToColumn() method of Jacobian provided"); + throw Kernel::Exception::NotImplementedError("No addNumberToColumn() method of Jacobian provided"); } ///@endcond diff --git a/Framework/API/inc/MantidAPI/LiveListenerFactory.h b/Framework/API/inc/MantidAPI/LiveListenerFactory.h index b3052497af34a69a0cbd1b88ac3d8358b2a5c2ed..06c4ad99650bb31fe2a288f75167a13164e0ec6e 100644 --- a/Framework/API/inc/MantidAPI/LiveListenerFactory.h +++ b/Framework/API/inc/MantidAPI/LiveListenerFactory.h @@ -14,12 +14,10 @@ * The second operation that this macro performs is to provide the definition * of the unitID method for the concrete unit. */ -#define DECLARE_LISTENER(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper register_listener_##classname( \ - ((Mantid::API::LiveListenerFactory::Instance().subscribe( \ - #classname)), \ - 0)); \ +#define DECLARE_LISTENER(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper register_listener_##classname( \ + ((Mantid::API::LiveListenerFactory::Instance().subscribe(#classname)), 0)); \ } //---------------------------------------------------------------------- @@ -36,17 +34,14 @@ namespace API { class IAlgorithm; /** The factory for creating instances of ILiveListener implementations. */ -class MANTID_API_DLL LiveListenerFactoryImpl - : public Kernel::DynamicFactory { +class MANTID_API_DLL LiveListenerFactoryImpl : public Kernel::DynamicFactory { public: - std::shared_ptr - create(const std::string &instrumentName, bool connect = false, - const API::IAlgorithm *callingAlgorithm = nullptr, - const std::string &listenerConnectionName = "") const; + std::shared_ptr create(const std::string &instrumentName, bool connect = false, + const API::IAlgorithm *callingAlgorithm = nullptr, + const std::string &listenerConnectionName = "") const; - std::shared_ptr - create(const Kernel::LiveListenerInfo &info, bool connect = false, - const API::IAlgorithm *callingAlgorithm = nullptr) const; + std::shared_ptr create(const Kernel::LiveListenerInfo &info, bool connect = false, + const API::IAlgorithm *callingAlgorithm = nullptr) const; LiveListenerFactoryImpl(const LiveListenerFactoryImpl &) = delete; LiveListenerFactoryImpl &operator=(const LiveListenerFactoryImpl &) = delete; @@ -74,7 +69,6 @@ using LiveListenerFactory = Kernel::SingletonHolder; namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/LogFilterGenerator.h b/Framework/API/inc/MantidAPI/LogFilterGenerator.h index 71f97a41e162d325c29f1831290f3534eec98f0f..633d2c9691983f4804200bc3a66a19923c725974 100644 --- a/Framework/API/inc/MantidAPI/LogFilterGenerator.h +++ b/Framework/API/inc/MantidAPI/LogFilterGenerator.h @@ -27,15 +27,13 @@ public: enum class FilterType { None, Status, Period, StatusAndPeriod }; /// Constructor taking workspace - LogFilterGenerator(const FilterType filterType, - const Mantid::API::MatrixWorkspace_const_sptr &workspace); + LogFilterGenerator(const FilterType filterType, const Mantid::API::MatrixWorkspace_const_sptr &workspace); /// Constructor taking run object LogFilterGenerator(const FilterType filterType, const Mantid::API::Run &run); /// Generate log filter from given workspace and log name - std::unique_ptr - generateFilter(const std::string &logName) const; + std::unique_ptr generateFilter(const std::string &logName) const; private: /// Filter log by "running" status @@ -43,8 +41,7 @@ private: /// Filter log by period void filterByPeriod(Mantid::Kernel::LogFilter *filter) const; /// Get log data from workspace - Mantid::Kernel::Property *getLogData(const std::string &logName, - bool warnIfNotFound = true) const; + Mantid::Kernel::Property *getLogData(const std::string &logName, bool warnIfNotFound = true) const; /// Type of filter const FilterType m_filterType; /// Run object containing logs diff --git a/Framework/API/inc/MantidAPI/LogManager.h b/Framework/API/inc/MantidAPI/LogManager.h index 522fd0c754463b0637e141de96372d1cd07fe202..a734c94c2dcc296680316fdf7a2467dd5b3b4fb6 100644 --- a/Framework/API/inc/MantidAPI/LogManager.h +++ b/Framework/API/inc/MantidAPI/LogManager.h @@ -55,8 +55,7 @@ public: //------------------------------------------------------------- /// Set the run start and end - void setStartAndEndTime(const Types::Core::DateAndTime &start, - const Types::Core::DateAndTime &end); + void setStartAndEndTime(const Types::Core::DateAndTime &start, const Types::Core::DateAndTime &end); /// Return the run start time const Types::Core::DateAndTime startTime() const; /// Return the run end time @@ -64,15 +63,12 @@ public: //------------------------------------------------------------- /// Filter the logs by time - virtual void filterByTime(const Types::Core::DateAndTime start, - const Types::Core::DateAndTime stop); + virtual void filterByTime(const Types::Core::DateAndTime start, const Types::Core::DateAndTime stop); /// Split the logs based on the given intervals - virtual void splitByTime(Kernel::TimeSplitterType &splitter, - std::vector outputs) const; + virtual void splitByTime(Kernel::TimeSplitterType &splitter, std::vector outputs) const; /// Filter the run by the given boolean log void filterByLog(const Kernel::TimeSeriesProperty &filter, - const std::vector &excludedFromFiltering = - std::vector()); + const std::vector &excludedFromFiltering = std::vector()); /// Return an approximate memory size for the object in bytes virtual size_t getMemorySize() const; @@ -83,16 +79,12 @@ public: addProperty(std::unique_ptr(prop), overwrite); }; /// Add data to the object in the form of a property - void addProperty(std::unique_ptr prop, - bool overwrite = false); + void addProperty(std::unique_ptr prop, bool overwrite = false); /// Add a property of given type - template - void addProperty(const std::string &name, const TYPE &value, - bool overwrite = false); + template void addProperty(const std::string &name, const TYPE &value, bool overwrite = false); template - void addProperty(const std::string &name, const TYPE &value, - const std::string &units, bool overwrite = false); + void addProperty(const std::string &name, const TYPE &value, const std::string &units, bool overwrite = false); /// Does the property exist on the object bool hasProperty(const std::string &name) const; @@ -102,17 +94,13 @@ public: /// Returns a property as a time series property. It will throw if it is not /// valid - template - Kernel::TimeSeriesProperty * - getTimeSeriesProperty(const std::string &name) const; + template Kernel::TimeSeriesProperty *getTimeSeriesProperty(const std::string &name) const; /// Get the value of a property as the given TYPE. Throws if the type is not /// correct - template - HeldType getPropertyValueAsType(const std::string &name) const; + template HeldType getPropertyValueAsType(const std::string &name) const; /// Returns a property as a single double value from its name - double getPropertyAsSingleValue( - const std::string &name, - Kernel::Math::StatisticType statistic = Kernel::Math::Mean) const; + double getPropertyAsSingleValue(const std::string &name, + Kernel::Math::StatisticType statistic = Kernel::Math::Mean) const; /// Returns a property as an integer value int getPropertyAsIntegerValue(const std::string &name) const; /// Returns the named property as a pointer @@ -123,34 +111,26 @@ public: * @param p :: A pointer to the property containing the log entry * @deprecated new code should use smart pointers */ - void addLogData(Kernel::Property *p) { - addLogData(std::unique_ptr(p)); - } + void addLogData(Kernel::Property *p) { addLogData(std::unique_ptr(p)); } /** * Add a log entry * @param p :: A pointer to the property containing the log entry * @param overwrite :: Overwrite existing if requested */ - void addLogData(std::unique_ptr p, bool overwrite = false) { - addProperty(std::move(p), overwrite); - } + void addLogData(std::unique_ptr p, bool overwrite = false) { addProperty(std::move(p), overwrite); } /** * Access a single log entry * @param name :: The name of the log entry to retrieve * @returns A pointer to a property containing the log entry */ - Kernel::Property *getLogData(const std::string &name) const { - return getProperty(name); - } + Kernel::Property *getLogData(const std::string &name) const { return getProperty(name); } /** * Access all log entries * @returns A list of all of the log entries */ - const std::vector &getLogData() const { - return getProperties(); - } + const std::vector &getLogData() const { return getProperties(); } /** * Remove a named log entry * @param name :: The name of the entry to remove @@ -165,9 +145,8 @@ public: * (default=Mean) * @return A log as a single value using the given statistic type */ - double getLogAsSingleValue( - const std::string &name, - Kernel::Math::StatisticType statistic = Kernel::Math::Mean) const { + double getLogAsSingleValue(const std::string &name, + Kernel::Math::StatisticType statistic = Kernel::Math::Mean) const { return getPropertyAsSingleValue(name, statistic); } @@ -180,11 +159,9 @@ public: void clearOutdatedTimeSeriesLogValues(); /// Save the run to a NeXus file with a given group name - virtual void saveNexus(::NeXus::File *file, const std::string &group, - bool keepOpen = false) const; + virtual void saveNexus(::NeXus::File *file, const std::string &group, bool keepOpen = false) const; /// Load the run from a NeXus file with a given group name - virtual void loadNexus(::NeXus::File *file, const std::string &group, - bool keepOpen = false); + virtual void loadNexus(::NeXus::File *file, const std::string &group, bool keepOpen = false); /// Clear the logs void clearLogs(); @@ -193,16 +170,14 @@ public: // returns the invalid values log if the log has a matching invalid values log // filter - Kernel::TimeSeriesProperty * - getInvalidValuesFilter(const std::string &logName) const; + Kernel::TimeSeriesProperty *getInvalidValuesFilter(const std::string &logName) const; bool operator==(const LogManager &other) const; bool operator!=(const LogManager &other) const; protected: /// Load the run from a NeXus file with a given group name - void loadNexus(::NeXus::File *file, - const std::map &entries); + void loadNexus(::NeXus::File *file, const std::map &entries); /// A pointer to a property manager std::unique_ptr m_manager; /// Name of the log entry containing the proton charge when retrieved using @@ -211,9 +186,7 @@ protected: private: /// Cache for the retrieved single values - std::unique_ptr, double>> - m_singleValueCache; + std::unique_ptr, double>> m_singleValueCache; }; /// shared pointer to the logManager base class using LogManager_sptr = std::shared_ptr; @@ -227,11 +200,8 @@ using LogManager_const_sptr = std::shared_ptr; * @param value :: The value of the property * @param overwrite :: If true, a current value is overwritten. (Default: False) */ -template -void LogManager::addProperty(const std::string &name, const TYPE &value, - bool overwrite) { - addProperty(std::make_unique>(name, value), - overwrite); +template void LogManager::addProperty(const std::string &name, const TYPE &value, bool overwrite) { + addProperty(std::make_unique>(name, value), overwrite); } /** @@ -244,8 +214,7 @@ void LogManager::addProperty(const std::string &name, const TYPE &value, * @param overwrite :: If true, a current value is overwritten. (Default: False) */ template -void LogManager::addProperty(const std::string &name, const TYPE &value, - const std::string &units, bool overwrite) { +void LogManager::addProperty(const std::string &name, const TYPE &value, const std::string &units, bool overwrite) { auto newProp = std::make_unique>(name, value); newProp->setUnits(units); addProperty(std::move(newProp), overwrite); diff --git a/Framework/API/inc/MantidAPI/MDFrameValidator.h b/Framework/API/inc/MantidAPI/MDFrameValidator.h index cdf5ea59c55e607bdfcd832af7187a496f7ebbb8..c11683814af2c3866dc695397bd42a46b92630c9 100644 --- a/Framework/API/inc/MantidAPI/MDFrameValidator.h +++ b/Framework/API/inc/MantidAPI/MDFrameValidator.h @@ -16,8 +16,7 @@ */ namespace Mantid { namespace API { -class MANTID_API_DLL MDFrameValidator - : public Kernel::TypedValidator { +class MANTID_API_DLL MDFrameValidator : public Kernel::TypedValidator { public: explicit MDFrameValidator(const std::string &frameName); /// Gets the type of the validator diff --git a/Framework/API/inc/MantidAPI/MDGeometry.h b/Framework/API/inc/MantidAPI/MDGeometry.h index 4fd0dfdeb60f980e4779eda8be25f4689ed8a5e2..8e080857484fc004d868801422f832e8cb8419b0 100644 --- a/Framework/API/inc/MantidAPI/MDGeometry.h +++ b/Framework/API/inc/MantidAPI/MDGeometry.h @@ -39,22 +39,18 @@ public: MDGeometry(); MDGeometry(const MDGeometry &other); virtual ~MDGeometry(); - void initGeometry( - std::vector> &dimensions); + void initGeometry(std::vector> &dimensions); // -------------------------------------------------------------------------------------------- // These are the main methods for dimensions, that CAN be overridden (e.g. by // MatrixWorkspace) virtual size_t getNumDims() const; virtual size_t getNumNonIntegratedDims() const; - virtual std::shared_ptr - getDimension(size_t index) const; - virtual std::shared_ptr - getDimensionWithId(std::string id) const; + virtual std::shared_ptr getDimension(size_t index) const; + virtual std::shared_ptr getDimensionWithId(std::string id) const; size_t getDimensionIndexByName(const std::string &name) const; size_t getDimensionIndexById(const std::string &id) const; - std::vector> - getNonIntegratedDimensions() const; + std::vector> getNonIntegratedDimensions() const; virtual std::vector estimateResolution() const; // -------------------------------------------------------------------------------------------- @@ -79,17 +75,12 @@ public: size_t numOriginalWorkspaces() const; std::shared_ptr getOriginalWorkspace(size_t index = 0) const; void setOriginalWorkspace(std::shared_ptr ws, size_t index = 0); - Mantid::API::CoordTransform const * - getTransformFromOriginal(size_t index = 0) const; - void setTransformFromOriginal(Mantid::API::CoordTransform *transform, - size_t index = 0); - Mantid::API::CoordTransform const * - getTransformToOriginal(size_t index = 0) const; - void setTransformToOriginal(Mantid::API::CoordTransform *transform, - size_t index = 0); - - void transformDimensions(std::vector &scaling, - std::vector &offset); + Mantid::API::CoordTransform const *getTransformFromOriginal(size_t index = 0) const; + void setTransformFromOriginal(Mantid::API::CoordTransform *transform, size_t index = 0); + Mantid::API::CoordTransform const *getTransformToOriginal(size_t index = 0) const; + void setTransformToOriginal(Mantid::API::CoordTransform *transform, size_t index = 0); + + void transformDimensions(std::vector &scaling, std::vector &offset); size_t getNumberTransformsToOriginal() const; size_t getNumberTransformsFromOriginal() const; @@ -125,8 +116,7 @@ public: protected: /// Function called when observer objects recieves a notification - void - deleteNotificationReceived(const std::shared_ptr &deleted); + void deleteNotificationReceived(const std::shared_ptr &deleted); /// Vector of the dimensions used, in the order X Y Z t, etc. std::vector> m_dimensions; @@ -141,13 +131,11 @@ protected: /// Coordinate Transformation that goes from the original workspace to this /// workspace's coordinates. - std::vector> - m_transforms_FromOriginal; + std::vector> m_transforms_FromOriginal; /// Coordinate Transformation that goes from this workspace's coordinates to /// the original workspace coordinates. - std::vector> - m_transforms_ToOriginal; + std::vector> m_transforms_ToOriginal; /// Helper that deals with notifications and observing the ADS std::unique_ptr m_notificationHelper; diff --git a/Framework/API/inc/MantidAPI/MatrixWorkspace.h b/Framework/API/inc/MantidAPI/MatrixWorkspace.h index 2848870cc21a3ab9818b44c1b97f71d7625821bf..db7b99b90e4b799664859fe74fb014cf9f4b3c75 100644 --- a/Framework/API/inc/MantidAPI/MatrixWorkspace.h +++ b/Framework/API/inc/MantidAPI/MatrixWorkspace.h @@ -49,8 +49,7 @@ using MantidImage_const_sptr = std::shared_ptr; @author Laurent C Chapon, ISIS, RAL @date 26/09/2007 */ -class MANTID_API_DLL MatrixWorkspace : public IMDWorkspace, - public ExperimentInfo { +class MANTID_API_DLL MatrixWorkspace : public IMDWorkspace, public ExperimentInfo { private: using ExperimentInfo::toString; @@ -60,12 +59,9 @@ public: // axes. friend class WorkspaceFactoryImpl; - void initialize(const std::size_t &NVectors, const std::size_t &XLength, - const std::size_t &YLength); - void initialize(const std::size_t &NVectors, - const HistogramData::Histogram &histogram); - void initialize(const Indexing::IndexInfo &indexInfo, - const HistogramData::Histogram &histogram); + void initialize(const std::size_t &NVectors, const std::size_t &XLength, const std::size_t &YLength); + void initialize(const std::size_t &NVectors, const HistogramData::Histogram &histogram); + void initialize(const Indexing::IndexInfo &indexInfo, const HistogramData::Histogram &histogram); MatrixWorkspace &operator=(const MatrixWorkspace &other) = delete; /// Delete @@ -75,9 +71,7 @@ public: MatrixWorkspace_uptr clone() const { return MatrixWorkspace_uptr(doClone()); } /// Returns a default-initialized clone of the workspace - MatrixWorkspace_uptr cloneEmpty() const { - return MatrixWorkspace_uptr(doCloneEmpty()); - } + MatrixWorkspace_uptr cloneEmpty() const { return MatrixWorkspace_uptr(doCloneEmpty()); } const Indexing::IndexInfo &indexInfo() const; void setIndexInfo(const Indexing::IndexInfo &indexInfo); @@ -88,8 +82,7 @@ public: /**@name Instrument queries */ //@{ - std::shared_ptr - getDetector(const size_t workspaceIndex) const; + std::shared_ptr getDetector(const size_t workspaceIndex) const; double detectorTwoTheta(const Geometry::IDetector &det) const; double detectorSignedTwoTheta(const Geometry::IDetector &det) const; @@ -98,26 +91,19 @@ public: virtual void updateSpectraUsing(const SpectrumDetectorMapping &map); /// Build the default spectra mapping, most likely wanted after an instrument /// update - void rebuildSpectraMapping(const bool includeMonitors = true, - const specnum_t specNumOffset = 1); + void rebuildSpectraMapping(const bool includeMonitors = true, const specnum_t specNumOffset = 1); // More mapping spec2index_map getSpectrumToWorkspaceIndexMap() const; - detid2index_map - getDetectorIDToWorkspaceIndexMap(bool throwIfMultipleDets = false) const; - virtual std::vector - getDetectorIDToWorkspaceIndexVector(detid_t &offset, - bool throwIfMultipleDets = false) const; - - virtual std::vector - getSpectrumToWorkspaceIndexVector(specnum_t &offset) const; - std::vector - getIndicesFromSpectra(const std::vector &spectraList) const; + detid2index_map getDetectorIDToWorkspaceIndexMap(bool throwIfMultipleDets = false) const; + virtual std::vector getDetectorIDToWorkspaceIndexVector(detid_t &offset, + bool throwIfMultipleDets = false) const; + + virtual std::vector getSpectrumToWorkspaceIndexVector(specnum_t &offset) const; + std::vector getIndicesFromSpectra(const std::vector &spectraList) const; size_t getIndexFromSpectrumNumber(const specnum_t specNo) const; - std::vector - getIndicesFromDetectorIDs(const std::vector &detIdList) const; - std::vector - getSpectraFromDetectorIDs(const std::vector &detIdList) const; + std::vector getIndicesFromDetectorIDs(const std::vector &detIdList) const; + std::vector getSpectraFromDetectorIDs(const std::vector &detIdList) const; bool hasGroupedDetectors() const; @@ -152,7 +138,7 @@ public: /// Returns the y index which corresponds to the X Value provided std::size_t yIndexOfX(const double xValue, const std::size_t &index = 0, - const double tolerance = 0.0) const; + [[maybe_unused]] const double tolerance = 0.0) const; //---------------------------------------------------------------------- // DATA ACCESSORS @@ -165,146 +151,85 @@ public: virtual const ISpectrum &getSpectrum(const size_t index) const = 0; /// Returns the Histogram at the given workspace index. - HistogramData::Histogram histogram(const size_t index) const { - return getSpectrum(index).histogram(); - } - template - void setHistogram(const size_t index, T &&... data) & { + HistogramData::Histogram histogram(const size_t index) const { return getSpectrum(index).histogram(); } + template void setHistogram(const size_t index, T &&...data) & { getSpectrum(index).setHistogram(std::forward(data)...); } - void convertToCounts(const size_t index) { - getSpectrumWithoutInvalidation(index).convertToCounts(); - } - void convertToFrequencies(const size_t index) { - getSpectrumWithoutInvalidation(index).convertToFrequencies(); - } - HistogramData::BinEdges binEdges(const size_t index) const { - return getSpectrum(index).binEdges(); - } - HistogramData::Points points(const size_t index) const { - return getSpectrum(index).points(); - } - HistogramData::PointStandardDeviations - pointStandardDeviations(const size_t index) const { + void convertToCounts(const size_t index) { getSpectrumWithoutInvalidation(index).convertToCounts(); } + void convertToFrequencies(const size_t index) { getSpectrumWithoutInvalidation(index).convertToFrequencies(); } + HistogramData::BinEdges binEdges(const size_t index) const { return getSpectrum(index).binEdges(); } + HistogramData::Points points(const size_t index) const { return getSpectrum(index).points(); } + HistogramData::PointStandardDeviations pointStandardDeviations(const size_t index) const { return getSpectrum(index).pointStandardDeviations(); } - template - void setBinEdges(const size_t index, T &&... data) & { + template void setBinEdges(const size_t index, T &&...data) & { getSpectrum(index).setBinEdges(std::forward(data)...); } - template void setPoints(const size_t index, T &&... data) & { + template void setPoints(const size_t index, T &&...data) & { getSpectrum(index).setPoints(std::forward(data)...); } - template - void setPointVariances(const size_t index, T &&... data) & { - getSpectrumWithoutInvalidation(index).setPointVariances( - std::forward(data)...); - } - template - void setPointStandardDeviations(const size_t index, T &&... data) & { - getSpectrumWithoutInvalidation(index).setPointStandardDeviations( - std::forward(data)...); - } - HistogramData::Counts counts(const size_t index) const { - return getSpectrum(index).counts(); + template void setPointVariances(const size_t index, T &&...data) & { + getSpectrumWithoutInvalidation(index).setPointVariances(std::forward(data)...); } - HistogramData::CountVariances countVariances(const size_t index) const { - return getSpectrum(index).countVariances(); + template void setPointStandardDeviations(const size_t index, T &&...data) & { + getSpectrumWithoutInvalidation(index).setPointStandardDeviations(std::forward(data)...); } - HistogramData::CountStandardDeviations - countStandardDeviations(const size_t index) const { + HistogramData::Counts counts(const size_t index) const { return getSpectrum(index).counts(); } + HistogramData::CountVariances countVariances(const size_t index) const { return getSpectrum(index).countVariances(); } + HistogramData::CountStandardDeviations countStandardDeviations(const size_t index) const { return getSpectrum(index).countStandardDeviations(); } - HistogramData::Frequencies frequencies(const size_t index) const { - return getSpectrum(index).frequencies(); - } - HistogramData::FrequencyVariances - frequencyVariances(const size_t index) const { + HistogramData::Frequencies frequencies(const size_t index) const { return getSpectrum(index).frequencies(); } + HistogramData::FrequencyVariances frequencyVariances(const size_t index) const { return getSpectrum(index).frequencyVariances(); } - HistogramData::FrequencyStandardDeviations - frequencyStandardDeviations(const size_t index) const { + HistogramData::FrequencyStandardDeviations frequencyStandardDeviations(const size_t index) const { return getSpectrum(index).frequencyStandardDeviations(); } - template void setCounts(const size_t index, T &&... data) & { + template void setCounts(const size_t index, T &&...data) & { getSpectrumWithoutInvalidation(index).setCounts(std::forward(data)...); } - template - void setCountVariances(const size_t index, T &&... data) & { - getSpectrumWithoutInvalidation(index).setCountVariances( - std::forward(data)...); - } - template - void setCountStandardDeviations(const size_t index, T &&... data) & { - getSpectrumWithoutInvalidation(index).setCountStandardDeviations( - std::forward(data)...); - } - template - void setFrequencies(const size_t index, T &&... data) & { - getSpectrumWithoutInvalidation(index).setFrequencies( - std::forward(data)...); - } - template - void setFrequencyVariances(const size_t index, T &&... data) & { - getSpectrumWithoutInvalidation(index).setFrequencyVariances( - std::forward(data)...); + template void setCountVariances(const size_t index, T &&...data) & { + getSpectrumWithoutInvalidation(index).setCountVariances(std::forward(data)...); } - template - void setFrequencyStandardDeviations(const size_t index, T &&... data) & { - getSpectrumWithoutInvalidation(index).setFrequencyStandardDeviations( - std::forward(data)...); + template void setCountStandardDeviations(const size_t index, T &&...data) & { + getSpectrumWithoutInvalidation(index).setCountStandardDeviations(std::forward(data)...); } - const HistogramData::HistogramX &x(const size_t index) const { - return getSpectrum(index).x(); + template void setFrequencies(const size_t index, T &&...data) & { + getSpectrumWithoutInvalidation(index).setFrequencies(std::forward(data)...); } - const HistogramData::HistogramY &y(const size_t index) const { - return getSpectrum(index).y(); + template void setFrequencyVariances(const size_t index, T &&...data) & { + getSpectrumWithoutInvalidation(index).setFrequencyVariances(std::forward(data)...); } - const HistogramData::HistogramE &e(const size_t index) const { - return getSpectrum(index).e(); - } - const HistogramData::HistogramDx &dx(const size_t index) const { - return getSpectrum(index).dx(); - } - HistogramData::HistogramX &mutableX(const size_t index) & { - return getSpectrum(index).mutableX(); + template void setFrequencyStandardDeviations(const size_t index, T &&...data) & { + getSpectrumWithoutInvalidation(index).setFrequencyStandardDeviations(std::forward(data)...); } + const HistogramData::HistogramX &x(const size_t index) const { return getSpectrum(index).x(); } + const HistogramData::HistogramY &y(const size_t index) const { return getSpectrum(index).y(); } + const HistogramData::HistogramE &e(const size_t index) const { return getSpectrum(index).e(); } + const HistogramData::HistogramDx &dx(const size_t index) const { return getSpectrum(index).dx(); } + HistogramData::HistogramX &mutableX(const size_t index) & { return getSpectrum(index).mutableX(); } HistogramData::HistogramDx &mutableDx(const size_t index) & { return getSpectrumWithoutInvalidation(index).mutableDx(); } - HistogramData::HistogramY &mutableY(const size_t index) & { - return getSpectrumWithoutInvalidation(index).mutableY(); - } - HistogramData::HistogramE &mutableE(const size_t index) & { - return getSpectrumWithoutInvalidation(index).mutableE(); - } - Kernel::cow_ptr sharedX(const size_t index) const { - return getSpectrum(index).sharedX(); - } - Kernel::cow_ptr sharedY(const size_t index) const { - return getSpectrum(index).sharedY(); - } - Kernel::cow_ptr sharedE(const size_t index) const { - return getSpectrum(index).sharedE(); - } - Kernel::cow_ptr - sharedDx(const size_t index) const { + HistogramData::HistogramY &mutableY(const size_t index) & { return getSpectrumWithoutInvalidation(index).mutableY(); } + HistogramData::HistogramE &mutableE(const size_t index) & { return getSpectrumWithoutInvalidation(index).mutableE(); } + Kernel::cow_ptr sharedX(const size_t index) const { return getSpectrum(index).sharedX(); } + Kernel::cow_ptr sharedY(const size_t index) const { return getSpectrum(index).sharedY(); } + Kernel::cow_ptr sharedE(const size_t index) const { return getSpectrum(index).sharedE(); } + Kernel::cow_ptr sharedDx(const size_t index) const { return getSpectrum(index).sharedDx(); } - void setSharedX(const size_t index, - const Kernel::cow_ptr &x) & { + void setSharedX(const size_t index, const Kernel::cow_ptr &x) & { getSpectrum(index).setSharedX(x); } - void setSharedDx(const size_t index, - const Kernel::cow_ptr &dx) & { + void setSharedDx(const size_t index, const Kernel::cow_ptr &dx) & { getSpectrumWithoutInvalidation(index).setSharedDx(dx); } - void setSharedY(const size_t index, - const Kernel::cow_ptr &y) & { + void setSharedY(const size_t index, const Kernel::cow_ptr &y) & { getSpectrumWithoutInvalidation(index).setSharedY(y); } - void setSharedE(const size_t index, - const Kernel::cow_ptr &e) & { + void setSharedE(const size_t index, const Kernel::cow_ptr &e) & { getSpectrumWithoutInvalidation(index).setSharedE(e); } // Methods for getting read-only access to the data. @@ -312,83 +237,56 @@ public: /// Deprecated, use x() instead. Returns a read-only (i.e. const) reference to /// the specified X array /// @param index :: workspace index to retrieve. - const MantidVec &readX(std::size_t const index) const { - return getSpectrum(index).dataX(); - } + const MantidVec &readX(std::size_t const index) const { return getSpectrum(index).dataX(); } /// Deprecated, use y() instead. Returns a read-only (i.e. const) reference to /// the specified Y array /// @param index :: workspace index to retrieve. - const MantidVec &readY(std::size_t const index) const { - return getSpectrum(index).dataY(); - } + const MantidVec &readY(std::size_t const index) const { return getSpectrum(index).dataY(); } /// Deprecated, use e() instead. Returns a read-only (i.e. const) reference to /// the specified E array /// @param index :: workspace index to retrieve. - const MantidVec &readE(std::size_t const index) const { - return getSpectrum(index).dataE(); - } + const MantidVec &readE(std::size_t const index) const { return getSpectrum(index).dataE(); } /// Deprecated, use dx() instead. Returns a read-only (i.e. const) reference /// to the specified X error array /// @param index :: workspace index to retrieve. - const MantidVec &readDx(size_t const index) const { - return getSpectrum(index).dataDx(); - } + const MantidVec &readDx(size_t const index) const { return getSpectrum(index).dataDx(); } /// Deprecated, use mutableX() instead. Returns the x data - virtual MantidVec &dataX(const std::size_t index) { - return getSpectrum(index).dataX(); - } + virtual MantidVec &dataX(const std::size_t index) { return getSpectrum(index).dataX(); } /// Deprecated, use mutableY() instead. Returns the y data - virtual MantidVec &dataY(const std::size_t index) { - return getSpectrumWithoutInvalidation(index).dataY(); - } + virtual MantidVec &dataY(const std::size_t index) { return getSpectrumWithoutInvalidation(index).dataY(); } /// Deprecated, use mutableE() instead. Returns the error data - virtual MantidVec &dataE(const std::size_t index) { - return getSpectrumWithoutInvalidation(index).dataE(); - } + virtual MantidVec &dataE(const std::size_t index) { return getSpectrumWithoutInvalidation(index).dataE(); } /// Deprecated, use mutableDx() instead. Returns the x error data - virtual MantidVec &dataDx(const std::size_t index) { - return getSpectrumWithoutInvalidation(index).dataDx(); - } + virtual MantidVec &dataDx(const std::size_t index) { return getSpectrumWithoutInvalidation(index).dataDx(); } /// Deprecated, use x() instead. Returns the x data const - virtual const MantidVec &dataX(const std::size_t index) const { - return getSpectrum(index).dataX(); - } + virtual const MantidVec &dataX(const std::size_t index) const { return getSpectrum(index).dataX(); } /// Deprecated, use y() instead. Returns the y data const - virtual const MantidVec &dataY(const std::size_t index) const { - return getSpectrum(index).dataY(); - } + virtual const MantidVec &dataY(const std::size_t index) const { return getSpectrum(index).dataY(); } /// Deprecated, use e() instead. Returns the error const - virtual const MantidVec &dataE(const std::size_t index) const { - return getSpectrum(index).dataE(); - } + virtual const MantidVec &dataE(const std::size_t index) const { return getSpectrum(index).dataE(); } /// Deprecated, use dx() instead. Returns the error const - virtual const MantidVec &dataDx(const std::size_t index) const { - return getSpectrum(index).dataDx(); - } + virtual const MantidVec &dataDx(const std::size_t index) const { return getSpectrum(index).dataDx(); } virtual double getXMin() const; virtual double getXMax() const; virtual void getXMinMax(double &xmin, double &xmax) const; /// Deprecated, use sharedX() instead. Returns a pointer to the x data - virtual Kernel::cow_ptr - refX(const std::size_t index) const { + virtual Kernel::cow_ptr refX(const std::size_t index) const { return getSpectrum(index).ptrX(); } /// Deprecated, use setSharedX() instead. Set the specified X array to point /// to the given existing array - virtual void setX(const std::size_t index, - const Kernel::cow_ptr &X) { + virtual void setX(const std::size_t index, const Kernel::cow_ptr &X) { getSpectrum(index).setX(X); } /// Deprecated, use setSharedX() instead. Set the specified X array to point /// to the given existing array - virtual void setX(const std::size_t index, - const std::shared_ptr &X) { + virtual void setX(const std::size_t index, const std::shared_ptr &X) { getSpectrum(index).setX(X); } @@ -396,24 +294,19 @@ public: * Probes if DX (X Error) values were set on a particular spectrum * @param index: the workspace index */ - virtual bool hasDx(const std::size_t index) const { - return getSpectrum(index).hasDx(); - } + virtual bool hasDx(const std::size_t index) const { return getSpectrum(index).hasDx(); } /// Generate the histogram or rebin the existing histogram. - virtual void generateHistogram(const std::size_t index, const MantidVec &X, - MantidVec &Y, MantidVec &E, + virtual void generateHistogram(const std::size_t index, const MantidVec &X, MantidVec &Y, MantidVec &E, bool skipError = false) const = 0; /// Return a vector with the integrated counts for all spectra withing the /// given range - virtual void getIntegratedSpectra(std::vector &out, const double minX, - const double maxX, + virtual void getIntegratedSpectra(std::vector &out, const double minX, const double maxX, const bool entireRange) const; /// Return an index in the X vector for an x-value close to a given value - std::pair getXIndex(size_t i, double x, bool isLeft = true, - size_t start = 0) const; + std::pair getXIndex(size_t i, double x, bool isLeft = true, size_t start = 0) const; //---------------------------------------------------------------------- @@ -437,8 +330,7 @@ public: std::string YUnit() const; void setYUnit(const std::string &newUnit); - std::string YUnitLabel(bool useLatex = false, - bool plotAsDistribution = false) const; + std::string YUnitLabel(bool useLatex = false, bool plotAsDistribution = false) const; void setYUnitLabel(const std::string &newLabel); /// Are the Y-values dimensioned? @@ -446,10 +338,8 @@ public: void setDistribution(bool newValue); // Methods to set and access masked bins - void maskBin(const size_t &workspaceIndex, const size_t &binIndex, - const double &weight = 1.0); - void flagMasked(const size_t &index, const size_t &binIndex, - const double &weight = 1.0); + void maskBin(const size_t &workspaceIndex, const size_t &binIndex, const double &weight = 1.0); + void flagMasked(const size_t &index, const size_t &binIndex, const double &weight = 1.0); bool hasMaskedBins(const size_t &workspaceIndex) const; bool hasAnyMaskedBins() const; /// Masked bins for each spectrum are stored as a set of pairs containing &monitorWS); + virtual void setMonitorWorkspace(const std::shared_ptr &monitorWS); std::shared_ptr monitorWorkspace() const; void loadInstrumentNexus(::NeXus::File *file); @@ -470,10 +359,8 @@ public: // MD Geometry methods //===================================================================================== size_t getNumDims() const override; - std::shared_ptr - getDimension(size_t index) const override; - std::shared_ptr - getDimensionWithId(std::string id) const override; + std::shared_ptr getDimension(size_t index) const override; + std::shared_ptr getDimensionWithId(std::string id) const override; //===================================================================================== // End MD Geometry methods //===================================================================================== @@ -491,32 +378,26 @@ public: /// Dimensin id for y-dimension. static const std::string yDimensionId; /// Generate a line plot through the matrix workspace. - LinePlot getLinePlot(const Mantid::Kernel::VMD &start, - const Mantid::Kernel::VMD &end, + LinePlot getLinePlot(const Mantid::Kernel::VMD &start, const Mantid::Kernel::VMD &end, Mantid::API::MDNormalization normalize) const override; /// Get the signal at a coordinate in the workspace. - signal_t getSignalAtCoord( - const coord_t *coords, - const Mantid::API::MDNormalization &normalization) const override; + signal_t getSignalAtCoord(const coord_t *coords, const Mantid::API::MDNormalization &normalization) const override; /// Get the signal at a coordinate in the workspace - signal_t getSignalWithMaskAtCoord( - const coord_t *coords, - const Mantid::API::MDNormalization &normalization) const override; + signal_t getSignalWithMaskAtCoord(const coord_t *coords, + const Mantid::API::MDNormalization &normalization) const override; /// Create iterators. Partitions the iterators according to the number of /// cores. - std::vector> createIterators( - size_t suggestedNumCores = 1, - Mantid::Geometry::MDImplicitFunction *function = nullptr) const override; + std::vector> + createIterators(size_t suggestedNumCores = 1, + Mantid::Geometry::MDImplicitFunction *function = nullptr) const override; /// Apply masking. - void setMDMasking(std::unique_ptr - maskingRegion) override; + void setMDMasking(std::unique_ptr maskingRegion) override; /// Clear exsting masking. void clearMDMasking() override; /// @return the special coordinate system used if any. - Mantid::Kernel::SpecialCoordinateSystem - getSpecialCoordinateSystem() const override; + Mantid::Kernel::SpecialCoordinateSystem getSpecialCoordinateSystem() const override; // Check if this class has an oriented lattice on a sample object virtual bool hasOrientedLattice() const override; @@ -525,8 +406,7 @@ public: /// @param value Number to find in Y /// @param idx starting indices for search /// @return Tuple with the ihistogram and bin indices. - virtual std::pair - findY(double value, const std::pair &idx = {0, 0}) const; + virtual std::pair findY(double value, const std::pair &idx = {0, 0}) const; //===================================================================================== // End IMDWorkspace methods @@ -537,22 +417,17 @@ public: //===================================================================================== /// Get start and end x indices for images - std::pair getImageStartEndXIndices(size_t i, double startX, - double endX) const; + std::pair getImageStartEndXIndices(size_t i, double startX, double endX) const; /// Create an image of Ys. - MantidImage_sptr getImageY(size_t start = 0, size_t stop = 0, - size_t width = 0, double startX = EMPTY_DBL(), + MantidImage_sptr getImageY(size_t start = 0, size_t stop = 0, size_t width = 0, double startX = EMPTY_DBL(), double endX = EMPTY_DBL()) const; /// Create an image of Es. - MantidImage_sptr getImageE(size_t start = 0, size_t stop = 0, - size_t width = 0, double startX = EMPTY_DBL(), + MantidImage_sptr getImageE(size_t start = 0, size_t stop = 0, size_t width = 0, double startX = EMPTY_DBL(), double endX = EMPTY_DBL()) const; /// Copy the data (Y's) from an image to this workspace. - virtual void setImageY(const MantidImage &image, size_t start = 0, - bool parallelExecution = true); + virtual void setImageY(const MantidImage &image, size_t start = 0, bool parallelExecution = true); /// Copy the data from an image to this workspace's errors. - virtual void setImageE(const MantidImage &image, size_t start = 0, - bool parallelExecution = true); + virtual void setImageE(const MantidImage &image, size_t start = 0, bool parallelExecution = true); //===================================================================================== // End image methods @@ -568,13 +443,11 @@ protected: /// Protected copy constructor. May be used by childs for cloning. MatrixWorkspace(const MatrixWorkspace &other); - MatrixWorkspace( - const Parallel::StorageMode storageMode = Parallel::StorageMode::Cloned); + MatrixWorkspace(const Parallel::StorageMode storageMode = Parallel::StorageMode::Cloned); /// Initialises the workspace. Sets the size and lengths of the arrays. Must /// be overloaded. - virtual void init(const std::size_t &NVectors, const std::size_t &XLength, - const std::size_t &YLength) = 0; + virtual void init(const std::size_t &NVectors, const std::size_t &XLength, const std::size_t &YLength) = 0; virtual void init(const HistogramData::Histogram &histogram) = 0; virtual ISpectrum &getSpectrumWithoutInvalidation(const size_t index) = 0; @@ -585,23 +458,20 @@ protected: std::vector> m_axes; private: - std::size_t binIndexOfValue(Mantid::HistogramData::HistogramX const &xValues, - const double xValue, + std::size_t binIndexOfValue(Mantid::HistogramData::HistogramX const &xValues, const double xValue, const bool ascendingOrder) const; - std::size_t xIndexOfValue(const Mantid::HistogramData::HistogramX &xValues, - const double xValue, const double tolerance) const; + std::size_t xIndexOfValue(const Mantid::HistogramData::HistogramX &xValues, const double xValue, + const double tolerance) const; MatrixWorkspace *doClone() const override = 0; MatrixWorkspace *doCloneEmpty() const override = 0; /// Create an MantidImage instance. - MantidImage_sptr - getImage(const MantidVec &(MatrixWorkspace::*read)(std::size_t const) const, - size_t start, size_t stop, size_t width, size_t indexStart, - size_t indexEnd) const; + MantidImage_sptr getImage(const MantidVec &(MatrixWorkspace::*read)(std::size_t const) const, size_t start, + size_t stop, size_t width, size_t indexStart, size_t indexEnd) const; /// Copy data from an image. - void setImage(MantidVec &(MatrixWorkspace::*dataVec)(const std::size_t), - const MantidImage &image, size_t start, bool parallelExecution); + void setImage(MantidVec &(MatrixWorkspace::*dataVec)(const std::size_t), const MantidImage &image, size_t start, + [[maybe_unused]] bool parallelExecution); void setIndexInfoWithoutISpectrumUpdate(const Indexing::IndexInfo &indexInfo); void buildDefaultSpectrumDefinitions(); diff --git a/Framework/API/inc/MantidAPI/MatrixWorkspaceMDIterator.h b/Framework/API/inc/MantidAPI/MatrixWorkspaceMDIterator.h index 967b06c72907046f1f105bf0e2209876b5f905c0..0d25bc093dbb7e7402731b772953efd882547780 100644 --- a/Framework/API/inc/MantidAPI/MatrixWorkspaceMDIterator.h +++ b/Framework/API/inc/MantidAPI/MatrixWorkspaceMDIterator.h @@ -23,8 +23,7 @@ namespace API { */ class MANTID_API_DLL MatrixWorkspaceMDIterator : public IMDIterator { public: - MatrixWorkspaceMDIterator(const MatrixWorkspace *workspace, - Mantid::Geometry::MDImplicitFunction *function, + MatrixWorkspaceMDIterator(const MatrixWorkspace *workspace, Mantid::Geometry::MDImplicitFunction *function, size_t beginWI = 0, size_t endWI = size_t(-1)); size_t getDataSize() const override; @@ -44,18 +43,18 @@ public: signal_t getError() const override; - std::unique_ptr - getVertexesArray(size_t &numVertices) const override; + std::unique_ptr getVertexesArray(size_t &numVertices) const override; - std::unique_ptr - getVertexesArray(size_t &numVertices, const size_t outDimensions, - const bool *maskDim) const override; + std::unique_ptr getVertexesArray(size_t &numVertices, const size_t outDimensions, + const bool *maskDim) const override; Mantid::Kernel::VMD getCenter() const override; size_t getNumEvents() const override; - uint16_t getInnerRunIndex(size_t index) const override; + uint16_t getInnerExpInfoIndex(size_t index) const override; + + uint16_t getInnerGoniometerIndex(size_t index) const override; int32_t getInnerDetectorID(size_t index) const override; diff --git a/Framework/API/inc/MantidAPI/MatrixWorkspaceValidator.h b/Framework/API/inc/MantidAPI/MatrixWorkspaceValidator.h index 6911adbd6703c38768d420b79b0579dba55b87bd..c03bb7b4d1255292f2738bc5fcc2e8533aa3b924 100644 --- a/Framework/API/inc/MantidAPI/MatrixWorkspaceValidator.h +++ b/Framework/API/inc/MantidAPI/MatrixWorkspaceValidator.h @@ -16,8 +16,7 @@ namespace API { /** An interface for those validators that require the MatrixWorkspace interface */ -class MANTID_API_DLL MatrixWorkspaceValidator - : public Kernel::TypedValidator {}; +class MANTID_API_DLL MatrixWorkspaceValidator : public Kernel::TypedValidator {}; } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/MuParserUtils.h b/Framework/API/inc/MantidAPI/MuParserUtils.h index a77d2ee9bd15c47a3c1c08ee676bd4e3dc443c90..35a7cbee059e5f54271eb00793930d6c6062c31e 100644 --- a/Framework/API/inc/MantidAPI/MuParserUtils.h +++ b/Framework/API/inc/MantidAPI/MuParserUtils.h @@ -27,8 +27,7 @@ extern const MANTID_API_DLL std::map MUPARSER_CONSTANTS; void MANTID_API_DLL addDefaultConstants(mu::Parser &parser); using oneVarFun = double (*)(double); // pointer to a function of one variable -extern const MANTID_API_DLL std::map - MUPARSER_ONEVAR_FUNCTIONS; +extern const MANTID_API_DLL std::map MUPARSER_ONEVAR_FUNCTIONS; void MANTID_API_DLL extraOneVarFunctions(mu::Parser &parser); diff --git a/Framework/API/inc/MantidAPI/MultiDomainFunction.h b/Framework/API/inc/MantidAPI/MultiDomainFunction.h index e430787d23b521e9e97661a650083b48aab5f9ef..82d287be64c40ea0a0e24bd35592dbfd04bbbaa8 100644 --- a/Framework/API/inc/MantidAPI/MultiDomainFunction.h +++ b/Framework/API/inc/MantidAPI/MultiDomainFunction.h @@ -36,8 +36,7 @@ public: /// @param domain :: The input domain over which the function is to be /// calculated /// @param values :: A storage object for the calculated values - void function(const FunctionDomain &domain, - FunctionValues &values) const override; + void function(const FunctionDomain &domain, FunctionValues &values) const override; /// Derivatives of function with respect to active parameters void functionDeriv(const FunctionDomain &domain, Jacobian &jacobian) override; /// Called at the start of each iteration @@ -48,15 +47,13 @@ public: /// Associate a function and a domain void setDomainIndex(size_t funIndex, size_t domainIndex); /// Associate a function and a list of domains - void setDomainIndices(size_t funIndex, - const std::vector &domainIndices); + void setDomainIndices(size_t funIndex, const std::vector &domainIndices); /// Clear all domain indices void clearDomainIndices(); /// Get the largest domain index size_t getMaxIndex() const { return m_maxIndex; } /// Get domain indices for a member function - void getDomainIndices(size_t i, size_t nDomains, - std::vector &domains) const; + void getDomainIndices(size_t i, size_t nDomains, std::vector &domains) const; /// Get number of domains required by this function size_t getNumberDomains() const override; /// Create a list of equivalent functions @@ -68,19 +65,13 @@ public: /// of individual member functions. size_t nLocalAttributes() const override { return 1; } /// Returns a list of attribute names - std::vector getLocalAttributeNames() const override { - return std::vector(1, "domains"); - } + std::vector getLocalAttributeNames() const override { return std::vector(1, "domains"); } /// Return a value of attribute attName - Attribute getLocalAttribute(size_t i, - const std::string &attName) const override; + Attribute getLocalAttribute(size_t i, const std::string &attName) const override; /// Set a value to attribute attName - void setLocalAttribute(size_t i, const std::string &attName, - const Attribute &) override; + void setLocalAttribute(size_t i, const std::string &attName, const Attribute &) override; /// Check if attribute attName exists - bool hasLocalAttribute(const std::string &attName) const override { - return attName == "domains"; - } + bool hasLocalAttribute(const std::string &attName) const override { return attName == "domains"; } protected: /// Counts number of the domains diff --git a/Framework/API/inc/MantidAPI/MultiPeriodGroupWorker.h b/Framework/API/inc/MantidAPI/MultiPeriodGroupWorker.h index 8d4e713f00bf4c09663ce629d9ca8959df180821..cccea7addcd047f166e31a5088b3ca76c82e21dc 100644 --- a/Framework/API/inc/MantidAPI/MultiPeriodGroupWorker.h +++ b/Framework/API/inc/MantidAPI/MultiPeriodGroupWorker.h @@ -41,8 +41,7 @@ public: /// Check groups VecWSGroupType findMultiPeriodGroups(Algorithm const *const sourceAlg) const; /// Process groups - bool processGroups(Algorithm *const sourceAlg, - const VecWSGroupType &vecMultiPeriodGroups) const; + bool processGroups(Algorithm *const sourceAlg, const VecWSGroupType &vecMultiPeriodGroups) const; private: // Disable copy @@ -51,23 +50,18 @@ private: MultiPeriodGroupWorker &operator=(const MultiPeriodGroupWorker &); /// Try ot add a workspace to the group of input workspaces. - void tryAddInputWorkspaceToInputGroups( - const Workspace_sptr &ws, VecWSGroupType &vecMultiPeriodWorkspaceGroups, - VecWSGroupType &vecWorkspaceGroups) const; + void tryAddInputWorkspaceToInputGroups(const Workspace_sptr &ws, VecWSGroupType &vecMultiPeriodWorkspaceGroups, + VecWSGroupType &vecWorkspaceGroups) const; /// Copy input workspace properties to spawned algorithm. - void copyInputWorkspaceProperties(IAlgorithm *targetAlg, - IAlgorithm *sourceAlg, - const int &periodNumber) const; + void copyInputWorkspaceProperties(IAlgorithm *targetAlg, IAlgorithm *sourceAlg, const int &periodNumber) const; /// Create an input workspace string from the workspace groups. - std::string createFormattedInputWorkspaceNames( - const size_t &periodIndex, - const VecWSGroupType &vecWorkspaceGroups) const; + std::string createFormattedInputWorkspaceNames(const size_t &periodIndex, + const VecWSGroupType &vecWorkspaceGroups) const; /// Validate the input group workspace - void validateMultiPeriodGroupInputs( - const VecWSGroupType &vecMultiPeriodGroups) const; + void validateMultiPeriodGroupInputs(const VecWSGroupType &vecMultiPeriodGroups) const; /// Workspace property name std::string m_workspacePropertyName; diff --git a/Framework/API/inc/MantidAPI/MultipleExperimentInfos.h b/Framework/API/inc/MantidAPI/MultipleExperimentInfos.h index 94c4d6c202d7bf506ee6567dfbe565f4b7d34d6c..4e95e40758472bf51d0b0698d0d3540fc7854f14 100644 --- a/Framework/API/inc/MantidAPI/MultipleExperimentInfos.h +++ b/Framework/API/inc/MantidAPI/MultipleExperimentInfos.h @@ -23,13 +23,13 @@ public: MultipleExperimentInfos(const MultipleExperimentInfos &other); virtual ~MultipleExperimentInfos() = default; - ExperimentInfo_sptr getExperimentInfo(const uint16_t runIndex); + ExperimentInfo_sptr getExperimentInfo(const uint16_t expInfoIndex); - ExperimentInfo_const_sptr getExperimentInfo(const uint16_t runIndex) const; + ExperimentInfo_const_sptr getExperimentInfo(const uint16_t expInfoIndex) const; uint16_t addExperimentInfo(const ExperimentInfo_sptr &ei); - void setExperimentInfo(const uint16_t runIndex, ExperimentInfo_sptr ei); + void setExperimentInfo(const uint16_t expInfoIndex, ExperimentInfo_sptr ei); uint16_t getNumExperimentInfo() const; @@ -48,8 +48,7 @@ private: }; using MultipleExperimentInfos_sptr = std::shared_ptr; -using MultipleExperimentInfos_const_sptr = - std::shared_ptr; +using MultipleExperimentInfos_const_sptr = std::shared_ptr; } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/MultipleFileProperty.h b/Framework/API/inc/MantidAPI/MultipleFileProperty.h index 498acf08f0e1e94f02ac2983d9b81c181c08f43d..4ada85de470be221040ba4e14ff8c3f58314d876 100644 --- a/Framework/API/inc/MantidAPI/MultipleFileProperty.h +++ b/Framework/API/inc/MantidAPI/MultipleFileProperty.h @@ -111,24 +111,18 @@ namespace API { ------------------------------------------------------------------------------------------------------ */ -class MANTID_API_DLL MultipleFileProperty - : public Kernel::PropertyWithValue>> { +class MANTID_API_DLL MultipleFileProperty : public Kernel::PropertyWithValue>> { public: - MultipleFileProperty( - const std::string &name, unsigned int action, - const std::vector &exts = std::vector(), - bool allowEmptyTokens = false); + MultipleFileProperty(const std::string &name, unsigned int action, + const std::vector &exts = std::vector(), + bool allowEmptyTokens = false); - MultipleFileProperty( - const std::string &name, - const std::vector &exts = std::vector()); + MultipleFileProperty(const std::string &name, const std::vector &exts = std::vector()); MultipleFileProperty(const MultipleFileProperty &) = default; MultipleFileProperty &operator=(const MultipleFileProperty &) = default; - MultipleFileProperty *clone() const override { - return new MultipleFileProperty(*this); - } + MultipleFileProperty *clone() const override { return new MultipleFileProperty(*this); } std::string setValue(const std::string &propValue) override; std::string value() const override; @@ -142,8 +136,7 @@ public: std::string getDefaultExt() const { return m_defaultExt; } // Unhide the PropertyWithValue assignment operator - using Kernel::PropertyWithValue>>:: - operator=; + using Kernel::PropertyWithValue>>::operator=; private: /// Returns a string depending on whether an empty value is valid diff --git a/Framework/API/inc/MantidAPI/NexusFileLoader.h b/Framework/API/inc/MantidAPI/NexusFileLoader.h index 39a35fce17cd50055622deeb3bede9098822edf3..9033f54b1d9f01a708e9dded182d5054e80a5b09 100644 --- a/Framework/API/inc/MantidAPI/NexusFileLoader.h +++ b/Framework/API/inc/MantidAPI/NexusFileLoader.h @@ -12,31 +12,25 @@ namespace Mantid::API { -class MANTID_API_DLL NexusFileLoader - : public API::IFileLoader { +class MANTID_API_DLL NexusFileLoader : public API::IFileLoader { public: - void - exec() override final; // makes sure the NexusHDF5Descriptor is initialized + void exec() override final; // makes sure the NexusHDF5Descriptor is initialized virtual void execLoader() = 0; // what would normally be called exec // the name of the property that the NexusHDF5Descriptor should be created // against virtual std::string getFilenamePropertyName() const; - std::shared_ptr createChildAlgorithm( - const std::string &name, const double startProgress = -1., - const double endProgress = -1., const bool enableLogging = true, - const int &version = -1) override; - virtual void - setFileInfo(std::shared_ptr fileInfo); + std::shared_ptr createChildAlgorithm(const std::string &name, const double startProgress = -1., + const double endProgress = -1., const bool enableLogging = true, + const int &version = -1) override; + virtual void setFileInfo(std::shared_ptr fileInfo); /// Required to pass m_fileInfo to static functions /// Keeping it shared_ptr to match setFileInfo signature (although passing /// ownership is not the main goal). - virtual const std::shared_ptr - getFileInfo() const noexcept; + virtual const std::shared_ptr getFileInfo() const noexcept; - virtual int - confidence(Kernel::NexusHDF5Descriptor &descriptor) const override = 0; + virtual int confidence(Kernel::NexusHDF5Descriptor &descriptor) const override = 0; private: std::shared_ptr m_fileInfo; diff --git a/Framework/API/inc/MantidAPI/NotebookBuilder.h b/Framework/API/inc/MantidAPI/NotebookBuilder.h index daf9f80a76f7d8714734d2b831913f56b2525d81..9aab36cb27b864ea4b752a14f0b5a121d3d9c887 100644 --- a/Framework/API/inc/MantidAPI/NotebookBuilder.h +++ b/Framework/API/inc/MantidAPI/NotebookBuilder.h @@ -26,21 +26,16 @@ namespace API { class MANTID_API_DLL NotebookBuilder { public: - NotebookBuilder(const std::shared_ptr &view, - std::string versionSpecificity = "old"); + NotebookBuilder(const std::shared_ptr &view, std::string versionSpecificity = "old"); virtual ~NotebookBuilder() = default; /// build an ipython notebook from the history view - const std::string build(const std::string &ws_name, - const std::string &ws_title, - const std::string &ws_comment); + const std::string build(const std::string &ws_name, const std::string &ws_title, const std::string &ws_comment); private: void writeHistoryToStream(std::vector::const_iterator &iter); void buildChildren(std::vector::const_iterator &iter); - const std::string - buildAlgorithmString(const AlgorithmHistory_const_sptr &algHistory); - const std::string buildPropertyString( - const Mantid::Kernel::PropertyHistory_const_sptr &propHistory); + const std::string buildAlgorithmString(const AlgorithmHistory_const_sptr &algHistory); + const std::string buildPropertyString(const Mantid::Kernel::PropertyHistory_const_sptr &propHistory); const std::vector m_historyItems; std::string m_output; diff --git a/Framework/API/inc/MantidAPI/NullCoordTransform.h b/Framework/API/inc/MantidAPI/NullCoordTransform.h index 2717cd8d9729e6d1c47bb2b5985139d1afea512d..1445813b8532261d6b9a13cd6b87ad90211420d9 100644 --- a/Framework/API/inc/MantidAPI/NullCoordTransform.h +++ b/Framework/API/inc/MantidAPI/NullCoordTransform.h @@ -22,8 +22,7 @@ public: NullCoordTransform(size_t ndims = 3); std::string toXMLString() const override; std::string id() const override; - void apply(const Mantid::coord_t *inputVector, - Mantid::coord_t *outVector) const override; + void apply(const Mantid::coord_t *inputVector, Mantid::coord_t *outVector) const override; CoordTransform *clone() const override; private: diff --git a/Framework/API/inc/MantidAPI/NumericAxis.h b/Framework/API/inc/MantidAPI/NumericAxis.h index 1371a4c5a42e1fbf513c33c9d4d385ed3749711d..92477b2b372aac7e18cb37104a6362cb9a5d0ad5 100644 --- a/Framework/API/inc/MantidAPI/NumericAxis.h +++ b/Framework/API/inc/MantidAPI/NumericAxis.h @@ -32,20 +32,17 @@ public: NumericAxis(const std::vector ¢res); Axis *clone(const MatrixWorkspace *const parentWorkspace) override; - Axis *clone(const std::size_t length, - const MatrixWorkspace *const parentWorkspace) override; + Axis *clone(const std::size_t length, const MatrixWorkspace *const parentWorkspace) override; /// Is the axis numeric - always true for this class bool isNumeric() const override { return true; } std::size_t length() const override { return m_values.size(); } /// Get a value at the specified index - double operator()(const std::size_t &index, - const std::size_t &verticalIndex = 0) const override; + double operator()(const std::size_t &index, const std::size_t &verticalIndex = 0) const override; /// Set the value at a specific index void setValue(const std::size_t &index, const double &value) override; size_t indexOfValue(const double value) const override; bool operator==(const Axis &) const override; - virtual bool equalWithinTolerance(const Axis &axis2, - const double tolerance) const; + virtual bool equalWithinTolerance(const Axis &axis2, const double tolerance) const; std::string label(const std::size_t &index) const override; /// Create bin boundaries from the point values virtual std::vector createBinBoundaries() const; @@ -62,6 +59,9 @@ protected: /// A vector holding the centre values. std::vector m_values; + + /// Get number label + std::string formatLabel(const double value) const; }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/OrientedLatticeValidator.h b/Framework/API/inc/MantidAPI/OrientedLatticeValidator.h index a90c1c7d30ec899e935229afe6c9426a9be1fc45..ebe9a7333fa0758bfaae114e05cbdafcb722fdca 100644 --- a/Framework/API/inc/MantidAPI/OrientedLatticeValidator.h +++ b/Framework/API/inc/MantidAPI/OrientedLatticeValidator.h @@ -16,8 +16,7 @@ */ namespace Mantid { namespace API { -class MANTID_API_DLL OrientedLatticeValidator - : public Kernel::TypedValidator { +class MANTID_API_DLL OrientedLatticeValidator : public Kernel::TypedValidator { public: /// Gets the type of the validator std::string getType() const { return "orientedlattice"; } @@ -26,8 +25,7 @@ public: private: /// Check for validity. - std::string - checkValidity(const ExperimentInfo_sptr &workspace) const override; + std::string checkValidity(const ExperimentInfo_sptr &workspace) const override; }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/ParallelAlgorithm.h b/Framework/API/inc/MantidAPI/ParallelAlgorithm.h index e362d53afe98506765d74cc7020dcc70322a6796..93bdcf5062a17c9baabe5fdb516ae82762f03890 100644 --- a/Framework/API/inc/MantidAPI/ParallelAlgorithm.h +++ b/Framework/API/inc/MantidAPI/ParallelAlgorithm.h @@ -31,9 +31,8 @@ namespace API { */ class MANTID_API_DLL ParallelAlgorithm : public API::Algorithm { protected: - Parallel::ExecutionMode getParallelExecutionMode( - const std::map &storageModes) - const override; + Parallel::ExecutionMode + getParallelExecutionMode(const std::map &storageModes) const override; }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/ParamFunction.h b/Framework/API/inc/MantidAPI/ParamFunction.h index 553594f2ea9f3ad0ec76b6d2d1e94676657da2ac..9c31dffbd075c2f8c140ec6a23dfa297338ffcdb 100644 --- a/Framework/API/inc/MantidAPI/ParamFunction.h +++ b/Framework/API/inc/MantidAPI/ParamFunction.h @@ -36,18 +36,15 @@ public: ParamFunction() {} /// Set i-th parameter - void setParameter(size_t, const double &value, - bool explicitlySet = true) override; + void setParameter(size_t, const double &value, bool explicitlySet = true) override; /// Set i-th parameter description void setParameterDescription(size_t, const std::string &description) override; /// Get i-th parameter double getParameter(size_t i) const override; /// Set parameter by name. - void setParameter(const std::string &name, const double &value, - bool explicitlySet = true) override; + void setParameter(const std::string &name, const double &value, bool explicitlySet = true) override; /// Set description of parameter by name. - void setParameterDescription(const std::string &name, - const std::string &description) override; + void setParameterDescription(const std::string &name, const std::string &description) override; /// Get parameter by name. double getParameter(const std::string &name) const override; /// Check if function has a parameter with this name. @@ -81,8 +78,7 @@ public: protected: /// Declare a new parameter - void declareParameter(const std::string &name, double initValue = 0, - const std::string &description = "") override; + void declareParameter(const std::string &name, double initValue = 0, const std::string &description = "") override; /// Get the address of the parameter. For use in UserFunction with mu::Parser virtual double *getParameterAddress(size_t i); /// Nonvirtual member which removes all declared parameters @@ -97,8 +93,7 @@ private: /// @param i :: Index to check. inline void checkParameterIndex(size_t i) const { if (i >= nParams()) { - throw std::out_of_range("ParamFunction parameter index " + - std::to_string(i) + " out of range " + + throw std::out_of_range("ParamFunction parameter index " + std::to_string(i) + " out of range " + std::to_string(nParams())); } } diff --git a/Framework/API/inc/MantidAPI/ParameterTie.h b/Framework/API/inc/MantidAPI/ParameterTie.h index 130b779966f5594892b023ee6900c6417d5702b4..cb2c72f86460a6673772f64ca0065bbcd008b490 100644 --- a/Framework/API/inc/MantidAPI/ParameterTie.h +++ b/Framework/API/inc/MantidAPI/ParameterTie.h @@ -35,14 +35,13 @@ namespace API { class MANTID_API_DLL ParameterTie final : public ParameterReference { public: /// Constructor - ParameterTie(IFunction *funct, const std::string &parName, - const std::string &expr = "", bool isDefault = false); + ParameterTie(IFunction *funct, const std::string &parName, const std::string &expr = "", bool isDefault = false); /// Destructor ~ParameterTie() override; /// Set the tie expression virtual void set(const std::string &expr); /// Evaluate the expression - virtual double eval(); + virtual double eval(bool setParameterValue = true); /// Return the string that can be used to recreate this tie virtual std::string asString(const IFunction *fun = nullptr) const; diff --git a/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h b/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h index 880d797edac57cc1d2004703f1d5a68dd537796e..492874f83ce15a73d079462911ffd5ad6c2b8b30 100644 --- a/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h +++ b/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h @@ -26,9 +26,9 @@ namespace API { */ struct MANTID_API_DLL IntegrationResult { - double result; - double error; - size_t intervals; + double result; // integrated intensity + double error; // error in result due to numerical errors in the integration algorithm + size_t intervals; // number of bins in which the integration range is divided int errorCode; bool success; @@ -43,17 +43,14 @@ public: double requiredRelativePrecision() const; IntegrationResult integrateInfinity(const IPeakFunction &peakFunction) const; - IntegrationResult integratePositiveInfinity(const IPeakFunction &peakFunction, - double lowerLimit) const; - IntegrationResult integrateNegativeInfinity(const IPeakFunction &peakFunction, - double upperLimit) const; + IntegrationResult integratePositiveInfinity(const IPeakFunction &peakFunction, double lowerLimit) const; + IntegrationResult integrateNegativeInfinity(const IPeakFunction &peakFunction, double upperLimit) const; - IntegrationResult integrate(const IPeakFunction &peakFunction, - double lowerLimit, double upperLimit) const; + IntegrationResult integrate(const IPeakFunction &peakFunction, double lowerLimit, double upperLimit) const; + double integrateError(const IPeakFunction &peakFunction, double lowerLimit, double upperLimit) const; protected: gsl_function getGSLFunction(const IPeakFunction &peakFunction) const; - gsl_integration_workspace *m_integrationWorkspace; double m_relativePrecision; diff --git a/Framework/API/inc/MantidAPI/PreviewManager.h b/Framework/API/inc/MantidAPI/PreviewManager.h index 50fdea0dea0ccacb33f2a30cbb210a8cc21d8d54..a9c84f2d06e739a58bb550839dc7846bd276d98d 100644 --- a/Framework/API/inc/MantidAPI/PreviewManager.h +++ b/Framework/API/inc/MantidAPI/PreviewManager.h @@ -19,9 +19,7 @@ namespace Mantid { namespace API { -using PreviewRegister = - std::map>>; +using PreviewRegister = std::map>>; /** PreviewManager : Manages the raw data previews. */ @@ -30,10 +28,8 @@ public: PreviewManagerImpl() = default; PreviewManagerImpl(const PreviewManagerImpl &) = delete; PreviewManagerImpl &operator=(const PreviewManagerImpl &) = delete; - std::vector getPreviews(const std::string &facility, - const std::string &technique = "") const; - const IPreview &getPreview(const std::string &facility, - const std::string &technique, + std::vector getPreviews(const std::string &facility, const std::string &technique = "") const; + const IPreview &getPreview(const std::string &facility, const std::string &technique, const std::string &preview) const; template void subscribe() { static_assert(std::is_base_of::value); @@ -42,19 +38,16 @@ public: const auto technique = preview->technique(); const auto name = preview->name(); if (checkPreview(facility, technique, name)) { - throw std::runtime_error( - "Preview with the same name is already registered for the same " - "facility and technique."); + throw std::runtime_error("Preview with the same name is already registered for the same " + "facility and technique."); } m_previews[facility][technique][name] = std::move(preview); } private: bool checkFacility(const std::string &facility) const; - bool checkTechnique(const std::string &facility, - const std::string &technique) const; - bool checkPreview(const std::string &facility, const std::string &technique, - const std::string &preview) const; + bool checkTechnique(const std::string &facility, const std::string &technique) const; + bool checkPreview(const std::string &facility, const std::string &technique, const std::string &preview) const; PreviewRegister m_previews; }; @@ -65,13 +58,12 @@ using PreviewManager = Mantid::Kernel::SingletonHolder; namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid -#define DECLARE_PREVIEW(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper register_preview_##classname( \ - ((Mantid::API::PreviewManager::Instance().subscribe()), 0)); \ +#define DECLARE_PREVIEW(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper \ + register_preview_##classname(((Mantid::API::PreviewManager::Instance().subscribe()), 0)); \ } diff --git a/Framework/API/inc/MantidAPI/RefAxis.h b/Framework/API/inc/MantidAPI/RefAxis.h index a12c89304e56bfdb4f8d06fe1d1d87991d537d6a..1495120e6f8c4e2fa374cf2203fc125374bf992a 100644 --- a/Framework/API/inc/MantidAPI/RefAxis.h +++ b/Framework/API/inc/MantidAPI/RefAxis.h @@ -25,16 +25,13 @@ public: RefAxis(const MatrixWorkspace *const parentWorkspace); Axis *clone(const MatrixWorkspace *const parentWorkspace) override; - Axis *clone(const std::size_t length, - const MatrixWorkspace *const parentWorkspace) override; + Axis *clone(const std::size_t length, const MatrixWorkspace *const parentWorkspace) override; std::size_t length() const override; /// Get a value at the specified index - double operator()(const std::size_t &index, - const std::size_t &verticalIndex) const override; + double operator()(const std::size_t &index, const std::size_t &verticalIndex) const override; void setValue(const std::size_t &index, const double &value) override; bool operator==(const Axis &) const override; - bool equalWithinTolerance(const Axis &axis2, - const double tolerance) const override; + bool equalWithinTolerance(const Axis &axis2, const double tolerance) const override; // We must override these to prevent access to NumericAxis::m_values and // m_edges, which are unused by RefAxis and thus do not hold sensible values. size_t indexOfValue(const double value) const override; diff --git a/Framework/API/inc/MantidAPI/RegisterFileLoader.h b/Framework/API/inc/MantidAPI/RegisterFileLoader.h index ff4ed68da97387f16c15cfc0ea05dbd80c6dd585..e8908dc2ff16309efd16a8589f718ae98272cf9e 100644 --- a/Framework/API/inc/MantidAPI/RegisterFileLoader.h +++ b/Framework/API/inc/MantidAPI/RegisterFileLoader.h @@ -16,12 +16,11 @@ * It both registers the algorithm as usual and subscribes it to the * registry. */ -#define DECLARE_FILELOADER_ALGORITHM(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper reg_loader_##classname( \ - (Mantid::API::FileLoaderRegistry::Instance().subscribe( \ - Mantid::API::FileLoaderRegistryImpl::Generic), \ - 0)); \ +#define DECLARE_FILELOADER_ALGORITHM(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper reg_loader_##classname( \ + (Mantid::API::FileLoaderRegistry::Instance().subscribe(Mantid::API::FileLoaderRegistryImpl::Generic), \ + 0)); \ } /** @@ -31,12 +30,11 @@ * It both registers the algorithm as usual and subscribes it to the * registry. */ -#define DECLARE_NEXUS_FILELOADER_ALGORITHM(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper reg_hdf_loader_##classname( \ - (Mantid::API::FileLoaderRegistry::Instance().subscribe( \ - Mantid::API::FileLoaderRegistryImpl::Nexus), \ - 0)); \ +#define DECLARE_NEXUS_FILELOADER_ALGORITHM(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper reg_hdf_loader_##classname( \ + (Mantid::API::FileLoaderRegistry::Instance().subscribe(Mantid::API::FileLoaderRegistryImpl::Nexus), \ + 0)); \ } /** @@ -46,10 +44,10 @@ * It both registers the algorithm as usual and subscribes it to the * registry. */ -#define DECLARE_NEXUS_HDF5_FILELOADER_ALGORITHM(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper reg_hdf_loader_##classname( \ - (Mantid::API::FileLoaderRegistry::Instance().subscribe( \ - Mantid::API::FileLoaderRegistryImpl::NexusHDF5), \ - 0)); \ +#define DECLARE_NEXUS_HDF5_FILELOADER_ALGORITHM(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper \ + reg_hdf_loader_##classname((Mantid::API::FileLoaderRegistry::Instance().subscribe( \ + Mantid::API::FileLoaderRegistryImpl::NexusHDF5), \ + 0)); \ } diff --git a/Framework/API/inc/MantidAPI/RemoteJobManagerFactory.h b/Framework/API/inc/MantidAPI/RemoteJobManagerFactory.h index 5646d0da63e9e3347c68f2594f504319bbf5c9da..8547cec2fda1ea05e162eb5538df1ea1f30164cc 100644 --- a/Framework/API/inc/MantidAPI/RemoteJobManagerFactory.h +++ b/Framework/API/inc/MantidAPI/RemoteJobManagerFactory.h @@ -37,18 +37,15 @@ factory is implemented as a singleton class. Typical usages: Mantid::API::IRemoteJob|Manager_sptr jobManager = Mantid::API::RemoteJobManagerFactory::Instance().create("Fermi"); */ -class MANTID_API_DLL RemoteJobManagerFactoryImpl - : public Kernel::DynamicFactory { +class MANTID_API_DLL RemoteJobManagerFactoryImpl : public Kernel::DynamicFactory { public: /// Create a remote job manager that will know how to use the /// underlying mechanism that suits the compute resource passed - IRemoteJobManager_sptr - create(const std::string &computeResourceName) const override; + IRemoteJobManager_sptr create(const std::string &computeResourceName) const override; /// alternative (lower level) create where the specific type of /// manager and base URL are directly given - IRemoteJobManager_sptr create(const std::string &baseURL, - const std::string &jobManagerType) const; + IRemoteJobManager_sptr create(const std::string &baseURL, const std::string &jobManagerType) const; private: /// So that the singleton can be created (cons/destructor are private) @@ -67,8 +64,7 @@ private: }; // The factory is just a specialisation of SingletonHolder -using RemoteJobManagerFactory = - Mantid::Kernel::SingletonHolder; +using RemoteJobManagerFactory = Mantid::Kernel::SingletonHolder; } // namespace API } // namespace Mantid @@ -90,10 +86,8 @@ EXTERN_MANTID_API template class MANTID_API_DLL * You need to use this in every remote job manager. For example: * DECLARE_REMOTEJOBMANAGER(MantidWebServiceAPI) */ -#define DECLARE_REMOTEJOBMANAGER(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper register_job_manager_##classname( \ - ((Mantid::API::RemoteJobManagerFactory::Instance().subscribe( \ - #classname)), \ - 0)); \ +#define DECLARE_REMOTEJOBMANAGER(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper register_job_manager_##classname( \ + ((Mantid::API::RemoteJobManagerFactory::Instance().subscribe(#classname)), 0)); \ } diff --git a/Framework/API/inc/MantidAPI/ResizeRectangularDetectorHelper.h b/Framework/API/inc/MantidAPI/ResizeRectangularDetectorHelper.h index af32cc69a5ad183e860f3b5515fb485bfcf8a266..90775794d2a6eeaa0e50b3363fd9eb35fc783799 100644 --- a/Framework/API/inc/MantidAPI/ResizeRectangularDetectorHelper.h +++ b/Framework/API/inc/MantidAPI/ResizeRectangularDetectorHelper.h @@ -16,8 +16,8 @@ class IComponent; namespace API { /** Helpers for resizing RectangularDetectors */ -MANTID_API_DLL void applyRectangularDetectorScaleToComponentInfo( - Geometry::ComponentInfo &componentInfo, Geometry::IComponent *componentId, - const double scaleX, const double scaleY); +MANTID_API_DLL void applyRectangularDetectorScaleToComponentInfo(Geometry::ComponentInfo &componentInfo, + Geometry::IComponent *componentId, const double scaleX, + const double scaleY); } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/Run.h b/Framework/API/inc/MantidAPI/Run.h index d87ccca47079720fd96f2312f2e94ad93b593a18..a88e3cfa663816d32960caf99516a8b6b50e1f47 100644 --- a/Framework/API/inc/MantidAPI/Run.h +++ b/Framework/API/inc/MantidAPI/Run.h @@ -51,11 +51,9 @@ public: Run &operator+=(const Run &rhs); /// Filter the logs by time - void filterByTime(const Types::Core::DateAndTime start, - const Types::Core::DateAndTime stop) override; + void filterByTime(const Types::Core::DateAndTime start, const Types::Core::DateAndTime stop) override; /// Split the logs based on the given intervals - void splitByTime(Kernel::TimeSplitterType &splitter, - std::vector outputs) const override; + void splitByTime(Kernel::TimeSplitterType &splitter, std::vector outputs) const override; /// Return an approximate memory size for the object in bytes size_t getMemorySize() const override; @@ -66,8 +64,7 @@ public: double getProtonCharge() const; /// Integrate the proton charge over the whole run time - default log /// proton_charge - void - integrateProtonCharge(const std::string &logname = "proton_charge") const; + void integrateProtonCharge(const std::string &logname = "proton_charge") const; /// Store the given values as a set of histogram bin boundaries void storeHistogramBinBoundaries(const std::vector &histoBins); @@ -78,8 +75,7 @@ public: /// Set a single gonoimeter & read the average values from the logs if told to /// do so - void setGoniometer(const Geometry::Goniometer &goniometer, - const bool useLogValues); + void setGoniometer(const Geometry::Goniometer &goniometer, const bool useLogValues); /// Set the gonoimeters using the individual values void setGoniometers(const Geometry::Goniometer &goniometer); /// Return reference to the first const Goniometer object for this run @@ -107,11 +103,9 @@ public: const std::vector> getGoniometerMatrices() const; /// Save the run to a NeXus file with a given group name - void saveNexus(::NeXus::File *file, const std::string &group, - bool keepOpen = false) const override; + void saveNexus(::NeXus::File *file, const std::string &group, bool keepOpen = false) const override; /// Load the run from a NeXus file with a given group name - void loadNexus(::NeXus::File *file, const std::string &group, - bool keepOpen = false) override; + void loadNexus(::NeXus::File *file, const std::string &group, bool keepOpen = false) override; private: /// Calculate the average gonoimeter matrix @@ -125,8 +119,7 @@ private: std::vector m_histoBins; /// Adds all the time series in from one property manager into another - void mergeMergables(Mantid::Kernel::PropertyManager &sum, - const Mantid::Kernel::PropertyManager &toAdd); + void mergeMergables(Mantid::Kernel::PropertyManager &sum, const Mantid::Kernel::PropertyManager &toAdd); void copyGoniometers(const Run &other); }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/Sample.h b/Framework/API/inc/MantidAPI/Sample.h index dbaaa41d4ab547cd59c97fb91644952466b0791e..fb7ddd15e8a22cdafb904a1e22d6ff1d33a26b05 100644 --- a/Framework/API/inc/MantidAPI/Sample.h +++ b/Framework/API/inc/MantidAPI/Sample.h @@ -68,7 +68,7 @@ public: /// Get a reference to the sample's environment const Geometry::SampleEnvironment &getEnvironment() const; /// Set the environment used to contain the sample - void setEnvironment(std::unique_ptr env); + void setEnvironment(std::shared_ptr env); //@} /** @name Access the sample's lattice structure and orientation */ @@ -86,8 +86,7 @@ public: /** @name Access the sample's crystal structure */ //@{ const Geometry::CrystalStructure &getCrystalStructure() const; - void - setCrystalStructure(const Geometry::CrystalStructure &newCrystalStructure); + void setCrystalStructure(const Geometry::CrystalStructure &newCrystalStructure); bool hasCrystalStructure() const; void clearCrystalStructure(); //@} diff --git a/Framework/API/inc/MantidAPI/SampleShapeValidator.h b/Framework/API/inc/MantidAPI/SampleShapeValidator.h index 8e4cf794a864c31348a18ec1e14ecfe8e9db8dd9..8e114e233767866575ba7d245053f59759131e20 100644 --- a/Framework/API/inc/MantidAPI/SampleShapeValidator.h +++ b/Framework/API/inc/MantidAPI/SampleShapeValidator.h @@ -17,15 +17,13 @@ namespace API { /** Verify that a workspace has valid sample shape. */ -class MANTID_API_DLL SampleShapeValidator - : public Kernel::TypedValidator> { +class MANTID_API_DLL SampleShapeValidator : public Kernel::TypedValidator> { public: std::string getType() const; Kernel::IValidator_sptr clone() const override; private: - std::string - checkValidity(const std::shared_ptr &value) const override; + std::string checkValidity(const std::shared_ptr &value) const override; }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/ScriptBuilder.h b/Framework/API/inc/MantidAPI/ScriptBuilder.h index 32d97f6724677dc909fb7596b26e3c94d2168b4f..77ed2f80a9f6e9ec91c3a4016fea86974696cee3 100644 --- a/Framework/API/inc/MantidAPI/ScriptBuilder.h +++ b/Framework/API/inc/MantidAPI/ScriptBuilder.h @@ -30,31 +30,20 @@ namespace API { class MANTID_API_DLL ScriptBuilder { public: - ScriptBuilder( - const std::shared_ptr &view, - std::string versionSpecificity = "old", bool appendTimestamp = false, - std::vector ignoreTheseAlgs = {}, - std::vector> ignoreTheseAlgProperties = {}, - bool appendExecCount = false); + ScriptBuilder(const std::shared_ptr &view, std::string versionSpecificity = "old", + bool appendTimestamp = false, std::vector ignoreTheseAlgs = {}, + std::vector> ignoreTheseAlgProperties = {}, bool appendExecCount = false); virtual ~ScriptBuilder() = default; /// build a python script from the history view const std::string build(); private: - void writeHistoryToStream(std::ostringstream &os, - std::vector::const_iterator &iter, - int depth = 1); - void buildChildren(std::ostringstream &os, - std::vector::const_iterator &iter, - int depth = 1); + void writeHistoryToStream(std::ostringstream &os, std::vector::const_iterator &iter, int depth = 1); + void buildChildren(std::ostringstream &os, std::vector::const_iterator &iter, int depth = 1); const std::string buildCommentString(const AlgorithmHistory &algHistory); const std::string buildAlgorithmString(const AlgorithmHistory &algHistory); - const std::string - buildPropertyString(const Mantid::Kernel::PropertyHistory &propHistory, - const std::string &algName); - void createStringForAlg( - std::ostringstream &os, - std::shared_ptr &algHistory); + const std::string buildPropertyString(const Mantid::Kernel::PropertyHistory &propHistory, const std::string &algName); + void createStringForAlg(std::ostringstream &os, std::shared_ptr &algHistory); const std::vector m_historyItems; std::string m_output; diff --git a/Framework/API/inc/MantidAPI/ScriptRepository.h b/Framework/API/inc/MantidAPI/ScriptRepository.h index 8a66fcc38e94ac1ef7d8eea026aae4540374913b..11e3a9ebb823555a1775ff913e2cfa899d96e53f 100644 --- a/Framework/API/inc/MantidAPI/ScriptRepository.h +++ b/Framework/API/inc/MantidAPI/ScriptRepository.h @@ -98,15 +98,11 @@ class MANTID_API_DLL ScriptRepoException : public std::exception { public: /// default constructor - ScriptRepoException( - const std::string &info = std::string("Unknown Exception")) + ScriptRepoException(const std::string &info = std::string("Unknown Exception")) : _system_error(""), _user_info(info), _file_path(""){}; - ScriptRepoException(int err_, const std::string &info = std::string(), - const std::string &file = std::string(), int line = -1); - - ScriptRepoException(const std::string &info, const std::string &system, - const std::string &file = std::string(), int line = -1); + ScriptRepoException(const std::string &info, const std::string &system, const std::string &file = std::string(), + int line = -1); /// Returns the message string. const char *what() const noexcept override; @@ -504,8 +500,8 @@ public: */ - virtual void upload(const std::string &file_path, const std::string &comment, - const std::string &author, const std::string &email) = 0; + virtual void upload(const std::string &file_path, const std::string &comment, const std::string &author, + const std::string &email) = 0; /** Delete the file from the remote repository (it does not touch the local @@ -539,8 +535,8 @@ public: or a non existent file, or not allowed operation, or any network erros. */ - virtual void remove(const std::string &file_path, const std::string &comment, - const std::string &author, const std::string &email) = 0; + virtual void remove(const std::string &file_path, const std::string &comment, const std::string &author, + const std::string &email) = 0; /** Define the file patterns that will not be listed in listFiles. This is important to force the ScriptRepository to not list hidden files, diff --git a/Framework/API/inc/MantidAPI/ScriptRepositoryFactory.h b/Framework/API/inc/MantidAPI/ScriptRepositoryFactory.h index cca3eb73e60eadc1e54344a23b3dd87ce1810b76..329a5eb754910df79cfa1cfe76a2fe83c16aa325 100644 --- a/Framework/API/inc/MantidAPI/ScriptRepositoryFactory.h +++ b/Framework/API/inc/MantidAPI/ScriptRepositoryFactory.h @@ -36,12 +36,10 @@ class ScriptRepository; @date 20/12/2012 */ -class MANTID_API_DLL ScriptRepositoryFactoryImpl - : public Kernel::DynamicFactory { +class MANTID_API_DLL ScriptRepositoryFactoryImpl : public Kernel::DynamicFactory { public: ScriptRepositoryFactoryImpl(const ScriptRepositoryFactoryImpl &) = delete; - ScriptRepositoryFactoryImpl & - operator=(const ScriptRepositoryFactoryImpl &) = delete; + ScriptRepositoryFactoryImpl &operator=(const ScriptRepositoryFactoryImpl &) = delete; private: friend struct Mantid::Kernel::CreateUsingNew; @@ -52,8 +50,7 @@ private: ~ScriptRepositoryFactoryImpl() override = default; }; -using ScriptRepositoryFactory = - Mantid::Kernel::SingletonHolder; +using ScriptRepositoryFactory = Mantid::Kernel::SingletonHolder; } // namespace API } // namespace Mantid @@ -69,10 +66,8 @@ EXTERN_MANTID_API template class MANTID_API_DLL * Macro for declaring a new type of function to be used with the * FunctionFactory */ -#define DECLARE_SCRIPTREPOSITORY(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper register_function_##classname( \ - ((Mantid::API::ScriptRepositoryFactory::Instance().subscribe( \ - #classname)), \ - 0)); \ +#define DECLARE_SCRIPTREPOSITORY(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper register_function_##classname( \ + ((Mantid::API::ScriptRepositoryFactory::Instance().subscribe(#classname)), 0)); \ } diff --git a/Framework/API/inc/MantidAPI/SerialAlgorithm.h b/Framework/API/inc/MantidAPI/SerialAlgorithm.h index 8855695ef806b26afaae864925becfa9fc7a7467..0afe42779d7c2742c902c554d7dd581c49f51990 100644 --- a/Framework/API/inc/MantidAPI/SerialAlgorithm.h +++ b/Framework/API/inc/MantidAPI/SerialAlgorithm.h @@ -33,9 +33,8 @@ namespace API { */ class MANTID_API_DLL SerialAlgorithm : public API::Algorithm { protected: - Parallel::ExecutionMode getParallelExecutionMode( - const std::map &storageModes) - const override; + Parallel::ExecutionMode + getParallelExecutionMode(const std::map &storageModes) const override; }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/SingleValueParameter.h b/Framework/API/inc/MantidAPI/SingleValueParameter.h index 3e18a1611c1c2288841963fdedcaf83e1ba482f4..72fa1ca69aadb8c11a323055602082999d9c34e6 100644 --- a/Framework/API/inc/MantidAPI/SingleValueParameter.h +++ b/Framework/API/inc/MantidAPI/SingleValueParameter.h @@ -24,8 +24,7 @@ in a very simple manner. @author Owen Arnold, Tessella plc @date 21/07/2011 */ -template -class DLLExport SingleValueParameter : public ImplicitFunctionParameter { +template class DLLExport SingleValueParameter : public ImplicitFunctionParameter { public: using ValueType = ValType; SingleValueParameter(ValType value); @@ -47,8 +46,7 @@ protected: /* Getter for the valid state. @return raw underlying value. */ -template -ValType SingleValueParameter::getValue() const { +template ValType SingleValueParameter::getValue() const { return m_value; } @@ -56,8 +54,7 @@ ValType SingleValueParameter::getValue() const { /* Getter for the valid state. @return true if the object is in a valid state. */ -template -bool SingleValueParameter::isValid() const { +template bool SingleValueParameter::isValid() const { return m_isValid; } @@ -68,8 +65,7 @@ terms of derived class. @return Ref to assigned object. */ template -Derived &SingleValueParameter:: -operator=(const Derived &other) { +Derived &SingleValueParameter::operator=(const Derived &other) { if (&other != this) { this->m_isValid = other.m_isValid; this->m_value = other.m_value; @@ -83,8 +79,7 @@ operator=(const Derived &other) { @return true only if the two objects are considered equal. */ template -bool SingleValueParameter:: -operator==(const Derived &other) const { +bool SingleValueParameter::operator==(const Derived &other) const { return other.m_value == this->m_value; } @@ -94,8 +89,7 @@ operator==(const Derived &other) const { @return true only if the two objects are not considered equal. */ template -bool SingleValueParameter:: -operator!=(const Derived &other) const { +bool SingleValueParameter::operator!=(const Derived &other) const { return !(*this == other); } @@ -104,29 +98,25 @@ operator!=(const Derived &other) const { @param other : ref to object to use as origin for the new instance. */ template -SingleValueParameter::SingleValueParameter( - const SingleValueParameter &other) +SingleValueParameter::SingleValueParameter(const SingleValueParameter &other) : m_value(other.m_value), m_isValid(other.m_isValid) {} /// Default constructor. Object is created in invalid state. template -SingleValueParameter::SingleValueParameter() - : m_isValid(false) {} +SingleValueParameter::SingleValueParameter() : m_isValid(false) {} //---------------------------------------------------------------- /* Constructor. Leads to a valid instance/state. @param value : Internal value for the object to wrap. */ template -SingleValueParameter::SingleValueParameter(ValType value) - : m_value(value), m_isValid(true) {} +SingleValueParameter::SingleValueParameter(ValType value) : m_value(value), m_isValid(true) {} //---------------------------------------------------------------- /* Serializes the object to an xml string. @return xml string containing the underlying value. */ -template -std::string SingleValueParameter::toXMLString() const { +template std::string SingleValueParameter::toXMLString() const { std::string valueXMLtext = ElementTraits::format(m_value); return this->parameterXMLTemplate(valueXMLtext); } @@ -139,16 +129,15 @@ std::string SingleValueParameter::toXMLString() const { // CRTP. // //-----------------------------------------------------------------------------------------------------------------// -#define DECLARE_SINGLE_VALUE_PARAMETER(classname, type_) \ - class classname \ - : public Mantid::API::SingleValueParameter { \ - public: \ - using SuperType = Mantid::API::SingleValueParameter; \ - static std::string parameterName() { return #classname; } \ - classname(type_ value) : SuperType(value) {} \ - classname() : SuperType() {} \ - std::string getName() const override { return #classname; } \ - classname *clone() const override { return new classname(m_value); } \ +#define DECLARE_SINGLE_VALUE_PARAMETER(classname, type_) \ + class classname : public Mantid::API::SingleValueParameter { \ + public: \ + using SuperType = Mantid::API::SingleValueParameter; \ + static std::string parameterName() { return #classname; } \ + classname(type_ value) : SuperType(value) {} \ + classname() : SuperType() {} \ + std::string getName() const override { return #classname; } \ + classname *clone() const override { return new classname(m_value); } \ }; } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/SingleValueParameterParser.h b/Framework/API/inc/MantidAPI/SingleValueParameterParser.h index a31432512788871d170a839b1e9100819fdecea8..c332ae6616e9b2313e22b00bdf4605337441066c 100644 --- a/Framework/API/inc/MantidAPI/SingleValueParameterParser.h +++ b/Framework/API/inc/MantidAPI/SingleValueParameterParser.h @@ -38,17 +38,13 @@ namespace API { */ template -class DLLExport SingleValueParameterParser - : public Mantid::API::ImplicitFunctionParameterParser { +class DLLExport SingleValueParameterParser : public Mantid::API::ImplicitFunctionParameterParser { public: - Mantid::API::ImplicitFunctionParameter * - createParameter(Poco::XML::Element *parameterElement) override; + Mantid::API::ImplicitFunctionParameter *createParameter(Poco::XML::Element *parameterElement) override; - SingleValueParameterType * - createWithoutDelegation(Poco::XML::Element *parameterElement); + SingleValueParameterType *createWithoutDelegation(Poco::XML::Element *parameterElement); - void setSuccessorParser( - Mantid::API::ImplicitFunctionParameterParser *paramParser) override; + void setSuccessorParser(Mantid::API::ImplicitFunctionParameterParser *paramParser) override; }; ////////////////////////////////////////////////////////////////////////////////// @@ -61,15 +57,13 @@ parser. */ template Mantid::API::ImplicitFunctionParameter * -SingleValueParameterParser::createParameter( - Poco::XML::Element *parameterElement) { +SingleValueParameterParser::createParameter(Poco::XML::Element *parameterElement) { using ValType = typename SingleValueParameterType::ValueType; std::string typeName = parameterElement->getChildElement("Type")->innerText(); if (SingleValueParameterType::parameterName() != typeName) { return m_successor->createParameter(parameterElement); } else { - std::string sParameterValue = - parameterElement->getChildElement("Value")->innerText(); + std::string sParameterValue = parameterElement->getChildElement("Value")->innerText(); ValType value = boost::lexical_cast(sParameterValue); return new SingleValueParameterType(value); } @@ -83,16 +77,14 @@ to successor if it fails!. */ template SingleValueParameterType * -SingleValueParameterParser::createWithoutDelegation( - Poco::XML::Element *parameterElement) { +SingleValueParameterParser::createWithoutDelegation(Poco::XML::Element *parameterElement) { using ValType = typename SingleValueParameterType::ValueType; std::string typeName = parameterElement->getChildElement("Type")->innerText(); if (SingleValueParameterType::parameterName() != typeName) { throw std::runtime_error("The attempted ::createWithoutDelegation failed. " "The type provided does not match this parser."); } else { - std::string sParameterValue = - parameterElement->getChildElement("Value")->innerText(); + std::string sParameterValue = parameterElement->getChildElement("Value")->innerText(); ValType value = boost::lexical_cast(sParameterValue); return new SingleValueParameterType(value); } diff --git a/Framework/API/inc/MantidAPI/SpectraAxis.h b/Framework/API/inc/MantidAPI/SpectraAxis.h index d7b3c361f1e7ea76dfb02feb253fe2e4416fedf5..60913541f169cf06a06adde41b45f5f6edaf4073 100644 --- a/Framework/API/inc/MantidAPI/SpectraAxis.h +++ b/Framework/API/inc/MantidAPI/SpectraAxis.h @@ -32,13 +32,11 @@ class MANTID_API_DLL SpectraAxis : public Axis { public: explicit SpectraAxis(const MatrixWorkspace *const parentWorkspace); Axis *clone(const MatrixWorkspace *const parentWorkspace) override; - Axis *clone(const std::size_t length, - const MatrixWorkspace *const parentWorkspace) override; + Axis *clone(const std::size_t length, const MatrixWorkspace *const parentWorkspace) override; std::size_t length() const override; /// If this is a spectra Axis - always true for this class bool isSpectra() const override { return true; } - double operator()(const std::size_t &index, - const std::size_t &verticalIndex = 0) const override; + double operator()(const std::size_t &index, const std::size_t &verticalIndex = 0) const override; void setValue(const std::size_t &index, const double &value) override; size_t indexOfValue(const double value) const override; bool operator==(const Axis &) const override; diff --git a/Framework/API/inc/MantidAPI/SpectrumDetectorMapping.h b/Framework/API/inc/MantidAPI/SpectrumDetectorMapping.h index 08885eb4bc9ea62cf770966d60717cf0a2abdff3..0f79b7c6a7b0780d964664e0b127be12ecd8b90e 100644 --- a/Framework/API/inc/MantidAPI/SpectrumDetectorMapping.h +++ b/Framework/API/inc/MantidAPI/SpectrumDetectorMapping.h @@ -31,32 +31,24 @@ class MANTID_API_DLL SpectrumDetectorMapping { using sdmap = std::unordered_map>; public: - explicit SpectrumDetectorMapping(const MatrixWorkspace_const_sptr &workspace, - const bool useSpecNoIndex = true); - SpectrumDetectorMapping( - const std::vector &spectrumNumbers, - const std::vector &detectorIDs, - const std::vector &ignoreDetIDs = std::vector()); - SpectrumDetectorMapping(const specnum_t *const spectrumNumbers, - const detid_t *const detectorIDs, + explicit SpectrumDetectorMapping(const MatrixWorkspace_const_sptr &workspace, const bool useSpecNoIndex = true); + SpectrumDetectorMapping(const std::vector &spectrumNumbers, const std::vector &detectorIDs, + const std::vector &ignoreDetIDs = std::vector()); + SpectrumDetectorMapping(const specnum_t *const spectrumNumbers, const detid_t *const detectorIDs, size_t arrayLengths); SpectrumDetectorMapping(); virtual ~SpectrumDetectorMapping() = default; std::set getSpectrumNumbers() const; - const std::set & - getDetectorIDsForSpectrumNo(const specnum_t spectrumNo) const; - const std::set & - getDetectorIDsForSpectrumIndex(const size_t spectrumIndex) const; + const std::set &getDetectorIDsForSpectrumNo(const specnum_t spectrumNo) const; + const std::set &getDetectorIDsForSpectrumIndex(const size_t spectrumIndex) const; const sdmap &getMapping() const; bool indexIsSpecNumber() const; private: - void fillMapFromArray(const specnum_t *const spectrumNumbers, - const detid_t *const detectorIDs, + void fillMapFromArray(const specnum_t *const spectrumNumbers, const detid_t *const detectorIDs, const size_t arrayLengths); - void fillMapFromVector(const std::vector &spectrumNumbers, - const std::vector &detectorIDs, + void fillMapFromVector(const std::vector &spectrumNumbers, const std::vector &detectorIDs, const std::vector &ignoreDetIDs); bool m_indexIsSpecNo; diff --git a/Framework/API/inc/MantidAPI/SpectrumInfo.h b/Framework/API/inc/MantidAPI/SpectrumInfo.h index 1ba9f3a6b4e610f4fd3551e57a45a7b2471d75d3..4ee666e3d7e281f3d1f8c85e7513b97807b16b6e 100644 --- a/Framework/API/inc/MantidAPI/SpectrumInfo.h +++ b/Framework/API/inc/MantidAPI/SpectrumInfo.h @@ -8,6 +8,8 @@ #include "MantidAPI/DllConfig.h" #include "MantidAPI/SpectrumInfoIterator.h" +#include "MantidKernel/DeltaEMode.h" +#include "MantidKernel/Unit.h" #include "MantidKernel/V3D.h" #include "MantidKernel/cow_ptr.h" @@ -50,8 +52,7 @@ class ExperimentInfo; */ class MANTID_API_DLL SpectrumInfo { public: - SpectrumInfo(const Beamline::SpectrumInfo &spectrumInfo, - const ExperimentInfo &experimentInfo, + SpectrumInfo(const Beamline::SpectrumInfo &spectrumInfo, const ExperimentInfo &experimentInfo, Geometry::DetectorInfo &detectorInfo); ~SpectrumInfo(); @@ -59,8 +60,7 @@ public: size_t detectorCount() const; const SpectrumDefinition &spectrumDefinition(const size_t index) const; - const Kernel::cow_ptr> & - sharedSpectrumDefinitions() const; + const Kernel::cow_ptr> &sharedSpectrumDefinitions() const; bool isMonitor(const size_t index) const; bool isMasked(const size_t index) const; @@ -70,6 +70,9 @@ public: double azimuthal(const size_t index) const; std::pair geographicalAngles(const size_t index) const; Kernel::V3D position(const size_t index) const; + Kernel::UnitParametersMap diffractometerConstants(const size_t index, std::vector &uncalibratedDets) const; + Kernel::UnitParametersMap diffractometerConstants(const size_t index) const; + double difcUncalibrated(const size_t index) const; bool hasDetectors(const size_t index) const; bool hasUniqueDetector(const size_t index) const; @@ -86,6 +89,11 @@ public: Kernel::V3D samplePosition() const; double l1() const; + void getDetectorValues(const Kernel::Unit &inputUnit, const Kernel::Unit &outputUnit, + const Kernel::DeltaEMode::Type emode, const bool signedTheta, int64_t wsIndex, + Kernel::UnitParametersMap &pmap) const; + void createDetectorIdLogMessages(const std::vector &detids, int64_t wsIndex) const; + SpectrumInfoIterator begin(); SpectrumInfoIterator end(); const SpectrumInfoIterator cbegin() const; @@ -95,14 +103,12 @@ public: private: const Geometry::IDetector &getDetector(const size_t index) const; - const SpectrumDefinition & - checkAndGetSpectrumDefinition(const size_t index) const; + const SpectrumDefinition &checkAndGetSpectrumDefinition(const size_t index) const; const ExperimentInfo &m_experimentInfo; Geometry::DetectorInfo &m_detectorInfo; const Beamline::SpectrumInfo &m_spectrumInfo; - mutable std::vector> - m_lastDetector; + mutable std::vector> m_lastDetector; mutable std::vector m_lastIndex; }; diff --git a/Framework/API/inc/MantidAPI/SpectrumInfoItem.h b/Framework/API/inc/MantidAPI/SpectrumInfoItem.h index 15062d08639c7d74565ea733b617ff93efb156e2..7cd4bce50a7a4d5b5e3f03abea8078266eba48e7 100644 --- a/Framework/API/inc/MantidAPI/SpectrumInfoItem.h +++ b/Framework/API/inc/MantidAPI/SpectrumInfoItem.h @@ -49,28 +49,19 @@ public: double twoTheta() const { return m_spectrumInfo->twoTheta(m_index); } - double signedTwoTheta() const { - return m_spectrumInfo->signedTwoTheta(m_index); - } + double signedTwoTheta() const { return m_spectrumInfo->signedTwoTheta(m_index); } double l2() const { return m_spectrumInfo->l2(m_index); } - bool hasUniqueDetector() const { - return m_spectrumInfo->hasUniqueDetector(m_index); - } + bool hasUniqueDetector() const { return m_spectrumInfo->hasUniqueDetector(m_index); } bool hasDetectors() const { return m_spectrumInfo->hasDetectors(m_index); } - const Mantid::SpectrumDefinition &spectrumDefinition() const { - return m_spectrumInfo->spectrumDefinition(m_index); - } + const Mantid::SpectrumDefinition &spectrumDefinition() const { return m_spectrumInfo->spectrumDefinition(m_index); } - Mantid::Kernel::V3D position() const { - return m_spectrumInfo->position(m_index); - } + Mantid::Kernel::V3D position() const { return m_spectrumInfo->position(m_index); } - SpectrumInfoItem(T &spectrumInfo, const size_t index) - : m_spectrumInfo(&spectrumInfo), m_index(index) {} + SpectrumInfoItem(T &spectrumInfo, const size_t index) : m_spectrumInfo(&spectrumInfo), m_index(index) {} // Non-owning pointer. A reference makes the class unable to define an // assignment operator that we need. diff --git a/Framework/API/inc/MantidAPI/SpectrumInfoIterator.h b/Framework/API/inc/MantidAPI/SpectrumInfoIterator.h index f604aeb4ea08d2ce58a9083d7377dd0b27a27f79..f74bd6f079a366e71a435991e211c46b7220db3f 100644 --- a/Framework/API/inc/MantidAPI/SpectrumInfoIterator.h +++ b/Framework/API/inc/MantidAPI/SpectrumInfoIterator.h @@ -26,14 +26,11 @@ iterator. */ template -class SpectrumInfoIterator - : public boost::iterator_facade, - SpectrumInfoItem &, - boost::random_access_traversal_tag> { +class SpectrumInfoIterator : public boost::iterator_facade, SpectrumInfoItem &, + boost::random_access_traversal_tag> { public: - SpectrumInfoIterator(T &spectrumInfo, const size_t index) - : m_item(spectrumInfo, index) {} + SpectrumInfoIterator(T &spectrumInfo, const size_t index) : m_item(spectrumInfo, index) {} private: // Allow boost iterator access @@ -41,11 +38,8 @@ private: // Iterator methods void advance(int64_t delta) { - m_item.m_index = - delta < 0 ? std::max(static_cast(0), - static_cast(m_item.m_index) + delta) - : std::min(m_item.m_spectrumInfo->size(), - m_item.m_index + static_cast(delta)); + m_item.m_index = delta < 0 ? std::max(static_cast(0), static_cast(m_item.m_index) + delta) + : std::min(m_item.m_spectrumInfo->size(), m_item.m_index + static_cast(delta)); } // This could cause a segmentation fault if a user goes past the end of the @@ -69,13 +63,10 @@ private: void setIndex(const size_t index) { m_item.m_index = index; } uint64_t distance_to(const SpectrumInfoIterator &other) const { - return static_cast(other.getIndex()) - - static_cast(getIndex()); + return static_cast(other.getIndex()) - static_cast(getIndex()); } - bool equal(const SpectrumInfoIterator &other) const { - return getIndex() == other.getIndex(); - } + bool equal(const SpectrumInfoIterator &other) const { return getIndex() == other.getIndex(); } SpectrumInfoItem &dereference() const { return m_item; } diff --git a/Framework/API/inc/MantidAPI/TableRow.h b/Framework/API/inc/MantidAPI/TableRow.h index 75fba382964e3fc166ba84cefc27153391dc14a5..afc2c1041c8aef61869f755c09df37bdce2dc5fc 100644 --- a/Framework/API/inc/MantidAPI/TableRow.h +++ b/Framework/API/inc/MantidAPI/TableRow.h @@ -61,15 +61,13 @@ public: template TableRow &operator<<(const T &t) { if (m_col >= m_columns.size()) { std::stringstream errss; - errss << "Column index " << m_col << " is out of range " - << m_columns.size() << " of operator << "; + errss << "Column index " << m_col << " is out of range " << m_columns.size() << " of operator << "; throw std::range_error(errss.str()); } Column_sptr c = m_columns[m_col]; if (!c->isType()) { std::ostringstream err; - err << "Type mismatch: " << typeid(T).name() << " (expected " - << c->get_type_info().name() << ")"; + err << "Type mismatch: " << typeid(T).name() << " (expected " << c->get_type_info().name() << ")"; throw std::runtime_error(err.str()); } c->cell(m_row) = t; @@ -94,8 +92,7 @@ public: template const TableRow &operator>>(T &t) const { if (m_col >= m_columns.size()) { std::stringstream errss; - errss << "Column index " << m_col << " is out of range " - << m_columns.size() << " of operator >> "; + errss << "Column index " << m_col << " is out of range " << m_columns.size() << " of operator >> "; throw std::range_error(errss.str()); } Column_sptr c = m_columns[m_col]; @@ -118,8 +115,7 @@ public: template T &cell(size_t col) { if (col >= m_columns.size()) { std::stringstream errss; - errss << "Column index " << m_col << " is out of range " - << m_columns.size() << " of method cell(). "; + errss << "Column index " << m_col << " is out of range " << m_columns.size() << " of method cell(). "; throw std::range_error(errss.str()); } m_col = col; @@ -154,15 +150,12 @@ public: std::string &String(size_t col) { return cell(col); } private: - friend MANTID_API_DLL std::ostream &operator<<(std::ostream &s, - const TableRow &row); - std::vector - m_columns; ///< Pointers to the columns in the ITableWorkspace - size_t m_row; ///< Row number in the TableWorkspace - mutable size_t m_col; ///< Current column number (for streaming operations) - size_t m_nrows; ///< Number of rows in the TableWorkspace - std::string - m_sep; ///< Separator character(s) between elements in a text output + friend MANTID_API_DLL std::ostream &operator<<(std::ostream &s, const TableRow &row); + std::vector m_columns; ///< Pointers to the columns in the ITableWorkspace + size_t m_row; ///< Row number in the TableWorkspace + mutable size_t m_col; ///< Current column number (for streaming operations) + size_t m_nrows; ///< Number of rows in the TableWorkspace + std::string m_sep; ///< Separator character(s) between elements in a text output }; MANTID_API_DLL std::ostream &operator<<(std::ostream &s, const TableRow &row); diff --git a/Framework/API/inc/MantidAPI/TempFunction.h b/Framework/API/inc/MantidAPI/TempFunction.h index b76b4dfa32b1652eb42543096da90c3d715eb622..b47ccebd27d1c8ef62f763d29b97c3bb90626e6d 100644 --- a/Framework/API/inc/MantidAPI/TempFunction.h +++ b/Framework/API/inc/MantidAPI/TempFunction.h @@ -33,9 +33,7 @@ public: virtual std::string name() const { return m_function->name(); } /// Set the workspace. Make /// @param ws :: Shared pointer to a workspace - virtual void setWorkspace(std::shared_ptr ws) { - UNUSED_ARG(ws) - } + virtual void setWorkspace(std::shared_ptr ws) { UNUSED_ARG(ws) } /// Get the workspace // virtual std::shared_ptr getWorkspace()const {return // m_function->getWorkspace();} @@ -51,73 +49,49 @@ public: virtual void functionDeriv(FunctionDomain &domain, Jacobian &jacobian); /// Set i-th parameter - virtual void setParameter(size_t i, const double &value, - bool explicitlySet = true) { + virtual void setParameter(size_t i, const double &value, bool explicitlySet = true) { m_function->setParameter(i, value, explicitlySet); } /// Set i-th parameter description - virtual void setParameterDescription(size_t i, - const std::string &description) { + virtual void setParameterDescription(size_t i, const std::string &description) { m_function->setParameterDescription(i, description); } /// Get i-th parameter - virtual double getParameter(size_t i) const { - return m_function->getParameter(i); - } + virtual double getParameter(size_t i) const { return m_function->getParameter(i); } /// Set parameter by name. - virtual void setParameter(const std::string &name, const double &value, - bool explicitlySet = true) { + virtual void setParameter(const std::string &name, const double &value, bool explicitlySet = true) { m_function->setParameter(name, value, explicitlySet); } /// Set description of parameter by name. - virtual void setParameterDescription(const std::string &name, - const std::string &description) { + virtual void setParameterDescription(const std::string &name, const std::string &description) { m_function->setParameterDescription(name, description); } /// Get parameter by name. - virtual double getParameter(const std::string &name) const { - return m_function->getParameter(name); - } + virtual double getParameter(const std::string &name) const { return m_function->getParameter(name); } /// Total number of parameters virtual size_t nParams() const { return m_function->nParams(); } /// Returns the index of parameter name - virtual size_t parameterIndex(const std::string &name) const { - return m_function->parameterIndex(name); - } + virtual size_t parameterIndex(const std::string &name) const { return m_function->parameterIndex(name); } /// Returns the name of parameter i - virtual std::string parameterName(size_t i) const { - return m_function->parameterName(i); - } + virtual std::string parameterName(size_t i) const { return m_function->parameterName(i); } /// Returns the description of parameter i - virtual std::string parameterDescription(size_t i) const { - return m_function->parameterDescription(i); - } + virtual std::string parameterDescription(size_t i) const { return m_function->parameterDescription(i); } /// Checks if a parameter has been set explicitly - virtual bool isExplicitlySet(size_t i) const { - return m_function->isExplicitlySet(i); - } + virtual bool isExplicitlySet(size_t i) const { return m_function->isExplicitlySet(i); } /// Number of active (in terms of fitting) parameters virtual size_t nActive() const { return m_function->nActive(); } /// Returns "global" index of active parameter i - virtual size_t indexOfActive(size_t i) const { - return m_function->indexOfActive(i); - } + virtual size_t indexOfActive(size_t i) const { return m_function->indexOfActive(i); } /// Returns the name of active parameter i - virtual std::string nameOfActive(size_t i) const { - return m_function->nameOfActive(i); - } + virtual std::string nameOfActive(size_t i) const { return m_function->nameOfActive(i); } /// Returns the name of active parameter i - virtual std::string descriptionOfActive(size_t i) const { - return m_function->descriptionOfActive(i); - } + virtual std::string descriptionOfActive(size_t i) const { return m_function->descriptionOfActive(i); } /// Check if a declared parameter i is active virtual bool isActive(size_t i) const { return m_function->isActive(i); } /// Get active index for a declared parameter i - virtual size_t activeIndex(size_t i) const { - return m_function->activeIndex(i); - } + virtual size_t activeIndex(size_t i) const { return m_function->activeIndex(i); } /// Removes a declared parameter i from the list of active virtual void removeActive(size_t i) { m_function->removeActive(i); } /// Restores a declared parameter i to the active status @@ -125,9 +99,7 @@ public: /// Return parameter index from a parameter reference. Usefull for constraints /// and ties in composite functions - virtual size_t getParameterIndex(const ParameterReference &ref) const { - return m_function->getParameterIndex(ref); - } + virtual size_t getParameterIndex(const ParameterReference &ref) const { return m_function->getParameterIndex(ref); } /// Get a function containing the parameter refered to by the reference. In /// case of a simple function /// it will be the same as ParameterReference::getFunction(). In case of a @@ -136,14 +108,11 @@ public: /// itself can be a CompositeFunction /// @param ref :: The Parameter reference /// @return A pointer to the containing function - virtual IFunction * - getContainingFunction(const ParameterReference &ref) const { + virtual IFunction *getContainingFunction(const ParameterReference &ref) const { return m_function->getContainingFunction(ref); } /// The same as the method above but the argument is a function - virtual IFunction *getContainingFunction(const IFunction *fun) { - return m_function->getContainingFunction(fun); - } + virtual IFunction *getContainingFunction(const IFunction *fun) { return m_function->getContainingFunction(fun); } /// Apply the ties virtual void applyTies() { m_function->applyTies(); } @@ -151,29 +120,22 @@ public: virtual void clearTies() { m_function->clearTies(); } /// Removes i-th parameter's tie virtual bool removeTie(size_t i) { return m_function->removeTie(i); } - virtual void removeTie(const std::string &parName) { - IFunction::removeTie(parName); - } + virtual void removeTie(const std::string &parName) { IFunction::removeTie(parName); } /// Get the tie of i-th parameter virtual ParameterTie *getTie(size_t i) const { return m_function->getTie(i); } /// Add a constraint to function virtual void addConstraint(IConstraint *ic) { m_function->addConstraint(ic); } /// Get constraint of i-th parameter - virtual IConstraint *getConstraint(size_t i) const { - return m_function->getConstraint(i); - } + virtual IConstraint *getConstraint(size_t i) const { return m_function->getConstraint(i); } /// Remove a constraint - virtual void removeConstraint(const std::string &parName) { - m_function->removeConstraint(parName); - } + virtual void removeConstraint(const std::string &parName) { m_function->removeConstraint(parName); } protected: /// Function initialization. Declare function parameters in this method. virtual void init() { m_function->init(); } /// Declare a new parameter - virtual void declareParameter(const std::string &name, double initValue = 0, - const std::string &description = "") { + virtual void declareParameter(const std::string &name, double initValue = 0, const std::string &description = "") { m_function->declareParameter(name, initValue, description); } /// Add a new tie diff --git a/Framework/API/inc/MantidAPI/TextAxis.h b/Framework/API/inc/MantidAPI/TextAxis.h index 3e04d37a7aacae563f8d35fed2b546abb3538a0b..0db5a3d6b59274a91df71c7685a1c89bbe2e7150 100644 --- a/Framework/API/inc/MantidAPI/TextAxis.h +++ b/Framework/API/inc/MantidAPI/TextAxis.h @@ -37,14 +37,12 @@ class MANTID_API_DLL TextAxis : public Axis { public: TextAxis(const std::size_t &length); Axis *clone(const MatrixWorkspace *const parentWorkspace) override; - Axis *clone(const std::size_t length, - const MatrixWorkspace *const parentWorkspace) override; + Axis *clone(const std::size_t length, const MatrixWorkspace *const parentWorkspace) override; std::size_t length() const override { return m_values.size(); } /// If this is a TextAxis, always return true for this class bool isText() const override { return true; } /// Get a value at the specified index - double operator()(const std::size_t &index, - const std::size_t &verticalIndex = 0) const override; + double operator()(const std::size_t &index, const std::size_t &verticalIndex = 0) const override; /// Set the value at the specified index void setValue(const std::size_t &index, const double &value) override; size_t indexOfValue(const double value) const override; diff --git a/Framework/API/inc/MantidAPI/TransformScaleFactory.h b/Framework/API/inc/MantidAPI/TransformScaleFactory.h index dacb5f1b8affee8e84a5ef963ba8164c077064cc..d5e75272d2464af8caca99ec26406348d7e2a6c6 100644 --- a/Framework/API/inc/MantidAPI/TransformScaleFactory.h +++ b/Framework/API/inc/MantidAPI/TransformScaleFactory.h @@ -27,15 +27,12 @@ class ITransformScale; Constructs a scaling transform object from a string */ -class MANTID_API_DLL TransformScaleFactoryImpl - : public Kernel::DynamicFactory { +class MANTID_API_DLL TransformScaleFactoryImpl : public Kernel::DynamicFactory { public: /// Returns scaling transform - std::shared_ptr - create(const std::string &type) const override; + std::shared_ptr create(const std::string &type) const override; TransformScaleFactoryImpl(const TransformScaleFactoryImpl &) = delete; - TransformScaleFactoryImpl & - operator=(const TransformScaleFactoryImpl &) = delete; + TransformScaleFactoryImpl &operator=(const TransformScaleFactoryImpl &) = delete; private: friend struct Mantid::Kernel::CreateUsingNew; @@ -50,15 +47,13 @@ private: // Do not use default methods }; -using TransformScaleFactory = - Mantid::Kernel::SingletonHolder; +using TransformScaleFactory = Mantid::Kernel::SingletonHolder; } // namespace API } // namespace Mantid namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/VectorParameter.h b/Framework/API/inc/MantidAPI/VectorParameter.h index 56bd81bbfc536107cf74f423981c3e8457547a5f..5d3bf318bf585dca361fdd3cc4630ae74cb64791 100644 --- a/Framework/API/inc/MantidAPI/VectorParameter.h +++ b/Framework/API/inc/MantidAPI/VectorParameter.h @@ -20,8 +20,7 @@ pattern to implement common code associated with vector storage. @date 21/07/2011 */ -template -class DLLExport VectorParameter : public ImplicitFunctionParameter { +template class DLLExport VectorParameter : public ImplicitFunctionParameter { public: using ValueType = ElemType; VectorParameter(); @@ -52,8 +51,7 @@ private: /* Getter for the valid state. @return true if object is valid. */ -template -bool VectorParameter::isValid() const { +template bool VectorParameter::isValid() const { return m_isValid; } @@ -83,8 +81,7 @@ Derived &VectorParameter::assignFrom(const Derived &other) { @return true if to be considered equal */ template -bool VectorParameter:: -operator==(const Derived &other) const { +bool VectorParameter::operator==(const Derived &other) const { if (other.m_isValid != this->m_isValid) { return false; // Early termination } @@ -105,8 +102,7 @@ operator==(const Derived &other) const { @return true if to be considered not equal */ template -bool VectorParameter:: -operator!=(const Derived &other) const { +bool VectorParameter::operator!=(const Derived &other) const { return !(*this == other); } @@ -115,8 +111,7 @@ operator!=(const Derived &other) const { @param other : object to act as source of copy. */ template -VectorParameter::VectorParameter( - const VectorParameter &other) +VectorParameter::VectorParameter(const VectorParameter &other) : m_size(other.m_size), m_isValid(other.m_isValid) { m_arry = new ElemType[other.getSize()]; for (size_t i = 0; i < other.getSize(); i++) { @@ -126,8 +121,7 @@ VectorParameter::VectorParameter( /// Default constructor template -VectorParameter::VectorParameter() - : m_arry(nullptr), m_size(0) { +VectorParameter::VectorParameter() : m_arry(nullptr), m_size(0) { m_isValid = false; } @@ -136,15 +130,13 @@ VectorParameter::VectorParameter() @param size : size of array */ template -VectorParameter::VectorParameter(size_t size) - : m_size(size) { +VectorParameter::VectorParameter(size_t size) : m_size(size) { m_arry = new ElemType[size]; m_isValid = true; } /// Destructor -template -VectorParameter::~VectorParameter() { +template VectorParameter::~VectorParameter() { delete[] m_arry; } @@ -153,8 +145,7 @@ VectorParameter::~VectorParameter() { @param value : Value to add. */ template -void VectorParameter::addValue(const size_t index, - const ElemType &value) { +void VectorParameter::addValue(const size_t index, const ElemType &value) { m_arry[index] = value; } @@ -162,20 +153,16 @@ void VectorParameter::addValue(const size_t index, /* Serialize the object to an xml string. @return string containing object in xml serialized form. */ -template -std::string VectorParameter::toXMLString() const { +template std::string VectorParameter::toXMLString() const { if (!m_isValid) { - throw std::runtime_error( - "Cannot serialize VectorParameter if it is not valid!"); + throw std::runtime_error("Cannot serialize VectorParameter if it is not valid!"); } std::string valueXMLtext; for (size_t i = 0; i < m_size; i++) { if (i < (m_size - 1)) { - valueXMLtext.append( - ElementTraits::formatCS(m_arry[i])); // Comma-seperated + valueXMLtext.append(ElementTraits::formatCS(m_arry[i])); // Comma-seperated } else { - valueXMLtext.append(ElementTraits::format( - m_arry[i])); // No comma sepearation for last value + valueXMLtext.append(ElementTraits::format(m_arry[i])); // No comma sepearation for last value } } return this->parameterXMLTemplate(valueXMLtext); @@ -186,8 +173,7 @@ std::string VectorParameter::toXMLString() const { @param index : array index to access. @return ref to the element at the specified index. */ -template -ElemType &VectorParameter::operator[](int index) { +template ElemType &VectorParameter::operator[](int index) { return m_arry[index]; } @@ -195,8 +181,7 @@ ElemType &VectorParameter::operator[](int index) { /* Getter for the vector size. @return the size of the vector */ -template -size_t VectorParameter::getSize() const { +template size_t VectorParameter::getSize() const { return m_size; } @@ -204,8 +189,7 @@ size_t VectorParameter::getSize() const { /* Getter to pointer to the start of the underlying array @return pointer to start. */ -template -const ElemType *VectorParameter::getPointerToStart() { +template const ElemType *VectorParameter::getPointerToStart() { return m_arry; } @@ -214,8 +198,7 @@ const ElemType *VectorParameter::getPointerToStart() { @param index : index to get element at @return element at index */ -template -ElemType &VectorParameter::at(size_t index) { +template ElemType &VectorParameter::at(size_t index) { return m_arry[index]; } @@ -226,15 +209,15 @@ ElemType &VectorParameter::at(size_t index) { // Most of the work is done in the VectorParamter base class, which utilises // CRTP. //-----------------------------------------------------------------------------------------------------------------// -#define DECLARE_VECTOR_PARAMETER(classname, type_) \ - class classname : public Mantid::API::VectorParameter { \ - public: \ - using SuperType = Mantid::API::VectorParameter; \ - static std::string parameterName() { return #classname; } \ - classname() : SuperType() {} \ - classname(size_t index) : SuperType(index) {} \ - std::string getName() const override { return #classname; } \ - classname *clone() const override { return new classname(*this); } \ +#define DECLARE_VECTOR_PARAMETER(classname, type_) \ + class classname : public Mantid::API::VectorParameter { \ + public: \ + using SuperType = Mantid::API::VectorParameter; \ + static std::string parameterName() { return #classname; } \ + classname() : SuperType() {} \ + classname(size_t index) : SuperType(index) {} \ + std::string getName() const override { return #classname; } \ + classname *clone() const override { return new classname(*this); } \ }; } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/VectorParameterParser.h b/Framework/API/inc/MantidAPI/VectorParameterParser.h index e591d285e0cde3e49f91d0a0999d6365d097d83b..68d6c73cb4b858b3bc7c3cadc461a5b10663ed66 100644 --- a/Framework/API/inc/MantidAPI/VectorParameterParser.h +++ b/Framework/API/inc/MantidAPI/VectorParameterParser.h @@ -35,19 +35,15 @@ namespace API { @date 21/07/2011 */ template -class DLLExport VectorParameterParser - : public Mantid::API::ImplicitFunctionParameterParser { +class DLLExport VectorParameterParser : public Mantid::API::ImplicitFunctionParameterParser { public: VectorValueParameterType *parseVectorParameter(std::string sValue); - Mantid::API::ImplicitFunctionParameter * - createParameter(Poco::XML::Element *parameterElement) override; + Mantid::API::ImplicitFunctionParameter *createParameter(Poco::XML::Element *parameterElement) override; - VectorValueParameterType * - createWithoutDelegation(Poco::XML::Element *parameterElement); + VectorValueParameterType *createWithoutDelegation(Poco::XML::Element *parameterElement); - void setSuccessorParser( - Mantid::API::ImplicitFunctionParameterParser *paramParser) override; + void setSuccessorParser(Mantid::API::ImplicitFunctionParameterParser *paramParser) override; }; //////////////////////////////////////////////////////////////////// @@ -58,9 +54,7 @@ public: @return new parameter object. */ template -VectorValueParameterType * -VectorParameterParser::parseVectorParameter( - std::string sValue) { +VectorValueParameterType *VectorParameterParser::parseVectorParameter(std::string sValue) { std::vector strs; boost::split(strs, sValue, boost::is_any_of(",")); @@ -83,8 +77,7 @@ VectorParameterParser::parseVectorParameter( */ template Mantid::API::ImplicitFunctionParameter * -VectorParameterParser::createParameter( - Poco::XML::Element *parameterElement) { +VectorParameterParser::createParameter(Poco::XML::Element *parameterElement) { std::string typeName = parameterElement->getChildElement("Type")->innerText(); if (VectorValueParameterType::parameterName() != typeName) { if (!m_successor) { @@ -92,8 +85,7 @@ VectorParameterParser::createParameter( } return m_successor->createParameter(parameterElement); } else { - std::string sParameterValue = - parameterElement->getChildElement("Value")->innerText(); + std::string sParameterValue = parameterElement->getChildElement("Value")->innerText(); return parseVectorParameter(sParameterValue); } } @@ -106,15 +98,13 @@ to successor if it fails!. */ template VectorValueParameterType * -VectorParameterParser::createWithoutDelegation( - Poco::XML::Element *parameterElement) { +VectorParameterParser::createWithoutDelegation(Poco::XML::Element *parameterElement) { std::string typeName = parameterElement->getChildElement("Type")->innerText(); if (VectorValueParameterType::parameterName() != typeName) { throw std::runtime_error("The attempted ::createWithoutDelegation failed. " "The type provided does not match this parser."); } else { - std::string sParameterValue = - parameterElement->getChildElement("Value")->innerText(); + std::string sParameterValue = parameterElement->getChildElement("Value")->innerText(); return parseVectorParameter(sParameterValue); } } diff --git a/Framework/API/inc/MantidAPI/Workspace.h b/Framework/API/inc/MantidAPI/Workspace.h index 8e3717fa1e0938a1430ef674efa332ee44cbc7af..390eec53bceb57db931e70c550d1b93629c425bf 100644 --- a/Framework/API/inc/MantidAPI/Workspace.h +++ b/Framework/API/inc/MantidAPI/Workspace.h @@ -29,8 +29,7 @@ class WorkspaceHistory; */ class MANTID_API_DLL Workspace : public Kernel::DataItem { public: - Workspace( - const Parallel::StorageMode storageMode = Parallel::StorageMode::Cloned); + Workspace(const Parallel::StorageMode storageMode = Parallel::StorageMode::Cloned); ~Workspace(); /** Returns a clone (copy) of the workspace with covariant return type in all diff --git a/Framework/API/inc/MantidAPI/WorkspaceFactory.h b/Framework/API/inc/MantidAPI/WorkspaceFactory.h index 21e0ff2c147b286d2ba62af666651f4b47bd93be..86ca515e0dc9b5622e66b587844ceed1b622c001 100644 --- a/Framework/API/inc/MantidAPI/WorkspaceFactory.h +++ b/Framework/API/inc/MantidAPI/WorkspaceFactory.h @@ -11,12 +11,10 @@ * is used in the call to its constructor to effect a call to the factory's * subscribe method. */ -#define DECLARE_WORKSPACE(classname) \ - namespace { \ - Mantid::Kernel::RegistrationHelper \ - register_ws_##classname(((Mantid::API::WorkspaceFactory::Instance() \ - .subscribe(#classname)), \ - 0)); \ +#define DECLARE_WORKSPACE(classname) \ + namespace { \ + Mantid::Kernel::RegistrationHelper \ + register_ws_##classname(((Mantid::API::WorkspaceFactory::Instance().subscribe(#classname)), 0)); \ } #include "MantidAPI/DllConfig.h" @@ -43,30 +41,22 @@ class Workspace; @date 26/09/2007 */ -class MANTID_API_DLL WorkspaceFactoryImpl - : public Kernel::DynamicFactory { +class MANTID_API_DLL WorkspaceFactoryImpl : public Kernel::DynamicFactory { public: WorkspaceFactoryImpl(const WorkspaceFactoryImpl &) = delete; WorkspaceFactoryImpl &operator=(const WorkspaceFactoryImpl &) = delete; - MatrixWorkspace_sptr create(const MatrixWorkspace_const_sptr &parent, - size_t NVectors = size_t(-1), - size_t XLength = size_t(-1), - size_t YLength = size_t(-1)) const; - MatrixWorkspace_sptr create(const std::string &className, - const size_t &NVectors, const size_t &XLength, + MatrixWorkspace_sptr create(const MatrixWorkspace_const_sptr &parent, size_t NVectors = size_t(-1), + size_t XLength = size_t(-1), size_t YLength = size_t(-1)) const; + MatrixWorkspace_sptr create(const std::string &className, const size_t &NVectors, const size_t &XLength, const size_t &YLength) const; - void initializeFromParent(const MatrixWorkspace &parent, - MatrixWorkspace &child, - const bool differentSize) const; + void initializeFromParent(const MatrixWorkspace &parent, MatrixWorkspace &child, const bool differentSize) const; /// Create a ITableWorkspace - std::shared_ptr - createTable(const std::string &className = "TableWorkspace") const; + std::shared_ptr createTable(const std::string &className = "TableWorkspace") const; /// Create a IPeaksWorkspace - std::shared_ptr - createPeaks(const std::string &className = "PeaksWorkspace") const; + std::shared_ptr createPeaks(const std::string &className = "PeaksWorkspace") const; private: friend struct Mantid::Kernel::CreateUsingNew; @@ -81,8 +71,7 @@ private: using WorkspaceFactory = Mantid::Kernel::SingletonHolder; -template -std::shared_ptr createWorkspace(InitArgs... args) { +template std::shared_ptr createWorkspace(InitArgs... args) { auto ws = std::make_shared(); ws->initialize(args...); return ws; @@ -93,7 +82,6 @@ std::shared_ptr createWorkspace(InitArgs... args) { namespace Mantid { namespace Kernel { -EXTERN_MANTID_API template class MANTID_API_DLL - Mantid::Kernel::SingletonHolder; +EXTERN_MANTID_API template class MANTID_API_DLL Mantid::Kernel::SingletonHolder; } } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/WorkspaceGroup.h b/Framework/API/inc/MantidAPI/WorkspaceGroup.h index ea174d3cbefa2bd1aa4183b14f9140a0c66eee82..3613630fab5c887ef1ece2d28e5450003895517c 100644 --- a/Framework/API/inc/MantidAPI/WorkspaceGroup.h +++ b/Framework/API/inc/MantidAPI/WorkspaceGroup.h @@ -37,8 +37,7 @@ class Algorithm; class MANTID_API_DLL WorkspaceGroup : public Workspace { public: /// Default constructor. - WorkspaceGroup( - const Parallel::StorageMode storageMode = Parallel::StorageMode::Cloned); + WorkspaceGroup(const Parallel::StorageMode storageMode = Parallel::StorageMode::Cloned); /// Destructor ~WorkspaceGroup() override; /// Return a string ID of the class @@ -96,18 +95,12 @@ public: //@{ /// Invokes the ADS to sort group members by workspace name - void sortByName() { - AnalysisDataService::Instance().sortGroupByName(this->getName()); - } + void sortByName() { AnalysisDataService::Instance().sortGroupByName(this->getName()); } /// Adds a workspace to the group. - void add(const std::string &wsName) { - AnalysisDataService::Instance().addToGroup(this->getName(), wsName); - } + void add(const std::string &wsName) { AnalysisDataService::Instance().addToGroup(this->getName(), wsName); } /// Remove a name from the group - void remove(const std::string &wsName) { - AnalysisDataService::Instance().removeFromGroup(this->getName(), wsName); - } + void remove(const std::string &wsName) { AnalysisDataService::Instance().removeFromGroup(this->getName(), wsName); } /// Does a workspace exist within the group or any groups within this group bool containsInChildren(const std::string &wsName) const; /// Does a workspace exist within the group @@ -141,20 +134,15 @@ private: bool isInChildGroup(const Workspace &workspaceToCheck) const; /// Callback when a delete notification is received - void workspaceDeleteHandle( - Mantid::API::WorkspacePostDeleteNotification_ptr notice); + void workspaceDeleteHandle(Mantid::API::WorkspacePostDeleteNotification_ptr notice); /// Callback when a before-replace notification is received - void workspaceBeforeReplaceHandle( - Mantid::API::WorkspaceBeforeReplaceNotification_ptr notice); + void workspaceBeforeReplaceHandle(Mantid::API::WorkspaceBeforeReplaceNotification_ptr notice); /// Observer for workspace delete notifications - Poco::NObserver - m_deleteObserver; + Poco::NObserver m_deleteObserver; /// Observer for workspace before-replace notifications - Poco::NObserver - m_beforeReplaceObserver; + Poco::NObserver m_beforeReplaceObserver; /// The list of workspace pointers in the group std::vector m_workspaces; /// Flag as to whether the observers have been added to the ADS diff --git a/Framework/API/inc/MantidAPI/WorkspaceHasDxValidator.h b/Framework/API/inc/MantidAPI/WorkspaceHasDxValidator.h index be840ee80ce99d3a11ac0990362f574b24e97a39..e5d5e97bb1600179adfde8f332c08b9652d349ce 100644 --- a/Framework/API/inc/MantidAPI/WorkspaceHasDxValidator.h +++ b/Framework/API/inc/MantidAPI/WorkspaceHasDxValidator.h @@ -16,8 +16,7 @@ namespace API { /** WorkspaceHasDxValidator : A validator which checks that all histograms in a * workspace have Dx values. */ -class MANTID_API_DLL WorkspaceHasDxValidator final - : public MatrixWorkspaceValidator { +class MANTID_API_DLL WorkspaceHasDxValidator final : public MatrixWorkspaceValidator { public: Kernel::IValidator_sptr clone() const override; diff --git a/Framework/API/inc/MantidAPI/WorkspaceHistory.h b/Framework/API/inc/MantidAPI/WorkspaceHistory.h index e1bec128a13b285e6a5f31478184888fa59b06c0..d5852be3e278021908c7933d02f2133e75222887 100644 --- a/Framework/API/inc/MantidAPI/WorkspaceHistory.h +++ b/Framework/API/inc/MantidAPI/WorkspaceHistory.h @@ -80,9 +80,7 @@ public: private: /// Recursive function to load the algorithm history tree from file - void loadNestedHistory( - ::NeXus::File *file, - AlgorithmHistory_sptr parent = std::shared_ptr()); + void loadNestedHistory(::NeXus::File *file, AlgorithmHistory_sptr parent = std::shared_ptr()); /// Parse an algorithm history string loaded from file AlgorithmHistory_sptr parseAlgorithmHistory(const std::string &rawData); /// Find the history entries at this level in the file. @@ -93,8 +91,7 @@ private: Mantid::API::AlgorithmHistories m_algorithms; }; -MANTID_API_DLL std::ostream &operator<<(std::ostream &, - const WorkspaceHistory &); +MANTID_API_DLL std::ostream &operator<<(std::ostream &, const WorkspaceHistory &); } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/WorkspaceNearestNeighbourInfo.h b/Framework/API/inc/MantidAPI/WorkspaceNearestNeighbourInfo.h index 083666cec60eefe0ab82eb3db7aaa8aaa10ec478..63ac1b8c518575ff8193a84c213ff54393af1d63 100644 --- a/Framework/API/inc/MantidAPI/WorkspaceNearestNeighbourInfo.h +++ b/Framework/API/inc/MantidAPI/WorkspaceNearestNeighbourInfo.h @@ -27,16 +27,12 @@ class WorkspaceNearestNeighbours; */ class MANTID_API_DLL WorkspaceNearestNeighbourInfo { public: - WorkspaceNearestNeighbourInfo(const MatrixWorkspace &workspace, - const bool ignoreMaskedDetectors, + WorkspaceNearestNeighbourInfo(const MatrixWorkspace &workspace, const bool ignoreMaskedDetectors, const int nNeighbours = 8); ~WorkspaceNearestNeighbourInfo(); - std::map - getNeighbours(const Geometry::IDetector *comp, - const double radius = 0.0) const; - std::map getNeighbours(specnum_t spec, - const double radius) const; + std::map getNeighbours(const Geometry::IDetector *comp, const double radius = 0.0) const; + std::map getNeighbours(specnum_t spec, const double radius) const; std::map getNeighboursExact(specnum_t spec) const; private: diff --git a/Framework/API/inc/MantidAPI/WorkspaceNearestNeighbours.h b/Framework/API/inc/MantidAPI/WorkspaceNearestNeighbours.h index 5a45df64235c4b79ca3b963bde7e2cc15f975201..ae77921e9f9e20585cb4f36b02143972ab24d5f8 100644 --- a/Framework/API/inc/MantidAPI/WorkspaceNearestNeighbours.h +++ b/Framework/API/inc/MantidAPI/WorkspaceNearestNeighbours.h @@ -12,7 +12,9 @@ #include // Boost graphing #ifndef Q_MOC_RUN +#define BOOST_ALLOW_DEPRECATED_HEADERS #include +#undef BOOST_ALLOW_DEPRECATED_HEADERS #include #endif @@ -47,13 +49,11 @@ class SpectrumInfo; */ class MANTID_API_DLL WorkspaceNearestNeighbours { public: - WorkspaceNearestNeighbours(int nNeighbours, const SpectrumInfo &spectrumInfo, - std::vector spectrumNumbers, + WorkspaceNearestNeighbours(int nNeighbours, const SpectrumInfo &spectrumInfo, std::vector spectrumNumbers, bool ignoreMaskedDetectors = false); // Neighbouring spectra by radius - std::map - neighboursInRadius(specnum_t spectrum, double radius = 0.0) const; + std::map neighboursInRadius(specnum_t spectrum, double radius = 0.0) const; // Neighbouring spectra by std::map neighbours(specnum_t spectrum) const; @@ -68,10 +68,9 @@ private: const std::vector m_spectrumNumbers; /// typedef for Graph object used to hold the calculated information - using Graph = boost::adjacency_list< - boost::vecS, boost::vecS, boost::directedS, - boost::property, - boost::property>; + using Graph = + boost::adjacency_list, + boost::property>; /// Vertex descriptor object for Graph using Vertex = boost::graph_traits::vertex_descriptor; /// map object of int to Graph Vertex descriptor @@ -82,8 +81,7 @@ private: void build(const int noNeighbours); /// Query the graph for the default number of nearest neighbours to specified /// detector - std::map - defaultNeighbours(const specnum_t spectrum) const; + std::map defaultNeighbours(const specnum_t spectrum) const; /// The current number of nearest neighbours int m_noNeighbours; /// The largest value of the distance to a nearest neighbour diff --git a/Framework/API/inc/MantidAPI/WorkspaceOpOverloads.h b/Framework/API/inc/MantidAPI/WorkspaceOpOverloads.h index f40c7b19dbea0f2c6a3030caa43a5c787b00dc76..f2bd86b39dd03927fc36f2b3a072532cfa9c1ffd 100644 --- a/Framework/API/inc/MantidAPI/WorkspaceOpOverloads.h +++ b/Framework/API/inc/MantidAPI/WorkspaceOpOverloads.h @@ -16,58 +16,36 @@ namespace API { namespace OperatorOverloads { // Helper function for operator overloads template -DLLExport ResultType executeBinaryOperation( - const std::string &algorithmName, const LHSType lhs, const RHSType rhs, - bool lhsAsOutput = false, bool child = true, const std::string &name = "", - bool rethrow = false); +DLLExport ResultType executeBinaryOperation(const std::string &algorithmName, const LHSType lhs, const RHSType rhs, + bool lhsAsOutput = false, bool child = true, const std::string &name = "", + bool rethrow = false); } // namespace OperatorOverloads -bool MANTID_API_DLL equals(const MatrixWorkspace_sptr &lhs, - const MatrixWorkspace_sptr &rhs, - double tolerance = 0.0); +bool MANTID_API_DLL equals(const MatrixWorkspace_sptr &lhs, const MatrixWorkspace_sptr &rhs, double tolerance = 0.0); // Workspace operator overloads -MatrixWorkspace_sptr MANTID_API_DLL operator+(const MatrixWorkspace_sptr &lhs, - const MatrixWorkspace_sptr &rhs); -MatrixWorkspace_sptr MANTID_API_DLL operator-(const MatrixWorkspace_sptr &lhs, - const MatrixWorkspace_sptr &rhs); -MatrixWorkspace_sptr MANTID_API_DLL operator*(const MatrixWorkspace_sptr &lhs, - const MatrixWorkspace_sptr &rhs); -MatrixWorkspace_sptr MANTID_API_DLL operator/(const MatrixWorkspace_sptr &lhs, - const MatrixWorkspace_sptr &rhs); +MatrixWorkspace_sptr MANTID_API_DLL operator+(const MatrixWorkspace_sptr &lhs, const MatrixWorkspace_sptr &rhs); +MatrixWorkspace_sptr MANTID_API_DLL operator-(const MatrixWorkspace_sptr &lhs, const MatrixWorkspace_sptr &rhs); +MatrixWorkspace_sptr MANTID_API_DLL operator*(const MatrixWorkspace_sptr &lhs, const MatrixWorkspace_sptr &rhs); +MatrixWorkspace_sptr MANTID_API_DLL operator/(const MatrixWorkspace_sptr &lhs, const MatrixWorkspace_sptr &rhs); -MatrixWorkspace_sptr MANTID_API_DLL operator+(const MatrixWorkspace_sptr &lhs, - const double &rhsValue); -MatrixWorkspace_sptr MANTID_API_DLL operator-(const MatrixWorkspace_sptr &lhs, - const double &rhsValue); -MatrixWorkspace_sptr MANTID_API_DLL operator-(const double &lhsValue, - const MatrixWorkspace_sptr &rhs); -MatrixWorkspace_sptr MANTID_API_DLL operator*(const MatrixWorkspace_sptr &lhs, - const double &rhsValue); -MatrixWorkspace_sptr MANTID_API_DLL operator*(const double &lhsValue, - const MatrixWorkspace_sptr &rhs); -MatrixWorkspace_sptr MANTID_API_DLL operator/(const MatrixWorkspace_sptr &lhs, - const double &rhsValue); -MatrixWorkspace_sptr MANTID_API_DLL operator/(const double &lhsValue, - const MatrixWorkspace_sptr &rhs); +MatrixWorkspace_sptr MANTID_API_DLL operator+(const MatrixWorkspace_sptr &lhs, const double &rhsValue); +MatrixWorkspace_sptr MANTID_API_DLL operator-(const MatrixWorkspace_sptr &lhs, const double &rhsValue); +MatrixWorkspace_sptr MANTID_API_DLL operator-(const double &lhsValue, const MatrixWorkspace_sptr &rhs); +MatrixWorkspace_sptr MANTID_API_DLL operator*(const MatrixWorkspace_sptr &lhs, const double &rhsValue); +MatrixWorkspace_sptr MANTID_API_DLL operator*(const double &lhsValue, const MatrixWorkspace_sptr &rhs); +MatrixWorkspace_sptr MANTID_API_DLL operator/(const MatrixWorkspace_sptr &lhs, const double &rhsValue); +MatrixWorkspace_sptr MANTID_API_DLL operator/(const double &lhsValue, const MatrixWorkspace_sptr &rhs); -MatrixWorkspace_sptr MANTID_API_DLL operator+=(const MatrixWorkspace_sptr &lhs, - const MatrixWorkspace_sptr &rhs); -MatrixWorkspace_sptr MANTID_API_DLL operator-=(const MatrixWorkspace_sptr &lhs, - const MatrixWorkspace_sptr &rhs); -MatrixWorkspace_sptr MANTID_API_DLL operator*=(const MatrixWorkspace_sptr &lhs, - const MatrixWorkspace_sptr &rhs); -MatrixWorkspace_sptr MANTID_API_DLL operator/=(const MatrixWorkspace_sptr &lhs, - const MatrixWorkspace_sptr &rhs); +MatrixWorkspace_sptr MANTID_API_DLL operator+=(const MatrixWorkspace_sptr &lhs, const MatrixWorkspace_sptr &rhs); +MatrixWorkspace_sptr MANTID_API_DLL operator-=(const MatrixWorkspace_sptr &lhs, const MatrixWorkspace_sptr &rhs); +MatrixWorkspace_sptr MANTID_API_DLL operator*=(const MatrixWorkspace_sptr &lhs, const MatrixWorkspace_sptr &rhs); +MatrixWorkspace_sptr MANTID_API_DLL operator/=(const MatrixWorkspace_sptr &lhs, const MatrixWorkspace_sptr &rhs); -MatrixWorkspace_sptr MANTID_API_DLL operator+=(const MatrixWorkspace_sptr &lhs, - const double &rhsValue); -MatrixWorkspace_sptr MANTID_API_DLL operator-=(const MatrixWorkspace_sptr &lhs, - const double &rhsValue); -MatrixWorkspace_sptr MANTID_API_DLL operator*=(const MatrixWorkspace_sptr &lhs, - const double &rhsValue); -MatrixWorkspace_sptr MANTID_API_DLL operator/=(const MatrixWorkspace_sptr &lhs, - const double &rhsValue); +MatrixWorkspace_sptr MANTID_API_DLL operator+=(const MatrixWorkspace_sptr &lhs, const double &rhsValue); +MatrixWorkspace_sptr MANTID_API_DLL operator-=(const MatrixWorkspace_sptr &lhs, const double &rhsValue); +MatrixWorkspace_sptr MANTID_API_DLL operator*=(const MatrixWorkspace_sptr &lhs, const double &rhsValue); +MatrixWorkspace_sptr MANTID_API_DLL operator/=(const MatrixWorkspace_sptr &lhs, const double &rhsValue); /** A collection of static functions for use with workspaces @@ -76,15 +54,12 @@ MatrixWorkspace_sptr MANTID_API_DLL operator/=(const MatrixWorkspace_sptr &lhs, */ struct MANTID_API_DLL WorkspaceHelpers { // Checks whether the binning is the same in two workspaces - static bool matchingBins(const MatrixWorkspace &ws1, - const MatrixWorkspace &ws2, - const bool firstOnly = false); + static bool matchingBins(const MatrixWorkspace &ws1, const MatrixWorkspace &ws2, const bool firstOnly = false); // Checks whether a the X vectors in a workspace are actually the same vector static bool sharedXData(const MatrixWorkspace &WS); // Divides the data in a workspace by the bin width to make it a distribution // (or the reverse) - static void makeDistribution(const MatrixWorkspace_sptr &workspace, - const bool forwards = true); + static void makeDistribution(const MatrixWorkspace_sptr &workspace, const bool forwards = true); }; } // namespace API diff --git a/Framework/API/inc/MantidAPI/WorkspaceProperty.h b/Framework/API/inc/MantidAPI/WorkspaceProperty.h index e7b0578d8bbeb9345f1a44e8e4e1aa35beebf9c5..478ff2dd92b455651fb2dfa8d7aa2aa5ff815011 100644 --- a/Framework/API/inc/MantidAPI/WorkspaceProperty.h +++ b/Framework/API/inc/MantidAPI/WorkspaceProperty.h @@ -52,28 +52,21 @@ and the overwriting the old one at the end.) @date 10/12/2007 */ template -class WorkspaceProperty - : public Kernel::PropertyWithValue>, - public IWorkspaceProperty { +class WorkspaceProperty : public Kernel::PropertyWithValue>, public IWorkspaceProperty { public: explicit WorkspaceProperty( - const std::string &name, const std::string &wsName, - const unsigned int direction, - const Kernel::IValidator_sptr &validator = - Kernel::IValidator_sptr(new Kernel::NullValidator)); + const std::string &name, const std::string &wsName, const unsigned int direction, + const Kernel::IValidator_sptr &validator = Kernel::IValidator_sptr(new Kernel::NullValidator)); explicit WorkspaceProperty( - const std::string &name, const std::string &wsName, - const unsigned int direction, const PropertyMode::Type optional, - const Kernel::IValidator_sptr &validator = - Kernel::IValidator_sptr(new Kernel::NullValidator)); + const std::string &name, const std::string &wsName, const unsigned int direction, + const PropertyMode::Type optional, + const Kernel::IValidator_sptr &validator = Kernel::IValidator_sptr(new Kernel::NullValidator)); explicit WorkspaceProperty( - const std::string &name, const std::string &wsName, - const unsigned int direction, const PropertyMode::Type optional, - const LockMode::Type locking, - const Kernel::IValidator_sptr &validator = - Kernel::IValidator_sptr(new Kernel::NullValidator)); + const std::string &name, const std::string &wsName, const unsigned int direction, + const PropertyMode::Type optional, const LockMode::Type locking, + const Kernel::IValidator_sptr &validator = Kernel::IValidator_sptr(new Kernel::NullValidator)); WorkspaceProperty(const WorkspaceProperty &right); @@ -97,8 +90,7 @@ public: std::string setValueFromJson(const Json::Value &value) override; - std::string - setDataItem(const std::shared_ptr &value) override; + std::string setDataItem(const std::shared_ptr &value) override; std::string isValid() const override; @@ -118,8 +110,7 @@ public: void setIsMasterRank(bool isMasterRank) override; private: - std::string - isValidGroup(const std::shared_ptr &wsGroup) const; + std::string isValidGroup(const std::shared_ptr &wsGroup) const; std::string isValidOutputWs() const; @@ -146,8 +137,7 @@ private: bool m_isMasterRank{true}; }; -template -Kernel::Logger WorkspaceProperty::g_log("WorkspaceProperty"); +template Kernel::Logger WorkspaceProperty::g_log("WorkspaceProperty"); } // namespace API } // namespace Mantid diff --git a/Framework/API/inc/MantidAPI/WorkspaceProperty.tcc b/Framework/API/inc/MantidAPI/WorkspaceProperty.tcc index f351626dcf7b66fca9df6e4b4faf1609e6865777..1d14233cf971e8bcd7ca9879d79deb08a5602126 100644 --- a/Framework/API/inc/MantidAPI/WorkspaceProperty.tcc +++ b/Framework/API/inc/MantidAPI/WorkspaceProperty.tcc @@ -29,13 +29,11 @@ namespace API { * Direction enum (i.e. 0-2) */ template -WorkspaceProperty::WorkspaceProperty( - const std::string &name, const std::string &wsName, - const unsigned int direction, const Kernel::IValidator_sptr &validator) - : Kernel::PropertyWithValue>( - name, std::shared_ptr(), validator, direction), - m_workspaceName(wsName), m_initialWSName(wsName), - m_optional(PropertyMode::Mandatory), m_locking(LockMode::Lock) {} +WorkspaceProperty::WorkspaceProperty(const std::string &name, const std::string &wsName, + const unsigned int direction, const Kernel::IValidator_sptr &validator) + : Kernel::PropertyWithValue>(name, std::shared_ptr(), validator, direction), + m_workspaceName(wsName), m_initialWSName(wsName), m_optional(PropertyMode::Mandatory), m_locking(LockMode::Lock) { +} /** Constructor. * Sets the property and workspace names but initializes the workspace pointer @@ -50,14 +48,11 @@ WorkspaceProperty::WorkspaceProperty( * Direction enum (i.e. 0-2) */ template -WorkspaceProperty::WorkspaceProperty( - const std::string &name, const std::string &wsName, - const unsigned int direction, const PropertyMode::Type optional, - const Kernel::IValidator_sptr &validator) - : Kernel::PropertyWithValue>( - name, std::shared_ptr(), validator, direction), - m_workspaceName(wsName), m_initialWSName(wsName), m_optional(optional), - m_locking(LockMode::Lock) {} +WorkspaceProperty::WorkspaceProperty(const std::string &name, const std::string &wsName, + const unsigned int direction, const PropertyMode::Type optional, + const Kernel::IValidator_sptr &validator) + : Kernel::PropertyWithValue>(name, std::shared_ptr(), validator, direction), + m_workspaceName(wsName), m_initialWSName(wsName), m_optional(optional), m_locking(LockMode::Lock) {} /** Constructor. * Sets the property and workspace names but initializes the workspace pointer @@ -76,29 +71,22 @@ WorkspaceProperty::WorkspaceProperty( * Direction enum (i.e. 0-2) */ template -WorkspaceProperty::WorkspaceProperty( - const std::string &name, const std::string &wsName, - const unsigned int direction, const PropertyMode::Type optional, - const LockMode::Type locking, const Kernel::IValidator_sptr &validator) - : Kernel::PropertyWithValue>( - name, std::shared_ptr(), validator, direction), - m_workspaceName(wsName), m_initialWSName(wsName), m_optional(optional), - m_locking(locking) {} +WorkspaceProperty::WorkspaceProperty(const std::string &name, const std::string &wsName, + const unsigned int direction, const PropertyMode::Type optional, + const LockMode::Type locking, const Kernel::IValidator_sptr &validator) + : Kernel::PropertyWithValue>(name, std::shared_ptr(), validator, direction), + m_workspaceName(wsName), m_initialWSName(wsName), m_optional(optional), m_locking(locking) {} /// Copy constructor, the default name stored in the new object is the same as /// the default name from the original object template WorkspaceProperty::WorkspaceProperty(const WorkspaceProperty &right) - : Kernel::PropertyWithValue>(right), - m_workspaceName(right.m_workspaceName), - m_initialWSName(right.m_initialWSName), m_optional(right.m_optional), - m_locking(right.m_locking) {} + : Kernel::PropertyWithValue>(right), m_workspaceName(right.m_workspaceName), + m_initialWSName(right.m_initialWSName), m_optional(right.m_optional), m_locking(right.m_locking) {} /// Copy assignment operator. Only copies the value (i.e. the pointer to the /// workspace) -template -WorkspaceProperty &WorkspaceProperty:: -operator=(const WorkspaceProperty &right) { +template WorkspaceProperty &WorkspaceProperty::operator=(const WorkspaceProperty &right) { if (&right == this) return *this; Kernel::PropertyWithValue>::operator=(right); @@ -111,8 +99,7 @@ operator=(const WorkspaceProperty &right) { * @return assigned PropertyWithValue */ template -WorkspaceProperty &WorkspaceProperty:: -operator=(const std::shared_ptr &value) { +WorkspaceProperty &WorkspaceProperty::operator=(const std::shared_ptr &value) { std::string wsName = value->getName(); if (this->direction() == Kernel::Direction::Input && !wsName.empty()) { m_workspaceName = wsName; @@ -123,50 +110,37 @@ operator=(const std::shared_ptr &value) { //-------------------------------------------------------------------------------------- /// Add the value of another property -template -WorkspaceProperty &WorkspaceProperty:: -operator+=(Kernel::Property const *) { - throw Kernel::Exception::NotImplementedError( - "+= operator is not implemented for WorkspaceProperty."); +template WorkspaceProperty &WorkspaceProperty::operator+=(Kernel::Property const *) { + throw Kernel::Exception::NotImplementedError("+= operator is not implemented for WorkspaceProperty."); return *this; } /// 'Virtual copy constructor' -template -WorkspaceProperty *WorkspaceProperty::clone() const { +template WorkspaceProperty *WorkspaceProperty::clone() const { return new WorkspaceProperty(*this); } /** Get the name of the workspace * @return The workspace's name */ -template std::string WorkspaceProperty::value() const { - return m_workspaceName; -} +template std::string WorkspaceProperty::value() const { return m_workspaceName; } /** * @returns The name of the workspace encode as a Json::Value */ -template -Json::Value WorkspaceProperty::valueAsJson() const { - return Json::Value(value()); -} +template Json::Value WorkspaceProperty::valueAsJson() const { return Json::Value(value()); } /** Returns true if the workspace is in the ADS or there is none. * @return true if the string returned by value() is valid */ -template -bool WorkspaceProperty::isValueSerializable() const { +template bool WorkspaceProperty::isValueSerializable() const { return !m_workspaceName.empty() || !this->m_value; } /** Get the value the property was initialised with -its default value * @return The default value */ -template -std::string WorkspaceProperty::getDefault() const { - return m_initialWSName; -} +template std::string WorkspaceProperty::getDefault() const { return m_initialWSName; } /** Set the name of the workspace. * Also tries to retrieve it from the AnalysisDataService. @@ -174,8 +148,7 @@ std::string WorkspaceProperty::getDefault() const { * @return An empty string indicating success otherwise a string containing the * error */ -template -std::string WorkspaceProperty::setValue(const std::string &value) { +template std::string WorkspaceProperty::setValue(const std::string &value) { m_workspaceName = value; if (Kernel::PropertyWithValue>::autoTrim()) { boost::trim(m_workspaceName); @@ -191,9 +164,7 @@ std::string WorkspaceProperty::setValue(const std::string &value) { * @return An empty string indicating success otherwise a string containing the * error */ -template -std::string -WorkspaceProperty::setValueFromJson(const Json::Value &value) { +template std::string WorkspaceProperty::setValueFromJson(const Json::Value &value) { try { return setValue(value.asString()); } catch (std::exception &exc) { @@ -207,8 +178,7 @@ WorkspaceProperty::setValueFromJson(const Json::Value &value) { * @return */ template -std::string WorkspaceProperty::setDataItem( - const std::shared_ptr &value) { +std::string WorkspaceProperty::setDataItem(const std::shared_ptr &value) { std::shared_ptr typed = std::dynamic_pointer_cast(value); if (typed) { if (this->direction() == Kernel::Direction::Input) { @@ -241,8 +211,7 @@ template std::string WorkspaceProperty::isValid() const { // If an input (or inout) workspace, must point to something, although it // doesn't have to have a name // unless it's optional - if (this->direction() == Kernel::Direction::Input || - this->direction() == Kernel::Direction::InOut) { + if (this->direction() == Kernel::Direction::Input || this->direction() == Kernel::Direction::InOut) { // Workspace groups will not have a value since they are not of type TYPE if (!Kernel::PropertyWithValue>::m_value) { Mantid::API::Workspace_sptr wksp; @@ -274,8 +243,7 @@ template std::string WorkspaceProperty::isValid() const { // At this point we have a valid pointer to a Workspace so we need to // test whether it is a group if (std::dynamic_pointer_cast(wksp)) { - return isValidGroup( - std::dynamic_pointer_cast(wksp)); + return isValidGroup(std::dynamic_pointer_cast(wksp)); } else { error = "Workspace " + this->value() + " is not of the correct type"; } @@ -305,22 +273,17 @@ template bool WorkspaceProperty::isOptional() const { } /** Does the workspace need to be locked before starting an algorithm? * @return true (default) if the workspace will be locked */ -template bool WorkspaceProperty::isLocking() const { - return (m_locking == LockMode::Lock); -} +template bool WorkspaceProperty::isLocking() const { return (m_locking == LockMode::Lock); } /** Returns the current contents of the AnalysisDataService for input * workspaces. * For output workspaces, an empty set is returned * @return set of objects in AnalysisDataService */ -template -std::vector WorkspaceProperty::allowedValues() const { - if (this->direction() == Kernel::Direction::Input || - this->direction() == Kernel::Direction::InOut) { +template std::vector WorkspaceProperty::allowedValues() const { + if (this->direction() == Kernel::Direction::Input || this->direction() == Kernel::Direction::InOut) { // If an input workspace, get the list of workspaces currently in the ADS - auto vals = AnalysisDataService::Instance().getObjectNames( - Mantid::Kernel::DataServiceSort::Sorted); + auto vals = AnalysisDataService::Instance().getObjectNames(Mantid::Kernel::DataServiceSort::Sorted); if (isOptional()) // Insert an empty option { vals.emplace_back(""); @@ -331,9 +294,7 @@ std::vector WorkspaceProperty::allowedValues() const { // Remove any workspace that's not valid for this algorithm auto eraseIter = remove_if(vals.begin(), vals.end(), - [&tester](const std::string &wsName) { - return !tester.setValue(wsName).empty(); - }); + [&tester](const std::string &wsName) { return !tester.setValue(wsName).empty(); }); // Erase everything past returned iterator afterwards for readability vals.erase(eraseIter, vals.end()); return vals; @@ -345,8 +306,7 @@ std::vector WorkspaceProperty::allowedValues() const { /// Create a history record /// @return A populated PropertyHistory for this class -template -const Kernel::PropertyHistory WorkspaceProperty::createHistory() const { +template const Kernel::PropertyHistory WorkspaceProperty::createHistory() const { std::string wsName = m_workspaceName; bool isdefault = this->isDefault(); @@ -357,8 +317,7 @@ const Kernel::PropertyHistory WorkspaceProperty::createHistory() const { wsName = os.str(); isdefault = false; } - return Kernel::PropertyHistory(this->name(), wsName, this->type(), isdefault, - this->direction()); + return Kernel::PropertyHistory(this->name(), wsName, this->type(), isdefault, this->direction()); } /** If this is an output workspace, store it into the AnalysisDataService @@ -374,11 +333,9 @@ template bool WorkspaceProperty::store() { // Check that workspace exists if (this->operator()()) { // Note use of addOrReplace rather than add - API::AnalysisDataService::Instance().addOrReplace(m_workspaceName, - this->operator()()); + API::AnalysisDataService::Instance().addOrReplace(m_workspaceName, this->operator()()); } else if (m_isMasterRank) { - throw std::runtime_error( - "WorkspaceProperty doesn't point to a workspace"); + throw std::runtime_error("WorkspaceProperty doesn't point to a workspace"); } result = true; } @@ -388,14 +345,10 @@ template bool WorkspaceProperty::store() { return result; } -template -Workspace_sptr WorkspaceProperty::getWorkspace() const { - return this->operator()(); -} +template Workspace_sptr WorkspaceProperty::getWorkspace() const { return this->operator()(); } /// Sets a flag indicating whether this is the master rank in MPI builds. -template -void WorkspaceProperty::setIsMasterRank(bool isMasterRank) { +template void WorkspaceProperty::setIsMasterRank(bool isMasterRank) { m_isMasterRank = isMasterRank; } @@ -405,8 +358,7 @@ void WorkspaceProperty::setIsMasterRank(bool isMasterRank) { * @returns A user level description of the problem or "" if it is valid. */ template -std::string WorkspaceProperty::isValidGroup( - const std::shared_ptr &wsGroup) const { +std::string WorkspaceProperty::isValidGroup(const std::shared_ptr &wsGroup) const { g_log.debug() << " Input WorkspaceGroup found \n"; std::vector wsGroupNames = wsGroup->getNames(); @@ -414,8 +366,7 @@ std::string WorkspaceProperty::isValidGroup( // Cycle through each workspace in the group ... for (const auto &memberWsName : wsGroupNames) { - std::shared_ptr memberWs = - AnalysisDataService::Instance().retrieve(memberWsName); + std::shared_ptr memberWs = AnalysisDataService::Instance().retrieve(memberWsName); // Table Workspaces are ignored if ("TableWorkspace" == memberWs->id()) { @@ -455,8 +406,7 @@ std::string WorkspaceProperty::isValidGroup( * @see AnalysisDataServiceImpl * @returns A user level description of the problem or "" if it is valid. */ -template -std::string WorkspaceProperty::isValidOutputWs() const { +template std::string WorkspaceProperty::isValidOutputWs() const { std::string error; const std::string value = this->value(); if (!value.empty()) { @@ -476,8 +426,7 @@ std::string WorkspaceProperty::isValidOutputWs() const { * is actually an optional workspace and so still valid. * @returns A user level description of the problem or "" if it is valid. */ -template -std::string WorkspaceProperty::isOptionalWs() const { +template std::string WorkspaceProperty::isOptionalWs() const { std::string error; if (m_workspaceName.empty()) { @@ -487,8 +436,7 @@ std::string WorkspaceProperty::isOptionalWs() const { error = "Enter a name for the Input/InOut workspace"; } } else { - error = "Workspace \"" + this->value() + - "\" was not found in the Analysis Data Service"; + error = "Workspace \"" + this->value() + "\" was not found in the Analysis Data Service"; } return error; @@ -496,15 +444,13 @@ std::string WorkspaceProperty::isOptionalWs() const { /// Reset the pointer to the workspace template void WorkspaceProperty::clear() { - Kernel::PropertyWithValue>::m_value = - std::shared_ptr(); + Kernel::PropertyWithValue>::m_value = std::shared_ptr(); } /** Attempts to retreive the data from the ADS * if the data is not foung the internal pointer is set to null. */ -template -void WorkspaceProperty::retrieveWorkspaceFromADS() { +template void WorkspaceProperty::retrieveWorkspaceFromADS() { // Try and get the workspace from the ADS, but don't worry if we can't try { Kernel::PropertyWithValue>::m_value = diff --git a/Framework/API/src/ADSValidator.cpp b/Framework/API/src/ADSValidator.cpp index 07db11fe0d583dfd88cb45ec0cd432ba71cc19ae..835b150eec6e619f0eb0a32874925459f8c4df06 100644 --- a/Framework/API/src/ADSValidator.cpp +++ b/Framework/API/src/ADSValidator.cpp @@ -15,38 +15,29 @@ namespace Mantid { namespace API { /// Default constructor. Sets up an empty list of valid values. -ADSValidator::ADSValidator(const bool allowMultiSelection, - const bool isOptional) - : TypedValidator>(), - m_AllowMultiSelection(allowMultiSelection), m_isOptional(isOptional) {} +ADSValidator::ADSValidator(const bool allowMultiSelection, const bool isOptional) + : TypedValidator>(), m_AllowMultiSelection(allowMultiSelection), m_isOptional(isOptional) { +} /// Clone the validator -Kernel::IValidator_sptr ADSValidator::clone() const { - return std::make_shared(*this); -} +Kernel::IValidator_sptr ADSValidator::clone() const { return std::make_shared(*this); } -bool ADSValidator::isMultipleSelectionAllowed() { - return m_AllowMultiSelection; -} +bool ADSValidator::isMultipleSelectionAllowed() { return m_AllowMultiSelection; } -void ADSValidator::setMultipleSelectionAllowed( - const bool isMultiSelectionAllowed) { +void ADSValidator::setMultipleSelectionAllowed(const bool isMultiSelectionAllowed) { m_AllowMultiSelection = isMultiSelectionAllowed; } bool ADSValidator::isOptional() const { return m_isOptional; } -void ADSValidator::setOptional(const bool setOptional) { - m_isOptional = setOptional; -} +void ADSValidator::setOptional(const bool setOptional) { m_isOptional = setOptional; } /** Checks if the string passed is in the ADS, or if all members are in the ADS * @param value :: The value to test * @return "" if the value is on the list, or "The workspace is not in the * workspace list" */ -std::string -ADSValidator::checkValidity(const std::vector &value) const { +std::string ADSValidator::checkValidity(const std::vector &value) const { if (!m_isOptional && value.empty()) return "Select a value"; if (!m_AllowMultiSelection && (value.size() > 1)) { @@ -56,8 +47,7 @@ ADSValidator::checkValidity(const std::vector &value) const { std::ostringstream os; for (const auto &wsName : value) { if (!ads.doesExist(wsName)) { - os << "The workspace \"" << wsName - << "\" is not in the workspace list.\n"; + os << "The workspace \"" << wsName << "\" is not in the workspace list.\n"; } } return os.str(); @@ -70,8 +60,7 @@ ADSValidator::checkValidity(const std::vector &value) const { */ std::vector ADSValidator::allowedValues() const { // Get the list of workspaces currently in the ADS - auto vals = AnalysisDataService::Instance().getObjectNames( - Mantid::Kernel::DataServiceSort::Sorted); + auto vals = AnalysisDataService::Instance().getObjectNames(Mantid::Kernel::DataServiceSort::Sorted); if (isOptional()) // Insert an empty option { vals.emplace_back(""); diff --git a/Framework/API/src/AlgoTimeRegister.cpp b/Framework/API/src/AlgoTimeRegister.cpp index a49502de592d7389e606e973b9474166af66fb1c..c57028297b83590edcaaa4e92de7b47aa7ba893a 100644 --- a/Framework/API/src/AlgoTimeRegister.cpp +++ b/Framework/API/src/AlgoTimeRegister.cpp @@ -12,8 +12,7 @@ namespace Mantid { namespace Instrumentation { -AlgoTimeRegister::Dump::Dump(AlgoTimeRegister &atr, const std::string &nm) - : m_algoTimeRegister(atr), m_name(nm) { +AlgoTimeRegister::Dump::Dump(AlgoTimeRegister &atr, const std::string &nm) : m_algoTimeRegister(atr), m_name(nm) { clock_gettime(CLOCK_MONOTONIC, &m_regStart); } @@ -34,31 +33,25 @@ AlgoTimeRegister::Dump::~Dump() { clock_gettime(CLOCK_MONOTONIC, ®Finish); { std::lock_guard lock(m_algoTimeRegister.m_mutex); - m_algoTimeRegister.m_info.emplace_back(m_name, std::this_thread::get_id(), - m_regStart, regFinish); + m_algoTimeRegister.m_info.emplace_back(m_name, std::this_thread::get_id(), m_regStart, regFinish); } } -AlgoTimeRegister::AlgoTimeRegister() - : m_start(std::chrono::high_resolution_clock::now()) { +AlgoTimeRegister::AlgoTimeRegister() : m_start(std::chrono::high_resolution_clock::now()) { clock_gettime(CLOCK_MONOTONIC, &m_hstart); } AlgoTimeRegister::~AlgoTimeRegister() { std::fstream fs; fs.open("./algotimeregister.out", std::ios::out); - fs << "START_POINT: " - << std::chrono::duration_cast( - m_start.time_since_epoch()) - .count() + fs << "START_POINT: " << std::chrono::duration_cast(m_start.time_since_epoch()).count() << " MAX_THREAD: " << PARALLEL_GET_MAX_THREADS << "\n"; for (auto &elem : m_info) { auto st = diff(m_hstart, elem.m_begin); auto fi = diff(m_hstart, elem.m_end); fs << "ThreadID=" << elem.m_threadId << ", AlgorithmName=" << elem.m_name << ", StartTime=" << std::size_t(st.tv_sec * 1000000000) + st.tv_nsec - << ", EndTime=" << std::size_t(fi.tv_sec * 1000000000) + fi.tv_nsec - << "\n"; + << ", EndTime=" << std::size_t(fi.tv_sec * 1000000000) + fi.tv_nsec << "\n"; } } diff --git a/Framework/API/src/Algorithm.cpp b/Framework/API/src/Algorithm.cpp index 50557308740d9618243d88baa9262a3da3afdb06..7e22e69d181fefa07824afc17174ba162dd97fc7 100644 --- a/Framework/API/src/Algorithm.cpp +++ b/Framework/API/src/Algorithm.cpp @@ -14,6 +14,7 @@ #include "MantidAPI/WorkspaceGroup.h" #include "MantidAPI/WorkspaceHistory.h" +#include "MantidJson/Json.h" #include "MantidKernel/CompositeValidator.h" #include "MantidKernel/ConfigService.h" #include "MantidKernel/EmptyValues.h" @@ -55,8 +56,7 @@ const size_t DELAY_BEFORE_GC = 5; class WorkspacePropertyValueIs { public: - explicit WorkspacePropertyValueIs(const std::string &value) - : m_value(value) {} + explicit WorkspacePropertyValueIs(const std::string &value) : m_value(value) {} bool operator()(IWorkspaceProperty *property) { auto *prop = dynamic_cast(property); if (!prop) @@ -69,7 +69,6 @@ private: }; template struct RunOnFinish { - RunOnFinish(T &&task) : m_onfinsh(std::move(task)) {} ~RunOnFinish() { m_onfinsh(); } @@ -107,17 +106,13 @@ size_t Algorithm::g_execCount = 0; /// Constructor Algorithm::Algorithm() - : PropertyManagerOwner(), m_cancel(false), m_parallelException(false), - m_log("Algorithm"), g_log(m_log), m_groupSize(0), m_executeAsync(nullptr), - m_notificationCenter(nullptr), m_progressObserver(nullptr), - m_executionState(ExecutionState::Uninitialized), - m_resultState(ResultState::NotFinished), m_isChildAlgorithm(false), - m_recordHistoryForChild(false), m_alwaysStoreInADS(true), - m_runningAsync(false), m_rethrow(false), - m_isAlgStartupLoggingEnabled(true), m_startChildProgress(0.), - m_endChildProgress(0.), m_algorithmID(this), m_singleGroup(-1), - m_groupsHaveSimilarNames(false), m_inputWorkspaceHistories(), - m_communicator(std::make_unique()) {} + : m_cancel(false), m_parallelException(false), m_log("Algorithm"), g_log(m_log), m_groupSize(0), + m_executeAsync(nullptr), m_notificationCenter(nullptr), m_progressObserver(nullptr), + m_executionState(ExecutionState::Uninitialized), m_resultState(ResultState::NotFinished), + m_isChildAlgorithm(false), m_recordHistoryForChild(false), m_alwaysStoreInADS(true), m_runningAsync(false), + m_rethrow(false), m_isAlgStartupLoggingEnabled(true), m_startChildProgress(0.), m_endChildProgress(0.), + m_algorithmID(this), m_singleGroup(-1), m_groupsHaveSimilarNames(false), m_inputWorkspaceHistories(), + m_communicator(std::make_unique()), m_properties() {} /// Virtual destructor Algorithm::~Algorithm() {} @@ -131,9 +126,7 @@ Algorithm::~Algorithm() {} ExecutionState Algorithm::executionState() const { return m_executionState; } /// Sets the current execution state -void Algorithm::setExecutionState(const ExecutionState state) { - m_executionState = state; -} +void Algorithm::setExecutionState(const ExecutionState state) { m_executionState = state; } /// Gets the current result State ResultState Algorithm::resultState() const { return m_resultState; } @@ -149,14 +142,11 @@ void Algorithm::setResultState(const ResultState state) { //--------------------------------------------------------------------------------------------- /// Has the Algorithm already been initialized -bool Algorithm::isInitialized() const { - return (m_executionState != ExecutionState::Uninitialized); -} +bool Algorithm::isInitialized() const { return (m_executionState != ExecutionState::Uninitialized); } /// Has the Algorithm already been executed successfully bool Algorithm::isExecuted() const { - return ((executionState() == ExecutionState::Finished) && - (resultState() == ResultState::Success)); + return ((executionState() == ExecutionState::Finished) && (resultState() == ResultState::Success)); } //--------------------------------------------------------------------------------------------- @@ -180,18 +170,14 @@ void Algorithm::setChild(const bool isChild) { * child algorithms. * @param on :: The new state of the flag */ -void Algorithm::enableHistoryRecordingForChild(const bool on) { - m_recordHistoryForChild = on; -} +void Algorithm::enableHistoryRecordingForChild(const bool on) { m_recordHistoryForChild = on; } /** Do we ALWAYS store in the AnalysisDataService? This is set to true * for python algorithms' child algorithms * * @param doStore :: always store in ADS */ -void Algorithm::setAlwaysStoreInADS(const bool doStore) { - m_alwaysStoreInADS = doStore; -} +void Algorithm::setAlwaysStoreInADS(const bool doStore) { m_alwaysStoreInADS = doStore; } /** Returns true if we always store in the AnalysisDataService. * @return true if output is saved to the AnalysisDataService. @@ -204,9 +190,7 @@ bool Algorithm::getAlwaysStoreInADS() const { return m_alwaysStoreInADS; } void Algorithm::setRethrows(const bool rethrow) { this->m_rethrow = rethrow; } /// True if the algorithm is running. -bool Algorithm::isRunning() const { - return (executionState() == ExecutionState::Running); -} +bool Algorithm::isRunning() const { return (executionState() == ExecutionState::Running); } /// True if the algorithm is ready for garbage collection. bool Algorithm::isReadyForGarbageCollection() const { @@ -241,19 +225,16 @@ void Algorithm::removeObserver(const Poco::AbstractObserver &observer) const { * @param progressPrecision :: optional, int number of digits after the decimal * point to show. */ -void Algorithm::progress(double p, const std::string &msg, double estimatedTime, - int progressPrecision) { - notificationCenter().postNotification( - new ProgressNotification(this, p, msg, estimatedTime, progressPrecision)); +void Algorithm::progress(double p, const std::string &msg, double estimatedTime, int progressPrecision) { + notificationCenter().postNotification(new ProgressNotification(this, p, msg, estimatedTime, progressPrecision)); } //--------------------------------------------------------------------------------------------- /// Function to return all of the categories that contain this algorithm const std::vector Algorithm::categories() const { - Mantid::Kernel::StringTokenizer tokenizer( - category(), categorySeparator(), - Mantid::Kernel::StringTokenizer::TOK_TRIM | - Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY); + Mantid::Kernel::StringTokenizer tokenizer(category(), categorySeparator(), + Mantid::Kernel::StringTokenizer::TOK_TRIM | + Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY); auto res = tokenizer.asVector(); @@ -276,10 +257,9 @@ const std::string Algorithm::workspaceMethodName() const { return ""; } *workspaceMethodName attached */ const std::vector Algorithm::workspaceMethodOn() const { - Mantid::Kernel::StringTokenizer tokenizer( - this->workspaceMethodOnTypes(), WORKSPACE_TYPES_SEPARATOR, - Mantid::Kernel::StringTokenizer::TOK_TRIM | - Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY); + Mantid::Kernel::StringTokenizer tokenizer(this->workspaceMethodOnTypes(), WORKSPACE_TYPES_SEPARATOR, + Mantid::Kernel::StringTokenizer::TOK_TRIM | + Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY); return tokenizer.asVector(); } @@ -338,9 +318,7 @@ void Algorithm::initialize() { * @return a map where: Key = string name of the the property; Value = string describing the problem with the property. */ -std::map Algorithm::validateInputs() { - return std::map(); -} +std::map Algorithm::validateInputs() { return std::map(); } //--------------------------------------------------------------------------------------------- /** @@ -369,9 +347,8 @@ void Algorithm::cacheWorkspaceProperties() { m_pureOutputWorkspaceProps.emplace_back(wsProp); break; default: - throw std::logic_error( - "Unexpected property direction found for property " + prop->name() + - " of algorithm " + this->name()); + throw std::logic_error("Unexpected property direction found for property " + prop->name() + " of algorithm " + + this->name()); } } } @@ -386,8 +363,7 @@ void Algorithm::cacheInputWorkspaceHistories() { auto cacheHistories = [this](const Workspace_sptr &ws) { if (auto group = dynamic_cast(ws.get())) { - m_inputWorkspaceHistories.reserve(m_inputWorkspaceHistories.size() + - group->size()); + m_inputWorkspaceHistories.reserve(m_inputWorkspaceHistories.size() + group->size()); for (const auto &memberWS : *group) { m_inputWorkspaceHistories.emplace_back(memberWS); } @@ -401,8 +377,7 @@ void Algorithm::cacheInputWorkspaceHistories() { return false; if (dynamic_cast(validator.get())) return true; - if (const auto compValidator = - dynamic_cast(validator.get())) + if (const auto compValidator = dynamic_cast(validator.get())) return compValidator->contains(); return false; @@ -415,8 +390,7 @@ void Algorithm::cacheInputWorkspaceHistories() { m_inputWorkspaceHistories.clear(); const auto &props = this->getProperties(); for (const auto &prop : props) { - if (prop->direction() != Direction::Input && - prop->direction() != Direction::InOut) + if (prop->direction() != Direction::Input && prop->direction() != Direction::InOut) continue; if (auto wsProp = dynamic_cast(prop)) { @@ -463,10 +437,8 @@ void Algorithm::lockWorkspaces() { if (ws) { // The workspace property says to do locking, // AND it has NOT already been write-locked - if (outputWorkspaceProp->isLocking() && - std::find(m_writeLockedWorkspaces.begin(), - m_writeLockedWorkspaces.end(), - ws) == m_writeLockedWorkspaces.end()) { + if (outputWorkspaceProp->isLocking() && std::find(m_writeLockedWorkspaces.begin(), m_writeLockedWorkspaces.end(), + ws) == m_writeLockedWorkspaces.end()) { // Write-lock it if not already debugLog << "Write-locking " << ws->getName() << '\n'; ws->getLock()->writeLock(); @@ -481,10 +453,8 @@ void Algorithm::lockWorkspaces() { if (ws) { // The workspace property says to do locking, // AND it has NOT already been write-locked - if (inputWorkspaceProp->isLocking() && - std::find(m_writeLockedWorkspaces.begin(), - m_writeLockedWorkspaces.end(), - ws) == m_writeLockedWorkspaces.end()) { + if (inputWorkspaceProp->isLocking() && std::find(m_writeLockedWorkspaces.begin(), m_writeLockedWorkspaces.end(), + ws) == m_writeLockedWorkspaces.end()) { // Read-lock it if not already write-locked debugLog << "Read-locking " << ws->getName() << '\n'; ws->getLock()->readLock(); @@ -580,8 +550,7 @@ bool Algorithm::executeInternal() { } // Try the validation again if (!validateProperties()) { - notificationCenter().postNotification( - new ErrorNotification(this, "Some invalid Properties found")); + notificationCenter().postNotification(new ErrorNotification(this, "Some invalid Properties found")); throw std::runtime_error("Some invalid Properties found"); } } @@ -599,11 +568,8 @@ bool Algorithm::executeInternal() { // Checking the input is a group. Throws if the sizes are wrong callProcessGroups = this->checkGroups(); } catch (std::exception &ex) { - getLogger().error() << "Error in execution of algorithm " << this->name() - << "\n" - << ex.what() << "\n"; - notificationCenter().postNotification( - new ErrorNotification(this, ex.what())); + getLogger().error() << "Error in execution of algorithm " << this->name() << "\n" << ex.what() << "\n"; + notificationCenter().postNotification(new ErrorNotification(this, ex.what())); setResultState(ResultState::Failed); if (m_isChildAlgorithm || m_runningAsync || m_rethrow) { m_runningAsync = false; @@ -616,10 +582,9 @@ bool Algorithm::executeInternal() { timingInit += timer.elapsed(resetTimer); // ----- Perform validation of the whole set of properties ------------- - if ((!callProcessGroups) && - (executionMode != Parallel::ExecutionMode::MasterOnly || - communicator().rank() == 0)) // for groups this is called on each - // workspace separately + if ((!callProcessGroups) && (executionMode != Parallel::ExecutionMode::MasterOnly || + communicator().rank() == 0)) // for groups this is called on each + // workspace separately { std::map errors = this->validateInputs(); if (!errors.empty()) { @@ -629,12 +594,10 @@ bool Algorithm::executeInternal() { auto &warnLog = getLogger().warning(); for (auto &error : errors) { if (this->existsProperty(error.first)) - errorLog << "Invalid value for " << error.first << ": " - << error.second << "\n"; + errorLog << "Invalid value for " << error.first << ": " << error.second << "\n"; else { numErrors -= 1; // don't count it as an error - warnLog << "validateInputs() references non-existant property \"" - << error.first << "\"\n"; + warnLog << "validateInputs() references non-existant property \"" << error.first << "\"\n"; } } // Throw because something was invalid @@ -645,8 +608,7 @@ bool Algorithm::executeInternal() { msg << error.first << " "; } msg << "]"; - notificationCenter().postNotification( - new ErrorNotification(this, "Some invalid Properties found")); + notificationCenter().postNotification(new ErrorNotification(this, "Some invalid Properties found")); throw std::runtime_error(msg.str()); } } @@ -690,13 +652,11 @@ bool Algorithm::executeInternal() { interruption_point(); const float timingExec = timer.elapsed(resetTimer); // The total runtime including all init steps is used for general logging. - const float duration = timingInit + timingPropertyValidation + - timingInputValidation + timingExec; + const float duration = timingInit + timingPropertyValidation + timingInputValidation + timingExec; // need it to throw before trying to run fillhistory() on an algorithm // which has failed if (trackingHistory() && m_history) { - m_history->fillAlgorithmHistory(this, startTime, duration, - Algorithm::g_execCount); + m_history->fillAlgorithmHistory(this, startTime, duration, Algorithm::g_execCount); fillHistory(); linkHistoryWithLastChild(); } @@ -710,43 +670,33 @@ bool Algorithm::executeInternal() { algIsExecuted = true; // Log that execution has completed. - getLogger().debug( - "Time to validate properties: " + - std::to_string(timingPropertyValidation) + " seconds\n" + - "Time for other input validation: " + - std::to_string(timingInputValidation) + " seconds\n" + - "Time for other initialization: " + std::to_string(timingInit) + - " seconds\n" + "Time to run exec: " + std::to_string(timingExec) + - " seconds\n"); + getLogger().debug("Time to validate properties: " + std::to_string(timingPropertyValidation) + " seconds\n" + + "Time for other input validation: " + std::to_string(timingInputValidation) + " seconds\n" + + "Time for other initialization: " + std::to_string(timingInit) + " seconds\n" + + "Time to run exec: " + std::to_string(timingExec) + " seconds\n"); reportCompleted(duration); } catch (std::runtime_error &ex) { m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() += (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC); setResultState(ResultState::Failed); - notificationCenter().postNotification( - new ErrorNotification(this, ex.what())); + notificationCenter().postNotification(new ErrorNotification(this, ex.what())); this->unlockWorkspaces(); if (m_isChildAlgorithm || m_runningAsync || m_rethrow) throw; else { - getLogger().error() - << "Error in execution of algorithm " << this->name() << '\n' - << ex.what() << '\n'; + getLogger().error() << "Error in execution of algorithm " << this->name() << '\n' << ex.what() << '\n'; } } catch (std::logic_error &ex) { m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() += (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC); - notificationCenter().postNotification( - new ErrorNotification(this, ex.what())); + notificationCenter().postNotification(new ErrorNotification(this, ex.what())); setResultState(ResultState::Failed); this->unlockWorkspaces(); if (m_isChildAlgorithm || m_runningAsync || m_rethrow) throw; else { - getLogger().error() - << "Logic Error in execution of algorithm " << this->name() << '\n' - << ex.what() << '\n'; + getLogger().error() << "Logic Error in execution of algorithm " << this->name() << '\n' << ex.what() << '\n'; } } } catch (CancelException &ex) { @@ -755,8 +705,7 @@ bool Algorithm::executeInternal() { m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() += (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC); setResultState(ResultState::Failed); - notificationCenter().postNotification( - new ErrorNotification(this, ex.what())); + notificationCenter().postNotification(new ErrorNotification(this, ex.what())); this->unlockWorkspaces(); throw; @@ -764,14 +713,11 @@ bool Algorithm::executeInternal() { // Gaudi also specifically catches GaudiException & std:exception. catch (std::exception &ex) { m_runningAsync = false; - getLogger().error() << "Error in execution of algorithm " << this->name() - << ":\n" - << ex.what() << "\n"; + getLogger().error() << "Error in execution of algorithm " << this->name() << ":\n" << ex.what() << "\n"; m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() += (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC); setResultState(ResultState::Failed); - notificationCenter().postNotification( - new ErrorNotification(this, ex.what())); + notificationCenter().postNotification(new ErrorNotification(this, ex.what())); this->unlockWorkspaces(); throw; @@ -784,10 +730,8 @@ bool Algorithm::executeInternal() { m_gcTime = Mantid::Types::Core::DateAndTime::getCurrentTime() += (Mantid::Types::Core::DateAndTime::ONE_SECOND * DELAY_BEFORE_GC); setResultState(ResultState::Failed); - notificationCenter().postNotification( - new ErrorNotification(this, "UNKNOWN Exception is caught in exec()")); - getLogger().error() << this->name() - << ": UNKNOWN Exception is caught in exec()\n"; + notificationCenter().postNotification(new ErrorNotification(this, "UNKNOWN Exception is caught in exec()")); + getLogger().error() << this->name() << ": UNKNOWN Exception is caught in exec()\n"; this->unlockWorkspaces(); throw; @@ -801,8 +745,7 @@ bool Algorithm::executeInternal() { setResultState(ResultState::Success); } // Only gets to here if algorithm ended normally - notificationCenter().postNotification( - new FinishedNotification(this, isExecuted())); + notificationCenter().postNotification(new FinishedNotification(this, isExecuted())); return isExecuted(); } @@ -821,8 +764,7 @@ void Algorithm::executeAsChildAlg() { } if (!executed) { - throw std::runtime_error("Unable to successfully run ChildAlgorithm " + - this->name()); + throw std::runtime_error("Unable to successfully run ChildAlgorithm " + this->name()); } } @@ -841,8 +783,7 @@ void Algorithm::store() { if (wsProp) { // check if the workspace is a group, if so remember where it is and add // it later - auto group = - std::dynamic_pointer_cast(wsProp->getWorkspace()); + auto group = std::dynamic_pointer_cast(wsProp->getWorkspace()); if (!group) { try { wsProp->store(); @@ -857,8 +798,7 @@ void Algorithm::store() { // now store workspace groups once their members have been added std::vector::const_iterator wsIndex; - for (wsIndex = groupWsIndicies.begin(); wsIndex != groupWsIndicies.end(); - ++wsIndex) { + for (wsIndex = groupWsIndicies.begin(); wsIndex != groupWsIndicies.end(); ++wsIndex) { auto *wsProp = dynamic_cast(props[*wsIndex]); if (wsProp) { try { @@ -888,13 +828,9 @@ void Algorithm::store() { *default gives the latest version. * @return shared pointer to the newly created algorithm object */ -Algorithm_sptr Algorithm::createChildAlgorithm(const std::string &name, - const double startProgress, - const double endProgress, - const bool enableLogging, - const int &version) { - Algorithm_sptr alg = - AlgorithmManager::Instance().createUnmanaged(name, version); +Algorithm_sptr Algorithm::createChildAlgorithm(const std::string &name, const double startProgress, + const double endProgress, const bool enableLogging, const int &version) { + Algorithm_sptr alg = AlgorithmManager::Instance().createUnmanaged(name, version); setupAsChildAlgorithm(alg, startProgress, endProgress, enableLogging); return alg; } @@ -905,9 +841,7 @@ Algorithm_sptr Algorithm::createChildAlgorithm(const std::string &name, * Can also be used manually for algorithms created otherwise. This allows * running algorithms that are not declared into the factory as child * algorithms. */ -void Algorithm::setupAsChildAlgorithm(const Algorithm_sptr &alg, - const double startProgress, - const double endProgress, +void Algorithm::setupAsChildAlgorithm(const Algorithm_sptr &alg, const double startProgress, const double endProgress, const bool enableLogging) { // set as a child alg->setChild(true); @@ -917,8 +851,7 @@ void Algorithm::setupAsChildAlgorithm(const Algorithm_sptr &alg, try { alg->initialize(); } catch (std::runtime_error &) { - throw std::runtime_error("Unable to initialise Child Algorithm '" + - alg->name() + "'"); + throw std::runtime_error("Unable to initialise Child Algorithm '" + alg->name() + "'"); } // If output workspaces are nameless, give them a temporary name to satisfy @@ -933,8 +866,7 @@ void Algorithm::setupAsChildAlgorithm(const Algorithm_sptr &alg, } } - if (startProgress >= 0.0 && endProgress > startProgress && - endProgress <= 1.0) { + if (startProgress >= 0.0 && endProgress > startProgress && endProgress <= 1.0) { alg->addObserver(this->progressObserver()); m_startChildProgress = startProgress; m_endChildProgress = endProgress; @@ -946,9 +878,7 @@ void Algorithm::setupAsChildAlgorithm(const Algorithm_sptr &alg, // It must be protected by a critical block so that Child Algorithms can run // in parallel safely. std::weak_ptr weakPtr(alg); - PARALLEL_CRITICAL(Algorithm_StoreWeakPtr) { - m_ChildAlgorithms.emplace_back(weakPtr); - } + PARALLEL_CRITICAL(Algorithm_StoreWeakPtr) { m_ChildAlgorithms.emplace_back(weakPtr); } } //============================================================================================= @@ -961,11 +891,7 @@ void Algorithm::setupAsChildAlgorithm(const Algorithm_sptr &alg, * a json formatted string. * @returns This object serialized as a string */ -std::string Algorithm::toString() const { - ::Json::FastWriter writer; - - return writer.write(toJson()); -} +std::string Algorithm::toString() const { return Mantid::JsonHelpers::jsonToString(toJson()); } /** * Serialize this object to a json object) @@ -976,7 +902,7 @@ std::string Algorithm::toString() const { root["name"] = name(); root["version"] = this->version(); - root["properties"] = Kernel::PropertyManagerOwner::asJson(false); + root["properties"] = m_properties.asJson(false); return root; } @@ -992,7 +918,6 @@ std::string Algorithm::toString() const { IAlgorithm_sptr Algorithm::fromHistory(const AlgorithmHistory &history) { ::Json::Value root; ::Json::Value jsonMap; - ::Json::FastWriter writer; auto props = history.getProperties(); const size_t numProps(props.size()); @@ -1007,15 +932,14 @@ IAlgorithm_sptr Algorithm::fromHistory(const AlgorithmHistory &history) { root["version"] = history.version(); root["properties"] = jsonMap; - const std::string output = writer.write(root); + const std::string output = Mantid::JsonHelpers::jsonToString(root); IAlgorithm_sptr alg; try { alg = Algorithm::fromString(output); } catch (std::invalid_argument &) { - throw std::runtime_error( - "Could not create algorithm from history. " - "Is this a child algorithm whose workspaces are not in the ADS?"); + throw std::runtime_error("Could not create algorithm from history. " + "Is this a child algorithm whose workspaces are not in the ADS?"); } return alg; } @@ -1031,8 +955,7 @@ IAlgorithm_sptr Algorithm::fromHistory(const AlgorithmHistory &history) { */ IAlgorithm_sptr Algorithm::fromString(const std::string &input) { ::Json::Value root; - ::Json::Reader reader; - if (reader.parse(input, root)) { + if (Mantid::JsonHelpers::parse(input, &root)) { return fromJson(root); } else { throw std::runtime_error("Cannot create algorithm, invalid string format."); @@ -1080,8 +1003,7 @@ void Algorithm::linkHistoryWithLastChild() { // iterate over the algorithms output workspaces const auto &algProperties = getProperties(); for (const auto &prop : algProperties) { - if (prop->direction() != Kernel::Direction::Output && - prop->direction() != Kernel::Direction::InOut) + if (prop->direction() != Kernel::Direction::Output && prop->direction() != Kernel::Direction::InOut) continue; const auto *wsProp = dynamic_cast(prop); if (!wsProp) @@ -1119,8 +1041,7 @@ void Algorithm::linkHistoryWithLastChild() { * is a child. * @param parentHist :: the parent algorithm history object the history in. */ -void Algorithm::trackAlgorithmHistory( - std::shared_ptr parentHist) { +void Algorithm::trackAlgorithmHistory(std::shared_ptr parentHist) { enableHistoryRecordingForChild(true); m_parentHistory = std::move(parentHist); } @@ -1128,9 +1049,7 @@ void Algorithm::trackAlgorithmHistory( /** Check if we are tracking history for this algorithm * @return if we are tracking the history of this algorithm */ -bool Algorithm::trackingHistory() { - return (!isChild() || m_recordHistoryForChild); -} +bool Algorithm::trackingHistory() { return (!isChild() || m_recordHistoryForChild); } /** Populate lists of the workspace properties for a given direction * (InOut workspaces are included in both input/output) @@ -1140,21 +1059,19 @@ bool Algorithm::trackingHistory() { * if the check on the workspace property value is empty. Most useful for * finding group workspaces that are never stored on the property */ -void Algorithm::findWorkspaces(WorkspaceVector &workspaces, - unsigned int direction, bool checkADS) const { - auto workspaceFromWSProperty = - [](const IWorkspaceProperty &prop, const AnalysisDataServiceImpl &ads, - const std::string &strValue, bool checkADS) { - auto workspace = prop.getWorkspace(); - if (workspace) - return workspace; - - // Empty string indicates optional workspace - if (checkADS && !strValue.empty()) { - return ads.retrieve(strValue); - } - return Workspace_sptr(); - }; +void Algorithm::findWorkspaces(WorkspaceVector &workspaces, unsigned int direction, bool checkADS) const { + auto workspaceFromWSProperty = [](const IWorkspaceProperty &prop, const AnalysisDataServiceImpl &ads, + const std::string &strValue, bool checkADS) { + auto workspace = prop.getWorkspace(); + if (workspace) + return workspace; + + // Empty string indicates optional workspace + if (checkADS && !strValue.empty()) { + return ads.retrieve(strValue); + } + return Workspace_sptr(); + }; auto appendWS = [&workspaces](const Workspace_sptr &workspace) { if (!workspace) return false; @@ -1292,13 +1209,11 @@ bool Algorithm::checkGroups() { // Check for matching group size if (m_groupSize > 1) if (thisGroup.size() != m_groupSize) - throw std::invalid_argument( - "Input WorkspaceGroups are not of the same size."); + throw std::invalid_argument("Input WorkspaceGroups are not of the same size."); // Are ALL the names similar? if (wsGroup) - m_groupsHaveSimilarNames = - m_groupsHaveSimilarNames && wsGroup->areNamesSimilar(); + m_groupsHaveSimilarNames = m_groupsHaveSimilarNames && wsGroup->areNamesSimilar(); // Save the size for the next group m_groupSize = thisGroup.size(); @@ -1318,8 +1233,7 @@ bool Algorithm::checkGroups() { * * @return whether processGroups succeeds. */ -bool Algorithm::doCallProcessGroups( - Mantid::Types::Core::DateAndTime &startTime) { +bool Algorithm::doCallProcessGroups(Mantid::Types::Core::DateAndTime &startTime) { // In the base implementation of processGroups, this normally calls // this->execute() again on each member of the group. Other algorithms may // choose to override that behavior (examples: CompareWorkspaces, @@ -1339,14 +1253,12 @@ bool Algorithm::doCallProcessGroups( // AlgorithmMonitor). setResultState(ResultState::Failed); m_runningAsync = false; - notificationCenter().postNotification( - new ErrorNotification(this, ex.what())); + notificationCenter().postNotification(new ErrorNotification(this, ex.what())); throw; } catch (...) { setResultState(ResultState::Failed); m_runningAsync = false; - notificationCenter().postNotification(new ErrorNotification( - this, "UNKNOWN Exception caught from processGroups")); + notificationCenter().postNotification(new ErrorNotification(this, "UNKNOWN Exception caught from processGroups")); throw; } @@ -1357,8 +1269,7 @@ bool Algorithm::doCallProcessGroups( // Get how long this algorithm took to run const float duration = timer.elapsed(); - m_history = std::make_shared(this, startTime, duration, - ++g_execCount); + m_history = std::make_shared(this, startTime, duration, ++g_execCount); if (trackingHistory() && m_history) { // find any further outputs created by the execution WorkspaceVector outputWorkspaces; @@ -1378,8 +1289,7 @@ bool Algorithm::doCallProcessGroups( setResultState(ResultState::Failed); } - notificationCenter().postNotification( - new FinishedNotification(this, isExecuted())); + notificationCenter().postNotification(new FinishedNotification(this, isExecuted())); return completed; } @@ -1391,8 +1301,7 @@ bool Algorithm::doCallProcessGroups( * @param outputWorkspaces :: A reference to a vector for the output * workspaces. Used in the non-child case. */ -void Algorithm::fillHistory( - const std::vector &outputWorkspaces) { +void Algorithm::fillHistory(const std::vector &outputWorkspaces) { // this is not a child algorithm. Add the history algorithm to the // WorkspaceHistory object. if (!isChild()) { @@ -1463,10 +1372,9 @@ bool Algorithm::processGroups() { // Go through each entry in the input group(s) for (size_t entry = 0; entry < m_groupSize; entry++) { // use create Child Algorithm that look like this one - Algorithm_sptr alg_sptr = this->createChildAlgorithm( - this->name(), progress_proportion * static_cast(entry), - progress_proportion * (1 + static_cast(entry)), - this->isLogging(), this->version()); + Algorithm_sptr alg_sptr = this->createChildAlgorithm(this->name(), progress_proportion * static_cast(entry), + progress_proportion * (1 + static_cast(entry)), + this->isLogging(), this->version()); // Make a child algorithm and turn off history recording for it, but always // store result in the ADS alg_sptr->setChild(true); @@ -1474,7 +1382,7 @@ bool Algorithm::processGroups() { alg_sptr->enableHistoryRecordingForChild(false); alg_sptr->setRethrows(true); - IAlgorithm *alg = alg_sptr.get(); + Algorithm *alg = alg_sptr.get(); // Set all non-workspace properties this->copyNonWorkspaceProperties(alg, int(entry) + 1); @@ -1502,9 +1410,8 @@ bool Algorithm::processGroups() { // with all N inputs of the second group. In this case processGroup // needs to be overridden, which is currently not possible in // python. - throw std::runtime_error( - "Unable to process over groups; consider passing workspaces " - "one-by-one or override processGroup method of the algorithm."); + throw std::runtime_error("Unable to process over groups; consider passing workspaces " + "one-by-one or override processGroup method of the algorithm."); } } // Append the names together @@ -1529,32 +1436,27 @@ bool Algorithm::processGroups() { std::vector outputWSNames(m_pureOutputWorkspaceProps.size()); // ---------- Set all the output workspaces ---------------------------- for (size_t owp = 0; owp < m_pureOutputWorkspaceProps.size(); owp++) { - if (auto *prop = - dynamic_cast(m_pureOutputWorkspaceProps[owp])) { + if (auto *prop = dynamic_cast(m_pureOutputWorkspaceProps[owp])) { // Default name = "in1_in2_out" const std::string inName = prop->value(); if (inName.empty()) continue; std::string outName; if (m_groupsHaveSimilarNames) { - outName.append(inName).append("_").append( - Strings::toString(entry + 1)); + outName.append(inName).append("_").append(Strings::toString(entry + 1)); } else { outName.append(outputBaseName).append("_").append(inName); } - auto inputProp = std::find_if(m_inputWorkspaceProps.begin(), - m_inputWorkspaceProps.end(), - WorkspacePropertyValueIs(inName)); + auto inputProp = + std::find_if(m_inputWorkspaceProps.begin(), m_inputWorkspaceProps.end(), WorkspacePropertyValueIs(inName)); // Overwrite workspaces in any input property if they have the same // name as an output (i.e. copy name button in algorithm dialog used) // (only need to do this for a single input, multiple will be handled // by ADS) if (inputProp != m_inputWorkspaceProps.end()) { - const auto &inputGroup = - m_unrolledInputWorkspaces[inputProp - - m_inputWorkspaceProps.begin()]; + const auto &inputGroup = m_unrolledInputWorkspaces[inputProp - m_inputWorkspaceProps.begin()]; if (!inputGroup.empty()) outName = inputGroup[entry]->getName(); } @@ -1575,8 +1477,7 @@ bool Algorithm::processGroups() { alg->execute(); } catch (std::exception &e) { std::ostringstream msg; - msg << "Execution of " << this->name() << " for group entry " - << (entry + 1) << " failed: "; + msg << "Execution of " << this->name() << " for group entry " << (entry + 1) << " failed: "; msg << e.what(); // Add original message throw std::runtime_error(msg.str()); } @@ -1632,9 +1533,7 @@ void Algorithm::copyNonWorkspaceProperties(IAlgorithm *alg, int periodNum) { * @param propertyValue :: value of the property * @param periodNum :: period number */ -void Algorithm::setOtherProperties(IAlgorithm *alg, - const std::string &propertyName, - const std::string &propertyValue, +void Algorithm::setOtherProperties(IAlgorithm *alg, const std::string &propertyName, const std::string &propertyValue, int periodNum) { (void)periodNum; // Avoid compiler warning if (alg) @@ -1666,9 +1565,7 @@ struct AsyncFlagHolder { /** Constructor * @param A :: reference to the running flag */ - explicit AsyncFlagHolder(bool &running_flag) : m_running_flag(running_flag) { - m_running_flag = true; - } + explicit AsyncFlagHolder(bool &running_flag) : m_running_flag(running_flag) { m_running_flag = true; } /// Destructor ~AsyncFlagHolder() { m_running_flag = false; } @@ -1686,8 +1583,7 @@ private: */ Poco::ActiveResult Algorithm::executeAsync() { m_executeAsync = - std::make_unique>( - this, &Algorithm::executeAsyncImpl); + std::make_unique>(this, &Algorithm::executeAsyncImpl); return (*m_executeAsync)(Poco::Void()); } @@ -1713,10 +1609,8 @@ Poco::NotificationCenter &Algorithm::notificationCenter() const { /** Handles and rescales child algorithm progress notifications. * @param pNf :: The progress notification from the child algorithm. */ -void Algorithm::handleChildProgressNotification( - const Poco::AutoPtr &pNf) { - double p = m_startChildProgress + - (m_endChildProgress - m_startChildProgress) * pNf->progress; +void Algorithm::handleChildProgressNotification(const Poco::AutoPtr &pNf) { + double p = m_startChildProgress + (m_endChildProgress - m_startChildProgress) * pNf->progress; progress(p, pNf->message); } @@ -1726,10 +1620,8 @@ void Algorithm::handleChildProgressNotification( */ const Poco::AbstractObserver &Algorithm::progressObserver() const { if (!m_progressObserver) - m_progressObserver = - std::make_unique>( - *const_cast(this), - &Algorithm::handleChildProgressNotification); + m_progressObserver = std::make_unique>( + *const_cast(this), &Algorithm::handleChildProgressNotification); return *m_progressObserver; } @@ -1798,8 +1690,7 @@ Report that the algorithm has completed. @param duration : Algorithm duration @param groupProcessing : We have been processing via processGroups if true. */ -void Algorithm::reportCompleted(const double &duration, - const bool groupProcessing) { +void Algorithm::reportCompleted(const double &duration, const bool groupProcessing) { std::string optionalMessage; if (groupProcessing) { optionalMessage = ". Processed as a workspace group"; @@ -1816,15 +1707,13 @@ void Algorithm::reportCompleted(const double &duration, msg << minutes << " minutes "; seconds = seconds - static_cast(minutes) * 60.; } - msg << std::fixed << std::setprecision(2) << seconds << " seconds" - << optionalMessage; + msg << std::fixed << std::setprecision(2) << seconds << " seconds" << optionalMessage; getLogger().notice(msg.str()); } } else { - getLogger().debug() << name() << " finished with isChild = " << isChild() - << '\n'; + getLogger().debug() << name() << " finished with isChild = " << isChild() << '\n'; } setExecutionState(ExecutionState::Finished); } @@ -1835,28 +1724,22 @@ void Algorithm::registerFeatureUsage() const { if (UsageService::Instance().isEnabled()) { std::ostringstream oss; oss << this->name() << ".v" << this->version(); - UsageService::Instance().registerFeatureUsage(FeatureType::Algorithm, - oss.str(), isChild()); + UsageService::Instance().registerFeatureUsage(FeatureType::Algorithm, oss.str(), isChild()); } } /** Enable or disable Logging of start and end messages @param enabled : true to enable logging, false to disable */ -void Algorithm::setAlgStartupLogging(const bool enabled) { - m_isAlgStartupLoggingEnabled = enabled; -} +void Algorithm::setAlgStartupLogging(const bool enabled) { m_isAlgStartupLoggingEnabled = enabled; } /** return the state of logging of start and end messages @returns : true to logging is enabled */ -bool Algorithm::getAlgStartupLogging() const { - return m_isAlgStartupLoggingEnabled; -} +bool Algorithm::getAlgStartupLogging() const { return m_isAlgStartupLoggingEnabled; } bool Algorithm::isCompoundProperty(const std::string &name) const { - return std::find(m_reservedList.cbegin(), m_reservedList.cend(), name) != - m_reservedList.cend(); + return std::find(m_reservedList.cbegin(), m_reservedList.cend(), name) != m_reservedList.cend(); } /// Runs the algorithm with the specified execution mode. @@ -1870,8 +1753,7 @@ void Algorithm::exec(Parallel::ExecutionMode executionMode) { case Parallel::ExecutionMode::MasterOnly: return execMasterOnly(); default: - throw(std::runtime_error("Algorithm " + name() + - " does not support execution mode " + + throw(std::runtime_error("Algorithm " + name() + " does not support execution mode " + Parallel::toString(executionMode))); } } @@ -1917,22 +1799,19 @@ Parallel::ExecutionMode Algorithm::getExecutionMode() const { throw(std::runtime_error(error)); } if (executionMode == Parallel::ExecutionMode::Serial) { - std::string error(Parallel::toString(executionMode) + - " is not a valid *parallel* execution mode."); + std::string error(Parallel::toString(executionMode) + " is not a valid *parallel* execution mode."); getLogger().error() << error << "\n"; throw(std::runtime_error(error)); } - getLogger().information() - << "MPI Rank " << communicator().rank() << " running with " - << Parallel::toString(executionMode) << '\n'; + getLogger().information() << "MPI Rank " << communicator().rank() << " running with " + << Parallel::toString(executionMode) << '\n'; return executionMode; } /** Get map of storage modes of all input workspaces. * * The key to the name is the property name of the respective workspace. */ -std::map -Algorithm::getInputWorkspaceStorageModes() const { +std::map Algorithm::getInputWorkspaceStorageModes() const { std::map map; for (const auto &wsProp : m_inputWorkspaceProps) { // This is the reverse cast of what is done in cacheWorkspaceProperties(), @@ -1944,11 +1823,9 @@ Algorithm::getInputWorkspaceStorageModes() const { else if (!wsProp->isOptional()) map.emplace(prop.name(), Parallel::StorageMode::MasterOnly); } - getLogger().information() - << "Input workspaces for determining execution mode:\n"; + getLogger().information() << "Input workspaces for determining execution mode:\n"; for (const auto &item : map) - getLogger().information() << " " << item.first << " --- " - << Parallel::toString(item.second) << '\n'; + getLogger().information() << " " << item.first << " --- " << Parallel::toString(item.second) << '\n'; return map; } @@ -1958,8 +1835,8 @@ Algorithm::getInputWorkspaceStorageModes() const { * inheriting from Algorithm can re-implement this if they support execution * with multiple MPI ranks. May not return ExecutionMode::Serial, because that * is not a "parallel" execution mode. */ -Parallel::ExecutionMode Algorithm::getParallelExecutionMode( - const std::map &storageModes) const { +Parallel::ExecutionMode +Algorithm::getParallelExecutionMode(const std::map &storageModes) const { UNUSED_ARG(storageModes) // By default no parallel execution is possible. return Parallel::ExecutionMode::Invalid; @@ -1979,9 +1856,7 @@ void Algorithm::setupSkipValidationMasterOnly() { } /// Returns a const reference to the (MPI) communicator of the algorithm. -const Parallel::Communicator &Algorithm::communicator() const { - return *m_communicator; -} +const Parallel::Communicator &Algorithm::communicator() const { return *m_communicator; } /// Sets the (MPI) communicator of the algorithm. void Algorithm::setCommunicator(const Parallel::Communicator &communicator) { @@ -1992,49 +1867,252 @@ void Algorithm::setCommunicator(const Parallel::Communicator &communicator) { // Algorithm's inner classes //--------------------------------------------------------------------------- -Algorithm::AlgorithmNotification::AlgorithmNotification( - const Algorithm *const alg) +Algorithm::AlgorithmNotification::AlgorithmNotification(const Algorithm *const alg) : Poco::Notification(), m_algorithm(alg) {} -const IAlgorithm *Algorithm::AlgorithmNotification::algorithm() const { - return m_algorithm; -} +const IAlgorithm *Algorithm::AlgorithmNotification::algorithm() const { return m_algorithm; } -Algorithm::StartedNotification::StartedNotification(const Algorithm *const alg) - : AlgorithmNotification(alg) {} -std::string Algorithm::StartedNotification::name() const { - return "StartedNotification"; -} ///< class name +Algorithm::StartedNotification::StartedNotification(const Algorithm *const alg) : AlgorithmNotification(alg) {} +std::string Algorithm::StartedNotification::name() const { return "StartedNotification"; } ///< class name -Algorithm::FinishedNotification::FinishedNotification( - const Algorithm *const alg, bool res) +Algorithm::FinishedNotification::FinishedNotification(const Algorithm *const alg, bool res) : AlgorithmNotification(alg), success(res) {} -std::string Algorithm::FinishedNotification::name() const { - return "FinishedNotification"; +std::string Algorithm::FinishedNotification::name() const { return "FinishedNotification"; } + +Algorithm::ProgressNotification::ProgressNotification(const Algorithm *const alg, double p, const std::string &msg, + double estimatedTime, int progressPrecision) + : AlgorithmNotification(alg), progress(p), message(msg), estimatedTime(estimatedTime), + progressPrecision(progressPrecision) {} + +std::string Algorithm::ProgressNotification::name() const { return "ProgressNotification"; } + +Algorithm::ErrorNotification::ErrorNotification(const Algorithm *const alg, const std::string &str) + : AlgorithmNotification(alg), what(str) {} + +std::string Algorithm::ErrorNotification::name() const { return "ErrorNotification"; } + +const char *Algorithm::CancelException::what() const noexcept { return "Algorithm terminated"; } + +/** Add a property to the list of managed properties + * @param p :: The property object to add + * @param doc :: A description of the property that may be displayed to users + * @throw Exception::ExistsError if a property with the given name already + * exists + */ +void Algorithm::declareProperty(std::unique_ptr p, const std::string &doc) { + m_properties.declareProperty(std::move(p), doc); } -Algorithm::ProgressNotification::ProgressNotification( - const Algorithm *const alg, double p, const std::string &msg, - double estimatedTime, int progressPrecision) - : AlgorithmNotification(alg), progress(p), message(msg), - estimatedTime(estimatedTime), progressPrecision(progressPrecision) {} +/** Add or replace property in the list of managed properties + * @param p :: The property object to add + * @param doc :: A description of the property that may be displayed to users + */ +void Algorithm::declareOrReplaceProperty(std::unique_ptr p, const std::string &doc) { + m_properties.declareOrReplaceProperty(std::move(p), doc); +} + +/** Reset property values back to initial values (blank or default values) + */ +void Algorithm::resetProperties() { m_properties.resetProperties(); } -std::string Algorithm::ProgressNotification::name() const { - return "ProgressNotification"; +/** Set the ordered list of properties by one string of values, separated by + *semicolons. + * + * The string should be a json formatted collection of name value pairs + * + * @param propertiesJson :: The string of property values + * @param ignoreProperties :: A set of names of any properties NOT to set + * from the propertiesArray + * @param createMissing :: If the property does not exist then create it + * @throw invalid_argument if error in parameters + */ +void Algorithm::setProperties(const std::string &propertiesJson, + const std::unordered_set &ignoreProperties, bool createMissing) { + m_properties.setProperties(propertiesJson, ignoreProperties, createMissing); } -Algorithm::ErrorNotification::ErrorNotification(const Algorithm *const alg, - const std::string &str) - : AlgorithmNotification(alg), what(str) {} +/** Sets all the declared properties from a json object + @param jsonValue :: A json name value pair collection + @param ignoreProperties :: A set of names of any properties NOT to set + from the propertiesArray + @param createMissing :: If the property does not exist then create it +*/ +void Algorithm::setProperties(const ::Json::Value &jsonValue, const std::unordered_set &ignoreProperties, + bool createMissing) { + m_properties.setProperties(jsonValue, ignoreProperties, createMissing); +} -std::string Algorithm::ErrorNotification::name() const { - return "ErrorNotification"; +/** Sets all the declared properties from a string. + @param propertiesString :: A list of name = value pairs separated by a + semicolon + @param ignoreProperties :: A set of names of any properties NOT to set + from the propertiesArray +*/ +void Algorithm::setPropertiesWithString(const std::string &propertiesString, + const std::unordered_set &ignoreProperties) { + m_properties.setPropertiesWithString(propertiesString, ignoreProperties); +} + +/** Set the value of a property by string + * N.B. bool properties must be set using 1/0 rather than true/false + * @param name :: The name of the property (case insensitive) + * @param value :: The value to assign to the property + * @throw Exception::NotFoundError if the named property is unknown + * @throw std::invalid_argument If the value is not valid for the property + * given + */ +void Algorithm::setPropertyValue(const std::string &name, const std::string &value) { + m_properties.setPropertyValue(name, value); + this->afterPropertySet(name); } -const char *Algorithm::CancelException::what() const noexcept { - return "Algorithm terminated"; +/** Set the value of a property by Json::Value object + * @param name :: The name of the property (case insensitive) + * @param value :: The value to assign to the property + * @throw Exception::NotFoundError if the named property is unknown + * @throw std::invalid_argument If the value is not valid for the property + * given + */ +void Algorithm::setPropertyValueFromJson(const std::string &name, const Json::Value &value) { + m_properties.setPropertyValueFromJson(name, value); + this->afterPropertySet(name); } +/** Set the value of a property by an index + * N.B. bool properties must be set using 1/0 rather than true/false + * @param index :: The index of the property to assign + * @param value :: The value to assign to the property + * @throw std::runtime_error if the property index is too high + */ +void Algorithm::setPropertyOrdinal(const int &index, const std::string &value) { + m_properties.setPropertyOrdinal(index, value); + this->afterPropertySet(m_properties.getPointerToPropertyOrdinal(index)->name()); +} + +/** Checks whether the named property is already in the list of managed + * property. + * @param name :: The name of the property (case insensitive) + * @return True if the property is already stored + */ +bool Algorithm::existsProperty(const std::string &name) const { return m_properties.existsProperty(name); } + +/** Validates all the properties in the collection + * @return True if all properties have a valid value + */ +bool Algorithm::validateProperties() const { return m_properties.validateProperties(); } + +/** + * Count the number of properties under management + * @returns The number of properties being managed + */ +size_t Algorithm::propertyCount() const { return m_properties.propertyCount(); } + +/** Get the value of a property as a string + * @param name :: The name of the property (case insensitive) + * @return The value of the named property + * @throw Exception::NotFoundError if the named property is unknown + */ +std::string Algorithm::getPropertyValue(const std::string &name) const { return m_properties.getPropertyValue(name); } + +/** Get a property by name + * @param name :: The name of the property (case insensitive) + * @return A pointer to the named property + * @throw Exception::NotFoundError if the named property is unknown + */ +Property *Algorithm::getPointerToProperty(const std::string &name) const { + return m_properties.getPointerToProperty(name); +} + +/** Get a property by an index + * @param index :: The name of the property (case insensitive) + * @return A pointer to the named property + * @throw std::runtime_error if the property index is too high + */ +Property *Algorithm::getPointerToPropertyOrdinal(const int &index) const { + return m_properties.getPointerToPropertyOrdinal(index); +} + +/** Get the list of managed properties. + * The properties will be stored in the order that they were declared. + * @return A vector holding pointers to the list of properties + */ +const std::vector &Algorithm::getProperties() const { return m_properties.getProperties(); } + +/** Get the value of a property. Allows you to assign directly to a variable of + *the property's type + * (if a supported type). + * + * *** This method does NOT work for assigning to an existing std::string. + * In this case you have to use getPropertyValue() instead. + * Note that you can, though, construct a local string variable by writing, + * e.g. std::string s = getProperty("myProperty"). *** + * + * @param name :: The name of the property + * @return The value of the property. Will be cast to the desired type (if a + *supported type). + * @throw std::runtime_error If an attempt is made to assign a property to a + *different type + * @throw Exception::NotFoundError If the property requested does not exist + */ +IPropertyManager::TypedValue Algorithm::getProperty(const std::string &name) const { + return m_properties.getProperty(name); +} + +/** + * @param name + * @return True if the property is its default value. + */ +bool Algorithm::isDefault(const std::string &name) const { + return m_properties.getPointerToProperty(name)->isDefault(); +} + +/** + * Return the property manager serialized as a string. + * The format is propName=value,propName=value,propName=value + * @param withDefaultValues :: If true then the value of default parameters will + * be included + * @returns A stringized version of the manager + */ +std::string Algorithm::asString(bool withDefaultValues) const { return m_properties.asString(withDefaultValues); } +/** + * Return the property manager serialized as a json object. + * @param withDefaultValues :: If true then the value of default parameters will + * be included + * @returns A jsonValue of the manager + */ +::Json::Value Algorithm::asJson(bool withDefaultValues) const { return m_properties.asJson(withDefaultValues); } + +/** + * Removes the property from properties map. + * @param name :: Name of the property to be removed. + * @param delproperty :: if true, delete the named property + */ +void Algorithm::removeProperty(const std::string &name, const bool delproperty) { + m_properties.removeProperty(name, delproperty); +} + +/** + * Removes a property from the properties map by index and return a pointer to it + * @param index :: index of the property to be removed + * @returns :: pointer to the removed property if found, NULL otherwise + */ +std::unique_ptr Algorithm::takeProperty(const size_t index) { + return m_properties.takeProperty(index); +} + +/** + * Clears all properties under management + */ +void Algorithm::clear() { m_properties.clear(); } + +/** + * Override this method to perform a custom action right after a property was + * set. + * The argument is the property name. Default - do nothing. + * @param name :: A property name. + */ +void Algorithm::afterPropertySet(const std::string &name) { m_properties.afterPropertySet(name); } + } // namespace API //--------------------------------------------------------------------------- @@ -2048,16 +2126,12 @@ namespace Kernel { * @returns A pointer to an algorithm */ template <> -MANTID_API_DLL API::IAlgorithm_sptr -IPropertyManager::getValue( - const std::string &name) const { - auto *prop = dynamic_cast *>( - getPointerToProperty(name)); +MANTID_API_DLL API::IAlgorithm_sptr IPropertyManager::getValue(const std::string &name) const { + auto *prop = dynamic_cast *>(getPointerToProperty(name)); if (prop) { return *prop; } else { - std::string message = "Attempt to assign property " + name + - " to incorrect type. Expected shared_ptr"; + std::string message = "Attempt to assign property " + name + " to incorrect type. Expected shared_ptr"; throw std::runtime_error(message); } } @@ -2070,19 +2144,17 @@ IPropertyManager::getValue( */ template <> MANTID_API_DLL API::IAlgorithm_const_sptr -IPropertyManager::getValue( - const std::string &name) const { - auto *prop = dynamic_cast *>( - getPointerToProperty(name)); +IPropertyManager::getValue(const std::string &name) const { + auto *prop = dynamic_cast *>(getPointerToProperty(name)); if (prop) { return prop->operator()(); } else { std::string message = - "Attempt to assign property " + name + - " to incorrect type. Expected const shared_ptr"; + "Attempt to assign property " + name + " to incorrect type. Expected const shared_ptr"; throw std::runtime_error(message); } } + } // namespace Kernel } // namespace Mantid diff --git a/Framework/API/src/AlgorithmExecuteProfile.cpp b/Framework/API/src/AlgorithmExecuteProfile.cpp index fee16c7c466a4fea49e72f2ab6f45d8d887e0383..db7e87e23e8a9e8cdd9a587a0b511a39676a922f 100644 --- a/Framework/API/src/AlgorithmExecuteProfile.cpp +++ b/Framework/API/src/AlgorithmExecuteProfile.cpp @@ -8,8 +8,7 @@ #include "MantidAPI/Algorithm.h" namespace Mantid { -Instrumentation::AlgoTimeRegister - Instrumentation::AlgoTimeRegister::globalAlgoTimeRegister; +Instrumentation::AlgoTimeRegister Instrumentation::AlgoTimeRegister::globalAlgoTimeRegister; namespace API { //--------------------------------------------------------------------------------------------- diff --git a/Framework/API/src/AlgorithmFactory.cpp b/Framework/API/src/AlgorithmFactory.cpp index 087589d2495da02c23570478892cae904546311a..e334c4ec835df9c719d1563461ef345b42e67fb6 100644 --- a/Framework/API/src/AlgorithmFactory.cpp +++ b/Framework/API/src/AlgorithmFactory.cpp @@ -24,8 +24,7 @@ namespace { Kernel::Logger g_log("AlgorithmFactory"); } // namespace -AlgorithmFactoryImpl::AlgorithmFactoryImpl() - : Kernel::DynamicFactory(), m_vmap(), m_amap() { +AlgorithmFactoryImpl::AlgorithmFactoryImpl() : Kernel::DynamicFactory(), m_vmap(), m_amap() { // we need to make sure the library manager has been loaded before we // are constructed so that it is destroyed after us and thus does // not close any loaded DLLs with loaded algorithms in them @@ -40,9 +39,7 @@ AlgorithmFactoryImpl::~AlgorithmFactoryImpl() = default; * @param version :: the version of the algroithm to create * @returns a shared pointer to the created algorithm */ -std::shared_ptr -AlgorithmFactoryImpl::create(const std::string &name, - const int &version) const { +std::shared_ptr AlgorithmFactoryImpl::create(const std::string &name, const int &version) const { int local_version = version; // Version not supplied if (version == -1) { @@ -64,15 +61,12 @@ AlgorithmFactoryImpl::create(const std::string &name, return this->createAlgorithm(realName.get(), local_version); } catch (Kernel::Exception::NotFoundError &) { // Get highest registered version - const auto hVersion = - highestVersion(realName.get()); // Throws if not found + const auto hVersion = highestVersion(realName.get()); // Throws if not found // The version registered does not match version supplied - g_log.error() << "algorithm " << name << " version " << version - << " is not registered \n"; + g_log.error() << "algorithm " << name << " version " << version << " is not registered \n"; g_log.error() << "the latest registered version is " << hVersion << '\n'; - throw std::runtime_error("algorithm not registered " + - createName(name, local_version)); + throw std::runtime_error("algorithm not registered " + createName(name, local_version)); } } else { throw std::runtime_error("algorithm not registered " + name); @@ -85,8 +79,7 @@ AlgorithmFactoryImpl::create(const std::string &name, * @param algorithmName :: The name of the algorithm to unsubscribe * @param version :: The version number of the algorithm to unsubscribe */ -void AlgorithmFactoryImpl::unsubscribe(const std::string &algorithmName, - const int version) { +void AlgorithmFactoryImpl::unsubscribe(const std::string &algorithmName, const int version) { std::string key = this->createName(algorithmName, version); try { Kernel::DynamicFactory::unsubscribe(key); @@ -94,16 +87,14 @@ void AlgorithmFactoryImpl::unsubscribe(const std::string &algorithmName, auto it = m_vmap.find(algorithmName); if (it != m_vmap.end()) { int highest_version = it->second; - if (highest_version > 1 && - version == highest_version) // Decrement the highest version + if (highest_version > 1 && version == highest_version) // Decrement the highest version { it->second -= 1; } else m_vmap.erase(algorithmName); } } catch (Kernel::Exception::NotFoundError &) { - g_log.warning() << "Error unsubscribing algorithm " << algorithmName - << " version " << version + g_log.warning() << "Error unsubscribing algorithm " << algorithmName << " version " << version << ". Nothing registered with this name and version."; } } @@ -114,8 +105,7 @@ void AlgorithmFactoryImpl::unsubscribe(const std::string &algorithmName, * @param version :: The version number. -1 checks whether anything exists * @returns True if a matching registration is found */ -bool AlgorithmFactoryImpl::exists(const std::string &algorithmName, - const int version) { +bool AlgorithmFactoryImpl::exists(const std::string &algorithmName, const int version) { if (version == -1) // Find anything { return (m_vmap.find(algorithmName) != m_vmap.end()); @@ -130,8 +120,7 @@ bool AlgorithmFactoryImpl::exists(const std::string &algorithmName, * @param version :: the version of the algroithm * @returns a mangled name string */ -std::string AlgorithmFactoryImpl::createName(const std::string &name, - const int &version) const { +std::string AlgorithmFactoryImpl::createName(const std::string &name, const int &version) const { std::ostringstream oss; oss << name << "|" << version; return (oss.str()); @@ -141,20 +130,17 @@ std::string AlgorithmFactoryImpl::createName(const std::string &name, * @param mangledName :: the mangled name of the Algrorithm * @returns a pair of the name and version */ -std::pair -AlgorithmFactoryImpl::decodeName(const std::string &mangledName) const { +std::pair AlgorithmFactoryImpl::decodeName(const std::string &mangledName) const { std::string::size_type seperatorPosition = mangledName.find('|'); if (seperatorPosition == std::string::npos) { - throw std::invalid_argument( - "Cannot decode a Name string without a \"|\" (bar) character "); + throw std::invalid_argument("Cannot decode a Name string without a \"|\" (bar) character "); } std::string name = mangledName.substr(0, seperatorPosition); int version; std::istringstream ss(mangledName.substr(seperatorPosition + 1)); ss >> version; - g_log.debug() << "mangled string:" << mangledName << " name:" << name - << " version:" << version << '\n'; + g_log.debug() << "mangled string:" << mangledName << " name:" << name << " version:" << version << '\n'; return std::pair(name, version); } @@ -179,8 +165,7 @@ const std::vector AlgorithmFactoryImpl::getKeys() const { * faster, the default is false * @returns The strings used to identify individual algorithms */ -const std::vector -AlgorithmFactoryImpl::getKeys(bool includeHidden) const { +const std::vector AlgorithmFactoryImpl::getKeys(bool includeHidden) const { // Start with those subscribed with the factory and add the cleanly // constructed algorithm keys std::vector names = Kernel::DynamicFactory::getKeys(); @@ -195,8 +180,7 @@ AlgorithmFactoryImpl::getKeys(bool includeHidden) const { // strip out any algorithms names where all of the categories are hidden std::vector validNames; std::vector::const_iterator itr_end = names.end(); - for (std::vector::const_iterator itr = names.begin(); - itr != itr_end; ++itr) { + for (std::vector::const_iterator itr = names.begin(); itr != itr_end; ++itr) { std::string name = *itr; // check the categories std::pair namePair = decodeName(name); @@ -205,11 +189,9 @@ AlgorithmFactoryImpl::getKeys(bool includeHidden) const { bool toBeRemoved = true; // for each category - std::vector::const_iterator itCategoriesEnd = - categories.end(); - for (std::vector::const_iterator itCategories = - categories.begin(); - itCategories != itCategoriesEnd; ++itCategories) { + std::vector::const_iterator itCategoriesEnd = categories.end(); + for (std::vector::const_iterator itCategories = categories.begin(); itCategories != itCategoriesEnd; + ++itCategories) { // if the entry is not in the set of hidden categories if (hiddenCategories.find(*itCategories) == hiddenCategories.end()) { toBeRemoved = false; @@ -230,9 +212,7 @@ AlgorithmFactoryImpl::getKeys(bool includeHidden) const { * @param alias The name of the algorithm to look up in the alias map * @return Real name of algroithm if found */ -boost::optional -AlgorithmFactoryImpl::getRealNameFromAlias(const std::string &alias) const - noexcept { +boost::optional AlgorithmFactoryImpl::getRealNameFromAlias(const std::string &alias) const noexcept { auto a_it = m_amap.find(alias); if (a_it == m_amap.end()) return boost::none; @@ -245,8 +225,7 @@ AlgorithmFactoryImpl::getRealNameFromAlias(const std::string &alias) const * @return An integer corresponding to the highest version registered * @throw std::invalid_argument if the algorithm cannot be found */ -int AlgorithmFactoryImpl::highestVersion( - const std::string &algorithmName) const { +int AlgorithmFactoryImpl::highestVersion(const std::string &algorithmName) const { auto viter = m_vmap.find(algorithmName); if (viter != m_vmap.end()) return viter->second; @@ -260,9 +239,7 @@ int AlgorithmFactoryImpl::highestVersion( if (viter != m_vmap.end()) return viter->second; else { - throw std::runtime_error( - "AlgorithmFactory::highestVersion() - Unknown algorithm '" + - algorithmName + "'"); + throw std::runtime_error("AlgorithmFactory::highestVersion() - Unknown algorithm '" + algorithmName + "'"); } } } @@ -274,8 +251,7 @@ int AlgorithmFactoryImpl::highestVersion( * @returns The map of the categories, together with a true false value * difining if they are hidden */ -const std::map -AlgorithmFactoryImpl::getCategoriesWithState() const { +const std::map AlgorithmFactoryImpl::getCategoriesWithState() const { std::map resultCategories; // hidden categories - empty initially @@ -288,8 +264,7 @@ AlgorithmFactoryImpl::getCategoriesWithState() const { std::vector::const_iterator itr_end = names.end(); // for each algorithm - for (std::vector::const_iterator itr = names.begin(); - itr != itr_end; ++itr) { + for (std::vector::const_iterator itr = names.begin(); itr != itr_end; ++itr) { std::string name = *itr; // decode the name and create an instance std::pair namePair = decodeName(name); @@ -299,9 +274,8 @@ AlgorithmFactoryImpl::getCategoriesWithState() const { // for each category of the algorithm std::vector::const_iterator itCategoriesEnd = categories.end(); - for (std::vector::const_iterator itCategories = - categories.begin(); - itCategories != itCategoriesEnd; ++itCategories) { + for (std::vector::const_iterator itCategories = categories.begin(); itCategories != itCategoriesEnd; + ++itCategories) { bool isHidden = true; // check if the category is hidden if (hiddenCategories.find(*itCategories) == hiddenCategories.end()) { @@ -321,8 +295,7 @@ AlgorithmFactoryImpl::getCategoriesWithState() const { * faster, the default is false * @returns The category strings */ -const std::unordered_set -AlgorithmFactoryImpl::getCategories(bool includeHidden) const { +const std::unordered_set AlgorithmFactoryImpl::getCategories(bool includeHidden) const { std::unordered_set validCategories; // get all of the information we need @@ -350,9 +323,7 @@ AlgorithmFactoryImpl::getCategories(bool includeHidden) const { * empty to the vector of descriptors, the default is true * @returns A vector of descriptor objects */ -std::vector -AlgorithmFactoryImpl::getDescriptors(bool includeHidden, - bool includeAliases) const { +std::vector AlgorithmFactoryImpl::getDescriptors(bool includeHidden, bool includeAliases) const { // algorithm names auto sv = getKeys(true); @@ -386,8 +357,7 @@ AlgorithmFactoryImpl::getDescriptors(bool includeHidden, // For each category auto itCategoriesEnd = categories.end(); - for (auto itCategories = categories.begin(); - itCategories != itCategoriesEnd; ++itCategories) { + for (auto itCategories = categories.begin(); itCategories != itCategoriesEnd; ++itCategories) { desc.category = *itCategories; // Let's check if this category or any of its parents are hidden. @@ -421,8 +391,7 @@ AlgorithmFactoryImpl::getDescriptors(bool includeHidden, aliasDesc.category = desc.category; aliasDesc.version = desc.version; res.emplace_back(aliasDesc);*/ - res.emplace_back( - AlgorithmDescriptor{desc.alias, desc.version, desc.category, ""}); + res.emplace_back(AlgorithmDescriptor{desc.alias, desc.version, desc.category, ""}); } } } @@ -430,24 +399,19 @@ AlgorithmFactoryImpl::getDescriptors(bool includeHidden, return res; } -void AlgorithmFactoryImpl::fillHiddenCategories( - std::unordered_set *categorySet) const { - std::string categoryString = Kernel::ConfigService::Instance().getString( - "algorithms.categories.hidden"); - Mantid::Kernel::StringTokenizer tokenizer( - categoryString, ";", - Mantid::Kernel::StringTokenizer::TOK_TRIM | - Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY); - std::copy(tokenizer.begin(), tokenizer.end(), - std::inserter(*categorySet, categorySet->end())); +void AlgorithmFactoryImpl::fillHiddenCategories(std::unordered_set *categorySet) const { + std::string categoryString = Kernel::ConfigService::Instance().getString("algorithms.categories.hidden"); + Mantid::Kernel::StringTokenizer tokenizer(categoryString, ";", + Mantid::Kernel::StringTokenizer::TOK_TRIM | + Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY); + std::copy(tokenizer.begin(), tokenizer.end(), std::inserter(*categorySet, categorySet->end())); } /** Extract the name of an algorithm * @param alg :: the Algrorithm to use * @returns the name of the algroithm */ -const std::string AlgorithmFactoryImpl::extractAlgName( - const std::shared_ptr &alg) const { +const std::string AlgorithmFactoryImpl::extractAlgName(const std::shared_ptr &alg) const { return alg->name(); } @@ -455,17 +419,13 @@ const std::string AlgorithmFactoryImpl::extractAlgName( * @param alg :: the Algrorithm to use * @returns the version of the algroithm */ -int AlgorithmFactoryImpl::extractAlgVersion( - const std::shared_ptr &alg) const { - return alg->version(); -} +int AlgorithmFactoryImpl::extractAlgVersion(const std::shared_ptr &alg) const { return alg->version(); } /** Extract the alias of an algorithm * @param alg :: the Algorithm to use * @returns the alias of the algorithm */ -const std::string AlgorithmFactoryImpl::extractAlgAlias( - const std::shared_ptr &alg) const { +const std::string AlgorithmFactoryImpl::extractAlgAlias(const std::shared_ptr &alg) const { return alg->alias(); } @@ -477,9 +437,7 @@ const std::string AlgorithmFactoryImpl::extractAlgAlias( * @param version :: Algorithm version * @returns A shared pointer to the algorithm object */ -std::shared_ptr -AlgorithmFactoryImpl::createAlgorithm(const std::string &name, - const int version) const { +std::shared_ptr AlgorithmFactoryImpl::createAlgorithm(const std::string &name, const int version) const { return Kernel::DynamicFactory::create(createName(name, version)); } diff --git a/Framework/API/src/AlgorithmFactoryObserver.cpp b/Framework/API/src/AlgorithmFactoryObserver.cpp index a2055ed52bab6a0d204dcdceb666da21a05ef558..bc3f75b9f540aefe667e8b05b2f16d1ec4a2727e 100644 --- a/Framework/API/src/AlgorithmFactoryObserver.cpp +++ b/Framework/API/src/AlgorithmFactoryObserver.cpp @@ -7,14 +7,11 @@ #include "MantidAPI/AlgorithmFactoryObserver.h" namespace { -template -void modifyObserver(const bool turnOn, bool &isObserving, Observer &observer) { +template void modifyObserver(const bool turnOn, bool &isObserving, Observer &observer) { if (turnOn && !isObserving) { - Mantid::API::AlgorithmFactory::Instance().notificationCenter.addObserver( - observer); + Mantid::API::AlgorithmFactory::Instance().notificationCenter.addObserver(observer); } else if (!turnOn && isObserving) { - Mantid::API::AlgorithmFactory::Instance().notificationCenter.removeObserver( - observer); + Mantid::API::AlgorithmFactory::Instance().notificationCenter.removeObserver(observer); } isObserving = turnOn; } @@ -61,8 +58,7 @@ void AlgorithmFactoryObserver::updateHandle() {} // ------------------------------------------------------------ // Private Methods // ------------------------------------------------------------ -void AlgorithmFactoryObserver::_updateHandle( - AlgorithmFactoryUpdateNotification_ptr pNf) { +void AlgorithmFactoryObserver::_updateHandle(AlgorithmFactoryUpdateNotification_ptr pNf) { UNUSED_ARG(pNf) this->updateHandle(); } diff --git a/Framework/API/src/AlgorithmHasProperty.cpp b/Framework/API/src/AlgorithmHasProperty.cpp index 6eb34ced08f79e87d2e62e8647f5c4b395c08a69..3be5eaf76b4d0180eff39cd202f0e313b26a6e51 100644 --- a/Framework/API/src/AlgorithmHasProperty.cpp +++ b/Framework/API/src/AlgorithmHasProperty.cpp @@ -13,21 +13,16 @@ namespace Mantid { namespace API { /// Constructor -AlgorithmHasProperty::AlgorithmHasProperty(const std::string &propName) - : m_propName(propName) {} +AlgorithmHasProperty::AlgorithmHasProperty(const std::string &propName) : m_propName(propName) {} /** * Get a string representation of the type * @returns A string containing the validator type */ -std::string AlgorithmHasProperty::getType() const { - return "AlgorithmHasProperty"; -} +std::string AlgorithmHasProperty::getType() const { return "AlgorithmHasProperty"; } /// Make a copy of the present type of validator -Kernel::IValidator_sptr AlgorithmHasProperty::clone() const { - return std::make_shared(*this); -} +Kernel::IValidator_sptr AlgorithmHasProperty::clone() const { return std::make_shared(*this); } /** * Checks the value based on the validator's rules @@ -35,18 +30,16 @@ Kernel::IValidator_sptr AlgorithmHasProperty::clone() const { * @returns An error message to display to users or an empty string on no * error */ -std::string AlgorithmHasProperty::checkValidity( - const std::shared_ptr &value) const { +std::string AlgorithmHasProperty::checkValidity(const std::shared_ptr &value) const { std::string message; if (value->existsProperty(m_propName)) { Kernel::Property *p = value->getProperty(m_propName); if (!p->isValid().empty()) { - message = "Algorithm object contains the required property \"" + - m_propName + "\" but it has an invalid value: " + p->value(); + message = "Algorithm object contains the required property \"" + m_propName + + "\" but it has an invalid value: " + p->value(); } } else { - message = "Algorithm object does not have the required property \"" + - m_propName + "\""; + message = "Algorithm object does not have the required property \"" + m_propName + "\""; } return message; diff --git a/Framework/API/src/AlgorithmHistory.cpp b/Framework/API/src/AlgorithmHistory.cpp index fee570d7b0ba001d6179743e53db6b18f95df09d..276e0a69a4236a8cf0641853cc52b4894a075174 100644 --- a/Framework/API/src/AlgorithmHistory.cpp +++ b/Framework/API/src/AlgorithmHistory.cpp @@ -46,13 +46,10 @@ static boost::uuids::random_generator uuidGen; * (optional) * @param uexeccount :: an unsigned int for algorithm execution order */ -AlgorithmHistory::AlgorithmHistory(const Algorithm *const alg, - const Types::Core::DateAndTime &start, - const double &duration, - std::size_t uexeccount) - : m_name(alg->name()), m_version(alg->version()), m_executionDate(start), - m_executionDuration(duration), m_execCount(uexeccount), - m_childHistories() { +AlgorithmHistory::AlgorithmHistory(const Algorithm *const alg, const Types::Core::DateAndTime &start, + const double &duration, std::size_t uexeccount) + : m_name(alg->name()), m_version(alg->version()), m_executionDate(start), m_executionDuration(duration), + m_execCount(uexeccount), m_childHistories() { // Now go through the algorithm's properties and create the PropertyHistory // objects. setProperties(alg); @@ -60,9 +57,7 @@ AlgorithmHistory::AlgorithmHistory(const Algorithm *const alg, } /// Default constructor -AlgorithmHistory::AlgorithmHistory() { - m_uuid = boost::uuids::to_string(uuidGen()); -} +AlgorithmHistory::AlgorithmHistory() { m_uuid = boost::uuids::to_string(uuidGen()); } /// Destructor AlgorithmHistory::~AlgorithmHistory() = default; @@ -79,13 +74,10 @@ AlgorithmHistory::~AlgorithmHistory() = default; (optional). @param uexeccount :: an unsigned int for algorithm execution order */ -AlgorithmHistory::AlgorithmHistory(const std::string &name, int vers, - std::string uuid, - const Types::Core::DateAndTime &start, - const double &duration, +AlgorithmHistory::AlgorithmHistory(const std::string &name, int vers, std::string uuid, + const Types::Core::DateAndTime &start, const double &duration, std::size_t uexeccount) - : m_name(name), m_version(vers), m_executionDate(start), - m_executionDuration(duration), m_execCount(uexeccount), + : m_name(name), m_version(vers), m_executionDate(start), m_executionDuration(duration), m_execCount(uexeccount), m_childHistories(), m_uuid(std::move(uuid)) {} /** @@ -100,8 +92,7 @@ void AlgorithmHistory::setProperties(const Algorithm *const alg) { // objects. const std::vector &properties = alg->getProperties(); for (const auto &property : properties) { - m_properties.emplace_back( - std::make_shared(property->createHistory())); + m_properties.emplace_back(std::make_shared(property->createHistory())); } } @@ -114,9 +105,8 @@ void AlgorithmHistory::setProperties(const Algorithm *const alg) { * (optional) * @param uexeccount :: an unsigned int for algorithm execution order */ -void AlgorithmHistory::fillAlgorithmHistory( - const Algorithm *const alg, const Types::Core::DateAndTime &start, - const double &duration, std::size_t uexeccount) { +void AlgorithmHistory::fillAlgorithmHistory(const Algorithm *const alg, const Types::Core::DateAndTime &start, + const double &duration, std::size_t uexeccount) { m_name = alg->name(); m_version = alg->version(); m_executionDate = start; @@ -130,10 +120,9 @@ void AlgorithmHistory::fillAlgorithmHistory( @param A :: AlgorithmHistory Item to copy */ AlgorithmHistory::AlgorithmHistory(const AlgorithmHistory &A) - : m_name(A.m_name), m_version(A.m_version), - m_executionDate(A.m_executionDate), - m_executionDuration(A.m_executionDuration), m_properties(A.m_properties), - m_execCount(A.m_execCount), m_uuid(A.m_uuid) { + : m_name(A.m_name), m_version(A.m_version), m_executionDate(A.m_executionDate), + m_executionDuration(A.m_executionDuration), m_properties(A.m_properties), m_execCount(A.m_execCount), + m_uuid(A.m_uuid) { m_childHistories = A.m_childHistories; } @@ -141,8 +130,7 @@ AlgorithmHistory::AlgorithmHistory(const AlgorithmHistory &A) * @param start :: The start time of the algorithm execution * @param duration :: The time (in seconds) that it took to run this algorithm */ -void AlgorithmHistory::addExecutionInfo(const DateAndTime &start, - const double &duration) { +void AlgorithmHistory::addExecutionInfo(const DateAndTime &start, const double &duration) { m_executionDate = start; m_executionDuration = duration; } @@ -153,11 +141,9 @@ void AlgorithmHistory::addExecutionInfo(const DateAndTime &start, @param isdefault :: True if the property is default @param direction :: The direction of the property */ -void AlgorithmHistory::addProperty(const std::string &name, - const std::string &value, bool isdefault, +void AlgorithmHistory::addProperty(const std::string &name, const std::string &value, bool isdefault, const unsigned int &direction) { - m_properties.emplace_back( - std::make_shared(name, value, "", isdefault, direction)); + m_properties.emplace_back(std::make_shared(name, value, "", isdefault, direction)); } /** Add a child algorithm history to history @@ -175,9 +161,7 @@ void AlgorithmHistory::addChildHistory(const AlgorithmHistory_sptr &childHist) { /* Return the child history length */ -size_t AlgorithmHistory::childHistorySize() const { - return m_childHistories.size(); -} +size_t AlgorithmHistory::childHistorySize() const { return m_childHistories.size(); } /** * Retrieve a child algorithm history by index @@ -185,11 +169,9 @@ size_t AlgorithmHistory::childHistorySize() const { * @returns A pointer to an AlgorithmHistory object * @throws std::out_of_range error if the index is invalid */ -AlgorithmHistory_sptr -AlgorithmHistory::getChildAlgorithmHistory(const size_t index) const { +AlgorithmHistory_sptr AlgorithmHistory::getChildAlgorithmHistory(const size_t index) const { if (index >= this->getChildHistories().size()) { - throw std::out_of_range( - "AlgorithmHistory::getAlgorithmHistory() - Index out of range"); + throw std::out_of_range("AlgorithmHistory::getAlgorithmHistory() - Index out of range"); } return *std::next(m_childHistories.cbegin(), index); } @@ -200,9 +182,7 @@ AlgorithmHistory::getChildAlgorithmHistory(const size_t index) const { * @returns A pointer to an AlgorithmHistory object * @throws std::out_of_range error if the index is invalid */ -AlgorithmHistory_sptr AlgorithmHistory::operator[](const size_t index) const { - return getChildAlgorithmHistory(index); -} +AlgorithmHistory_sptr AlgorithmHistory::operator[](const size_t index) const { return getChildAlgorithmHistory(index); } /** * Gets the value of a specified algorithm property @@ -210,14 +190,11 @@ AlgorithmHistory_sptr AlgorithmHistory::operator[](const size_t index) const { * @returns The string value of the property * @throw Exception::NotFoundError if the named property is unknown */ -const std::string & -AlgorithmHistory::getPropertyValue(const std::string &name) const { - const auto found = std::find_if( - m_properties.cbegin(), m_properties.cend(), - [&name](const auto &history) { return history->name() == name; }); +const std::string &AlgorithmHistory::getPropertyValue(const std::string &name) const { + const auto found = std::find_if(m_properties.cbegin(), m_properties.cend(), + [&name](const auto &history) { return history->name() == name; }); if (found == m_properties.cend()) { - throw Kernel::Exception::NotFoundError( - "Could not find the specified property", name); + throw Kernel::Exception::NotFoundError("Could not find the specified property", name); } return (*found)->value(); } @@ -227,8 +204,7 @@ AlgorithmHistory::getPropertyValue(const std::string &name) const { * @param index :: An index within the workspace history * @returns A shared pointer to an algorithm object */ -std::shared_ptr -AlgorithmHistory::getChildAlgorithm(const size_t index) const { +std::shared_ptr AlgorithmHistory::getChildAlgorithm(const size_t index) const { return Algorithm::fromHistory(*(this->getChildAlgorithmHistory(index))); } @@ -239,16 +215,14 @@ AlgorithmHistory::getChildAlgorithm(const size_t index) const { * @param maxPropertyLength :: the max length for any property value string (0 * = full length) */ -void AlgorithmHistory::printSelf(std::ostream &os, const int indent, - const size_t maxPropertyLength) const { +void AlgorithmHistory::printSelf(std::ostream &os, const int indent, const size_t maxPropertyLength) const { auto execDate = m_executionDate.toISO8601String(); execDate.replace(execDate.find("T"), 1, " "); os << std::string(indent, ' ') << "Algorithm: " << m_name; os << std::string(indent, ' ') << " v" << m_version << '\n'; os << std::string(indent, ' ') << "Execution Date: " << execDate << '\n'; - os << std::string(indent, ' ') - << "Execution Duration: " << m_executionDuration << " seconds\n"; + os << std::string(indent, ' ') << "Execution Duration: " << m_executionDuration << " seconds\n"; os << std::string(indent, ' ') << "UUID: " << m_uuid << '\n'; os << std::string(indent, ' ') << "Parameters:\n"; @@ -261,9 +235,7 @@ void AlgorithmHistory::printSelf(std::ostream &os, const int indent, * Create a concrete algorithm based on a history record * @returns An algorithm object constructed from this history record */ -std::shared_ptr AlgorithmHistory::createAlgorithm() const { - return Algorithm::fromHistory(*this); -} +std::shared_ptr AlgorithmHistory::createAlgorithm() const { return Algorithm::fromHistory(*this); } /** Standard Assignment operator @@ -302,8 +274,7 @@ std::ostream &operator<<(std::ostream &os, const AlgorithmHistory &AH) { void AlgorithmHistory::saveNexus(::NeXus::File *file, int &algCount) const { std::stringstream algNumber; ++algCount; - algNumber << "MantidAlgorithm_" - << algCount; // history entry names start at 1 not 0 + algNumber << "MantidAlgorithm_" << algCount; // history entry names start at 1 not 0 std::stringstream algData; printSelf(algData); diff --git a/Framework/API/src/AlgorithmManager.cpp b/Framework/API/src/AlgorithmManager.cpp index 35be4001522a2776cdfb7b16cb49414c0964f8d1..38ca50d3077b2f9fc46e1fd76b17cd7d9eb4a5b2 100644 --- a/Framework/API/src/AlgorithmManager.cpp +++ b/Framework/API/src/AlgorithmManager.cpp @@ -20,9 +20,7 @@ Kernel::Logger g_log("AlgorithmManager"); } // namespace /// Private Constructor for singleton class -AlgorithmManagerImpl::AlgorithmManagerImpl() : m_managed_algs() { - g_log.debug() << "Algorithm Manager created.\n"; -} +AlgorithmManagerImpl::AlgorithmManagerImpl() : m_managed_algs() { g_log.debug() << "Algorithm Manager created.\n"; } /** Private destructor * Prevents client from calling 'delete' on the pointer handed @@ -38,8 +36,7 @@ AlgorithmManagerImpl::~AlgorithmManagerImpl() = default; * @return A pointer to the created algorithm * @throw NotFoundError Thrown if algorithm requested is not registered */ -Algorithm_sptr AlgorithmManagerImpl::createUnmanaged(const std::string &algName, - const int &version) const { +Algorithm_sptr AlgorithmManagerImpl::createUnmanaged(const std::string &algName, const int &version) const { return AlgorithmFactory::Instance().create(algName, version); // Throws on fail: } @@ -56,27 +53,22 @@ Algorithm_sptr AlgorithmManagerImpl::createUnmanaged(const std::string &algName, * @throw NotFoundError Thrown if algorithm requested is not registered * @throw std::runtime_error Thrown if properties string is ill-formed */ -IAlgorithm_sptr AlgorithmManagerImpl::create(const std::string &algName, - const int &version) { +IAlgorithm_sptr AlgorithmManagerImpl::create(const std::string &algName, const int &version) { std::lock_guard _lock(this->m_managedMutex); IAlgorithm_sptr alg; try { alg = AlgorithmFactory::Instance().create(algName, version); // Throws on fail: auto count = removeFinishedAlgorithms(); - g_log.debug() - << count - << " Finished algorithms removed from the managed algorithms list. " - << m_managed_algs.size() << " remaining.\n"; + g_log.debug() << count << " Finished algorithms removed from the managed algorithms list. " << m_managed_algs.size() + << " remaining.\n"; // Add to list of managed ones m_managed_algs.emplace_back(alg); alg->initialize(); } catch (std::runtime_error &ex) { - g_log.error() << "AlgorithmManager:: Unable to create algorithm " << algName - << ' ' << ex.what() << '\n'; - throw std::runtime_error("AlgorithmManager:: Unable to create algorithm " + - algName + ' ' + ex.what()); + g_log.error() << "AlgorithmManager:: Unable to create algorithm " << algName << ' ' << ex.what() << '\n'; + throw std::runtime_error("AlgorithmManager:: Unable to create algorithm " + algName + ' ' + ex.what()); } return alg; } @@ -104,11 +96,8 @@ std::size_t AlgorithmManagerImpl::size() const { return m_managed_algs.size(); } */ IAlgorithm_sptr AlgorithmManagerImpl::getAlgorithm(AlgorithmID id) const { std::lock_guard _lock(this->m_managedMutex); - const auto found = - std::find_if(m_managed_algs.cbegin(), m_managed_algs.cend(), - [id](const auto &algorithm) { - return algorithm->getAlgorithmID() == id; - }); + const auto found = std::find_if(m_managed_algs.cbegin(), m_managed_algs.cend(), + [id](const auto &algorithm) { return algorithm->getAlgorithmID() == id; }); if (found == m_managed_algs.cend()) { return IAlgorithm_sptr(); } else { @@ -129,8 +118,7 @@ void AlgorithmManagerImpl::removeById(AlgorithmID id) { g_log.debug() << "Removing algorithm " << (*it)->name() << '\n'; m_managed_algs.erase(it); } else { - g_log.debug() << "Unable to remove algorithm " << (*it)->name() - << ". The algorithm is running.\n"; + g_log.debug() << "Unable to remove algorithm " << (*it)->name() << ". The algorithm is running.\n"; } break; } @@ -143,7 +131,7 @@ void AlgorithmManagerImpl::removeById(AlgorithmID id) { * @param id :: ID of the algorithm being started */ void AlgorithmManagerImpl::notifyAlgorithmStarting(AlgorithmID id) { - IAlgorithm_sptr alg = this->getAlgorithm(id); + auto alg = this->getAlgorithm(id); if (!alg) return; notificationCenter.postNotification(new AlgorithmStartingNotification(alg)); @@ -151,27 +139,21 @@ void AlgorithmManagerImpl::notifyAlgorithmStarting(AlgorithmID id) { /// Returns all running (& managed) occurances of the named algorithm, oldest /// first -std::vector AlgorithmManagerImpl::runningInstancesOf( - const std::string &algorithmName) const { +std::vector AlgorithmManagerImpl::runningInstancesOf(const std::string &algorithmName) const { std::vector theRunningInstances; std::lock_guard _lock(this->m_managedMutex); - std::copy_if(m_managed_algs.cbegin(), m_managed_algs.cend(), - std::back_inserter(theRunningInstances), - [&algorithmName](const auto &algorithm) { - return algorithm->name() == algorithmName && - algorithm->isRunning(); - }); + std::copy_if( + m_managed_algs.cbegin(), m_managed_algs.cend(), std::back_inserter(theRunningInstances), + [&algorithmName](const auto &algorithm) { return algorithm->name() == algorithmName && algorithm->isRunning(); }); return theRunningInstances; } /// Returns all running (& managed) occurances of any algorithm, oldest /// first -std::vector -AlgorithmManagerImpl::runningInstances() const { +std::vector AlgorithmManagerImpl::runningInstances() const { std::vector theRunningInstances; std::lock_guard _lock(this->m_managedMutex); - std::copy_if(m_managed_algs.cbegin(), m_managed_algs.cend(), - std::back_inserter(theRunningInstances), + std::copy_if(m_managed_algs.cbegin(), m_managed_algs.cend(), std::back_inserter(theRunningInstances), [](const auto &algorithm) { return algorithm->isRunning(); }); return theRunningInstances; } @@ -190,11 +172,8 @@ void AlgorithmManagerImpl::cancelAll() { /// place size_t AlgorithmManagerImpl::removeFinishedAlgorithms() { std::vector theCompletedInstances; - std::copy_if(m_managed_algs.cbegin(), m_managed_algs.cend(), - std::back_inserter(theCompletedInstances), - [](const auto &algorithm) { - return (algorithm->isReadyForGarbageCollection()); - }); + std::copy_if(m_managed_algs.cbegin(), m_managed_algs.cend(), std::back_inserter(theCompletedInstances), + [](const auto &algorithm) { return (algorithm->isReadyForGarbageCollection()); }); for (auto completedAlg : theCompletedInstances) { auto itend = m_managed_algs.end(); for (auto it = m_managed_algs.begin(); it != itend; ++it) { diff --git a/Framework/API/src/AlgorithmObserver.cpp b/Framework/API/src/AlgorithmObserver.cpp index a5f1aa4b2f44ac45831b6304a84de3343159fdf4..fb3aa8b02650a1b4de406b04069fbb6fc20fe64e 100644 --- a/Framework/API/src/AlgorithmObserver.cpp +++ b/Framework/API/src/AlgorithmObserver.cpp @@ -53,45 +53,34 @@ void AlgorithmObserver::observeAll(const IAlgorithm_const_sptr &alg) { /** Connect to algorithm alg and observe its progress notification @param alg :: Algorithm to be observed */ -void AlgorithmObserver::observeProgress(const IAlgorithm_const_sptr &alg) { - alg->addObserver(m_progressObserver); -} +void AlgorithmObserver::observeProgress(const IAlgorithm_const_sptr &alg) { alg->addObserver(m_progressObserver); } /** Connect to AlgorithmManager and observe its starting notifications */ void AlgorithmObserver::observeStarting() { - AlgorithmManager::Instance().notificationCenter.addObserver( - m_startingObserver); + AlgorithmManager::Instance().notificationCenter.addObserver(m_startingObserver); } /** Connect to algorithm alg and observe its start notification @param alg :: Algorithm to be observed */ -void AlgorithmObserver::observeStart(const IAlgorithm_const_sptr &alg) { - alg->addObserver(m_startObserver); -} +void AlgorithmObserver::observeStart(const IAlgorithm_const_sptr &alg) { alg->addObserver(m_startObserver); } /** Connect to algorithm alg and observe its finish notification @param alg :: Algorithm to be observed */ -void AlgorithmObserver::observeFinish(const IAlgorithm_const_sptr &alg) { - alg->addObserver(m_finishObserver); -} +void AlgorithmObserver::observeFinish(const IAlgorithm_const_sptr &alg) { alg->addObserver(m_finishObserver); } /** Connect to algorithm alg and observe its error notification @param alg :: Algorithm to be observed */ -void AlgorithmObserver::observeError(const IAlgorithm_const_sptr &alg) { - alg->addObserver(m_errorObserver); -} +void AlgorithmObserver::observeError(const IAlgorithm_const_sptr &alg) { alg->addObserver(m_errorObserver); } /** Disconnect from algorithm alg. Should be called in the destructor of inherited classes. @param alg :: Algorithm to be disconnected */ -void AlgorithmObserver::stopObserving(const IAlgorithm_const_sptr &alg) { - this->stopObserving(alg.get()); -} +void AlgorithmObserver::stopObserving(const IAlgorithm_const_sptr &alg) { this->stopObserving(alg.get()); } void AlgorithmObserver::stopObserving(const IAlgorithm *alg) { alg->removeObserver(m_progressObserver); @@ -104,8 +93,7 @@ void AlgorithmObserver::stopObserving(const IAlgorithm *alg) { * Disconnect from the algorithm manager. */ void AlgorithmObserver::stopObservingManager() { - AlgorithmManager::Instance().notificationCenter.removeObserver( - m_startingObserver); + AlgorithmManager::Instance().notificationCenter.removeObserver(m_startingObserver); } /// @cond Doxygen cannot handle the macro around the argument name @@ -119,10 +107,8 @@ The default handler is provided (doing nothing). @param estimatedTime :: estimated time to completion in seconds @param progressPrecision :: number of digits after the decimal */ -void AlgorithmObserver::progressHandle(const IAlgorithm *alg, double p, - const std::string &msg, - const double estimatedTime, - const int progressPrecision) { +void AlgorithmObserver::progressHandle(const IAlgorithm *alg, double p, const std::string &msg, + const double estimatedTime, const int progressPrecision) { UNUSED_ARG(alg) UNUSED_ARG(p) UNUSED_ARG(msg) @@ -153,8 +139,7 @@ The default handler is provided (doing nothing). @param alg :: Pointer to the algorithm sending the notification. @param what :: The error message */ -void AlgorithmObserver::errorHandle(const IAlgorithm *alg, - const std::string &what) { +void AlgorithmObserver::errorHandle(const IAlgorithm *alg, const std::string &what) { UNUSED_ARG(alg) UNUSED_ARG(what) } @@ -163,41 +148,35 @@ void AlgorithmObserver::errorHandle(const IAlgorithm *alg, /** Poco notification handler for Algorithm::ProgressNotification. @param pNf :: An pointer to the notification. */ -void AlgorithmObserver::_progressHandle( - const Poco::AutoPtr &pNf) { - this->progressHandle(pNf->algorithm(), pNf->progress, pNf->message, - pNf->estimatedTime, pNf->progressPrecision); +void AlgorithmObserver::_progressHandle(const Poco::AutoPtr &pNf) { + this->progressHandle(pNf->algorithm(), pNf->progress, pNf->message, pNf->estimatedTime, pNf->progressPrecision); } /** Poco notification handler for Algorithm::StartedNotification. @param pNf :: An pointer to the notification. */ -void AlgorithmObserver::_startHandle( - const Poco::AutoPtr &pNf) { +void AlgorithmObserver::_startHandle(const Poco::AutoPtr &pNf) { this->startHandle(pNf->algorithm()); } /** Poco notification handler for Algorithm::FinishedNotification. @param pNf :: An pointer to the notification. */ -void AlgorithmObserver::_finishHandle( - const Poco::AutoPtr &pNf) { +void AlgorithmObserver::_finishHandle(const Poco::AutoPtr &pNf) { this->finishHandle(pNf->algorithm()); } /** Poco notification handler for Algorithm::ErrorNotification. @param pNf :: An pointer to the notification. */ -void AlgorithmObserver::_errorHandle( - const Poco::AutoPtr &pNf) { +void AlgorithmObserver::_errorHandle(const Poco::AutoPtr &pNf) { this->errorHandle(pNf->algorithm(), pNf->what); } /** Poco notification handler for API::AlgorithmStartingNotification. @param pNf :: An pointer to the notification. */ -void AlgorithmObserver::_startingHandle( - const Poco::AutoPtr &pNf) { +void AlgorithmObserver::_startingHandle(const Poco::AutoPtr &pNf) { this->startingHandle(pNf->getAlgorithm()); } diff --git a/Framework/API/src/AlgorithmProperty.cpp b/Framework/API/src/AlgorithmProperty.cpp index 4bb4b6388b338c59b386e801bb617c652c8f97be..d7c29b6aaa3a0d8f66634f95417fb5d3fc35da7d 100644 --- a/Framework/API/src/AlgorithmProperty.cpp +++ b/Framework/API/src/AlgorithmProperty.cpp @@ -30,12 +30,9 @@ namespace API { * @param direction :: Whether this is a Direction::Input, Direction::Output or * Direction::InOut (Input & Output) property */ -AlgorithmProperty::AlgorithmProperty(const std::string &propName, - Kernel::IValidator_sptr validator, +AlgorithmProperty::AlgorithmProperty(const std::string &propName, Kernel::IValidator_sptr validator, unsigned int direction) - : Kernel::PropertyWithValue(propName, HeldType(), - std::move(validator), direction), - m_algmStr() {} + : Kernel::PropertyWithValue(propName, HeldType(), std::move(validator), direction), m_algmStr() {} /** * Return the algorithm as string @@ -46,9 +43,7 @@ std::string AlgorithmProperty::value() const { return m_algmStr; } /** * @return A Json::Value objectValue encoding the algorithm */ -Json::Value AlgorithmProperty::valueAsJson() const { - return (*this)()->toJson(); -} +Json::Value AlgorithmProperty::valueAsJson() const { return (*this)()->toJson(); } /** * Get the default @@ -91,8 +86,7 @@ std::string AlgorithmProperty::setValueFromJson(const Json::Value &value) { * @return An empty string if the value is valid, otherwise the string will * contain the error */ -std::string -AlgorithmProperty::setBaseValue(const AlgorithmProperty::HeldType &algm) { +std::string AlgorithmProperty::setBaseValue(const AlgorithmProperty::HeldType &algm) { std::string message; try { Kernel::PropertyWithValue::m_value = algm; diff --git a/Framework/API/src/AnalysisDataService.cpp b/Framework/API/src/AnalysisDataService.cpp index c7508dd2224849e46d41fe05c22cea2b35ba17e0..9eaad89e9b9de93ce2036008f675b6f2675df302 100644 --- a/Framework/API/src/AnalysisDataService.cpp +++ b/Framework/API/src/AnalysisDataService.cpp @@ -19,15 +19,12 @@ namespace API { * Constructor. * @param name :: The name of a workspace group. */ -AnalysisDataServiceImpl::GroupUpdatedNotification::GroupUpdatedNotification( - const std::string &name) - : DataServiceNotification(name, - AnalysisDataService::Instance().retrieve(name)) {} +AnalysisDataServiceImpl::GroupUpdatedNotification::GroupUpdatedNotification(const std::string &name) + : DataServiceNotification(name, AnalysisDataService::Instance().retrieve(name)) {} /** * Returns the workspace pointer cast to WorkspaceGroup */ -std::shared_ptr -AnalysisDataServiceImpl::GroupUpdatedNotification::getWorkspaceGroup() const { +std::shared_ptr AnalysisDataServiceImpl::GroupUpdatedNotification::getWorkspaceGroup() const { return std::dynamic_pointer_cast(this->object()); } @@ -41,8 +38,7 @@ AnalysisDataServiceImpl::GroupUpdatedNotification::getWorkspaceGroup() const { * problem * if the name is unacceptable. */ -const std::string -AnalysisDataServiceImpl::isValid(const std::string &name) const { +const std::string AnalysisDataServiceImpl::isValid(const std::string &name) const { std::string error; const std::string &illegal = illegalCharacters(); if (illegal.empty()) @@ -51,9 +47,7 @@ AnalysisDataServiceImpl::isValid(const std::string &name) const { for (size_t i = 0; i < length; ++i) { if (illegal.find_first_of(name[i]) != std::string::npos) { std::ostringstream strm; - strm << "Invalid object name '" << name - << "'. Names cannot contain any of the following characters: " - << illegal; + strm << "Invalid object name '" << name << "'. Names cannot contain any of the following characters: " << illegal; error = strm.str(); break; } @@ -70,8 +64,7 @@ AnalysisDataServiceImpl::isValid(const std::string &name) const { * @param name The name of the object * @param workspace The shared pointer to the workspace to store */ -void AnalysisDataServiceImpl::add( - const std::string &name, const std::shared_ptr &workspace) { +void AnalysisDataServiceImpl::add(const std::string &name, const std::shared_ptr &workspace) { auto group = std::dynamic_pointer_cast(workspace); verifyName(name, group); @@ -109,8 +102,7 @@ void AnalysisDataServiceImpl::add( * @param name The name of the object * @param workspace The shared pointer to the workspace to store */ -void AnalysisDataServiceImpl::addOrReplace( - const std::string &name, const std::shared_ptr &workspace) { +void AnalysisDataServiceImpl::addOrReplace(const std::string &name, const std::shared_ptr &workspace) { auto group = std::dynamic_pointer_cast(workspace); verifyName(name, group); @@ -144,14 +136,12 @@ void AnalysisDataServiceImpl::addOrReplace( * @param oldName The old name of the object * @param newName The new name of the object */ -void AnalysisDataServiceImpl::rename(const std::string &oldName, - const std::string &newName) { +void AnalysisDataServiceImpl::rename(const std::string &oldName, const std::string &newName) { auto oldWorkspace = retrieve(oldName); auto group = std::dynamic_pointer_cast(oldWorkspace); if (group && group->containsInChildren(newName)) { - throw std::invalid_argument( - "Unable to rename group as the new name matches its members"); + throw std::invalid_argument("Unable to rename group as the new name matches its members"); } Kernel::DataService::rename(oldName, newName); @@ -188,30 +178,25 @@ void AnalysisDataServiceImpl::remove(const std::string &name) { * @throws Mantid::Kernel::Exception::NotFoundError if a workspace does not * exist within the ADS */ -std::vector AnalysisDataServiceImpl::retrieveWorkspaces( - const std::vector &names, bool unrollGroups) const { +std::vector AnalysisDataServiceImpl::retrieveWorkspaces(const std::vector &names, + bool unrollGroups) const { using WorkspacesVector = std::vector; WorkspacesVector workspaces; workspaces.reserve(names.size()); - std::transform( - std::begin(names), std::end(names), std::back_inserter(workspaces), - [this](const std::string &name) { return this->retrieve(name); }); + std::transform(std::begin(names), std::end(names), std::back_inserter(workspaces), + [this](const std::string &name) { return this->retrieve(name); }); assert(names.size() == workspaces.size()); if (unrollGroups) { - using IteratorDifference = - std::iterator_traits::difference_type; + using IteratorDifference = std::iterator_traits::difference_type; bool done{workspaces.size() == 0}; size_t i{0}; while (!done) { - if (auto group = - std::dynamic_pointer_cast(workspaces.at(i))) { + if (auto group = std::dynamic_pointer_cast(workspaces.at(i))) { const auto groupLength(group->size()); - workspaces.erase(std::next(std::begin(workspaces), - static_cast(i))); + workspaces.erase(std::next(std::begin(workspaces), static_cast(i))); for (size_t j = 0; j < groupLength; ++j) { - workspaces.insert(std::next(std::begin(workspaces), - static_cast(i + j)), + workspaces.insert(std::next(std::begin(workspaces), static_cast(i + j)), group->getItem(j)); } i += groupLength; @@ -234,8 +219,7 @@ std::vector AnalysisDataServiceImpl::retrieveWorkspaces( void AnalysisDataServiceImpl::sortGroupByName(const std::string &groupName) { WorkspaceGroup_sptr group = retrieveWS(groupName); if (!group) { - throw std::runtime_error("Workspace " + groupName + - " is not a workspace group."); + throw std::runtime_error("Workspace " + groupName + " is not a workspace group."); } group->sortMembersByName(); notificationCenter.postNotification(new GroupUpdatedNotification(groupName)); @@ -246,12 +230,10 @@ void AnalysisDataServiceImpl::sortGroupByName(const std::string &groupName) { * @param groupName :: A group name. * @param wsName :: Name of a workspace to add to the group. */ -void AnalysisDataServiceImpl::addToGroup(const std::string &groupName, - const std::string &wsName) { +void AnalysisDataServiceImpl::addToGroup(const std::string &groupName, const std::string &wsName) { WorkspaceGroup_sptr group = retrieveWS(groupName); if (!group) { - throw std::runtime_error("Workspace " + groupName + - " is not a workspace group."); + throw std::runtime_error("Workspace " + groupName + " is not a workspace group."); } if (groupName == wsName) { @@ -270,8 +252,7 @@ void AnalysisDataServiceImpl::addToGroup(const std::string &groupName, void AnalysisDataServiceImpl::deepRemoveGroup(const std::string &name) { WorkspaceGroup_sptr group = retrieveWS(name); if (!group) { - throw std::runtime_error("Workspace " + name + - " is not a workspace group."); + throw std::runtime_error("Workspace " + name + " is not a workspace group."); } group->observeADSNotifications(false); for (size_t i = 0; i < group->size(); ++i) { @@ -293,16 +274,13 @@ void AnalysisDataServiceImpl::deepRemoveGroup(const std::string &name) { * @param groupName :: Name of a workspace group. * @param wsName :: Name of a workspace to remove. */ -void AnalysisDataServiceImpl::removeFromGroup(const std::string &groupName, - const std::string &wsName) { +void AnalysisDataServiceImpl::removeFromGroup(const std::string &groupName, const std::string &wsName) { WorkspaceGroup_sptr group = retrieveWS(groupName); if (!group) { - throw std::runtime_error("Workspace " + groupName + - " is not a workspace group."); + throw std::runtime_error("Workspace " + groupName + " is not a workspace group."); } if (!group->contains(wsName)) { - throw std::runtime_error("WorkspaceGroup " + groupName + - " does not containt workspace " + wsName); + throw std::runtime_error("WorkspaceGroup " + groupName + " does not containt workspace " + wsName); } group->removeByADS(wsName); notificationCenter.postNotification(new GroupUpdatedNotification(groupName)); @@ -313,8 +291,7 @@ void AnalysisDataServiceImpl::removeFromGroup(const std::string &groupName, * items that are part of a WorkspaceGroup already in the list * @return A lookup of name to Workspace pointer */ -std::map -AnalysisDataServiceImpl::topLevelItems() const { +std::map AnalysisDataServiceImpl::topLevelItems() const { std::map topLevel; auto topLevelNames = this->getObjectNames(); std::set groupMembers; @@ -354,9 +331,7 @@ void AnalysisDataServiceImpl::shutdown() { clear(); } * Constructor */ AnalysisDataServiceImpl::AnalysisDataServiceImpl() - : Mantid::Kernel::DataService( - "AnalysisDataService"), - m_illegalChars() {} + : Mantid::Kernel::DataService("AnalysisDataService"), m_illegalChars() {} // The following is commented using /// rather than /** to stop the compiler // complaining @@ -365,9 +340,7 @@ AnalysisDataServiceImpl::AnalysisDataServiceImpl() /// within ADS /// @returns A n array of c strings containing the following characters: " /// +-/*\%<>&|^~=!@()[]{},:.`$?" -const std::string &AnalysisDataServiceImpl::illegalCharacters() const { - return m_illegalChars; -} +const std::string &AnalysisDataServiceImpl::illegalCharacters() const { return m_illegalChars; } /** * Set the list of illegal characeters @@ -375,8 +348,7 @@ const std::string &AnalysisDataServiceImpl::illegalCharacters() const { * that are not to be accepted by the ADS * NOTE: This only affects further additions to the ADS */ -void AnalysisDataServiceImpl::setIllegalCharacterList( - const std::string &illegalChars) { +void AnalysisDataServiceImpl::setIllegalCharacterList(const std::string &illegalChars) { m_illegalChars = illegalChars; } @@ -389,17 +361,14 @@ void AnalysisDataServiceImpl::setIllegalCharacterList( * true throws std::runtime_error else nothing. */ -void AnalysisDataServiceImpl::verifyName( - const std::string &name, - const std::shared_ptr &group) { +void AnalysisDataServiceImpl::verifyName(const std::string &name, const std::shared_ptr &group) { const std::string error = isValid(name); if (!error.empty()) { throw std::invalid_argument(error); } if (group && group->containsInChildren(name)) { - throw std::invalid_argument( - "Unable to add group as name matches its members"); + throw std::invalid_argument("Unable to add group as name matches its members"); } } diff --git a/Framework/API/src/AnalysisDataServiceObserver.cpp b/Framework/API/src/AnalysisDataServiceObserver.cpp index 73c85386c77066984eff08b64465ee73b76216b0..319dcc0ec808d3fbe1d5d94b42d0a6d2a66e6630 100644 --- a/Framework/API/src/AnalysisDataServiceObserver.cpp +++ b/Framework/API/src/AnalysisDataServiceObserver.cpp @@ -7,8 +7,7 @@ #include "MantidAPI/AnalysisDataServiceObserver.h" namespace { -template -void modifyObserver(const bool turnOn, bool &isObserving, Observer &observer) { +template void modifyObserver(const bool turnOn, bool &isObserving, Observer &observer) { if (turnOn && !isObserving) { AnalysisDataService::Instance().notificationCenter.addObserver(observer); } else if (!turnOn && isObserving) { @@ -29,9 +28,7 @@ AnalysisDataServiceObserver::AnalysisDataServiceObserver() m_renameObserver(*this, &AnalysisDataServiceObserver::_renameHandle), m_groupObserver(*this, &AnalysisDataServiceObserver::_groupHandle), m_unGroupObserver(*this, &AnalysisDataServiceObserver::_unGroupHandle), - m_groupUpdatedObserver(*this, - &AnalysisDataServiceObserver::_groupUpdateHandle) { -} + m_groupUpdatedObserver(*this, &AnalysisDataServiceObserver::_groupUpdateHandle) {} AnalysisDataServiceObserver::~AnalysisDataServiceObserver() { // Turn off/remove all observers @@ -66,9 +63,7 @@ void AnalysisDataServiceObserver::observeAll(bool turnOn) { * @param turnOn bool; if this is True then, if not already present, the * observer will be added else removed if it's false. */ -void AnalysisDataServiceObserver::observeAdd(bool turnOn) { - modifyObserver(turnOn, m_observingAdd, m_addObserver); -} +void AnalysisDataServiceObserver::observeAdd(bool turnOn) { modifyObserver(turnOn, m_observingAdd, m_addObserver); } /** * @brief Function will add/remove the observer to the ADS for when a workspace @@ -163,8 +158,7 @@ void AnalysisDataServiceObserver::anyChangeHandle() {} * @param wsName std::string; the name of the workspace added * @param ws Workspace_sptr; the Workspace that is added */ -void AnalysisDataServiceObserver::addHandle( - const std::string &wsName, const Mantid::API::Workspace_sptr &ws) { +void AnalysisDataServiceObserver::addHandle(const std::string &wsName, const Mantid::API::Workspace_sptr &ws) { UNUSED_ARG(wsName) UNUSED_ARG(ws) } @@ -176,8 +170,7 @@ void AnalysisDataServiceObserver::addHandle( * @param wsName std::string; the name of the workspace replacing * @param ws Workspace_sptr; the Workspace that is replacing */ -void AnalysisDataServiceObserver::replaceHandle( - const std::string &wsName, const Mantid::API::Workspace_sptr &ws) { +void AnalysisDataServiceObserver::replaceHandle(const std::string &wsName, const Mantid::API::Workspace_sptr &ws) { UNUSED_ARG(wsName) UNUSED_ARG(ws) } @@ -189,8 +182,7 @@ void AnalysisDataServiceObserver::replaceHandle( * @param wsName std::string; the name of the workspace * @param ws Workspace_sptr; the Workspace that is deleted */ -void AnalysisDataServiceObserver::deleteHandle( - const std::string &wsName, const Mantid::API::Workspace_sptr &ws) { +void AnalysisDataServiceObserver::deleteHandle(const std::string &wsName, const Mantid::API::Workspace_sptr &ws) { UNUSED_ARG(wsName) UNUSED_ARG(ws) } @@ -208,8 +200,7 @@ void AnalysisDataServiceObserver::clearHandle() {} * @param wsName std::string; the name of the workspace * @param newName std::string; the new name of the workspace */ -void AnalysisDataServiceObserver::renameHandle(const std::string &wsName, - const std::string &newName) { +void AnalysisDataServiceObserver::renameHandle(const std::string &wsName, const std::string &newName) { UNUSED_ARG(wsName) UNUSED_ARG(newName) } @@ -221,8 +212,7 @@ void AnalysisDataServiceObserver::renameHandle(const std::string &wsName, * @param wsName std::string; the name of the workspace * @param ws Workspace_sptr; the WorkspaceGroup that was added/created */ -void AnalysisDataServiceObserver::groupHandle(const std::string &wsName, - const Workspace_sptr &ws) { +void AnalysisDataServiceObserver::groupHandle(const std::string &wsName, const Workspace_sptr &ws) { UNUSED_ARG(wsName) UNUSED_ARG(ws) } @@ -234,8 +224,7 @@ void AnalysisDataServiceObserver::groupHandle(const std::string &wsName, * @param wsName std::string; the name of the workspace * @param ws Workspace_sptr; the WorkspaceGroup that was ungrouped */ -void AnalysisDataServiceObserver::unGroupHandle(const std::string &wsName, - const Workspace_sptr &ws) { +void AnalysisDataServiceObserver::unGroupHandle(const std::string &wsName, const Workspace_sptr &ws) { UNUSED_ARG(wsName) UNUSED_ARG(ws) } @@ -248,8 +237,7 @@ void AnalysisDataServiceObserver::unGroupHandle(const std::string &wsName, * @param wsName std::string; the name of the workspace * @param ws Workspace_sptr; the WorkspaceGroup that was updated */ -void AnalysisDataServiceObserver::groupUpdateHandle(const std::string &wsName, - const Workspace_sptr &ws) { +void AnalysisDataServiceObserver::groupUpdateHandle(const std::string &wsName, const Workspace_sptr &ws) { UNUSED_ARG(wsName) UNUSED_ARG(ws) } @@ -257,15 +245,13 @@ void AnalysisDataServiceObserver::groupUpdateHandle(const std::string &wsName, // ------------------------------------------------------------ // Private Methods // ------------------------------------------------------------ -void AnalysisDataServiceObserver::_addHandle( - const Poco::AutoPtr &pNf) { +void AnalysisDataServiceObserver::_addHandle(const Poco::AutoPtr &pNf) { this->anyChangeHandle(); this->addHandle(pNf->objectName(), pNf->object()); } void AnalysisDataServiceObserver::_replaceHandle( - const Poco::AutoPtr - &pNf) { + const Poco::AutoPtr &pNf) { this->anyChangeHandle(); this->replaceHandle(pNf->objectName(), pNf->object()); } @@ -276,36 +262,31 @@ void AnalysisDataServiceObserver::_deleteHandle( this->deleteHandle(pNf->objectName(), pNf->object()); } -void AnalysisDataServiceObserver::_clearHandle( - const Poco::AutoPtr &pNf) { +void AnalysisDataServiceObserver::_clearHandle(const Poco::AutoPtr &pNf) { UNUSED_ARG(pNf) this->anyChangeHandle(); this->clearHandle(); } -void AnalysisDataServiceObserver::_renameHandle( - const Poco::AutoPtr &pNf) { +void AnalysisDataServiceObserver::_renameHandle(const Poco::AutoPtr &pNf) { this->anyChangeHandle(); this->renameHandle(pNf->objectName(), pNf->newObjectName()); } void AnalysisDataServiceObserver::_groupHandle( - const Poco::AutoPtr - &pNf) { + const Poco::AutoPtr &pNf) { this->anyChangeHandle(); this->groupHandle(pNf->objectName(), pNf->object()); } void AnalysisDataServiceObserver::_unGroupHandle( - const Poco::AutoPtr< - AnalysisDataServiceImpl::UnGroupingWorkspaceNotification> &pNf) { + const Poco::AutoPtr &pNf) { this->anyChangeHandle(); this->unGroupHandle(pNf->objectName(), pNf->object()); } void AnalysisDataServiceObserver::_groupUpdateHandle( - const Poco::AutoPtr - &pNf) { + const Poco::AutoPtr &pNf) { this->anyChangeHandle(); this->groupUpdateHandle(pNf->objectName(), pNf->object()); } diff --git a/Framework/API/src/Axis.cpp b/Framework/API/src/Axis.cpp index 4770a76b8e11335bfb1c9aeb040606429c193859..f109b162b2f58971662c36e4ed598722696129c6 100644 --- a/Framework/API/src/Axis.cpp +++ b/Framework/API/src/Axis.cpp @@ -15,9 +15,7 @@ namespace API { using std::size_t; /// Constructor -Axis::Axis() - : m_title(), - m_unit(Mantid::Kernel::UnitFactory::Instance().create("Empty")) {} +Axis::Axis() : m_title(), m_unit(Mantid::Kernel::UnitFactory::Instance().create("Empty")) {} /// Returns the user-defined title for this axis const std::string &Axis::title() const { return m_title; } @@ -51,8 +49,7 @@ const Kernel::Unit_sptr &Axis::setUnit(const std::string &unitName) { * @param verticalIndex :: The verticalIndex (used in RefAxis) * @returns The double value at the given index */ -double Axis::getValue(const std::size_t &index, - const std::size_t &verticalIndex) const { +double Axis::getValue(const std::size_t &index, const std::size_t &verticalIndex) const { return (*this)(index, verticalIndex); } diff --git a/Framework/API/src/BinEdgeAxis.cpp b/Framework/API/src/BinEdgeAxis.cpp index e28fc10f1aa0f6738bc0ce26173ab765a2fc1f33..bc99a3b66b9b58e8d2d32e132fb9959eb78819df 100644 --- a/Framework/API/src/BinEdgeAxis.cpp +++ b/Framework/API/src/BinEdgeAxis.cpp @@ -47,8 +47,7 @@ Axis *BinEdgeAxis::clone(const MatrixWorkspace *const parentWorkspace) { * @param parentWorkspace The workspace is not used in this implementation * @returns A pointer to a copy of the NumericAxis on which the method is called */ -Axis *BinEdgeAxis::clone(const std::size_t length, - const MatrixWorkspace *const parentWorkspace) { +Axis *BinEdgeAxis::clone(const std::size_t length, const MatrixWorkspace *const parentWorkspace) { UNUSED_ARG(parentWorkspace) auto *newAxis = new BinEdgeAxis(*this); newAxis->m_values.clear(); @@ -60,9 +59,7 @@ Axis *BinEdgeAxis::clone(const std::size_t length, * Return the values axis as they are * @return A vector containing the bin boundaries */ -std::vector BinEdgeAxis::createBinBoundaries() const { - return this->getValues(); -} +std::vector BinEdgeAxis::createBinBoundaries() const { return this->getValues(); } /** Sets the axis value at a given position * @param index :: The position along the axis for which to set the value @@ -72,8 +69,7 @@ std::vector BinEdgeAxis::createBinBoundaries() const { void BinEdgeAxis::setValue(const std::size_t &index, const double &value) { // Avoids setting edge information if (index >= length()) { - throw Kernel::Exception::IndexError(index, length() - 1, - "BinEdgeAxis: Index out of range."); + throw Kernel::Exception::IndexError(index, length() - 1, "BinEdgeAxis: Index out of range."); } m_values[index] = value; } @@ -88,5 +84,18 @@ size_t BinEdgeAxis::indexOfValue(const double value) const { return Mantid::Kernel::VectorHelper::indexOfValueFromEdges(m_values, value); } +/** Returns a text label which shows the value at the given bin index. + * Note that the bin index doesn't match the index in the value array for this + * type of axis. The value array has one more element than number of bins. + * @param index :: The bin index of the bin edge axis + * @return string of the center of that bin + * @throw IndexError if the bin index is out of range + */ +std::string BinEdgeAxis::label(const std::size_t &index) const { + if (index >= length() - 1) { + throw Kernel::Exception::IndexError(index, length() - 2, "BinEdgeAxis: Bin index out of range."); + } + return formatLabel(((*this)(index) + (*this)(index + 1)) / 2); +} } // namespace API } // namespace Mantid diff --git a/Framework/API/src/BoostOptionalToAlgorithmProperty.cpp b/Framework/API/src/BoostOptionalToAlgorithmProperty.cpp index ca6898c604e185cb9f9b3252aec7145f25743c84..35c37965eba47b690757b7d3ca6ba1c11b7b8a80 100644 --- a/Framework/API/src/BoostOptionalToAlgorithmProperty.cpp +++ b/Framework/API/src/BoostOptionalToAlgorithmProperty.cpp @@ -9,10 +9,9 @@ namespace Mantid { namespace API { template <> -std::string checkForMandatoryInstrumentDefault( - Mantid::API::Algorithm *const alg, const std::string &propName, - const Mantid::Geometry::Instrument_const_sptr &instrument, - const std::string &idf_name) { +std::string checkForMandatoryInstrumentDefault(Mantid::API::Algorithm *const alg, const std::string &propName, + const Mantid::Geometry::Instrument_const_sptr &instrument, + const std::string &idf_name) { auto algProperty = alg->getPointerToProperty(propName); if (algProperty->isDefault()) { auto defaults = instrument->getStringParameter(idf_name); @@ -28,10 +27,10 @@ std::string checkForMandatoryInstrumentDefault( } template <> -boost::optional checkForOptionalInstrumentDefault( - Mantid::API::Algorithm *const alg, const std::string &propName, - const Mantid::Geometry::Instrument_const_sptr &instrument, - const std::string &idf_name) { +boost::optional +checkForOptionalInstrumentDefault(Mantid::API::Algorithm *const alg, const std::string &propName, + const Mantid::Geometry::Instrument_const_sptr &instrument, + const std::string &idf_name) { auto algProperty = alg->getPointerToProperty(propName); if (algProperty->isDefault()) { auto defaults = instrument->getStringParameter(idf_name); diff --git a/Framework/API/src/BoxController.cpp b/Framework/API/src/BoxController.cpp index 862321c3ed7237d8cc461751dd9c19b93f5c51f9..3f48ab38f46eaadb32f3c2ee494a057d1871fa3d 100644 --- a/Framework/API/src/BoxController.cpp +++ b/Framework/API/src/BoxController.cpp @@ -41,25 +41,19 @@ BoxController *BoxController::clone() const { /*Private Copy constructor used in cloning */ BoxController::BoxController(const BoxController &other) - : nd(other.nd), m_maxId(other.m_maxId), - m_SplitThreshold(other.m_SplitThreshold), - m_significantEventsNumber(other.m_significantEventsNumber), - m_maxDepth(other.m_maxDepth), m_numEventsAtMax(other.m_numEventsAtMax), - m_splitInto(other.m_splitInto), m_splitTopInto(other.m_splitTopInto), + : nd(other.nd), m_maxId(other.m_maxId), m_SplitThreshold(other.m_SplitThreshold), + m_significantEventsNumber(other.m_significantEventsNumber), m_maxDepth(other.m_maxDepth), + m_numEventsAtMax(other.m_numEventsAtMax), m_splitInto(other.m_splitInto), m_splitTopInto(other.m_splitTopInto), m_numSplit(other.m_numSplit), m_numTopSplit(other.m_numTopSplit), m_addingEvents_eventsPerTask(other.m_addingEvents_eventsPerTask), - m_addingEvents_numTasksPerBlock(other.m_addingEvents_numTasksPerBlock), - m_numMDBoxes(other.m_numMDBoxes), - m_numMDGridBoxes(other.m_numMDGridBoxes), - m_maxNumMDBoxes(other.m_maxNumMDBoxes), + m_addingEvents_numTasksPerBlock(other.m_addingEvents_numTasksPerBlock), m_numMDBoxes(other.m_numMDBoxes), + m_numMDGridBoxes(other.m_numMDGridBoxes), m_maxNumMDBoxes(other.m_maxNumMDBoxes), m_fileIO(std::shared_ptr()) {} bool BoxController::operator==(const BoxController &other) const { - if (nd != other.nd || m_maxId != other.m_maxId || - m_SplitThreshold != other.m_SplitThreshold || + if (nd != other.nd || m_maxId != other.m_maxId || m_SplitThreshold != other.m_SplitThreshold || m_maxDepth != other.m_maxDepth || m_numSplit != other.m_numSplit || - m_splitInto.size() != other.m_splitInto.size() || - m_numMDBoxes.size() != other.m_numMDBoxes.size() || + m_splitInto.size() != other.m_splitInto.size() || m_numMDBoxes.size() != other.m_numMDBoxes.size() || m_numMDGridBoxes.size() != other.m_numMDGridBoxes.size() || m_maxNumMDBoxes.size() != other.m_maxNumMDBoxes.size()) return false; @@ -79,8 +73,7 @@ bool BoxController::operator==(const BoxController &other) const { } // Check top level splitting if they are set in both or not - if ((m_splitTopInto && !other.m_splitTopInto) || - (!m_splitTopInto && other.m_splitTopInto)) { + if ((m_splitTopInto && !other.m_splitTopInto) || (!m_splitTopInto && other.m_splitTopInto)) { return false; } @@ -143,40 +136,34 @@ std::string BoxController::toXMLString() const { std::string vecStr; element = pDoc->createElement("NumDims"); - text = - pDoc->createTextNode(boost::str(boost::format("%d") % this->getNDims())); + text = pDoc->createTextNode(boost::str(boost::format("%d") % this->getNDims())); element->appendChild(text); pBoxElement->appendChild(element); element = pDoc->createElement("MaxId"); - text = - pDoc->createTextNode(boost::str(boost::format("%d") % this->getMaxId())); + text = pDoc->createTextNode(boost::str(boost::format("%d") % this->getMaxId())); element->appendChild(text); pBoxElement->appendChild(element); element = pDoc->createElement("SplitThreshold"); - text = pDoc->createTextNode( - boost::str(boost::format("%d") % this->getSplitThreshold())); + text = pDoc->createTextNode(boost::str(boost::format("%d") % this->getSplitThreshold())); element->appendChild(text); pBoxElement->appendChild(element); element = pDoc->createElement("MaxDepth"); - text = pDoc->createTextNode( - boost::str(boost::format("%d") % this->getMaxDepth())); + text = pDoc->createTextNode(boost::str(boost::format("%d") % this->getMaxDepth())); element->appendChild(text); pBoxElement->appendChild(element); element = pDoc->createElement("SplitInto"); - vecStr = Kernel::Strings::join(this->m_splitInto.begin(), - this->m_splitInto.end(), ","); + vecStr = Kernel::Strings::join(this->m_splitInto.begin(), this->m_splitInto.end(), ","); text = pDoc->createTextNode(vecStr); element->appendChild(text); pBoxElement->appendChild(element); element = pDoc->createElement("SplitTopInto"); if (m_splitTopInto) { - vecStr = Kernel::Strings::join(this->m_splitTopInto.get().begin(), - this->m_splitTopInto.get().end(), ","); + vecStr = Kernel::Strings::join(this->m_splitTopInto.get().begin(), this->m_splitTopInto.get().end(), ","); } else { vecStr = ""; } @@ -185,15 +172,13 @@ std::string BoxController::toXMLString() const { pBoxElement->appendChild(element); element = pDoc->createElement("NumMDBoxes"); - vecStr = Kernel::Strings::join(this->m_numMDBoxes.begin(), - this->m_numMDBoxes.end(), ","); + vecStr = Kernel::Strings::join(this->m_numMDBoxes.begin(), this->m_numMDBoxes.end(), ","); text = pDoc->createTextNode(vecStr); element->appendChild(text); pBoxElement->appendChild(element); element = pDoc->createElement("NumMDGridBoxes"); - vecStr = Kernel::Strings::join(this->m_numMDGridBoxes.begin(), - this->m_numMDGridBoxes.end(), ","); + vecStr = Kernel::Strings::join(this->m_numMDGridBoxes.begin(), this->m_numMDGridBoxes.end(), ","); text = pDoc->createTextNode(vecStr); element->appendChild(text); pBoxElement->appendChild(element); @@ -216,9 +201,7 @@ std::string BoxController::getFilename() const { } /** the function left for compartibility with the previous bc python interface. @return true if the workspace is file based and false otherwise */ -bool BoxController::useWriteBuffer() const { - return static_cast(m_fileIO); -} +bool BoxController::useWriteBuffer() const { return static_cast(m_fileIO); } //------------------------------------------------------------------------------------------------------ /** Static method that sets the data inside this BoxController from an XML @@ -236,14 +219,12 @@ void BoxController::fromXMLString(const std::string &xml) { s = pBoxElement->getChildElement("NumDims")->innerText(); Strings::convert(s, nd); if (nd <= 0 || nd > 20) - throw std::runtime_error( - "BoxController::fromXMLString(): Bad number of dimensions found."); + throw std::runtime_error("BoxController::fromXMLString(): Bad number of dimensions found."); size_t ival; Strings::convert(pBoxElement->getChildElement("MaxId")->innerText(), ival); this->setMaxId(ival); - Strings::convert(pBoxElement->getChildElement("SplitThreshold")->innerText(), - ival); + Strings::convert(pBoxElement->getChildElement("SplitThreshold")->innerText(), ival); this->setSplitThreshold(ival); Strings::convert(pBoxElement->getChildElement("MaxDepth")->innerText(), ival); this->setMaxDepth(ival); @@ -254,8 +235,7 @@ void BoxController::fromXMLString(const std::string &xml) { // Need to make sure that we handle box controllers which did not have the // SplitTopInto // attribute - Poco::AutoPtr nodes = - pBoxElement->getElementsByTagName("SplitTopInto"); + Poco::AutoPtr nodes = pBoxElement->getElementsByTagName("SplitTopInto"); if (nodes->length() > 0) { s = pBoxElement->getChildElement("SplitTopInto")->innerText(); if (s.empty()) { @@ -296,15 +276,12 @@ void BoxController::clearFileBacked() { *@param fileName -- if newFileIO comes without opened file, this is the file *name to open for the file based IO operations */ -void BoxController::setFileBacked( - const std::shared_ptr &newFileIO, - const std::string &fileName) { +void BoxController::setFileBacked(const std::shared_ptr &newFileIO, const std::string &fileName) { if (!newFileIO->isOpened()) newFileIO->openFile(fileName, "w"); if (!newFileIO->isOpened()) { - throw(Kernel::Exception::FileError( - "Can not open target file for filebased box controller ", fileName)); + throw(Kernel::Exception::FileError("Can not open target file for filebased box controller ", fileName)); } this->m_fileIO = newFileIO; diff --git a/Framework/API/src/BoxControllerSettingsAlgorithm.cpp b/Framework/API/src/BoxControllerSettingsAlgorithm.cpp index 84a049a05b69ede3b0af926588808171e987249d..32e3f7c80917451d5de5b5870b2205b846515528 100644 --- a/Framework/API/src/BoxControllerSettingsAlgorithm.cpp +++ b/Framework/API/src/BoxControllerSettingsAlgorithm.cpp @@ -25,8 +25,8 @@ namespace API { * @param SplitThreshold :: default parameter value * @param MaxRecursionDepth :: default parameter value */ -void BoxControllerSettingsAlgorithm::initBoxControllerProps( - const std::string &SplitInto, int SplitThreshold, int MaxRecursionDepth) { +void BoxControllerSettingsAlgorithm::initBoxControllerProps(const std::string &SplitInto, int SplitThreshold, + int MaxRecursionDepth) { auto mustBePositive = std::make_shared>(); mustBePositive->setLower(0); auto mustBeMoreThen1 = std::make_shared>(); @@ -34,28 +34,23 @@ void BoxControllerSettingsAlgorithm::initBoxControllerProps( // Split up comma-separated properties using tokenizer = Mantid::Kernel::StringTokenizer; - tokenizer values(SplitInto, ",", - tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM); + tokenizer values(SplitInto, ",", tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM); std::vector valueVec; valueVec.reserve(values.count()); for (const auto &value : values) valueVec.emplace_back(boost::lexical_cast(value)); - declareProperty( - std::make_unique>("SplitInto", std::move(valueVec)), - "A comma separated list of into how many sub-grid elements each " - "dimension should split; " - "or just one to split into the same number for all dimensions. Default " + - SplitInto + "."); - - declareProperty( - std::make_unique>("SplitThreshold", SplitThreshold, - mustBePositive), - "How many events in a box before it should be split. Default " + - Strings::toString(SplitThreshold) + "."); - - declareProperty(std::make_unique>( - "MaxRecursionDepth", MaxRecursionDepth, mustBeMoreThen1), + declareProperty(std::make_unique>("SplitInto", std::move(valueVec)), + "A comma separated list of into how many sub-grid elements each " + "dimension should split; " + "or just one to split into the same number for all dimensions. Default " + + SplitInto + "."); + + declareProperty(std::make_unique>("SplitThreshold", SplitThreshold, mustBePositive), + "How many events in a box before it should be split. Default " + Strings::toString(SplitThreshold) + + "."); + + declareProperty(std::make_unique>("MaxRecursionDepth", MaxRecursionDepth, mustBeMoreThen1), "How many levels of box splitting recursion are allowed. " "The smallest box will have each side length :math:`l = " "(extents) / (SplitInto^{MaxRecursionDepth}).` " @@ -76,24 +71,20 @@ void BoxControllerSettingsAlgorithm::initBoxControllerProps( * @param ndims : Number of dimensions in output workspace. */ void BoxControllerSettingsAlgorithm::takeDefaultsFromInstrument( - const Mantid::Geometry::Instrument_const_sptr &instrument, - const size_t ndims) { + const Mantid::Geometry::Instrument_const_sptr &instrument, const size_t ndims) { const std::string splitThresholdName = "SplitThreshold"; const std::string splitIntoName = "SplitInto"; const std::string maxRecursionDepthName = "MaxRecursionDepth"; Property *p = getProperty(splitThresholdName); if (p->isDefault()) { - std::vector instrumentSplitThresholds = - instrument->getNumberParameter(splitThresholdName, true); + std::vector instrumentSplitThresholds = instrument->getNumberParameter(splitThresholdName, true); if (!instrumentSplitThresholds.empty()) { - setProperty(splitThresholdName, - static_cast(instrumentSplitThresholds.front())); + setProperty(splitThresholdName, static_cast(instrumentSplitThresholds.front())); } } p = getProperty(splitIntoName); if (p->isDefault()) { - std::vector instrumentSplitInto = - instrument->getNumberParameter(splitIntoName, true); + std::vector instrumentSplitInto = instrument->getNumberParameter(splitIntoName, true); if (!instrumentSplitInto.empty()) { const auto splitInto = static_cast(instrumentSplitInto.front()); std::vector newSplitInto(ndims, splitInto); @@ -102,11 +93,9 @@ void BoxControllerSettingsAlgorithm::takeDefaultsFromInstrument( } p = getProperty(maxRecursionDepthName); if (p->isDefault()) { - std::vector instrumentMaxRecursionDepth = - instrument->getNumberParameter(maxRecursionDepthName, true); + std::vector instrumentMaxRecursionDepth = instrument->getNumberParameter(maxRecursionDepthName, true); if (!instrumentMaxRecursionDepth.empty()) { - setProperty(maxRecursionDepthName, - static_cast(instrumentMaxRecursionDepth.front())); + setProperty(maxRecursionDepthName, static_cast(instrumentMaxRecursionDepth.front())); } } } @@ -118,9 +107,8 @@ void BoxControllerSettingsAlgorithm::takeDefaultsFromInstrument( * @param bc :: box controller to modify * @param instrument :: instrument to read parameters from. */ -void BoxControllerSettingsAlgorithm::setBoxController( - const BoxController_sptr &bc, - const Mantid::Geometry::Instrument_const_sptr &instrument) { +void BoxControllerSettingsAlgorithm::setBoxController(const BoxController_sptr &bc, + const Mantid::Geometry::Instrument_const_sptr &instrument) { size_t nd = bc->getNDims(); takeDefaultsFromInstrument(std::move(instrument), nd); @@ -134,8 +122,7 @@ void BoxControllerSettingsAlgorithm::setBoxController( * * @param bc :: box controller to modify */ -void BoxControllerSettingsAlgorithm::setBoxController( - const BoxController_sptr &bc) { +void BoxControllerSettingsAlgorithm::setBoxController(const BoxController_sptr &bc) { size_t nd = bc->getNDims(); int val; @@ -152,8 +139,7 @@ void BoxControllerSettingsAlgorithm::setBoxController( for (size_t d = 0; d < nd; ++d) bc->setSplitInto(d, splits[d]); } else - throw std::invalid_argument("SplitInto parameter has " + - Strings::toString(splits.size()) + + throw std::invalid_argument("SplitInto parameter has " + Strings::toString(splits.size()) + " arguments. It should have either 1, or the " "same as the number of dimensions."); bc->resetNumBoxes(); diff --git a/Framework/API/src/CatalogManager.cpp b/Framework/API/src/CatalogManager.cpp index 206cc2e905c9e4c38e85f7d2a1136d95060ab7ee..00b864c6a53e01632aed405f0d82b2cec3f0ed17 100644 --- a/Framework/API/src/CatalogManager.cpp +++ b/Framework/API/src/CatalogManager.cpp @@ -26,17 +26,11 @@ namespace API { * @param facility :: The facility of the catalog to log in to. * @return The session created if login was successful. */ -CatalogSession_sptr CatalogManagerImpl::login(const std::string &username, - const std::string &password, - const std::string &endpoint, - const std::string &facility) { - std::string className = Kernel::ConfigService::Instance() - .getFacility(facility) - .catalogInfo() - .catalogName(); +CatalogSession_sptr CatalogManagerImpl::login(const std::string &username, const std::string &password, + const std::string &endpoint, const std::string &facility) { + std::string className = Kernel::ConfigService::Instance().getFacility(facility).catalogInfo().catalogName(); auto catalog = CatalogFactory::Instance().create(className); - CatalogSession_sptr session = - catalog->login(username, password, endpoint, facility); + CatalogSession_sptr session = catalog->login(username, password, endpoint, facility); // Creates a new catalog and adds it to the compositeCatalog and activeCatalog // list. m_activeCatalogs.emplace(session, catalog); @@ -66,9 +60,7 @@ ICatalog_sptr CatalogManagerImpl::getCatalog(const std::string &sessionID) { const auto found = std::find_if(m_activeCatalogs.cbegin(), m_activeCatalogs.cend(), - [&sessionID](const auto &catalog) { - return catalog.first->getSessionId() == sessionID; - }); + [&sessionID](const auto &catalog) { return catalog.first->getSessionId() == sessionID; }); if (found == m_activeCatalogs.cend()) { throw std::runtime_error("The session ID you have provided is invalid."); } @@ -107,15 +99,12 @@ std::vector CatalogManagerImpl::getActiveSessions() { std::vector sessions; sessions.reserve(m_activeCatalogs.size()); - std::transform(m_activeCatalogs.begin(), m_activeCatalogs.end(), - std::back_inserter(sessions), + std::transform(m_activeCatalogs.begin(), m_activeCatalogs.end(), std::back_inserter(sessions), [](const auto &activeCatalog) { return activeCatalog.first; }); return sessions; } /// @returns An unsigned value indicating the number of active sessions -size_t CatalogManagerImpl::numberActiveSessions() const { - return m_activeCatalogs.size(); -} +size_t CatalogManagerImpl::numberActiveSessions() const { return m_activeCatalogs.size(); } } // namespace API } // namespace Mantid diff --git a/Framework/API/src/CatalogSession.cpp b/Framework/API/src/CatalogSession.cpp index 3e6f76f7abb531b9910265f142df11c9578173d3..604365a3b3d2076f11cf3227ee9320af5e270440 100644 --- a/Framework/API/src/CatalogSession.cpp +++ b/Framework/API/src/CatalogSession.cpp @@ -15,9 +15,7 @@ namespace API { * @param facility :: The facility of the catalog the user logged in to. * @param endpoint :: The endpoint of the catalog the user logged in to. */ -CatalogSession::CatalogSession(const std::string &sessionID, - const std::string &facility, - const std::string &endpoint) +CatalogSession::CatalogSession(const std::string &sessionID, const std::string &facility, const std::string &endpoint) : m_sessionID(sessionID), m_facility(facility), m_endpoint(endpoint) {} /** @@ -30,17 +28,13 @@ std::string CatalogSession::getSessionId() const { return m_sessionID; } * Used to clear the session ID on logout. * @param sessionID :: The value to set the session id. */ -void CatalogSession::setSessionId(const std::string &sessionID) { - m_sessionID = sessionID; -} +void CatalogSession::setSessionId(const std::string &sessionID) { m_sessionID = sessionID; } /** * Obtains the soap end-point of the catalog created. * @return The soap end-point used to create the catalog. */ -const std::string &CatalogSession::getSoapEndpoint() const { - return m_endpoint; -} +const std::string &CatalogSession::getSoapEndpoint() const { return m_endpoint; } /** * Obtain the facility of the catalog created. diff --git a/Framework/API/src/Citation.cpp b/Framework/API/src/Citation.cpp index 11e9ebeb4a666ed8135e535f0809dfdff72860c7..8fb4e056f4a1c2543edea2f2fa385115d0f844e8 100644 --- a/Framework/API/src/Citation.cpp +++ b/Framework/API/src/Citation.cpp @@ -28,39 +28,30 @@ namespace API { (there must be something there, even if this isn't citable a URL is better than nothing) */ -Citation::Citation(const std::string &doi, const std::string &bibtex, - const std::string &endnote, const std::string &url, - const std::string &description) - : m_doi(doi), m_bibtex(bibtex), m_endnote(endnote), m_url(url), - m_description(description) { - if (doi.empty() && bibtex.empty() && endnote.empty() && url.empty() && - description.empty()) +Citation::Citation(const std::string &doi, const std::string &bibtex, const std::string &endnote, + const std::string &url, const std::string &description) + : m_doi(doi), m_bibtex(bibtex), m_endnote(endnote), m_url(url), m_description(description) { + if (doi.empty() && bibtex.empty() && endnote.empty() && url.empty() && description.empty()) throw std::invalid_argument("No arguements were given!"); // This is an initial implementation that expects it but it should be possible // to generate one from the other - if ((!bibtex.empty() && endnote.empty()) || - (bibtex.empty() && !endnote.empty())) - throw std::invalid_argument( - "If bibtex is provided, endnote must also be provided and vice-versa"); + if ((!bibtex.empty() && endnote.empty()) || (bibtex.empty() && !endnote.empty())) + throw std::invalid_argument("If bibtex is provided, endnote must also be provided and vice-versa"); if (!doi.empty() && (bibtex.empty() || endnote.empty() || url.empty())) - throw std::invalid_argument( - "If doi is provided then url, bibtex and endnote must be"); + throw std::invalid_argument("If doi is provided then url, bibtex and endnote must be"); if (doi.empty() && bibtex.empty() && endnote.empty()) if (url.empty()) - throw std::invalid_argument( - "If none of doi, bibtex, or endnote is provided, then url must be"); + throw std::invalid_argument("If none of doi, bibtex, or endnote is provided, then url must be"); } -Citation::Citation(::NeXus::File *file, const std::string &group) { - loadNexus(file, group); -} +Citation::Citation(::NeXus::File *file, const std::string &group) { loadNexus(file, group); } bool Citation::operator==(const Citation &rhs) const { - return m_bibtex == rhs.m_bibtex && m_description == rhs.m_description && - m_doi == rhs.m_doi && m_endnote == rhs.m_endnote && m_url == rhs.m_url; + return m_bibtex == rhs.m_bibtex && m_description == rhs.m_description && m_doi == rhs.m_doi && + m_endnote == rhs.m_endnote && m_url == rhs.m_url; } const std::string &Citation::description() const { return m_description; } diff --git a/Framework/API/src/Column.cpp b/Framework/API/src/Column.cpp index 284608e92738bc7e80e81af6d1b9f2f1b77676a0..c53c746db0c22864c1306861acfc5de72e638891 100644 --- a/Framework/API/src/Column.cpp +++ b/Framework/API/src/Column.cpp @@ -27,12 +27,10 @@ template <> bool Column::isType() const { return isBool(); } /// X = 1, Y = 2, Z = 3, xErr = 4, yErr = 5, Label = 6 /// @param t plot type as defined above void Column::setPlotType(int t) { - if (t == -1000 || t == 0 || t == 1 || t == 2 || t == 3 || t == 4 || t == 5 || - t == 6) + if (t == -1000 || t == 0 || t == 1 || t == 2 || t == 3 || t == 4 || t == 5 || t == 6) m_plotType = t; else { - g_log.error() << "Cannot set plot of column to " << t - << " . Ignore this attempt.\n"; + g_log.error() << "Cannot set plot of column to " << t << " . Ignore this attempt.\n"; } } @@ -41,10 +39,8 @@ void Column::setLinkedYCol(const int yCol) { m_linkedYCol = yCol; } /** * No implementation by default. */ -void Column::sortIndex( - bool /*unused*/, size_t /*unused*/, size_t /*unused*/, - std::vector & /*unused*/, - std::vector> & /*unused*/) const { +void Column::sortIndex(bool /*unused*/, size_t /*unused*/, size_t /*unused*/, std::vector & /*unused*/, + std::vector> & /*unused*/) const { throw std::runtime_error("Cannot sort column of type " + m_type); } @@ -67,8 +63,7 @@ std::istream &operator>>(std::istream &istr, API::Boolean &b) { std::string buff; istr >> buff; std::transform(buff.begin(), buff.end(), buff.begin(), toupper); - if (buff == "TRUE" || buff == "1" || buff == "OK" || buff == "YES" || - buff == "ON") { + if (buff == "TRUE" || buff == "1" || buff == "OK" || buff == "YES" || buff == "ON") { b = true; } else { b = false; diff --git a/Framework/API/src/ColumnFactory.cpp b/Framework/API/src/ColumnFactory.cpp index 7003084500bf0116dfb31954c8709ee3321c9305..a7faa4b7a06da1bc5516ccd0cbd10a64df48ed1f 100644 --- a/Framework/API/src/ColumnFactory.cpp +++ b/Framework/API/src/ColumnFactory.cpp @@ -11,8 +11,7 @@ namespace Mantid { namespace API { -std::shared_ptr -ColumnFactoryImpl::create(const std::string &type) const { +std::shared_ptr ColumnFactoryImpl::create(const std::string &type) const { std::shared_ptr c = Kernel::DynamicFactory::create(type); c->m_type = type; return c; diff --git a/Framework/API/src/CommonBinsValidator.cpp b/Framework/API/src/CommonBinsValidator.cpp index 4d7e2ed1ce06316a836d796bbd2ad804a202692c..59b9110d85b0b2b762850561e4976f0a37fe0a26 100644 --- a/Framework/API/src/CommonBinsValidator.cpp +++ b/Framework/API/src/CommonBinsValidator.cpp @@ -11,17 +11,14 @@ namespace Mantid { namespace API { /// Clone the current state -Kernel::IValidator_sptr CommonBinsValidator::clone() const { - return std::make_shared(*this); -} +Kernel::IValidator_sptr CommonBinsValidator::clone() const { return std::make_shared(*this); } /** Checks that the bin boundaries of each histogram in the workspace are the * same * @param value :: The workspace to test * @return A message for users saying that bins are different, otherwise "" */ -std::string -CommonBinsValidator::checkValidity(const MatrixWorkspace_sptr &value) const { +std::string CommonBinsValidator::checkValidity(const MatrixWorkspace_sptr &value) const { if (!value) return "Enter an existing workspace"; if (value->isCommonBins()) diff --git a/Framework/API/src/CompositeCatalog.cpp b/Framework/API/src/CompositeCatalog.cpp index f838b719ca0c8c51905710f78fba0bcebee01ce4..15993dd7fccd287434a92b77bbe52d2ae56835ee 100644 --- a/Framework/API/src/CompositeCatalog.cpp +++ b/Framework/API/src/CompositeCatalog.cpp @@ -16,9 +16,7 @@ CompositeCatalog::CompositeCatalog() : m_catalogs() {} * Add a catalog to the catalog container. * @param catalog :: The catalog to add to the container. */ -void CompositeCatalog::add(const ICatalog_sptr &catalog) { - m_catalogs.emplace_back(catalog); -} +void CompositeCatalog::add(const ICatalog_sptr &catalog) { m_catalogs.emplace_back(catalog); } /** * Authenticate the user against all catalogues in the container. @@ -27,16 +25,13 @@ void CompositeCatalog::add(const ICatalog_sptr &catalog) { * @param endpoint :: The endpoint url of the catalog to log in to. * @param facility :: The facility of the catalog to log in to. */ -CatalogSession_sptr CompositeCatalog::login(const std::string &username, - const std::string &password, - const std::string &endpoint, - const std::string &facility) { +CatalogSession_sptr CompositeCatalog::login(const std::string &username, const std::string &password, + const std::string &endpoint, const std::string &facility) { UNUSED_ARG(username); UNUSED_ARG(password); UNUSED_ARG(endpoint); UNUSED_ARG(facility); - throw std::runtime_error( - "You cannot log into multiple catalogs at the same time."); + throw std::runtime_error("You cannot log into multiple catalogs at the same time."); } /** @@ -57,8 +52,7 @@ void CompositeCatalog::logout() { * point. * @param limit :: The limit of the number of rows returned by the query. */ -void CompositeCatalog::search(const ICat::CatalogSearchParam &inputs, - ITableWorkspace_sptr &outputws, const int &offset, +void CompositeCatalog::search(const ICat::CatalogSearchParam &inputs, ITableWorkspace_sptr &outputws, const int &offset, const int &limit) { for (auto &catalog : m_catalogs) { catalog->search(inputs, outputws, offset, limit); @@ -69,8 +63,7 @@ void CompositeCatalog::search(const ICat::CatalogSearchParam &inputs, * Obtain the number of investigations to be returned by the catalog. * @return The number of investigations from the search performed. */ -int64_t CompositeCatalog::getNumberOfSearchResults( - const ICat::CatalogSearchParam &inputs) { +int64_t CompositeCatalog::getNumberOfSearchResults(const ICat::CatalogSearchParam &inputs) { int64_t numberOfSearchResults = 0; for (auto &catalog : m_catalogs) { numberOfSearchResults += catalog->getNumberOfSearchResults(inputs); @@ -95,8 +88,7 @@ void CompositeCatalog::myData(ITableWorkspace_sptr &outputws) { * @param investigationId :: A unique identifier of the investigation. * @param outputws :: The workspace to store the results. */ -void CompositeCatalog::getDataSets(const std::string &investigationId, - ITableWorkspace_sptr &outputws) { +void CompositeCatalog::getDataSets(const std::string &investigationId, ITableWorkspace_sptr &outputws) { for (auto &catalog : m_catalogs) { catalog->getDataSets(investigationId, outputws); } @@ -108,8 +100,7 @@ void CompositeCatalog::getDataSets(const std::string &investigationId, * @param investigationId :: A unique identifier of the investigation. * @param outputws :: The workspace to store the results. */ -void CompositeCatalog::getDataFiles(const std::string &investigationId, - ITableWorkspace_sptr &outputws) { +void CompositeCatalog::getDataFiles(const std::string &investigationId, ITableWorkspace_sptr &outputws) { for (auto &catalog : m_catalogs) { catalog->getDataFiles(investigationId, outputws); } @@ -129,8 +120,7 @@ void CompositeCatalog::listInstruments(std::vector &instruments) { * Obtain a list of investigations from each catalog in the container. * @param invstTypes :: A reference to the vector to store the results. */ -void CompositeCatalog::listInvestigationTypes( - std::vector &invstTypes) { +void CompositeCatalog::listInvestigationTypes(std::vector &invstTypes) { for (auto &catalog : m_catalogs) { catalog->listInvestigationTypes(invstTypes); } diff --git a/Framework/API/src/CompositeDomainMD.cpp b/Framework/API/src/CompositeDomainMD.cpp index 6762e9be597c90814b65cba3a8147223193a11fa..548f809cee0a39629a2f33fe7cd3e0914bd6fd80 100644 --- a/Framework/API/src/CompositeDomainMD.cpp +++ b/Framework/API/src/CompositeDomainMD.cpp @@ -21,15 +21,13 @@ namespace API { * @param ws :: Pointer to a workspace. * @param maxDomainSize :: The maximum size each domain can have. */ -CompositeDomainMD::CompositeDomainMD(const IMDWorkspace_const_sptr &ws, - size_t maxDomainSize) +CompositeDomainMD::CompositeDomainMD(const IMDWorkspace_const_sptr &ws, size_t maxDomainSize) : m_iterator(ws->createIterator()) { m_totalSize = m_iterator->getDataSize(); size_t maxDomainSizeDiv = maxDomainSize + 1; if (maxDomainSizeDiv == 0) { - throw std::runtime_error( - "Attempted to use a maximum domain size that equals 0"); + throw std::runtime_error("Attempted to use a maximum domain size that equals 0"); } size_t nParts = m_totalSize / maxDomainSizeDiv; @@ -39,8 +37,7 @@ CompositeDomainMD::CompositeDomainMD(const IMDWorkspace_const_sptr &ws, m_domains[i] = std::make_unique(ws, start, maxDomainSize); } size_t start = (nParts - 1) * maxDomainSize; - m_domains.back() = - std::make_unique(ws, start, m_totalSize - start); + m_domains.back() = std::make_unique(ws, start, m_totalSize - start); } /** diff --git a/Framework/API/src/CompositeFunction.cpp b/Framework/API/src/CompositeFunction.cpp index b9e0742c3803f62c22cc797a98174bbe7f7983f6..fafbfe1c040b8a192c0a03feb30fd9acd7c94353 100644 --- a/Framework/API/src/CompositeFunction.cpp +++ b/Framework/API/src/CompositeFunction.cpp @@ -39,11 +39,9 @@ constexpr int NUMDEFAULTATTRIBUTES = 1; * function performs this operation. */ template -void replaceVariableIndexRange(std::vector &variableFunctionIndexList, - const size_t oldSize, const size_t newSize, +void replaceVariableIndexRange(std::vector &variableFunctionIndexList, const size_t oldSize, const size_t newSize, const T functionIndex) { - auto itFun = std::find(variableFunctionIndexList.begin(), - variableFunctionIndexList.end(), functionIndex); + auto itFun = std::find(variableFunctionIndexList.begin(), variableFunctionIndexList.end(), functionIndex); if (itFun != variableFunctionIndexList.end()) { if (oldSize > newSize) { variableFunctionIndexList.erase(itFun, itFun + oldSize - newSize); @@ -52,8 +50,7 @@ void replaceVariableIndexRange(std::vector &variableFunctionIndexList, } } else if (newSize > 0) { using std::placeholders::_1; - itFun = std::find_if(variableFunctionIndexList.begin(), - variableFunctionIndexList.end(), + itFun = std::find_if(variableFunctionIndexList.begin(), variableFunctionIndexList.end(), std::bind(std::greater(), _1, functionIndex)); variableFunctionIndexList.insert(itFun, newSize, functionIndex); } @@ -66,9 +63,7 @@ using std::size_t; DECLARE_FUNCTION(CompositeFunction) /// Default constructor -CompositeFunction::CompositeFunction() - : IFunction(), m_nParams(0), m_nAttributes(0), - m_iConstraintFunction(false) { +CompositeFunction::CompositeFunction() : IFunction(), m_nParams(0), m_nAttributes(0), m_iConstraintFunction(false) { createDefaultGlobalAttributes(); } @@ -97,8 +92,7 @@ void CompositeFunction::init() {} * Can be passed in by a CompositeFunction (eg MultiDomainFunction). * @return the string representation of the composite function */ -std::string CompositeFunction::writeToString( - const std::string &parentLocalAttributesStr) const { +std::string CompositeFunction::writeToString(const std::string &parentLocalAttributesStr) const { std::ostringstream ostr; // if empty just return function name @@ -106,8 +100,7 @@ std::string CompositeFunction::writeToString( return "name=" + name(); } - if (name() != "CompositeFunction" || - nGlobalAttributes() > NUMDEFAULTATTRIBUTES || + if (name() != "CompositeFunction" || nGlobalAttributes() > NUMDEFAULTATTRIBUTES || getAttribute(ATTNUMDERIV).asBool() || !parentLocalAttributesStr.empty()) { ostr << "composite=" << name(); std::vector attr = m_globalAttributeNames; @@ -127,12 +120,10 @@ std::string CompositeFunction::writeToString( ostr << '('; std::ostringstream localAttributesStr; for (const auto &localAttName : localAttr) { - const std::string localAttValue = - this->getLocalAttribute(i, localAttName).value(); + const std::string localAttValue = this->getLocalAttribute(i, localAttName).value(); if (!localAttValue.empty()) { // local attribute names are prefixed by dollar sign - localAttributesStr << ',' << '$' << localAttName << '=' - << localAttValue; + localAttributesStr << ',' << '$' << localAttName << '=' << localAttValue; } } ostr << fun->writeToString(localAttributesStr.str()); @@ -177,9 +168,8 @@ void CompositeFunction::setWorkspace(std::shared_ptr ws) { * @param startX :: A start of the fitting region. * @param endX :: An end of the fitting region. */ -void CompositeFunction::setMatrixWorkspace( - std::shared_ptr workspace, size_t wi, double startX, - double endX) { +void CompositeFunction::setMatrixWorkspace(std::shared_ptr workspace, size_t wi, double startX, + double endX) { for (size_t iFun = 0; iFun < nFunctions(); ++iFun) { m_functions[iFun]->setMatrixWorkspace(workspace, wi, startX, endX); } @@ -190,8 +180,7 @@ void CompositeFunction::setMatrixWorkspace( * @param values :: A FunctionValues instance for storing the calculated * values. */ -void CompositeFunction::function(const FunctionDomain &domain, - FunctionValues &values) const { +void CompositeFunction::function(const FunctionDomain &domain, FunctionValues &values) const { FunctionValues tmp(domain); values.zeroCalculated(); for (size_t iFun = 0; iFun < nFunctions(); ++iFun) { @@ -205,8 +194,7 @@ void CompositeFunction::function(const FunctionDomain &domain, * @param domain :: Function domain to get the arguments from. * @param jacobian :: A Jacobian to store the derivatives. */ -void CompositeFunction::functionDeriv(const FunctionDomain &domain, - Jacobian &jacobian) { +void CompositeFunction::functionDeriv(const FunctionDomain &domain, Jacobian &jacobian) { if (getAttribute(ATTNUMDERIV).asBool()) { calNumericalDeriv(domain, jacobian); } else { @@ -223,22 +211,18 @@ void CompositeFunction::functionDeriv(const FunctionDomain &domain, * @param explicitlySet :: A boolean falgging the parameter as explicitly set * (by user) */ -void CompositeFunction::setParameter(size_t i, const double &value, - bool explicitlySet) { +void CompositeFunction::setParameter(size_t i, const double &value, bool explicitlySet) { size_t iFun = functionIndex(i); - m_functions[iFun]->setParameter(i - m_paramOffsets[iFun], value, - explicitlySet); + m_functions[iFun]->setParameter(i - m_paramOffsets[iFun], value, explicitlySet); } /** Sets a new description to the i-th parameter. * @param i :: The parameter index * @param description :: The new description */ -void CompositeFunction::setParameterDescription( - size_t i, const std::string &description) { +void CompositeFunction::setParameterDescription(size_t i, const std::string &description) { size_t iFun = functionIndex(i); - m_functions[iFun]->setParameterDescription(i - m_paramOffsets[iFun], - description); + m_functions[iFun]->setParameterDescription(i - m_paramOffsets[iFun], description); } /** Get the i-th parameter. @@ -250,6 +234,13 @@ double CompositeFunction::getParameter(size_t i) const { return m_functions[iFun]->getParameter(i - m_paramOffsets[iFun]); } +/** Get the j-th parameter from the i-th function. + * @param i :: The function index + * @param j :: The i-th function's j-th parameter + * @return value of the requested parameter + */ +double CompositeFunction::getParameter(size_t i, size_t j) const { return m_functions[i]->getParameter(j); } + /** * Check if function has a parameter with a particular name. * @param name :: A name of a parameter. @@ -258,9 +249,7 @@ double CompositeFunction::getParameter(size_t i) const { bool CompositeFunction::hasParameter(const std::string &name) const { try { const auto [parameterName, index] = parseName(name); - return index < m_functions.size() - ? m_functions[index]->hasParameter(parameterName) - : false; + return index < m_functions.size() ? m_functions[index]->hasParameter(parameterName) : false; } catch (std::invalid_argument &) { return false; } @@ -273,14 +262,11 @@ bool CompositeFunction::hasParameter(const std::string &name) const { */ bool CompositeFunction::hasAttribute(const std::string &name) const { try { - if (std::find(m_globalAttributeNames.begin(), m_globalAttributeNames.end(), - name) != m_globalAttributeNames.end()) { + if (std::find(m_globalAttributeNames.begin(), m_globalAttributeNames.end(), name) != m_globalAttributeNames.end()) { return true; } const auto [attributeName, index] = parseName(name); - return index < m_functions.size() - ? m_functions[index]->hasAttribute(attributeName) - : false; + return index < m_functions.size() ? m_functions[index]->hasAttribute(attributeName) : false; } catch (std::invalid_argument &) { return false; } @@ -293,8 +279,7 @@ bool CompositeFunction::hasAttribute(const std::string &name) const { * @param explicitlySet :: A boolean flagging the parameter as explicitly set * (by user) */ -void CompositeFunction::setParameter(const std::string &name, - const double &value, bool explicitlySet) { +void CompositeFunction::setParameter(const std::string &name, const double &value, bool explicitlySet) { const auto [parameterName, index] = parseName(name); getFunction(index)->setParameter(parameterName, value, explicitlySet); } @@ -304,8 +289,7 @@ void CompositeFunction::setParameter(const std::string &name, * @param name :: The name of the parameter. * @param description :: The new description */ -void CompositeFunction::setParameterDescription( - const std::string &name, const std::string &description) { +void CompositeFunction::setParameterDescription(const std::string &name, const std::string &description) { const auto [parameterName, index] = parseName(name); getFunction(index)->setParameterDescription(parameterName, description); } @@ -324,19 +308,15 @@ double CompositeFunction::getParameter(const std::string &name) const { * Return a value of attribute attName * @param name :: Returns the named attribute */ -API::IFunction::Attribute -CompositeFunction::getAttribute(const std::string &name) const { +API::IFunction::Attribute CompositeFunction::getAttribute(const std::string &name) const { try { - if (std::find(m_globalAttributeNames.begin(), m_globalAttributeNames.end(), - name) != m_globalAttributeNames.end()) { + if (std::find(m_globalAttributeNames.begin(), m_globalAttributeNames.end(), name) != m_globalAttributeNames.end()) { return IFunction::getAttribute(name); } const auto [attributeName, index] = parseName(name); return m_functions[index]->getAttribute(attributeName); } catch (std::invalid_argument &) { - throw std::invalid_argument( - "ParamFunctionAttributeHolder::getAttribute - Unknown attribute '" + - name + "'"); + throw std::invalid_argument("ParamFunctionAttributeHolder::getAttribute - Unknown attribute '" + name + "'"); } } @@ -345,10 +325,8 @@ CompositeFunction::getAttribute(const std::string &name) const { * @param name :: The name of the attribute * @param value :: The value of the attribute */ -void CompositeFunction::setAttribute(const std::string &name, - const API::IFunction::Attribute &value) { - if (std::find(m_globalAttributeNames.begin(), m_globalAttributeNames.end(), - name) != m_globalAttributeNames.end()) { +void CompositeFunction::setAttribute(const std::string &name, const API::IFunction::Attribute &value) { + if (std::find(m_globalAttributeNames.begin(), m_globalAttributeNames.end(), name) != m_globalAttributeNames.end()) { return IFunction::setAttribute(name, value); } const auto [attributeName, index] = parseName(name); @@ -373,8 +351,7 @@ size_t CompositeFunction::nAttributes() const { */ size_t CompositeFunction::parameterIndex(const std::string &name) const { const auto [parameterName, index] = parseName(name); - return getFunction(index)->parameterIndex(parameterName) + - m_paramOffsets[index]; + return getFunction(index)->parameterIndex(parameterName) + m_paramOffsets[index]; } /// Returns the name of parameter @@ -383,8 +360,17 @@ size_t CompositeFunction::parameterIndex(const std::string &name) const { std::string CompositeFunction::parameterName(size_t i) const { const size_t iFun = functionIndex(i); std::ostringstream ostr; - ostr << 'f' << iFun << '.' - << m_functions[iFun]->parameterName(i - m_paramOffsets[iFun]); + ostr << 'f' << iFun << '.' << m_functions[iFun]->parameterName(i - m_paramOffsets[iFun]); + return ostr.str(); +} + +/// Returns the name of i-th function's j-th parameter +/// @param i :: The function index +/// @param j :: The local index of the parameter relative to the function index +/// @return The name of the parameter +std::string CompositeFunction::parameterName(size_t i, size_t j) const { + std::ostringstream ostr; + ostr << 'f' << i << '.' << m_functions[i]->parameterName(j); return ostr.str(); } @@ -399,9 +385,7 @@ std::string CompositeFunction::attributeName(size_t index) const { const size_t offsetIndex = index - nGlobalAttributes(); size_t functionIndex = attributeFunctionIndex(offsetIndex); std::ostringstream ostr; - ostr << 'f' << functionIndex << '.' - << m_functions[functionIndex]->attributeName( - getAttributeOffset(offsetIndex)); + ostr << 'f' << functionIndex << '.' << m_functions[functionIndex]->attributeName(getAttributeOffset(offsetIndex)); return ostr.str(); } @@ -423,6 +407,13 @@ double CompositeFunction::getError(size_t i) const { size_t iFun = functionIndex(i); return m_functions[iFun]->getError(i - m_paramOffsets[iFun]); } +/** + * Get the fitting error for the i-th function's j-th parameter + * @param i :: The index of the i-th function + * @param j :: The index of the i-th function's j-th parameter + * @return :: the error + */ +double CompositeFunction::getError(size_t i, size_t j) const { return m_functions[i]->getError(j); } /** * Get the fitting error for a parameter by name. @@ -472,8 +463,7 @@ void CompositeFunction::setActiveParameter(size_t i, double value) { std::string CompositeFunction::nameOfActive(size_t i) const { size_t iFun = functionIndex(i); std::ostringstream ostr; - ostr << 'f' << iFun << '.' - << m_functions[iFun]->nameOfActive(i - m_paramOffsets[iFun]); + ostr << 'f' << iFun << '.' << m_functions[iFun]->nameOfActive(i - m_paramOffsets[iFun]); return ostr.str(); } @@ -486,15 +476,13 @@ std::string CompositeFunction::descriptionOfActive(size_t i) const { } /// Change status of parameter -void CompositeFunction::setParameterStatus(size_t i, - IFunction::ParameterStatus status) { +void CompositeFunction::setParameterStatus(size_t i, IFunction::ParameterStatus status) { size_t iFun = functionIndex(i); m_functions[iFun]->setParameterStatus(i - m_paramOffsets[iFun], status); } /// Get status of parameter -IFunction::ParameterStatus -CompositeFunction::getParameterStatus(size_t i) const { +IFunction::ParameterStatus CompositeFunction::getParameterStatus(size_t i) const { size_t iFun = functionIndex(i); return m_functions[iFun]->getParameterStatus(i - m_paramOffsets[iFun]); } @@ -537,8 +525,7 @@ void CompositeFunction::clear() { */ size_t CompositeFunction::addFunction(IFunction_sptr f) { m_IFunction.insert(m_IFunction.end(), f->nParams(), m_functions.size()); - m_attributeIndex.insert(m_attributeIndex.end(), f->nAttributes(), - m_functions.size()); + m_attributeIndex.insert(m_attributeIndex.end(), f->nAttributes(), m_functions.size()); m_functions.emplace_back(f); if (m_paramOffsets.empty()) { m_paramOffsets.emplace_back(0); @@ -557,8 +544,7 @@ size_t CompositeFunction::addFunction(IFunction_sptr f) { */ void CompositeFunction::removeFunction(size_t i) { if (i >= nFunctions()) { - throw std::out_of_range("Function index (" + std::to_string(i) + - ") out of range (" + std::to_string(nFunctions()) + + throw std::out_of_range("Function index (" + std::to_string(i) + ") out of range (" + std::to_string(nFunctions()) + ")."); } @@ -585,11 +571,8 @@ void CompositeFunction::removeFunction(size_t i) { } }; - m_IFunction.erase( - std::remove_if(m_IFunction.begin(), m_IFunction.end(), shiftDown), - m_IFunction.end()); - m_attributeIndex.erase(std::remove_if(m_attributeIndex.begin(), - m_attributeIndex.end(), shiftDown), + m_IFunction.erase(std::remove_if(m_IFunction.begin(), m_IFunction.end(), shiftDown), m_IFunction.end()); + m_attributeIndex.erase(std::remove_if(m_attributeIndex.begin(), m_attributeIndex.end(), shiftDown), m_attributeIndex.end()); // Reduction in parameters and attributes @@ -612,10 +595,8 @@ void CompositeFunction::removeFunction(size_t i) { * a member of this composite function nothing happens * @param f_new :: A pointer to the new function */ -void CompositeFunction::replaceFunctionPtr(const IFunction_sptr &f_old, - const IFunction_sptr &f_new) { - std::vector::const_iterator it = - std::find(m_functions.begin(), m_functions.end(), f_old); +void CompositeFunction::replaceFunctionPtr(const IFunction_sptr &f_old, const IFunction_sptr &f_new) { + std::vector::const_iterator it = std::find(m_functions.begin(), m_functions.end(), f_old); if (it == m_functions.end()) return; std::vector::difference_type iFun = it - m_functions.begin(); @@ -626,12 +607,10 @@ void CompositeFunction::replaceFunctionPtr(const IFunction_sptr &f_old, * @param functionIndex :: The index of the function to replace * @param f :: A pointer to the new function */ -void CompositeFunction::replaceFunction(size_t functionIndex, - const IFunction_sptr &f) { +void CompositeFunction::replaceFunction(size_t functionIndex, const IFunction_sptr &f) { if (functionIndex >= nFunctions()) { - throw std::out_of_range("Function index (" + std::to_string(functionIndex) + - ") out of range (" + std::to_string(nFunctions()) + - ")."); + throw std::out_of_range("Function index (" + std::to_string(functionIndex) + ") out of range (" + + std::to_string(nFunctions()) + ")."); } const IFunction_sptr fun = getFunction(functionIndex); @@ -658,19 +637,46 @@ void CompositeFunction::replaceFunction(size_t functionIndex, m_functions[functionIndex] = f; } +/** + * @param functionName :: The function name to search for. + * @returns true if the composite function has at least one of a function with a + * matching name. + */ +bool CompositeFunction::hasFunction(const std::string &functionName) const { + return std::any_of(m_functions.cbegin(), m_functions.cend(), [&functionName](const IFunction_const_sptr &function) { + return function->name() == functionName; + }); +} + /** * @param i :: The index of the function * @return function at the requested index */ IFunction_sptr CompositeFunction::getFunction(std::size_t i) const { if (i >= nFunctions()) { - throw std::out_of_range("Function index (" + std::to_string(i) + - ") out of range (" + std::to_string(nFunctions()) + + throw std::out_of_range("Function index (" + std::to_string(i) + ") out of range (" + std::to_string(nFunctions()) + ")."); } return m_functions[i]; } +/** + * Gets the index of the first function with a matching function string. + * @param functionName :: The name of the function to search for. + * @returns function index of the first function with a matching function + * string. + */ +std::size_t CompositeFunction::functionIndex(const std::string &functionName) const { + const auto iter = + std::find_if(m_functions.cbegin(), m_functions.cend(), + [&functionName](const IFunction_const_sptr &function) { return function->name() == functionName; }); + + if (iter != m_functions.cend()) + return std::distance(m_functions.cbegin(), iter); + + throw std::invalid_argument("A function with name '" + functionName + "' does not exist in this composite function."); +} + /** * Get the index of the function to which parameter i belongs * @param i :: The parameter index @@ -678,9 +684,8 @@ IFunction_sptr CompositeFunction::getFunction(std::size_t i) const { */ size_t CompositeFunction::functionIndex(std::size_t i) const { if (i >= nParams()) { - throw std::out_of_range("Function parameter index (" + std::to_string(i) + - ") out of range (" + std::to_string(nParams()) + - ")."); + throw std::out_of_range("Function parameter index (" + std::to_string(i) + ") out of range (" + + std::to_string(nParams()) + ")."); } return m_IFunction[i]; } @@ -691,9 +696,8 @@ size_t CompositeFunction::functionIndex(std::size_t i) const { */ size_t CompositeFunction::attributeFunctionIndex(std::size_t i) const { if (i >= nAttributes()) { - throw std::out_of_range("Function attribute index (" + std::to_string(i) + - ") out of range (" + std::to_string(nAttributes()) + - ")."); + throw std::out_of_range("Function attribute index (" + std::to_string(i) + ") out of range (" + + std::to_string(nAttributes()) + ")."); } return m_attributeIndex[i]; } @@ -703,15 +707,13 @@ size_t CompositeFunction::attributeFunctionIndex(std::size_t i) const { * [f]name ) * @return pair containing the unprefixed variable name and functionIndex */ -std::pair -CompositeFunction::parseName(const std::string &varName) { +std::pair CompositeFunction::parseName(const std::string &varName) { const size_t i = varName.find('.'); if (i == std::string::npos) { throw std::invalid_argument("Variable " + varName + " not found."); } else { if (varName[0] != 'f') - throw std::invalid_argument( - "External function variable name must start with 'f'"); + throw std::invalid_argument("External function variable name must start with 'f'"); const std::string sindex = varName.substr(1, i - 1); const size_t index = boost::lexical_cast(sindex); @@ -747,8 +749,7 @@ size_t CompositeFunction::parameterLocalIndex(size_t i, bool recursive) const { * a non-composite function is reached. * @return The pure parameter name (without the function identifier f#.) */ -std::string CompositeFunction::parameterLocalName(size_t i, - bool recursive) const { +std::string CompositeFunction::parameterLocalName(size_t i, bool recursive) const { size_t iFun = functionIndex(i); auto localIndex = i - m_paramOffsets[iFun]; auto localFunction = m_functions[iFun].get(); @@ -818,26 +819,31 @@ ParameterTie *CompositeFunction::getTie(size_t i) const { * @param initValue :: The initial value for the parameter * @param description :: Parameter documentation */ -void CompositeFunction::declareParameter(const std::string &name, - double initValue, - const std::string &description) { +void CompositeFunction::declareParameter(const std::string &name, double initValue, const std::string &description) { (void)name; // Avoid compiler warning (void)initValue; // Avoid compiler warning (void)description; // Avoid compiler warning - throw Kernel::Exception::NotImplementedError( - "CompositeFunction cannot not have its own parameters."); + throw Kernel::Exception::NotImplementedError("CompositeFunction cannot not have its own parameters."); } /** * Declares a single (global) attribute on the composite function * @param name :: The name of the attribute * @param defaultValue :: A default value */ -void CompositeFunction::declareAttribute( - const std::string &name, const API::IFunction::Attribute &defaultValue) { +void CompositeFunction::declareAttribute(const std::string &name, const API::IFunction::Attribute &defaultValue) { m_globalAttributeNames.emplace_back(name); IFunction::declareAttribute(name, defaultValue); } +/** +Registers the usage of the function with the UsageService + */ +void CompositeFunction::registerFunctionUsage(bool internal) { + for (size_t i = 0; i < nFunctions(); i++) { + getFunction(i)->registerFunctionUsage(internal); + } +} + /** * Prepare the function for a fit. */ @@ -904,8 +910,7 @@ bool CompositeFunction::isExplicitlySet(size_t i) const { * @param ref :: A reference to a parameter * @return Parameter index or number of nParams() if parameter not found */ -size_t -CompositeFunction::getParameterIndex(const ParameterReference &ref) const { +size_t CompositeFunction::getParameterIndex(const ParameterReference &ref) const { if (ref.getLocalFunction() == this && ref.getLocalIndex() < nParams()) { return ref.getLocalIndex(); } @@ -924,8 +929,7 @@ CompositeFunction::getParameterIndex(const ParameterReference &ref) const { * @param ref :: The reference * @return A function containing parameter pointed to by ref */ -IFunction_sptr -CompositeFunction::getContainingFunction(const ParameterReference &ref) const { +IFunction_sptr CompositeFunction::getContainingFunction(const ParameterReference &ref) const { for (size_t iFun = 0; iFun < nFunctions(); iFun++) { IFunction_sptr fun = getFunction(iFun); if (fun->getParameterIndex(ref) < fun->nParams()) { @@ -956,12 +960,10 @@ size_t CompositeFunction::getNumberDomains() const { /// working on (== getNumberDomains()). The result of evaluation of the /// created functions on their domains must be the same as if this function /// was evaluated on the composition of those domains. -std::vector -CompositeFunction::createEquivalentFunctions() const { +std::vector CompositeFunction::createEquivalentFunctions() const { auto nd = getNumberDomains(); if (nd == 1) { - return std::vector( - 1, FunctionFactory::Instance().createInitialized(asString())); + return std::vector(1, FunctionFactory::Instance().createInitialized(asString())); } auto nf = nFunctions(); @@ -984,8 +986,7 @@ CompositeFunction::createEquivalentFunctions() const { } size_t CompositeFunction::getAttributeOffset(size_t attributeIndex) const { auto functionIndex = m_attributeIndex[attributeIndex]; - return std::distance(std::find(m_attributeIndex.begin(), - m_attributeIndex.end(), functionIndex), + return std::distance(std::find(m_attributeIndex.begin(), m_attributeIndex.end(), functionIndex), m_attributeIndex.begin() + attributeIndex); } diff --git a/Framework/API/src/ConstraintFactory.cpp b/Framework/API/src/ConstraintFactory.cpp index 95f9356ab4dc1d50235d3ae197b5198b1620b298..5625947b8911844e17d14e35d3864d2d05b323e4 100644 --- a/Framework/API/src/ConstraintFactory.cpp +++ b/Framework/API/src/ConstraintFactory.cpp @@ -13,8 +13,7 @@ namespace Mantid { namespace API { -ConstraintFactoryImpl::ConstraintFactoryImpl() - : Kernel::DynamicFactory() { +ConstraintFactoryImpl::ConstraintFactoryImpl() : Kernel::DynamicFactory() { // we need to make sure the library manager has been loaded before we // are constructed so that it is destroyed after us and thus does // not close any loaded DLLs with loaded algorithms in them @@ -30,9 +29,7 @@ ConstraintFactoryImpl::ConstraintFactoryImpl() * @param isDefault :: Is this initialization a default one? * @return A pointer to the created Constraint */ -IConstraint *ConstraintFactoryImpl::createInitialized(IFunction *fun, - const std::string &input, - bool isDefault) const { +IConstraint *ConstraintFactoryImpl::createInitialized(IFunction *fun, const std::string &input, bool isDefault) const { Expression expr; expr.parse(input); return createInitialized(fun, expr, isDefault); @@ -44,9 +41,7 @@ IConstraint *ConstraintFactoryImpl::createInitialized(IFunction *fun, * @param isDefault :: Is this initialization a default one? * @return A pointer to the created Constraint */ -IConstraint *ConstraintFactoryImpl::createInitialized(IFunction *fun, - const Expression &expr, - bool isDefault) const { +IConstraint *ConstraintFactoryImpl::createInitialized(IFunction *fun, const Expression &expr, bool isDefault) const { IConstraint *c = nullptr; if (expr.name() == "==") { c = createUnwrapped("BoundaryConstraint"); diff --git a/Framework/API/src/CoordTransform.cpp b/Framework/API/src/CoordTransform.cpp index 03a9a2e914700250a96eacb096b46ad15444d1e7..ebfd3caa430f5062f9b7f364620acb726ea07d70 100644 --- a/Framework/API/src/CoordTransform.cpp +++ b/Framework/API/src/CoordTransform.cpp @@ -26,17 +26,14 @@ namespace API { * @param outD :: output number of dimensions, <= inD * @throw std::runtime_error if outD > inD */ -CoordTransform::CoordTransform(const size_t inD, const size_t outD) - : inD(inD), outD(outD) { +CoordTransform::CoordTransform(const size_t inD, const size_t outD) : inD(inD), outD(outD) { if (outD > inD) throw std::runtime_error("CoordTransform: Cannot have more output " "dimensions than input dimensions!"); if (outD == 0) - throw std::runtime_error( - "CoordTransform: invalid number of output dimensions!"); + throw std::runtime_error("CoordTransform: invalid number of output dimensions!"); if (inD == 0) - throw std::runtime_error( - "CoordTransform: invalid number of input dimensions!"); + throw std::runtime_error("CoordTransform: invalid number of input dimensions!"); } //---------------------------------------------------------------------------------------------- @@ -46,8 +43,7 @@ CoordTransform::CoordTransform(const size_t inD, const size_t outD) * @param inputVector :: an inD-length vector * @return the output vector as VMD */ -Mantid::Kernel::VMD -CoordTransform::applyVMD(const Mantid::Kernel::VMD &inputVector) const { +Mantid::Kernel::VMD CoordTransform::applyVMD(const Mantid::Kernel::VMD &inputVector) const { if (inputVector.getNumDims() != inD) throw std::runtime_error("CoordTransform::apply(): inputVector has the " "wrong number of coordinates!"); diff --git a/Framework/API/src/CostFunctionFactory.cpp b/Framework/API/src/CostFunctionFactory.cpp index 759e407921be0a0ae2cecc211f005017ad4c8623..c10102ca8a961aefa6def6118bde5914c8e21e3e 100644 --- a/Framework/API/src/CostFunctionFactory.cpp +++ b/Framework/API/src/CostFunctionFactory.cpp @@ -11,8 +11,7 @@ namespace Mantid { namespace API { -CostFunctionFactoryImpl::CostFunctionFactoryImpl() - : Kernel::DynamicFactory() { +CostFunctionFactoryImpl::CostFunctionFactoryImpl() : Kernel::DynamicFactory() { // we need to make sure the library manager has been loaded before we // are constructed so that it is destroyed after us and thus does // not close any loaded DLLs with loaded algorithms in them diff --git a/Framework/API/src/DataProcessorAlgorithm.cpp b/Framework/API/src/DataProcessorAlgorithm.cpp index 687aeab175775bab89d1b187945b9f3c73d4b569..685535653b5c2efef8a0e7e1fb51c44bf32ab0c2 100644 --- a/Framework/API/src/DataProcessorAlgorithm.cpp +++ b/Framework/API/src/DataProcessorAlgorithm.cpp @@ -36,8 +36,7 @@ namespace API { */ template GenericDataProcessorAlgorithm::GenericDataProcessorAlgorithm() - : m_useMPI(false), m_loadAlg("Load"), m_accumulateAlg("Plus"), - m_loadAlgFileProp("Filename"), + : m_useMPI(false), m_loadAlg("Load"), m_accumulateAlg("Plus"), m_loadAlgFileProp("Filename"), m_propertyManagerPropertyName("ReductionProperties") { Base::enableHistoryRecordingForChild(true); } @@ -65,12 +64,11 @@ GenericDataProcessorAlgorithm::GenericDataProcessorAlgorithm() */ template std::shared_ptr -GenericDataProcessorAlgorithm::createChildAlgorithm( - const std::string &name, const double startProgress, - const double endProgress, const bool enableLogging, const int &version) { +GenericDataProcessorAlgorithm::createChildAlgorithm(const std::string &name, const double startProgress, + const double endProgress, const bool enableLogging, + const int &version) { // call parent method to create the child algorithm - auto alg = Algorithm::createChildAlgorithm(name, startProgress, endProgress, - enableLogging, version); + auto alg = Algorithm::createChildAlgorithm(name, startProgress, endProgress, enableLogging, version); alg->enableHistoryRecordingForChild(this->isRecordingHistoryForChild()); if (this->isRecordingHistoryForChild()) { // pass pointer to the history object created in Algorithm to the child @@ -79,34 +77,26 @@ GenericDataProcessorAlgorithm::createChildAlgorithm( return alg; } -template -void GenericDataProcessorAlgorithm::setLoadAlg(const std::string &alg) { +template void GenericDataProcessorAlgorithm::setLoadAlg(const std::string &alg) { if (alg.empty()) throw std::invalid_argument("Cannot set load algorithm to empty string"); m_loadAlg = alg; } -template -void GenericDataProcessorAlgorithm::setLoadAlgFileProp( - const std::string &filePropName) { +template void GenericDataProcessorAlgorithm::setLoadAlgFileProp(const std::string &filePropName) { if (filePropName.empty()) { - throw std::invalid_argument( - "Cannot set the load algorithm file property name"); + throw std::invalid_argument("Cannot set the load algorithm file property name"); } m_loadAlgFileProp = filePropName; } -template -void GenericDataProcessorAlgorithm::setAccumAlg(const std::string &alg) { +template void GenericDataProcessorAlgorithm::setAccumAlg(const std::string &alg) { if (alg.empty()) - throw std::invalid_argument( - "Cannot set accumulate algorithm to empty string"); + throw std::invalid_argument("Cannot set accumulate algorithm to empty string"); m_accumulateAlg = alg; } -template -void GenericDataProcessorAlgorithm::setPropManagerPropName( - const std::string &propName) { +template void GenericDataProcessorAlgorithm::setPropManagerPropName(const std::string &propName) { m_propertyManagerPropertyName = propName; } @@ -119,8 +109,8 @@ void GenericDataProcessorAlgorithm::setPropManagerPropName( * @param nameInPropManager Name of the property in the PropertyManager. */ template -void GenericDataProcessorAlgorithm::mapPropertyName( - const std::string &nameInProp, const std::string &nameInPropManager) { +void GenericDataProcessorAlgorithm::mapPropertyName(const std::string &nameInProp, + const std::string &nameInPropManager) { m_nameToPMName[nameInProp] = nameInPropManager; } @@ -136,18 +126,15 @@ void GenericDataProcessorAlgorithm::mapPropertyName( * @throws std::runtime_error If you ask to copy a non-existent property */ template -void GenericDataProcessorAlgorithm::copyProperty( - const API::Algorithm_sptr &alg, const std::string &name) { +void GenericDataProcessorAlgorithm::copyProperty(const API::Algorithm_sptr &alg, const std::string &name) { if (!alg->existsProperty(name)) { std::stringstream msg; - msg << "Algorithm \"" << alg->name() << "\" does not have property \"" - << name << "\""; + msg << "Algorithm \"" << alg->name() << "\" does not have property \"" << name << "\""; throw std::runtime_error(msg.str()); } auto prop = alg->getPointerToProperty(name); - Base::declareProperty(std::unique_ptr(prop->clone()), - prop->documentation()); + Base::declareProperty(std::unique_ptr(prop->clone()), prop->documentation()); } /** @@ -158,9 +145,7 @@ void GenericDataProcessorAlgorithm::copyProperty( * @param name * @return */ -template -std::string GenericDataProcessorAlgorithm::getPropertyValue( - const std::string &name) const { +template std::string GenericDataProcessorAlgorithm::getPropertyValue(const std::string &name) const { // explicitly specifying a property wins if (!Base::isDefault(name)) { return Algorithm::getPropertyValue(name); @@ -187,9 +172,7 @@ std::string GenericDataProcessorAlgorithm::getPropertyValue( * @return */ template -PropertyManagerOwner::TypedValue -GenericDataProcessorAlgorithm::getProperty( - const std::string &name) const { +PropertyManagerOwner::TypedValue GenericDataProcessorAlgorithm::getProperty(const std::string &name) const { // explicitely specifying a property wins if (!Base::isDefault(name)) { return Base::getProperty(name); @@ -209,21 +192,16 @@ GenericDataProcessorAlgorithm::getProperty( } template -ITableWorkspace_sptr GenericDataProcessorAlgorithm::determineChunk( - const std::string &filename) { +ITableWorkspace_sptr GenericDataProcessorAlgorithm::determineChunk(const std::string &filename) { UNUSED_ARG(filename); - throw std::runtime_error( - "DataProcessorAlgorithm::determineChunk is not implemented"); + throw std::runtime_error("DataProcessorAlgorithm::determineChunk is not implemented"); } -template -MatrixWorkspace_sptr -GenericDataProcessorAlgorithm::loadChunk(const size_t rowIndex) { +template MatrixWorkspace_sptr GenericDataProcessorAlgorithm::loadChunk(const size_t rowIndex) { UNUSED_ARG(rowIndex); - throw std::runtime_error( - "DataProcessorAlgorithm::loadChunk is not implemented"); + throw std::runtime_error("DataProcessorAlgorithm::loadChunk is not implemented"); } /** @@ -231,12 +209,10 @@ GenericDataProcessorAlgorithm::loadChunk(const size_t rowIndex) { * @param partialWS :: workspace to assemble * thread only) */ -template -Workspace_sptr -GenericDataProcessorAlgorithm::assemble(Workspace_sptr partialWS) { +template Workspace_sptr GenericDataProcessorAlgorithm::assemble(Workspace_sptr partialWS) { Workspace_sptr outputWS = std::move(partialWS); #ifdef MPI_BUILD - IAlgorithm_sptr gatherAlg = createChildAlgorithm("GatherWorkspaces"); + auto gatherAlg = createChildAlgorithm("GatherWorkspaces"); gatherAlg->setLogging(true); gatherAlg->setAlwaysStoreInADS(true); gatherAlg->setProperty("InputWorkspace", partialWS); @@ -259,14 +235,12 @@ GenericDataProcessorAlgorithm::assemble(Workspace_sptr partialWS) { * thread only) */ template -Workspace_sptr -GenericDataProcessorAlgorithm::assemble(const std::string &partialWSName, - const std::string &outputWSName) { +Workspace_sptr GenericDataProcessorAlgorithm::assemble(const std::string &partialWSName, + [[maybe_unused]] const std::string &outputWSName) { #ifdef MPI_BUILD std::string threadOutput = partialWSName; - Workspace_sptr partialWS = - AnalysisDataService::Instance().retrieve(partialWSName); - IAlgorithm_sptr gatherAlg = createChildAlgorithm("GatherWorkspaces"); + Workspace_sptr partialWS = AnalysisDataService::Instance().retrieve(partialWSName); + auto gatherAlg = createChildAlgorithm("GatherWorkspaces"); gatherAlg->setLogging(true); gatherAlg->setAlwaysStoreInADS(true); gatherAlg->setProperty("InputWorkspace", partialWS); @@ -277,12 +251,10 @@ GenericDataProcessorAlgorithm::assemble(const std::string &partialWSName, if (isMainThread()) threadOutput = outputWSName; #else - UNUSED_ARG(outputWSName) const std::string &threadOutput = partialWSName; #endif - Workspace_sptr outputWS = - AnalysisDataService::Instance().retrieve(threadOutput); + Workspace_sptr outputWS = AnalysisDataService::Instance().retrieve(threadOutput); return outputWS; } @@ -293,14 +265,13 @@ GenericDataProcessorAlgorithm::assemble(const std::string &partialWSName, * @param outputFile :: Path to the Nexus file to save */ template -void GenericDataProcessorAlgorithm::saveNexus( - const std::string &outputWSName, const std::string &outputFile) { +void GenericDataProcessorAlgorithm::saveNexus(const std::string &outputWSName, const std::string &outputFile) { #ifdef MPI_BUILD if (boost::mpi::communicator().rank() <= 0 && !outputFile.empty()) { #else if (!outputFile.empty()) { #endif - IAlgorithm_sptr saveAlg = createChildAlgorithm("SaveNexus"); + auto saveAlg = createChildAlgorithm("SaveNexus"); saveAlg->setPropertyValue("Filename", outputFile); saveAlg->setPropertyValue("InputWorkspace", outputWSName); saveAlg->execute(); @@ -333,9 +304,7 @@ template int GenericDataProcessorAlgorithm::getNThreads() { * @param loadQuiet :: If true then the output is not stored in the ADS */ template -Workspace_sptr -GenericDataProcessorAlgorithm::load(const std::string &inputData, - const bool loadQuiet) { +Workspace_sptr GenericDataProcessorAlgorithm::load(const std::string &inputData, const bool loadQuiet) { Workspace_sptr inputWS; // First, check whether we have the name of an existing workspace @@ -354,7 +323,7 @@ GenericDataProcessorAlgorithm::load(const std::string &inputData, Poco::Path p(foundFile); const std::string outputWSName = p.getBaseName(); - IAlgorithm_sptr loadAlg = createChildAlgorithm(m_loadAlg); + auto loadAlg = createChildAlgorithm(m_loadAlg); loadAlg->setProperty(m_loadAlgFileProp, foundFile); if (!loadQuiet) { loadAlg->setAlwaysStoreInADS(true); @@ -363,13 +332,11 @@ GenericDataProcessorAlgorithm::load(const std::string &inputData, // Set up MPI if available #ifdef MPI_BUILD // First, check whether the loader allows use to chunk the data - if (loadAlg->existsProperty("ChunkNumber") && - loadAlg->existsProperty("TotalChunks")) { + if (loadAlg->existsProperty("ChunkNumber") && loadAlg->existsProperty("TotalChunks")) { m_useMPI = true; // The communicator containing all processes boost::mpi::communicator world; - g_log.notice() << "Chunk/Total: " << world.rank() + 1 << "/" - << world.size() << '\n'; + g_log.notice() << "Chunk/Total: " << world.rank() + 1 << "/" << world.size() << '\n'; loadAlg->setPropertyValue("OutputWorkspace", outputWSName); loadAlg->setProperty("ChunkNumber", world.rank() + 1); loadAlg->setProperty("TotalChunks", world.size()); @@ -383,8 +350,7 @@ GenericDataProcessorAlgorithm::load(const std::string &inputData, inputWS = AnalysisDataService::Instance().retrieve(outputWSName); } } else - throw std::runtime_error( - "DataProcessorAlgorithm::load could process any data"); + throw std::runtime_error("DataProcessorAlgorithm::load could process any data"); } return inputWS; } @@ -399,14 +365,12 @@ GenericDataProcessorAlgorithm::load(const std::string &inputData, */ template std::shared_ptr -GenericDataProcessorAlgorithm::getProcessProperties( - const std::string &propertyManager) const { +GenericDataProcessorAlgorithm::getProcessProperties(const std::string &propertyManager) const { std::string propertyManagerName(propertyManager); if (propertyManager.empty() && (!m_propertyManagerPropertyName.empty())) { if (!Base::existsProperty(m_propertyManagerPropertyName)) { std::stringstream msg; - msg << "Failed to find property \"" << m_propertyManagerPropertyName - << "\""; + msg << "Failed to find property \"" << m_propertyManagerPropertyName << "\""; throw Exception::NotFoundError(msg.str(), this->name()); } propertyManagerName = this->getPropertyValue(m_propertyManagerPropertyName); @@ -414,29 +378,23 @@ GenericDataProcessorAlgorithm::getProcessProperties( std::shared_ptr processProperties; if (PropertyManagerDataService::Instance().doesExist(propertyManagerName)) { - processProperties = - PropertyManagerDataService::Instance().retrieve(propertyManagerName); + processProperties = PropertyManagerDataService::Instance().retrieve(propertyManagerName); } else { Base::getLogger().notice() << "Could not find property manager\n"; processProperties = std::make_shared(); - PropertyManagerDataService::Instance().addOrReplace(propertyManagerName, - processProperties); + PropertyManagerDataService::Instance().addOrReplace(propertyManagerName, processProperties); } return processProperties; } template -std::vector -GenericDataProcessorAlgorithm::splitInput(const std::string &input) { +std::vector GenericDataProcessorAlgorithm::splitInput(const std::string &input) { UNUSED_ARG(input); - throw std::runtime_error( - "DataProcessorAlgorithm::splitInput is not implemented"); + throw std::runtime_error("DataProcessorAlgorithm::splitInput is not implemented"); } -template -void GenericDataProcessorAlgorithm::forwardProperties() { - throw std::runtime_error( - "DataProcessorAlgorithm::forwardProperties is not implemented"); +template void GenericDataProcessorAlgorithm::forwardProperties() { + throw std::runtime_error("DataProcessorAlgorithm::forwardProperties is not implemented"); } //------------------------------------------------------------------------------------------ @@ -450,12 +408,10 @@ void GenericDataProcessorAlgorithm::forwardProperties() { * @return matrix workspace resulting from the operation */ template -MatrixWorkspace_sptr -GenericDataProcessorAlgorithm::divide(const MatrixWorkspace_sptr lhs, - const MatrixWorkspace_sptr rhs) { - return this->executeBinaryAlgorithm< - MatrixWorkspace_sptr, MatrixWorkspace_sptr, MatrixWorkspace_sptr>( - "Divide", lhs, rhs); +MatrixWorkspace_sptr GenericDataProcessorAlgorithm::divide(const MatrixWorkspace_sptr lhs, + const MatrixWorkspace_sptr rhs) { + return this->executeBinaryAlgorithm("Divide", lhs, + rhs); } /** @@ -465,11 +421,9 @@ GenericDataProcessorAlgorithm::divide(const MatrixWorkspace_sptr lhs, * @return matrix workspace resulting from the operation */ template -MatrixWorkspace_sptr -GenericDataProcessorAlgorithm::divide(const MatrixWorkspace_sptr lhs, - const double &rhsValue) { - return this->executeBinaryAlgorithm< - MatrixWorkspace_sptr, MatrixWorkspace_sptr, MatrixWorkspace_sptr>( +MatrixWorkspace_sptr GenericDataProcessorAlgorithm::divide(const MatrixWorkspace_sptr lhs, + const double &rhsValue) { + return this->executeBinaryAlgorithm( "Divide", lhs, createWorkspaceSingleValue(rhsValue)); } @@ -482,12 +436,10 @@ GenericDataProcessorAlgorithm::divide(const MatrixWorkspace_sptr lhs, * @return matrix workspace resulting from the operation */ template -MatrixWorkspace_sptr -GenericDataProcessorAlgorithm::multiply(const MatrixWorkspace_sptr lhs, - const MatrixWorkspace_sptr rhs) { - return this->executeBinaryAlgorithm< - MatrixWorkspace_sptr, MatrixWorkspace_sptr, MatrixWorkspace_sptr>( - "Divide", lhs, rhs); +MatrixWorkspace_sptr GenericDataProcessorAlgorithm::multiply(const MatrixWorkspace_sptr lhs, + const MatrixWorkspace_sptr rhs) { + return this->executeBinaryAlgorithm("Divide", lhs, + rhs); } /** @@ -499,11 +451,9 @@ GenericDataProcessorAlgorithm::multiply(const MatrixWorkspace_sptr lhs, * @return matrix workspace resulting from the operation */ template -MatrixWorkspace_sptr -GenericDataProcessorAlgorithm::multiply(const MatrixWorkspace_sptr lhs, - const double &rhsValue) { - return this->executeBinaryAlgorithm< - MatrixWorkspace_sptr, MatrixWorkspace_sptr, MatrixWorkspace_sptr>( +MatrixWorkspace_sptr GenericDataProcessorAlgorithm::multiply(const MatrixWorkspace_sptr lhs, + const double &rhsValue) { + return this->executeBinaryAlgorithm( "Multiply", lhs, createWorkspaceSingleValue(rhsValue)); } @@ -514,12 +464,10 @@ GenericDataProcessorAlgorithm::multiply(const MatrixWorkspace_sptr lhs, * @return matrix workspace resulting from the operation */ template -MatrixWorkspace_sptr -GenericDataProcessorAlgorithm::plus(const MatrixWorkspace_sptr lhs, - const MatrixWorkspace_sptr rhs) { - return this->executeBinaryAlgorithm< - MatrixWorkspace_sptr, MatrixWorkspace_sptr, MatrixWorkspace_sptr>( - "Plus", lhs, rhs); +MatrixWorkspace_sptr GenericDataProcessorAlgorithm::plus(const MatrixWorkspace_sptr lhs, + const MatrixWorkspace_sptr rhs) { + return this->executeBinaryAlgorithm("Plus", lhs, + rhs); } /** @@ -529,11 +477,8 @@ GenericDataProcessorAlgorithm::plus(const MatrixWorkspace_sptr lhs, * @return matrix workspace resulting from the operation */ template -MatrixWorkspace_sptr -GenericDataProcessorAlgorithm::plus(const MatrixWorkspace_sptr lhs, - const double &rhsValue) { - return this->executeBinaryAlgorithm< - MatrixWorkspace_sptr, MatrixWorkspace_sptr, MatrixWorkspace_sptr>( +MatrixWorkspace_sptr GenericDataProcessorAlgorithm::plus(const MatrixWorkspace_sptr lhs, const double &rhsValue) { + return this->executeBinaryAlgorithm( "Plus", lhs, createWorkspaceSingleValue(rhsValue)); } @@ -544,12 +489,10 @@ GenericDataProcessorAlgorithm::plus(const MatrixWorkspace_sptr lhs, * @return matrix workspace resulting from the operation */ template -MatrixWorkspace_sptr -GenericDataProcessorAlgorithm::minus(const MatrixWorkspace_sptr lhs, - const MatrixWorkspace_sptr rhs) { - return this->executeBinaryAlgorithm< - MatrixWorkspace_sptr, MatrixWorkspace_sptr, MatrixWorkspace_sptr>( - "Minus", lhs, rhs); +MatrixWorkspace_sptr GenericDataProcessorAlgorithm::minus(const MatrixWorkspace_sptr lhs, + const MatrixWorkspace_sptr rhs) { + return this->executeBinaryAlgorithm("Minus", lhs, + rhs); } /** @@ -560,11 +503,9 @@ GenericDataProcessorAlgorithm::minus(const MatrixWorkspace_sptr lhs, * @return matrix workspace resulting from the operation */ template -MatrixWorkspace_sptr -GenericDataProcessorAlgorithm::minus(const MatrixWorkspace_sptr lhs, - const double &rhsValue) { - return this->executeBinaryAlgorithm< - MatrixWorkspace_sptr, MatrixWorkspace_sptr, MatrixWorkspace_sptr>( +MatrixWorkspace_sptr GenericDataProcessorAlgorithm::minus(const MatrixWorkspace_sptr lhs, + const double &rhsValue) { + return this->executeBinaryAlgorithm( "Minus", lhs, createWorkspaceSingleValue(rhsValue)); } @@ -574,28 +515,21 @@ GenericDataProcessorAlgorithm::minus(const MatrixWorkspace_sptr lhs, * @return matrix workspace resulting from the operation */ template -MatrixWorkspace_sptr -GenericDataProcessorAlgorithm::createWorkspaceSingleValue( - const double &rhsValue) { - MatrixWorkspace_sptr retVal = - WorkspaceFactory::Instance().create("WorkspaceSingleValue", 1, 1, 1); +MatrixWorkspace_sptr GenericDataProcessorAlgorithm::createWorkspaceSingleValue(const double &rhsValue) { + MatrixWorkspace_sptr retVal = WorkspaceFactory::Instance().create("WorkspaceSingleValue", 1, 1, 1); retVal->dataY(0)[0] = rhsValue; return retVal; } -template -void GenericDataProcessorAlgorithm::visualStudioC4661Workaround() {} +template void GenericDataProcessorAlgorithm::visualStudioC4661Workaround() {} template class GenericDataProcessorAlgorithm; template class MANTID_API_DLL GenericDataProcessorAlgorithm; template class MANTID_API_DLL GenericDataProcessorAlgorithm; -template class MANTID_API_DLL - GenericDataProcessorAlgorithm; +template class MANTID_API_DLL GenericDataProcessorAlgorithm; -template <> -MANTID_API_DLL void -GenericDataProcessorAlgorithm::visualStudioC4661Workaround() {} +template <> MANTID_API_DLL void GenericDataProcessorAlgorithm::visualStudioC4661Workaround() {} } // namespace API } // namespace Mantid diff --git a/Framework/API/src/DeprecatedAlgorithm.cpp b/Framework/API/src/DeprecatedAlgorithm.cpp index ca6cfd051a9df2db7b25e762e94ab258b3419118..b2591546ec01eaee98e1fb9ae64ed269f352e684 100644 --- a/Framework/API/src/DeprecatedAlgorithm.cpp +++ b/Framework/API/src/DeprecatedAlgorithm.cpp @@ -18,8 +18,7 @@ Kernel::Logger g_log("DeprecatedAlgorithm"); } // namespace /// Does nothing other than make the compiler happy. -DeprecatedAlgorithm::DeprecatedAlgorithm() - : m_replacementAlgorithm(), m_replacementVersion(-1), m_deprecatedDate() {} +DeprecatedAlgorithm::DeprecatedAlgorithm() : m_replacementAlgorithm(), m_replacementVersion(-1), m_deprecatedDate() {} /// Does nothing other than make the compiler happy. DeprecatedAlgorithm::~DeprecatedAlgorithm() = default; @@ -27,8 +26,7 @@ DeprecatedAlgorithm::~DeprecatedAlgorithm() = default; /// The algorithm to use instead of this one. /// @param replacement Name of the algorithm that replaces the deprecated one /// @param version An optional version number for the replacement (default=-1) -void DeprecatedAlgorithm::useAlgorithm(const std::string &replacement, - const int version) { +void DeprecatedAlgorithm::useAlgorithm(const std::string &replacement, const int version) { // Replacement is not checked here as we cannot guarantee all algorithms have // been // registered when we are called. It is checked when the message is about to @@ -70,14 +68,11 @@ std::string DeprecatedAlgorithm::deprecationMsg(const IAlgorithm *algo) { msg << " and has no replacement."; } else { // sanity check - if (!AlgorithmFactory::Instance().exists(this->m_replacementAlgorithm, - this->m_replacementVersion)) { + if (!AlgorithmFactory::Instance().exists(this->m_replacementAlgorithm, this->m_replacementVersion)) { std::ostringstream invalidReplacementMsg; - invalidReplacementMsg << "Invalid replacement algorithm '" + - this->m_replacementAlgorithm + "'"; + invalidReplacementMsg << "Invalid replacement algorithm '" + this->m_replacementAlgorithm + "'"; if (this->m_replacementVersion > 0) - invalidReplacementMsg << " version " << this->m_replacementVersion - << "\n"; + invalidReplacementMsg << " version " << this->m_replacementVersion << "\n"; invalidReplacementMsg << "Replacement algorithm not registered."; g_log.warning(invalidReplacementMsg.str()); } diff --git a/Framework/API/src/DetectorSearcher.cpp b/Framework/API/src/DetectorSearcher.cpp index cd25bce0e98fc5cc3caa06aef7d12a31c0394379..e101e8d5d69d9704d9da0880528ffaed854b711e 100644 --- a/Framework/API/src/DetectorSearcher.cpp +++ b/Framework/API/src/DetectorSearcher.cpp @@ -7,6 +7,7 @@ #include "MantidAPI/DetectorSearcher.h" #include "MantidGeometry/Instrument/ReferenceFrame.h" #include "MantidKernel/ConfigService.h" +#include "MantidKernel/Logger.h" #include "MantidKernel/NearestNeighbours.h" #include @@ -16,9 +17,12 @@ using Mantid::Kernel::V3D; using namespace Mantid; using namespace Mantid::API; +namespace { +Kernel::Logger g_log("DetectorSearcher"); +} + double getQSign() { - const auto convention = - Kernel::ConfigService::Instance().getString("Q.convention"); + const auto convention = Kernel::ConfigService::Instance().getString("Q.convention"); return (convention == "Crystallography") ? -1.0 : 1.0; } @@ -30,13 +34,10 @@ double getQSign() { * @param instrument :: the instrument to find detectors in * @param detInfo :: the Geometry::DetectorInfo object for this instrument */ -DetectorSearcher::DetectorSearcher( - const Geometry::Instrument_const_sptr &instrument, - const Geometry::DetectorInfo &detInfo) - : m_usingFullRayTrace(instrument->containsRectDetectors() == - Geometry::Instrument::ContainsState::Full), - m_crystallography_convention(getQSign()), m_detInfo(detInfo), - m_instrument(instrument) { +DetectorSearcher::DetectorSearcher(const Geometry::Instrument_const_sptr &instrument, + const Geometry::DetectorInfo &detInfo) + : m_usingFullRayTrace(instrument->containsRectDetectors() == Geometry::Instrument::ContainsState::Full), + m_crystallography_convention(getQSign()), m_detInfo(detInfo), m_instrument(instrument) { /* Choose the search strategy to use * If the instrument uses rectangular detectors (e.g. TOPAZ) then it is faster @@ -92,8 +93,7 @@ void DetectorSearcher::createDetectorCache() { } // create KDtree of cached detector Q vectors - m_detectorCacheSearch = - std::make_unique>(points); + m_detectorCacheSearch = std::make_unique>(points); } /** Find the index of a detector given a vector in Qlab space @@ -103,8 +103,7 @@ void DetectorSearcher::createDetectorCache() { * @param q :: the Qlab vector to find a detector for * @return tuple with data */ -DetectorSearcher::DetectorSearchResult -DetectorSearcher::findDetectorIndex(const V3D &q) { +DetectorSearcher::DetectorSearchResult DetectorSearcher::findDetectorIndex(const V3D &q) { // quick check to see if this Q is valid if (q.nullVector()) return std::make_tuple(false, 0); @@ -125,8 +124,7 @@ DetectorSearcher::findDetectorIndex(const V3D &q) { * @param q :: the Qlab vector to find a detector for * @return tuple with data */ -DetectorSearcher::DetectorSearchResult -DetectorSearcher::searchUsingInstrumentRayTracing(const V3D &q) { +DetectorSearcher::DetectorSearchResult DetectorSearcher::searchUsingInstrumentRayTracing(const V3D &q) { const auto direction = convertQtoDirection(q); m_rayTracer->traceFromSample(direction); const auto det = m_rayTracer->getDetectorResult(); @@ -150,21 +148,25 @@ DetectorSearcher::searchUsingInstrumentRayTracing(const V3D &q) { * @param q :: the Qlab vector to find a detector for * @return tuple with data */ -DetectorSearcher::DetectorSearchResult -DetectorSearcher::searchUsingNearestNeighbours(const V3D &q) { +DetectorSearcher::DetectorSearchResult DetectorSearcher::searchUsingNearestNeighbours(const V3D &q) { const auto detectorDir = convertQtoDirection(q); // find where this Q vector should intersect with "extended" space - const auto neighbours = - m_detectorCacheSearch->findNearest(Eigen::Vector3d(q[0], q[1], q[2]), 5); - if (neighbours.empty()) + // NOTE: increase the Nneighbors from 5 to 11 to cover a wide extended space + const auto neighbours = m_detectorCacheSearch->findNearest(Eigen::Vector3d(q[0], q[1], q[2]), 11); + + // check if neighboring is empty + if (neighbours.empty()) { + g_log.information() << "empty neighbor list for given Q\n"; return std::make_tuple(false, 0); + } const auto result = checkInteceptWithNeighbours(detectorDir, neighbours); const auto hitDetector = std::get<0>(result); const auto index = std::get<1>(result); - if (hitDetector) + if (hitDetector) { return std::make_tuple(true, m_indexMap[index]); + } // Tube Gap Parameter specifically applies to tube instruments if (!hitDetector && m_instrument->hasParameter("tube-gap")) { @@ -183,9 +185,9 @@ DetectorSearcher::searchUsingNearestNeighbours(const V3D &q) { * @param neighbours :: the NearestNeighbour results to check interception with * @return a detector search result with whether a detector was hit */ -DetectorSearcher::DetectorSearchResult DetectorSearcher::handleTubeGap( - const V3D &detectorDir, - const Kernel::NearestNeighbours<3>::NearestNeighbourResults &neighbours) { +DetectorSearcher::DetectorSearchResult +DetectorSearcher::handleTubeGap(const V3D &detectorDir, + const Kernel::NearestNeighbours<3>::NearestNeighbourResults &neighbours) { std::vector gaps = m_instrument->getNumberParameter("tube-gap", true); if (!gaps.empty()) { const auto gap = static_cast(gaps.front()); @@ -221,9 +223,7 @@ DetectorSearcher::DetectorSearchResult DetectorSearcher::handleTubeGap( * @return tuple of */ std::tuple DetectorSearcher::checkInteceptWithNeighbours( - const V3D &direction, - const Kernel::NearestNeighbours<3>::NearestNeighbourResults &neighbours) - const { + const V3D &direction, const Kernel::NearestNeighbours<3>::NearestNeighbourResults &neighbours) const { Geometry::Track track(m_detInfo.samplePosition(), direction); // Find which of the neighbours we actually intersect with for (const auto &neighbour : neighbours) { diff --git a/Framework/API/src/DistributedAlgorithm.cpp b/Framework/API/src/DistributedAlgorithm.cpp index 98784997dc1fb47a53138d36071b3dc2cd1d02e6..47d53287bed05827b15c31b5113fd6a9fdc3a8c6 100644 --- a/Framework/API/src/DistributedAlgorithm.cpp +++ b/Framework/API/src/DistributedAlgorithm.cpp @@ -11,27 +11,24 @@ namespace Mantid { namespace API { -Parallel::ExecutionMode DistributedAlgorithm::getParallelExecutionMode( - const std::map &storageModes) const { +Parallel::ExecutionMode +DistributedAlgorithm::getParallelExecutionMode(const std::map &storageModes) const { using namespace Parallel; - if (std::any_of( - storageModes.begin(), storageModes.end(), - [](const std::pair &item) { - return item.second == StorageMode::Distributed; - })) { - if (std::any_of( - storageModes.begin(), storageModes.end(), - [](const std::pair &item) { - return item.second == StorageMode::MasterOnly; - })) + if (std::any_of(storageModes.begin(), storageModes.end(), + [](const std::pair &item) { + return item.second == StorageMode::Distributed; + })) { + if (std::any_of(storageModes.begin(), storageModes.end(), + [](const std::pair &item) { + return item.second == StorageMode::MasterOnly; + })) return ExecutionMode::Invalid; return ExecutionMode::Distributed; } - if (std::any_of( - storageModes.begin(), storageModes.end(), - [](const std::pair &item) { - return item.second == StorageMode::MasterOnly; - })) + if (std::any_of(storageModes.begin(), storageModes.end(), + [](const std::pair &item) { + return item.second == StorageMode::MasterOnly; + })) return ExecutionMode::MasterOnly; return ExecutionMode::Identical; } diff --git a/Framework/API/src/DomainCreatorFactory.cpp b/Framework/API/src/DomainCreatorFactory.cpp index bcdf324e545e600780d14d1a463c86af36599e94..ca9b110c311511f554b830f8cdddea2c0d1edf60 100644 --- a/Framework/API/src/DomainCreatorFactory.cpp +++ b/Framework/API/src/DomainCreatorFactory.cpp @@ -20,13 +20,11 @@ namespace API { * @param domainType * @returns A pointer to the new object */ -IDomainCreator *DomainCreatorFactoryImpl::createDomainCreator( - const std::string &id, Kernel::IPropertyManager *pm, - const std::string &workspacePropertyName, - const unsigned int domainType) const { +IDomainCreator *DomainCreatorFactoryImpl::createDomainCreator(const std::string &id, Kernel::IPropertyManager *pm, + const std::string &workspacePropertyName, + const unsigned int domainType) const { auto creator = this->createUnwrapped(id); - creator->initialize(pm, workspacePropertyName, - static_cast(domainType)); + creator->initialize(pm, workspacePropertyName, static_cast(domainType)); return creator; } diff --git a/Framework/API/src/EqualBinSizesValidator.cpp b/Framework/API/src/EqualBinSizesValidator.cpp index 9247822ca8183c420ac1d4528bf537938eaca54f..c2a963581e38e7b4c298382028b5edca1b4dbf47 100644 --- a/Framework/API/src/EqualBinSizesValidator.cpp +++ b/Framework/API/src/EqualBinSizesValidator.cpp @@ -14,8 +14,7 @@ namespace API { /** * Constructor - sets properties */ -EqualBinSizesValidator::EqualBinSizesValidator(const double errorLevel) - : m_errorLevel(errorLevel) {} +EqualBinSizesValidator::EqualBinSizesValidator(const double errorLevel) : m_errorLevel(errorLevel) {} /// Clone the current state Kernel::IValidator_sptr EqualBinSizesValidator::clone() const { @@ -26,8 +25,7 @@ Kernel::IValidator_sptr EqualBinSizesValidator::clone() const { * @param value :: [input] The workspace to test * @return :: An error message (empty if no error) */ -std::string -EqualBinSizesValidator::checkValidity(const MatrixWorkspace_sptr &value) const { +std::string EqualBinSizesValidator::checkValidity(const MatrixWorkspace_sptr &value) const { if (!value) return "Enter an existing workspace"; if (!value->isCommonBins()) diff --git a/Framework/API/src/ExperimentInfo.cpp b/Framework/API/src/ExperimentInfo.cpp index f37808dbdc7f59f86120cf56d440707835edacd5..7e07e87db30124dc36cdad9a1201e1d8f164521b 100644 --- a/Framework/API/src/ExperimentInfo.cpp +++ b/Framework/API/src/ExperimentInfo.cpp @@ -67,8 +67,7 @@ Kernel::Logger g_log("ExperimentInfo"); /** Constructor */ -ExperimentInfo::ExperimentInfo() - : m_parmap(new ParameterMap()), sptr_instrument(new Instrument()) { +ExperimentInfo::ExperimentInfo() : m_parmap(new ParameterMap()), sptr_instrument(new Instrument()) { m_parmap->setInstrument(sptr_instrument.get()); } @@ -104,9 +103,7 @@ void ExperimentInfo::copyExperimentInfoFrom(const ExperimentInfo *other) { /** Clone this ExperimentInfo class into a new one */ -ExperimentInfo *ExperimentInfo::cloneExperimentInfo() const { - return new ExperimentInfo(*this); -} +ExperimentInfo *ExperimentInfo::cloneExperimentInfo() const { return new ExperimentInfo(*this); } /// @returns A human-readable description of the object const std::string ExperimentInfo::toString() const { @@ -123,8 +120,7 @@ const std::string ExperimentInfo::toString() const { const auto instName = inst->getName(); out << "Instrument: "; if (!instName.empty()) { - out << instName << " (" - << inst->getValidFromDate().toFormattedString("%Y-%b-%d") << " to " + out << instName << " (" << inst->getValidFromDate().toFormattedString("%Y-%b-%d") << " to " << inst->getValidToDate().toFormattedString("%Y-%b-%d") << ")"; const auto instFilename = inst->getFilename(); if (!instFilename.empty()) { @@ -137,8 +133,7 @@ const std::string ExperimentInfo::toString() const { out << "\n"; // parameter files loaded - auto paramFileVector = - this->constInstrumentParameters().getParameterFilenames(); + auto paramFileVector = this->constInstrumentParameters().getParameterFilenames(); for (auto &itFilename : paramFileVector) { out << "Parameters from: " << itFilename; out << "\n"; @@ -152,15 +147,13 @@ const std::string ExperimentInfo::toString() const { if (runEnd.empty()) runEnd = msgNA; out << "Run start: " << runStart << "\n"; - out << "Run end: " << runEnd - << "\n"; // note extra space for pseudo/approx-alignment + out << "Run end: " << runEnd << "\n"; // note extra space for pseudo/approx-alignment if (this->sample().hasOrientedLattice()) { const Geometry::OrientedLattice &latt = this->sample().getOrientedLattice(); - out << "Sample: a " << std::fixed << std::setprecision(1) << latt.a() - << ", b " << latt.b() << ", c " << latt.c(); - out << "; alpha " << std::fixed << std::setprecision(0) << latt.alpha() - << ", beta " << latt.beta() << ", gamma " << latt.gamma(); + out << "Sample: a " << std::fixed << std::setprecision(1) << latt.a() << ", b " << latt.b() << ", c " << latt.c(); + out << "; alpha " << std::fixed << std::setprecision(0) << latt.alpha() << ", beta " << latt.beta() << ", gamma " + << latt.gamma(); out << "\n"; } return out.str(); @@ -168,8 +161,7 @@ const std::string ExperimentInfo::toString() const { // Helpers for setInstrument and getInstrument namespace { -void checkDetectorInfoSize(const Instrument &instr, - const Geometry::DetectorInfo &detInfo) { +void checkDetectorInfoSize(const Instrument &instr, const Geometry::DetectorInfo &detInfo) { const auto numDets = instr.getNumberDetectors(); if (numDets != detInfo.size()) throw std::runtime_error("ExperimentInfo: size mismatch between " @@ -188,8 +180,7 @@ void ExperimentInfo::setInstrument(const Instrument_const_sptr &instr) { // instrument may now suddenly be valid, so we have to reinitialize the // detector grouping. Also the index corresponding to specific IDs may have // changed. - if (sptr_instrument != - (instr->isParametrized() ? instr->baseInstrument() : instr)) + if (sptr_instrument != (instr->isParametrized() ? instr->baseInstrument() : instr)) invalidateAllSpectrumDefinitions(); if (instr->isParametrized()) { sptr_instrument = instr->baseInstrument(); @@ -212,8 +203,7 @@ void ExperimentInfo::setInstrument(const Instrument_const_sptr &instr) { Instrument_const_sptr ExperimentInfo::getInstrument() const { populateIfNotLoaded(); checkDetectorInfoSize(*sptr_instrument, detectorInfo()); - return Geometry::ParComponentFactory::createInstrument(sptr_instrument, - m_parmap); + return Geometry::ParComponentFactory::createInstrument(sptr_instrument, m_parmap); } /** Returns a new copy of the instrument parameters @@ -235,8 +225,7 @@ const Geometry::ParameterMap &ExperimentInfo::instrumentParameters() const { /** Returns a const reference to the instrument parameters. * @return a const reference to the instrument ParameterMap. */ -const Geometry::ParameterMap & -ExperimentInfo::constInstrumentParameters() const { +const Geometry::ParameterMap &ExperimentInfo::constInstrumentParameters() const { populateIfNotLoaded(); return *m_parmap; } @@ -256,16 +245,14 @@ struct RTP { }; struct ParameterValue { - ParameterValue(const Geometry::XMLInstrumentParameter ¶mInfo, - const API::Run &run) + ParameterValue(const Geometry::XMLInstrumentParameter ¶mInfo, const API::Run &run) : info(paramInfo), runData(run) {} operator double() { if (info.m_logfileID.empty()) return boost::lexical_cast(info.m_value); else - return info.createParamValue( - runData.getTimeSeriesProperty(info.m_logfileID)); + return info.createParamValue(runData.getTimeSeriesProperty(info.m_logfileID)); } operator int() { return boost::lexical_cast(info.m_value); } operator bool() { @@ -283,35 +270,26 @@ struct ParameterValue { } // namespace namespace { -bool isPositionParameter(const std::string &name) { - return ParameterMap::pos() == name; -} +bool isPositionParameter(const std::string &name) { return ParameterMap::pos() == name; } -bool isRotationParameter(const std::string &name) { - return ParameterMap::rot() == name; -} +bool isRotationParameter(const std::string &name) { return ParameterMap::rot() == name; } -bool isScaleParameter(const std::string &name) { - return (name == "scalex" || name == "scaley"); -} +bool isScaleParameter(const std::string &name) { return (name == "scalex" || name == "scaley"); } bool isRedundantPosOrRot(const std::string &name) { // Check size first as a small optimization. return (name.size() == 4) && - (name == "posx" || name == "posy" || name == "posz" || - name == "rotx" || name == "roty" || name == "rotz"); + (name == "posx" || name == "posy" || name == "posz" || name == "rotx" || name == "roty" || name == "rotz"); } -template -T getParam(const std::string ¶mType, const std::string ¶mValue) { +template T getParam(const std::string ¶mType, const std::string ¶mValue) { const std::string name = "dummy"; auto param = ParameterFactory::create(paramType, name); param->fromString(paramValue); return param->value(); } -void updatePosition(ComponentInfo &componentInfo, const IComponent *component, - const V3D &newRelPos) { +void updatePosition(ComponentInfo &componentInfo, const IComponent *component, const V3D &newRelPos) { const auto compIndex = componentInfo.indexOf(component->getComponentID()); V3D position = newRelPos; if (componentInfo.hasParent(compIndex)) { @@ -322,8 +300,7 @@ void updatePosition(ComponentInfo &componentInfo, const IComponent *component, componentInfo.setPosition(compIndex, position); } -void updateRotation(ComponentInfo &componentInfo, const IComponent *component, - const Quat &newRelRot) { +void updateRotation(ComponentInfo &componentInfo, const IComponent *component, const Quat &newRelRot) { const auto compIndex = componentInfo.indexOf(component->getComponentID()); auto rotation = newRelRot; @@ -334,18 +311,15 @@ void updateRotation(ComponentInfo &componentInfo, const IComponent *component, componentInfo.setRotation(compIndex, rotation); } -void adjustPositionsFromScaleFactor(ComponentInfo &componentInfo, - const IComponent *component, - const std::string ¶mName, - double factor) { +void adjustPositionsFromScaleFactor(ComponentInfo &componentInfo, const IComponent *component, + const std::string ¶mName, double factor) { double ScaleX = 1.0; double ScaleY = 1.0; if (paramName == "scalex") ScaleX = factor; else ScaleY = factor; - applyRectangularDetectorScaleToComponentInfo( - componentInfo, component->getComponentID(), ScaleX, ScaleY); + applyRectangularDetectorScaleToComponentInfo(componentInfo, component->getComponentID(), ScaleX, ScaleY); } } // namespace @@ -407,16 +381,13 @@ void ExperimentInfo::populateInstrumentParameters() { if (rtpValues.haveRadius) { V3D pos; pos.spherical(rtpValues.radius, rtpValues.theta, rtpValues.phi); - paramMapForPosAndRot.addV3D(paramInfo->m_component, - ParameterMap::pos(), pos); + paramMapForPosAndRot.addV3D(paramInfo->m_component, ParameterMap::pos(), pos); } } else { - populateWithParameter(paramMap, paramMapForPosAndRot, paramN, - *paramInfo, runData); + populateWithParameter(paramMap, paramMapForPosAndRot, paramN, *paramInfo, runData); } } catch (std::exception &exc) { - g_log.information() << "Unable to add component parameter '" - << nameComp.first << "'. Error: " << exc.what(); + g_log.information() << "Unable to add component parameter '" << nameComp.first << "'. Error: " << exc.what(); continue; } } @@ -435,9 +406,7 @@ void ExperimentInfo::populateInstrumentParameters() { // positions. for (const auto &item : paramMap) { if (isScaleParameter(item.second->name())) - adjustPositionsFromScaleFactor(componentInfo, item.first, - item.second->name(), - item.second->value()); + adjustPositionsFromScaleFactor(componentInfo, item.first, item.second->name(), item.second->value()); } // paramMapForPosAndRot goes out of scope, dropping all position and rotation // parameters of detectors (parameters for non-detector components have been @@ -462,16 +431,13 @@ void ExperimentInfo::setNumberOfDetectorGroups(const size_t count) const { * * For MatrixWorkspace this is equal to getNumberHistograms() (after *initialization). */ -size_t ExperimentInfo::numberOfDetectorGroups() const { - return m_spectrumDefinitionNeedsUpdate.size(); -} +size_t ExperimentInfo::numberOfDetectorGroups() const { return m_spectrumDefinitionNeedsUpdate.size(); } /** Sets the detector grouping for the spectrum with the given `index`. * * This method should not need to be called explicitly. Groupings are updated * automatically when modifying detector IDs in a workspace (via ISpectrum). */ -void ExperimentInfo::setDetectorGrouping( - const size_t index, const std::set &detIDs) const { +void ExperimentInfo::setDetectorGrouping(const size_t index, const std::set &detIDs) const { SpectrumDefinition specDef; for (const auto detID : detIDs) { try { @@ -492,8 +458,7 @@ void ExperimentInfo::setDetectorGrouping( * implementation throws, since no grouping information for update is available * when grouping comes from a call to `cacheDetectorGroupings`. This method is * overridden in MatrixWorkspace. */ -void ExperimentInfo::updateCachedDetectorGrouping( - const size_t /*unused*/) const { +void ExperimentInfo::updateCachedDetectorGrouping(const size_t /*unused*/) const { throw std::runtime_error("ExperimentInfo::updateCachedDetectorGrouping: " "Cannot update -- grouping information not " "available"); @@ -536,9 +501,7 @@ Run &ExperimentInfo::mutableRun() { } /// Set the run object. Use in particular to clear run without copying old run. -void ExperimentInfo::setSharedRun(Kernel::cow_ptr run) { - m_run = std::move(run); -} +void ExperimentInfo::setSharedRun(Kernel::cow_ptr run) { m_run = std::move(run); } /// Return the cow ptr of the run Kernel::cow_ptr ExperimentInfo::sharedRun() { return m_run; } @@ -564,12 +527,10 @@ Kernel::Property *ExperimentInfo::getLog(const std::string &log) const { } // If the instrument has a parameter with that name then take the value as a // log name - const std::string logName = - constInstrumentParameters().getString(sptr_instrument.get(), log); + const std::string logName = constInstrumentParameters().getString(sptr_instrument.get(), log); if (logName.empty()) { - throw std::invalid_argument( - "ExperimentInfo::getLog - No instrument parameter named \"" + log + - "\". Cannot access full log name"); + throw std::invalid_argument("ExperimentInfo::getLog - No instrument parameter named \"" + log + + "\". Cannot access full log name"); } return run().getProperty(logName); } @@ -591,12 +552,10 @@ double ExperimentInfo::getLogAsSingleValue(const std::string &log) const { } // If the instrument has a parameter with that name then take the value as a // log name - const std::string logName = - constInstrumentParameters().getString(sptr_instrument.get(), log); + const std::string logName = constInstrumentParameters().getString(sptr_instrument.get(), log); if (logName.empty()) { - throw std::invalid_argument( - "ExperimentInfo::getLog - No instrument parameter named \"" + log + - "\". Cannot access full log name"); + throw std::invalid_argument("ExperimentInfo::getLog - No instrument parameter named \"" + log + + "\". Cannot access full log name"); } return run().getPropertyAsSingleValue(logName); } @@ -640,10 +599,8 @@ Kernel::DeltaEMode::Type ExperimentInfo::getEMode() const { std::string emodeStr; if (run().hasProperty(emodeTag)) { emodeStr = run().getPropertyValueAsType(emodeTag); - } else if (sptr_instrument && constInstrumentParameters().contains( - sptr_instrument.get(), emodeTag)) { - Geometry::Parameter_sptr param = - constInstrumentParameters().get(sptr_instrument.get(), emodeTag); + } else if (sptr_instrument && constInstrumentParameters().contains(sptr_instrument.get(), emodeTag)) { + Geometry::Parameter_sptr param = constInstrumentParameters().get(sptr_instrument.get(), emodeTag); emodeStr = param->asString(); } else { return Kernel::DeltaEMode::Elastic; @@ -672,43 +629,68 @@ double ExperimentInfo::getEFixed(const detid_t detID) const { * required for Indirect mode * @return The current efixed value */ -double ExperimentInfo::getEFixed( - const std::shared_ptr &detector) const { +double ExperimentInfo::getEFixed(const std::shared_ptr &detector) const { populateIfNotLoaded(); Kernel::DeltaEMode::Type emode = getEMode(); - if (emode == Kernel::DeltaEMode::Direct) { - try { - return this->run().getPropertyValueAsType("Ei"); - } catch (Kernel::Exception::NotFoundError &) { - throw std::runtime_error( - "Experiment logs do not contain an Ei value. Have you run GetEi?"); - } - } else if (emode == Kernel::DeltaEMode::Indirect) { - if (!detector) - throw std::runtime_error("ExperimentInfo::getEFixed - Indirect mode " - "efixed requested without a valid detector."); - Parameter_sptr par = - constInstrumentParameters().getRecursive(detector.get(), "Efixed"); + return getEFixedGivenEMode(detector, emode); +} + +double ExperimentInfo::getEFixedForIndirect(const std::shared_ptr &detector, + const std::vector ¶meterNames) const { + double efixed = 0.; + for (auto ¶meterName : parameterNames) { + Parameter_sptr par = constInstrumentParameters().getRecursive(detector.get(), parameterName); if (par) { - return par->value(); + efixed = par->value(); } else { - std::vector efixedVec = detector->getNumberParameter("Efixed"); + std::vector efixedVec = detector->getNumberParameter(parameterName); if (efixedVec.empty()) { int detid = detector->getID(); - IDetector_const_sptr detectorSingle = - getInstrument()->getDetector(detid); - efixedVec = detectorSingle->getNumberParameter("Efixed"); + IDetector_const_sptr detectorSingle = getInstrument()->getDetector(detid); + efixedVec = detectorSingle->getNumberParameter(parameterName); } if (!efixedVec.empty()) { - return efixedVec.at(0); - } else { - std::ostringstream os; - os << "ExperimentInfo::getEFixed - Indirect mode efixed requested but " - "detector has no Efixed parameter attached. ID=" - << detector->getID(); - throw std::runtime_error(os.str()); + efixed = efixedVec.at(0); + } + } + } + if (efixed == 0.) { + std::ostringstream os; + os << "ExperimentInfo::getEFixed - Indirect mode efixed requested but " + "detector has no Efixed parameter attached. ID=" + << detector->getID(); + throw std::runtime_error(os.str()); + } + return efixed; +} + +/** + * Easy access to the efixed value for this run & detector + * @param detector :: The detector object to ask for the efixed mode. Only + * required for Indirect mode + * @param emode :: enum value indicating whether elastic, direct or indirect + * @return The current efixed value + */ +double ExperimentInfo::getEFixedGivenEMode(const std::shared_ptr &detector, + const Kernel::DeltaEMode::Type emode) const { + if (emode == Kernel::DeltaEMode::Direct) { + double efixed = 0.; + for (auto ¶meterName : {"Ei", "EnergyRequested", "EnergyEstimate"}) { + if (run().hasProperty(parameterName)) { + efixed = run().getPropertyValueAsType(parameterName); + break; } } + if (efixed == 0.) { + throw std::runtime_error("Experiment logs do not contain an Ei " + "value. Have you run GetEi?"); + } + return efixed; + } else if (emode == Kernel::DeltaEMode::Indirect) { + if (!detector) + throw std::runtime_error("ExperimentInfo::getEFixed - Indirect mode " + "efixed requested without a valid detector."); + return getEFixedForIndirect(detector, {"Efixed", "EFixed-val"}); } else { throw std::runtime_error("ExperimentInfo::getEFixed - EFixed requested for " "elastic mode, don't know what to do!"); @@ -808,8 +790,7 @@ const SpectrumInfo &ExperimentInfo::spectrumInfo() const { cacheDefaultDetectorGrouping(); if (!m_spectrumInfoWrapper) { static_cast(detectorInfo()); - m_spectrumInfoWrapper = std::make_unique( - *m_spectrumInfo, *this, m_parmap->mutableDetectorInfo()); + m_spectrumInfoWrapper = std::make_unique(*m_spectrumInfo, *this, m_parmap->mutableDetectorInfo()); } } // Rebuild any spectrum definitions that are out of date. Accessing @@ -829,12 +810,10 @@ const SpectrumInfo &ExperimentInfo::spectrumInfo() const { // is not possible for a read-only workspace. If the workspace is write-locked // detector IDs in ISpectrum may change, but the write-lock by `Algorithm` // guarantees that there is no concurrent reader and thus updating is safe. - if (std::any_of(m_spectrumDefinitionNeedsUpdate.cbegin(), - m_spectrumDefinitionNeedsUpdate.cend(), + if (std::any_of(m_spectrumDefinitionNeedsUpdate.cbegin(), m_spectrumDefinitionNeedsUpdate.cend(), [](char i) { return i == 1; })) { std::lock_guard lock{m_spectrumInfoMutex}; - if (std::any_of(m_spectrumDefinitionNeedsUpdate.cbegin(), - m_spectrumDefinitionNeedsUpdate.cend(), + if (std::any_of(m_spectrumDefinitionNeedsUpdate.cbegin(), m_spectrumDefinitionNeedsUpdate.cend(), [](char i) { return i == 1; })) { auto size = static_cast(m_spectrumInfoWrapper->size()); #pragma omp parallel for @@ -849,24 +828,17 @@ const SpectrumInfo &ExperimentInfo::spectrumInfo() const { /** Return a non-const reference to the SpectrumInfo object. Not thread safe. */ SpectrumInfo &ExperimentInfo::mutableSpectrumInfo() { - return const_cast( - static_cast(*this).spectrumInfo()); + return const_cast(static_cast(*this).spectrumInfo()); } -const Geometry::ComponentInfo &ExperimentInfo::componentInfo() const { - return m_parmap->componentInfo(); -} +const Geometry::ComponentInfo &ExperimentInfo::componentInfo() const { return m_parmap->componentInfo(); } -ComponentInfo &ExperimentInfo::mutableComponentInfo() { - return m_parmap->mutableComponentInfo(); -} +ComponentInfo &ExperimentInfo::mutableComponentInfo() { return m_parmap->mutableComponentInfo(); } /// Sets the SpectrumDefinition for all spectra. -void ExperimentInfo::setSpectrumDefinitions( - Kernel::cow_ptr> spectrumDefinitions) { +void ExperimentInfo::setSpectrumDefinitions(Kernel::cow_ptr> spectrumDefinitions) { if (spectrumDefinitions) { - m_spectrumInfo = std::make_unique( - std::move(spectrumDefinitions)); + m_spectrumInfo = std::make_unique(std::move(spectrumDefinitions)); m_spectrumDefinitionNeedsUpdate.resize(0); m_spectrumDefinitionNeedsUpdate.resize(m_spectrumInfo->size(), 0); } else { @@ -888,8 +860,7 @@ void ExperimentInfo::invalidateSpectrumDefinition(const size_t index) { m_spectrumDefinitionNeedsUpdate.at(index) = 1; } -void ExperimentInfo::updateSpectrumDefinitionIfNecessary( - const size_t index) const { +void ExperimentInfo::updateSpectrumDefinitionIfNecessary(const size_t index) const { if (m_spectrumDefinitionNeedsUpdate.at(index) != 0) updateCachedDetectorGrouping(index); } @@ -919,16 +890,14 @@ void ExperimentInfo::cacheDefaultDetectorGrouping() const { /// Sets flags for all spectrum definitions indicating that they need to be /// updated. void ExperimentInfo::invalidateAllSpectrumDefinitions() { - std::fill(m_spectrumDefinitionNeedsUpdate.begin(), - m_spectrumDefinitionNeedsUpdate.end(), 1); + std::fill(m_spectrumDefinitionNeedsUpdate.begin(), m_spectrumDefinitionNeedsUpdate.end(), 1); } /** Save the object to an open NeXus file. * @param file :: open NeXus file * @param saveLegacyInstrument : defaults to true, otherwise not in file output */ -void ExperimentInfo::saveExperimentInfoNexus(::NeXus::File *file, - bool saveLegacyInstrument) const { +void ExperimentInfo::saveExperimentInfoNexus(::NeXus::File *file, bool saveLegacyInstrument) const { Instrument_const_sptr instrument = getInstrument(); if (saveLegacyInstrument) { instrument->saveNexus(file, "instrument"); @@ -943,9 +912,7 @@ void ExperimentInfo::saveExperimentInfoNexus(::NeXus::File *file, * @param saveSample :: option to save Sample * @param saveLogs :: option to save Logs */ -void ExperimentInfo::saveExperimentInfoNexus(::NeXus::File *file, - bool saveInstrument, - bool saveSample, +void ExperimentInfo::saveExperimentInfoNexus(::NeXus::File *file, bool saveInstrument, bool saveSample, bool saveLogs) const { Instrument_const_sptr instrument = getInstrument(); @@ -985,8 +952,7 @@ void ExperimentInfo::loadSampleAndLogInfoNexus(::NeXus::File *file) { * file and cannot * be loaded from the IDF. */ -void ExperimentInfo::loadExperimentInfoNexus(const std::string &nxFilename, - ::NeXus::File *file, +void ExperimentInfo::loadExperimentInfoNexus(const std::string &nxFilename, ::NeXus::File *file, std::string ¶meterStr) { // load sample and log info loadSampleAndLogInfoNexus(file); @@ -1004,8 +970,7 @@ void ExperimentInfo::loadExperimentInfoNexus(const std::string &nxFilename, * file and cannot * be loaded from the IDF. */ -void ExperimentInfo::loadInstrumentInfoNexus(const std::string &nxFilename, - ::NeXus::File *file, +void ExperimentInfo::loadInstrumentInfoNexus(const std::string &nxFilename, ::NeXus::File *file, std::string ¶meterStr) { // Open instrument group @@ -1035,8 +1000,7 @@ void ExperimentInfo::loadInstrumentInfoNexus(const std::string &nxFilename, * file and cannot * be loaded from the IDF. */ -void ExperimentInfo::loadInstrumentInfoNexus(const std::string &nxFilename, - ::NeXus::File *file) { +void ExperimentInfo::loadInstrumentInfoNexus(const std::string &nxFilename, ::NeXus::File *file) { // Open instrument group file->openGroup("instrument", "NXinstrument"); @@ -1059,9 +1023,8 @@ void ExperimentInfo::loadInstrumentInfoNexus(const std::string &nxFilename, * @param[out] instrumentXml :: XML string of embedded instrument definition or * empty if not found */ -void ExperimentInfo::loadEmbeddedInstrumentInfoNexus( - ::NeXus::File *file, std::string &instrumentName, - std::string &instrumentXml) { +void ExperimentInfo::loadEmbeddedInstrumentInfoNexus(::NeXus::File *file, std::string &instrumentName, + std::string &instrumentXml) { file->readData("name", instrumentName); @@ -1083,8 +1046,7 @@ void ExperimentInfo::loadEmbeddedInstrumentInfoNexus( * @param instrumentXml :: XML string of instrument or empty to indicate load * of instrument definition file */ -void ExperimentInfo::setInstumentFromXML(const std::string &nxFilename, - std::string &instrumentName, +void ExperimentInfo::setInstumentFromXML(const std::string &nxFilename, std::string &instrumentName, std::string &instrumentXml) { instrumentXml = Strings::strip(instrumentXml); @@ -1099,16 +1061,14 @@ void ExperimentInfo::setInstumentFromXML(const std::string &nxFilename, } else { // XML was not included or was empty // Use the instrument name to find the file - instrumentFilename = InstrumentFileFinder::getInstrumentFilename( - instrumentName, getWorkspaceStartDate()); + instrumentFilename = InstrumentFileFinder::getInstrumentFilename(instrumentName, getWorkspaceStartDate()); // And now load the contents instrumentXml = loadInstrumentXML(instrumentFilename); } // ---------- Now parse that XML to make the instrument ------------------- if (!instrumentXml.empty() && !instrumentName.empty()) { - InstrumentDefinitionParser parser(instrumentFilename, instrumentName, - instrumentXml); + InstrumentDefinitionParser parser(instrumentFilename, instrumentName, instrumentXml); std::string instrumentNameMangled = parser.getMangledName(); Instrument_sptr instr; @@ -1157,17 +1117,14 @@ std::string ExperimentInfo::loadInstrumentXML(const std::string &filename) { * Feed that to ExperimentInfo::readParameterMap() after the * instrument is done. */ -void ExperimentInfo::loadInstrumentParametersNexus(::NeXus::File *file, - std::string ¶meterStr) { +void ExperimentInfo::loadInstrumentParametersNexus(::NeXus::File *file, std::string ¶meterStr) { try { file->openGroup("instrument_parameter_map", "NXnote"); file->readData("data", parameterStr); file->closeGroup(); } catch (NeXus::Exception &ex) { - g_log.debug(std::string("Unable to load instrument_parameter_map: ") + - ex.what()); - g_log.information( - "Parameter map entry missing from NeXus file. Continuing without it."); + g_log.debug(std::string("Unable to load instrument_parameter_map: ") + ex.what()); + g_log.information("Parameter map entry missing from NeXus file. Continuing without it."); } } @@ -1220,15 +1177,23 @@ void ExperimentInfo::readParameterMap(const std::string ¶meterStr) { auto size = static_cast(tokens.count()); for (int i = 4; i < size; i++) paramValue += ";" + tokens[i]; - const auto ¶mType = tokens[1]; const auto ¶mName = tokens[2]; + auto ¶mVisibility = tokens[size - 1]; // parameter visibility, if defined, is the last token + auto const visibilityKey = std::string("visible:"); // if visibility is defined, the value will follow this key + if (paramVisibility.find(visibilityKey) > paramVisibility.size()) + paramVisibility = "true"; // visibility not defined: default to visible + else { // defined, the paramValue has one too many entries, -1 to remove also the semicolon + paramVisibility = + paramVisibility.substr(paramVisibility.find(visibilityKey) + visibilityKey.size(), paramVisibility.size()); + paramValue = paramValue.substr(0, paramValue.find(visibilityKey) - 1); + } + const auto paramDescr = std::string(""); if (paramName == "masked") { auto value = getParam(paramType, paramValue); if (value) { // Do not add masking to ParameterMap, it is stored in DetectorInfo - const auto componentIndex = - componentInfo.indexOf(comp->getComponentID()); + const auto componentIndex = componentInfo.indexOf(comp->getComponentID()); if (!componentInfo.isDetector(componentIndex)) { throw std::runtime_error("Found masking for a non-detector " "component. This is not possible"); @@ -1255,9 +1220,8 @@ void ExperimentInfo::readParameterMap(const std::string ¶meterStr) { // Special case RectangularDetector: Parameters scalex and scaley affect // pixel positions, but we must also add the parameter below. if (isScaleParameter(paramName)) - adjustPositionsFromScaleFactor(componentInfo, comp, paramName, - getParam(paramType, paramValue)); - pmap.add(paramType, comp, paramName, paramValue); + adjustPositionsFromScaleFactor(componentInfo, comp, paramName, getParam(paramType, paramValue)); + pmap.add(paramType, comp, paramName, paramValue, ¶mDescr, paramVisibility); } } } @@ -1272,10 +1236,9 @@ void ExperimentInfo::readParameterMap(const std::string ¶meterStr) { * @param paramInfo A reference to the object describing this parameter * @param runData A reference to the run object, which stores log value entries */ -void ExperimentInfo::populateWithParameter( - Geometry::ParameterMap ¶mMap, - Geometry::ParameterMap ¶mMapForPosAndRot, const std::string &name, - const Geometry::XMLInstrumentParameter ¶mInfo, const Run &runData) { +void ExperimentInfo::populateWithParameter(Geometry::ParameterMap ¶mMap, + Geometry::ParameterMap ¶mMapForPosAndRot, const std::string &name, + const Geometry::XMLInstrumentParameter ¶mInfo, const Run &runData) { const std::string &category = paramInfo.m_type; ParameterValue paramValue(paramInfo, runData); // Defines implicit conversion operator @@ -1283,6 +1246,9 @@ void ExperimentInfo::populateWithParameter( const std::string *pDescription = nullptr; if (!paramInfo.m_description.empty()) pDescription = ¶mInfo.m_description; + std::string pVisible = "true"; + if (!paramInfo.m_visible.empty()) + pVisible = paramInfo.m_visible; // Some names are special. Values should be convertible to double if (name == "masked") { @@ -1290,43 +1256,34 @@ void ExperimentInfo::populateWithParameter( if (value) { // Do not add masking to ParameterMap, it is stored in DetectorInfo - const auto componentIndex = - componentInfo().indexOf(paramInfo.m_component->getComponentID()); + const auto componentIndex = componentInfo().indexOf(paramInfo.m_component->getComponentID()); if (!componentInfo().isDetector(componentIndex)) - throw std::runtime_error( - "Found masking for a non-detector component. This is not possible"); + throw std::runtime_error("Found masking for a non-detector component. This is not possible"); mutableDetectorInfo().setMasked(componentIndex, paramValue); // all detector indexes have // same component index // (guarantee) } } else if (name == "x" || name == "y" || name == "z") { - paramMapForPosAndRot.addPositionCoordinate(paramInfo.m_component, name, - paramValue); - } else if (name == "rot" || name == "rotx" || name == "roty" || - name == "rotz") { + paramMapForPosAndRot.addPositionCoordinate(paramInfo.m_component, name, paramValue); + } else if (name == "rot" || name == "rotx" || name == "roty" || name == "rotz") { // Effectively this is dropping any parameters named 'rot'. - paramMapForPosAndRot.addRotationParam(paramInfo.m_component, name, - paramValue, pDescription); + paramMapForPosAndRot.addRotationParam(paramInfo.m_component, name, paramValue, pDescription); } else if (category == "fitting") { std::ostringstream str; - str << paramInfo.m_value << " , " << paramInfo.m_fittingFunction << " , " - << name << " , " << paramInfo.m_constraint[0] << " , " - << paramInfo.m_constraint[1] << " , " << paramInfo.m_penaltyFactor - << " , " << paramInfo.m_tie << " , " << paramInfo.m_formula << " , " - << paramInfo.m_formulaUnit << " , " << paramInfo.m_resultUnit << " , " - << (*(paramInfo.m_interpolation)); - paramMap.add("fitting", paramInfo.m_component, name, str.str(), - pDescription); + str << paramInfo.m_value << " , " << paramInfo.m_fittingFunction << " , " << name << " , " + << paramInfo.m_constraint[0] << " , " << paramInfo.m_constraint[1] << " , " << paramInfo.m_penaltyFactor + << " , " << paramInfo.m_tie << " , " << paramInfo.m_formula << " , " << paramInfo.m_formulaUnit << " , " + << paramInfo.m_resultUnit << " , " << (*(paramInfo.m_interpolation)); + paramMap.add("fitting", paramInfo.m_component, name, str.str(), pDescription, pVisible); } else if (category == "string") { - paramMap.addString(paramInfo.m_component, name, paramInfo.m_value, - pDescription); + paramMap.addString(paramInfo.m_component, name, paramInfo.m_value, pDescription, pVisible); } else if (category == "bool") { - paramMap.addBool(paramInfo.m_component, name, paramValue, pDescription); + paramMap.addBool(paramInfo.m_component, name, paramValue, pDescription, pVisible); } else if (category == "int") { - paramMap.addInt(paramInfo.m_component, name, paramValue, pDescription); + paramMap.addInt(paramInfo.m_component, name, paramValue, pDescription, pVisible); } else { // assume double - paramMap.addDouble(paramInfo.m_component, name, paramValue, pDescription); + paramMap.addDouble(paramInfo.m_component, name, paramValue, pDescription, pVisible); } } @@ -1343,34 +1300,26 @@ namespace Kernel { template <> MANTID_API_DLL Mantid::API::ExperimentInfo_sptr -IPropertyManager::getValue( - const std::string &name) const { - auto *prop = - dynamic_cast *>( - getPointerToProperty(name)); +IPropertyManager::getValue(const std::string &name) const { + auto *prop = dynamic_cast *>(getPointerToProperty(name)); if (prop) { return *prop; } else { std::string message = - "Attempt to assign property " + name + - " to incorrect type. Expected shared_ptr."; + "Attempt to assign property " + name + " to incorrect type. Expected shared_ptr."; throw std::runtime_error(message); } } template <> MANTID_API_DLL Mantid::API::ExperimentInfo_const_sptr -IPropertyManager::getValue( - const std::string &name) const { - auto *prop = - dynamic_cast *>( - getPointerToProperty(name)); +IPropertyManager::getValue(const std::string &name) const { + auto *prop = dynamic_cast *>(getPointerToProperty(name)); if (prop) { return prop->operator()(); } else { std::string message = - "Attempt to assign property " + name + - " to incorrect type. Expected const shared_ptr."; + "Attempt to assign property " + name + " to incorrect type. Expected const shared_ptr."; throw std::runtime_error(message); } } diff --git a/Framework/API/src/Expression.cpp b/Framework/API/src/Expression.cpp index 5308ca5283ba369cc646dd73151157d8c03bec93..4db9bf1bd1fe21c322c38be4a9113a897ef271d2 100644 --- a/Framework/API/src/Expression.cpp +++ b/Framework/API/src/Expression.cpp @@ -17,8 +17,7 @@ namespace API { using tokenizer = Mantid::Kernel::StringTokenizer; -const std::string DEFAULT_OPS_STR[] = { - ";", ",", "=", "== != > < <= >=", "&& || ^^", "+ -", "* /", "^"}; +const std::string DEFAULT_OPS_STR[] = {";", ",", "=", "== != > < <= >=", "&& || ^^", "+ -", "* /", "^"}; const std::string EMPTY_EXPRESSION_NAME = "EMPTY"; namespace { @@ -27,8 +26,7 @@ namespace { /// @param expr :: An expression string that caused the error. /// @param i :: An index of a symbol in expr that may help identify the location /// of the error. -std::string makeErrorMessage(const std::string &msg, const std::string &expr, - size_t i) { +std::string makeErrorMessage(const std::string &msg, const std::string &expr, size_t i) { const size_t MAX_LEFT_SIZE = 10; const size_t MAX_RIGHT_SIZE = 10; std::ostringstream res; @@ -64,14 +62,12 @@ Kernel::Logger logger("Expression"); /// @param expr :: An expression string that caused the error. /// @param i :: An index of a symbol in expr that may help identify the location /// of the error. -Expression::ParsingError::ParsingError(const std::string &msg, - const std::string &expr, size_t i) +Expression::ParsingError::ParsingError(const std::string &msg, const std::string &expr, size_t i) : std::runtime_error(makeErrorMessage(msg, expr, i)) {} /// Constructor /// @param msg :: The text of the error message. -Expression::ParsingError::ParsingError(const std::string &msg) - : std::runtime_error(msg) {} +Expression::ParsingError::ParsingError(const std::string &msg) : std::runtime_error(msg) {} Expression::Expression() { m_operators.reset(new Operators()); @@ -96,8 +92,7 @@ Expression::Expression(const std::vector &ops) { } /// contructor -Expression::Expression(const std::vector &binary, - const std::unordered_set &unary) { +Expression::Expression(const std::vector &binary, const std::unordered_set &unary) { m_operators.reset(new Operators()); add_operators(binary); add_unary(unary); @@ -106,10 +101,8 @@ Expression::Expression(const std::vector &binary, Expression::Expression(const Expression &expr) : // m_tokens(expr.m_tokens), // m_expr(expr.m_expr), - m_funct(expr.m_funct), m_op(expr.m_op), m_terms(expr.m_terms), - m_operators(expr.m_operators) {} -Expression::Expression(const Expression *pexpr) - : m_operators(pexpr->m_operators) {} + m_funct(expr.m_funct), m_op(expr.m_op), m_terms(expr.m_terms), m_operators(expr.m_operators) {} +Expression::Expression(const Expression *pexpr) : m_operators(pexpr->m_operators) {} /// Assignment operator Expression &Expression::operator=(const Expression &expr) { @@ -127,8 +120,7 @@ void Expression::add_operators(const std::vector &ops) { // Fill in the precedence table (m_op_precedence) for (size_t i = 0; i < m_operators->binary.size(); i++) { char j = 0; - tokenizer tkz(m_operators->binary[i], " ", - tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM); + tokenizer tkz(m_operators->binary[i], " ", tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM); for (const auto &index : tkz) { m_operators->precedence[index] = i + 1; m_operators->op_number[index] = j++; @@ -152,8 +144,7 @@ void Expression::add_unary(const std::unordered_set &ops) { } size_t Expression::op_prec(const std::string &op) const { - std::map::const_iterator i = - m_operators->precedence.find(op); + std::map::const_iterator i = m_operators->precedence.find(op); if (i == m_operators->precedence.end()) return 0; return i->second; @@ -163,9 +154,7 @@ bool Expression::is_unary(const std::string &op) const { return m_operators->unary.find(op) != m_operators->unary.end(); } -bool Expression::is_op_symbol(const char c) const { - return m_operators->symbols.find(c) != m_operators->symbols.end(); -} +bool Expression::is_op_symbol(const char c) const { return m_operators->symbols.find(c) != m_operators->symbols.end(); } void Expression::trim(std::string &str) { size_t i = str.find_first_not_of(" \t\n\r"); @@ -199,8 +188,7 @@ void Expression::parse(const std::string &str) { std::string op = GetOp(0); // size_t prec = m_operators->precedence[op]; size_t prec = op_prec(op); - tokenizer tkz(m_operators->binary[prec - 1], " ", - tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM); + tokenizer tkz(m_operators->binary[prec - 1], " ", tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM); setFunct(*tkz.begin()); @@ -274,8 +262,7 @@ void Expression::tokenize() { m_expr.resize(last); break; } else { - throw ParsingError("A binary operator isn't followed by a value", - m_expr, i); + throw ParsingError("A binary operator isn't followed by a value", m_expr, i); } } auto is1 = i + (is_op_symbol(m_expr[i + 1]) ? 2 : 1); @@ -471,8 +458,7 @@ void Expression::setFunct(const std::string &name) { std::string f = name.substr(0, i); Expression tmp(this); tmp.parse(args); - if (tmp.name() != EMPTY_EXPRESSION_NAME && - (!tmp.isFunct() || tmp.name() != ",")) { + if (tmp.name() != EMPTY_EXPRESSION_NAME && (!tmp.isFunct() || tmp.name() != ",")) { m_terms.emplace_back(tmp); } else { if (f.empty() && tmp.name() == ",") { @@ -570,8 +556,7 @@ std::unordered_set Expression::getVariables() const { void Expression::rename(const std::string &newName) { m_funct = newName; } -void Expression::renameAll(const std::string &oldName, - const std::string &newName) { +void Expression::renameAll(const std::string &oldName, const std::string &newName) { if (!isFunct() && name() == oldName) { rename(newName); } else { diff --git a/Framework/API/src/FileBackedExperimentInfo.cpp b/Framework/API/src/FileBackedExperimentInfo.cpp index 73352c135d4fb0e43d1b1e5c2bd0c98f256f5b14..01ed996cb4750bad44da735706c5e4ee1eead5f8 100644 --- a/Framework/API/src/FileBackedExperimentInfo.cpp +++ b/Framework/API/src/FileBackedExperimentInfo.cpp @@ -27,19 +27,15 @@ Kernel::Logger g_log("FileBackedExperimentInfo"); * @param filename The full path to the file * @param nxpath Path to the location of the experiment information */ -FileBackedExperimentInfo::FileBackedExperimentInfo(const std::string &filename, - const std::string &nxpath) - : ExperimentInfo(), m_loaded(false), m_filename(filename), - m_nxpath(nxpath) {} +FileBackedExperimentInfo::FileBackedExperimentInfo(const std::string &filename, const std::string &nxpath) + : ExperimentInfo(), m_loaded(false), m_filename(filename), m_nxpath(nxpath) {} /** * This clones the FileBackedExperimentInfo and will not cause a load * of the information. * @return A clone of the object. */ -ExperimentInfo *FileBackedExperimentInfo::cloneExperimentInfo() const { - return new FileBackedExperimentInfo(*this); -} +ExperimentInfo *FileBackedExperimentInfo::cloneExperimentInfo() const { return new FileBackedExperimentInfo(*this); } /** * Check if the object has been populated and load the information if @@ -64,14 +60,11 @@ void FileBackedExperimentInfo::populateFromFile() const { m_loaded = true; std::string parameterStr; - const_cast(this)->loadExperimentInfoNexus( - m_filename, &nxFile, parameterStr); - const_cast(this)->readParameterMap( - parameterStr); + const_cast(this)->loadExperimentInfoNexus(m_filename, &nxFile, parameterStr); + const_cast(this)->readParameterMap(parameterStr); } catch (::NeXus::Exception &exc) { std::ostringstream os; - os << "Unable to load experiment information from NeXus file: " - << exc.what() << "\n"; + os << "Unable to load experiment information from NeXus file: " << exc.what() << "\n"; throw std::runtime_error(os.str()); } } diff --git a/Framework/API/src/FileFinder.cpp b/Framework/API/src/FileFinder.cpp index e945313ed0f6f7a3d89b6d0c5094421c25c4da33..561463b3c6eb994404a29566efcb31e2c1e35168 100644 --- a/Framework/API/src/FileFinder.cpp +++ b/Framework/API/src/FileFinder.cpp @@ -42,9 +42,12 @@ Mantid::Kernel::Logger g_log("FileFinder"); * * @returns true if extension contains a "*", else false. */ -bool containsWildCard(const std::string &ext) { - return std::string::npos != ext.find('*'); +bool containsWildCard(const std::string &ext) { return std::string::npos != ext.find('*'); } + +bool isASCII(const std::string &str) { + return !std::any_of(str.cbegin(), str.cend(), [](char c) { return static_cast(c) > 127; }); } + } // namespace namespace Mantid { @@ -68,9 +71,7 @@ FileFinderImpl::FileFinderImpl() { #ifdef _WIN32 m_globOption = Poco::Glob::GLOB_DEFAULT; #else - setCaseSensitive(Kernel::ConfigService::Instance() - .getValue("filefinder.casesensitive") - .get_value_or(false)); + setCaseSensitive(Kernel::ConfigService::Instance().getValue("filefinder.casesensitive").get_value_or(false)); #endif } @@ -90,9 +91,7 @@ void FileFinderImpl::setCaseSensitive(const bool cs) { * @return cs :: If case sensitive return true, if not case sensitive return * false */ -bool FileFinderImpl::getCaseSensitive() const { - return (m_globOption == Poco::Glob::GLOB_DEFAULT); -} +bool FileFinderImpl::getCaseSensitive() const { return (m_globOption == Poco::Glob::GLOB_DEFAULT); } /** * Return the full path to the file given its name @@ -104,10 +103,8 @@ bool FileFinderImpl::getCaseSensitive() const { * or an empty string otherwise. */ -std::string FileFinderImpl::getFullPath(const std::string &filename, - const bool ignoreDirs) const { - return Kernel::ConfigService::Instance().getFullPath(filename, ignoreDirs, - m_globOption); +std::string FileFinderImpl::getFullPath(const std::string &filename, const bool ignoreDirs) const { + return Kernel::ConfigService::Instance().getFullPath(filename, ignoreDirs, m_globOption); } /** Run numbers can be followed by an allowed string. Check if there is @@ -115,8 +112,7 @@ std::string FileFinderImpl::getFullPath(const std::string &filename, * @param userString run number that may have a suffix * @return the suffix, if there was one */ -std::string -FileFinderImpl::extractAllowedSuffix(std::string &userString) const { +std::string FileFinderImpl::extractAllowedSuffix(std::string &userString) const { if (userString.find(ALLOWED_SUFFIX) == std::string::npos) { // short cut processing as normally there is no suffix return ""; @@ -139,8 +135,7 @@ FileFinderImpl::extractAllowedSuffix(std::string &userString) const { * @param hint :: The name hint. * @return This will return the default instrument if it cannot be determined. */ -const Kernel::InstrumentInfo -FileFinderImpl::getInstrument(const string &hint) const { +const Kernel::InstrumentInfo FileFinderImpl::getInstrument(const string &hint) const { if ((!hint.empty()) && (!isdigit(hint[0]))) { string instrName(hint); Poco::Path path(instrName); @@ -157,14 +152,12 @@ FileFinderImpl::getInstrument(const string &hint) const { // code gets an overhaul as part of that ticket. Please think twice before // adding // any more instruments to this list. - else if ((instrName.find("SANS2D") == 0) || - (instrName.find("sans2d") == 0)) { + else if ((instrName.find("SANS2D") == 0) || (instrName.find("sans2d") == 0)) { instrName = "SANS2D"; } else { // go forwards looking for the run number to start { - const auto it = - std::find_if(instrName.begin(), instrName.end(), isdigit); + const auto it = std::find_if(instrName.begin(), instrName.end(), isdigit); const auto nChars = std::distance(instrName.begin(), it); instrName = instrName.substr(0, nChars); } @@ -172,15 +165,13 @@ FileFinderImpl::getInstrument(const string &hint) const { // go backwards looking for the instrument name to end - gets around // delimiters if (!instrName.empty()) { - const auto it = - std::find_if(instrName.rbegin(), instrName.rend(), isalpha); + const auto it = std::find_if(instrName.rbegin(), instrName.rend(), isalpha); const auto nChars = std::distance(it, instrName.rend()); instrName = instrName.substr(0, nChars); } } try { - const Kernel::InstrumentInfo instrument = - Kernel::ConfigService::Instance().getInstrument(instrName); + const Kernel::InstrumentInfo instrument = Kernel::ConfigService::Instance().getInstrument(instrName); return instrument; } catch (Kernel::Exception::NotFoundError &e) { g_log.debug() << e.what() << "\n"; @@ -194,8 +185,7 @@ FileFinderImpl::getInstrument(const string &hint) const { * @param hint :: The name hint * @return A pair of instrument name and run number */ -std::pair -FileFinderImpl::toInstrumentAndNumber(const std::string &hint) const { +std::pair FileFinderImpl::toInstrumentAndNumber(const std::string &hint) const { // g_log.debug() << "toInstrumentAndNumber(" << hint << ")\n"; std::string instrPart; std::string runPart; @@ -205,12 +195,10 @@ FileFinderImpl::toInstrumentAndNumber(const std::string &hint) const { runPart = hint; } else { /// Find the last non-digit as the instrument name can contain numbers - std::string::const_reverse_iterator it = - std::find_if(hint.rbegin(), hint.rend(), std::not_fn(isdigit)); + std::string::const_reverse_iterator it = std::find_if(hint.rbegin(), hint.rend(), std::not_fn(isdigit)); // No non-digit or all non-digits if (it == hint.rend() || it == hint.rbegin()) { - throw std::invalid_argument( - "Malformed hint to FileFinderImpl::makeFileName: " + hint); + throw std::invalid_argument("Malformed hint to FileFinderImpl::makeFileName: " + hint); } std::string::size_type nChars = std::distance(it, hint.rend()); @@ -238,8 +226,7 @@ FileFinderImpl::toInstrumentAndNumber(const std::string &hint) const { os << "Cannot convert '" << runPart << "' to run number."; throw std::invalid_argument(os.str()); } - Kernel::InstrumentInfo instr = - Kernel::ConfigService::Instance().getInstrument(instrPart); + Kernel::InstrumentInfo instr = Kernel::ConfigService::Instance().getInstrument(instrPart); size_t nZero = instr.zeroPadding(irunPart); // remove any leading zeros in case there are too many of them std::string::size_type i = runPart.find_first_not_of('0'); @@ -247,8 +234,7 @@ FileFinderImpl::toInstrumentAndNumber(const std::string &hint) const { while (runPart.size() < nZero) runPart.insert(0, "0"); if (runPart.size() > nZero && nZero != 0) { - throw std::invalid_argument( - "Run number does not match instrument's zero padding"); + throw std::invalid_argument("Run number does not match instrument's zero padding"); } instrPart = instr.filePrefix(irunPart); @@ -268,9 +254,7 @@ FileFinderImpl::toInstrumentAndNumber(const std::string &hint) const { * @throw std::invalid_argument if the argument is malformed or run number is * too long */ -std::string -FileFinderImpl::makeFileName(const std::string &hint, - const Kernel::InstrumentInfo &instrument) const { +std::string FileFinderImpl::makeFileName(const std::string &hint, const Kernel::InstrumentInfo &instrument) const { // g_log.debug() << "makeFileName(" << hint << ", " << instrument.shortName() // << ")\n"; if (hint.empty()) @@ -284,8 +268,7 @@ FileFinderImpl::makeFileName(const std::string &hint, // see if starts with the provided instrument name if (filename.substr(0, shortName.size()) == shortName) { filename = filename.substr(shortName.size()); - if ((!delimiter.empty()) && - (filename.substr(0, delimiter.size()) == delimiter)) + if ((!delimiter.empty()) && (filename.substr(0, delimiter.size()) == delimiter)) filename = filename.substr(delimiter.size()); filename = shortName + filename; @@ -315,25 +298,20 @@ FileFinderImpl::makeFileName(const std::string &hint, * * @return The extension. If one isn't determined it is an empty string. */ -std::string -FileFinderImpl::getExtension(const std::string &filename, - const std::vector &exts) const { - g_log.debug() << "getExtension(" << filename << ", exts[" << exts.size() - << "])\n"; +std::string FileFinderImpl::getExtension(const std::string &filename, const std::vector &exts) const { + g_log.debug() << "getExtension(" << filename << ", exts[" << exts.size() << "])\n"; // go through the list of supplied extensions for (const auto &ext : exts) { std::string extension = toUpper(ext); - if (extension.rfind('*') == - extension.size() - 1) // there is a wildcard at play + if (extension.rfind('*') == extension.size() - 1) // there is a wildcard at play { extension = extension.substr(0, extension.rfind('*')); } std::size_t found = toUpper(filename).rfind(extension); if (found != std::string::npos) { - g_log.debug() << "matched extension \"" << extension << "\" based on \"" - << ext << "\"\n"; + g_log.debug() << "matched extension \"" << extension << "\" based on \"" << ext << "\"\n"; return filename.substr(found); // grab the actual extensions found } } @@ -348,20 +326,16 @@ FileFinderImpl::getExtension(const std::string &filename, return ""; } -std::vector -FileFinderImpl::getArchiveSearch(const Kernel::FacilityInfo &facility) const { +std::vector FileFinderImpl::getArchiveSearch(const Kernel::FacilityInfo &facility) const { std::vector archs; // get the searchive option from config service and format it - std::string archiveOpt = - Kernel::ConfigService::Instance().getString("datasearch.searcharchive"); - std::transform(archiveOpt.begin(), archiveOpt.end(), archiveOpt.begin(), - tolower); + std::string archiveOpt = Kernel::ConfigService::Instance().getString("datasearch.searcharchive"); + std::transform(archiveOpt.begin(), archiveOpt.end(), archiveOpt.begin(), tolower); // if it is turned off, not specified, or the facility doesn't have // IArchiveSearch defined, return an empty vector - if (archiveOpt.empty() || archiveOpt == "off" || - facility.archiveSearch().empty()) + if (archiveOpt.empty() || archiveOpt == "off" || facility.archiveSearch().empty()) return archs; // determine if the user wants archive search for this facility @@ -371,37 +345,30 @@ FileFinderImpl::getArchiveSearch(const Kernel::FacilityInfo &facility) const { // default facility if (!createArchiveSearch) { std::string faciltyName = facility.name(); - std::transform(faciltyName.begin(), faciltyName.end(), faciltyName.begin(), - tolower); + std::transform(faciltyName.begin(), faciltyName.end(), faciltyName.begin(), tolower); if (archiveOpt == "on") { // only default facilty - std::string defaultFacility = - Kernel::ConfigService::Instance().getString("default.facility"); - std::transform(defaultFacility.begin(), defaultFacility.end(), - defaultFacility.begin(), tolower); + std::string defaultFacility = Kernel::ConfigService::Instance().getString("default.facility"); + std::transform(defaultFacility.begin(), defaultFacility.end(), defaultFacility.begin(), tolower); createArchiveSearch = bool(faciltyName == defaultFacility); } else { // everything in the list - createArchiveSearch = - bool(archiveOpt.find(faciltyName) != std::string::npos); + createArchiveSearch = bool(archiveOpt.find(faciltyName) != std::string::npos); } } // put together the list of IArchiveSearch to use if (createArchiveSearch) { for (const auto &facilityname : facility.archiveSearch()) { - g_log.debug() << "get archive search for the facility..." << facilityname - << "\n"; + g_log.debug() << "get archive search for the facility..." << facilityname << "\n"; archs.emplace_back(ArchiveSearchFactory::Instance().create(facilityname)); } } return archs; } -std::string FileFinderImpl::findRun(const std::string &hintstr, - const std::vector &exts, +std::string FileFinderImpl::findRun(const std::string &hintstr, const std::vector &exts, const bool useExtsOnly) const { std::string hint = Kernel::Strings::strip(hintstr); - g_log.debug() << "vector findRun(\'" << hint << "\', exts[" << exts.size() - << "])\n"; + g_log.debug() << "vector findRun(\'" << hint << "\', exts[" << exts.size() << "])\n"; // if partial filename or run number is not supplied, return here if (hint.empty()) @@ -453,12 +420,14 @@ std::string FileFinderImpl::findRun(const std::string &hintstr, } } catch (std::invalid_argument &) { if (filename.length() >= hint.length()) { - g_log.information() << "Could not form filename from standard rules '" - << filename << "'\n"; + g_log.information() << "Could not form filename from standard rules '" << filename << "'\n"; } } } + if (filename.empty()) + return ""; + // Look first at the original filename then for case variations. This is // important // on platforms where file names ARE case sensitive. @@ -470,11 +439,9 @@ std::string FileFinderImpl::findRun(const std::string &hintstr, filenames.insert(filename); if (!getCaseSensitive()) { std::string transformed(filename); - std::transform(filename.begin(), filename.end(), transformed.begin(), - toupper); + std::transform(filename.begin(), filename.end(), transformed.begin(), toupper); filenames.insert(transformed); - std::transform(filename.begin(), filename.end(), transformed.begin(), - tolower); + std::transform(filename.begin(), filename.end(), transformed.begin(), tolower); filenames.insert(transformed); } @@ -516,23 +483,33 @@ std::string FileFinderImpl::findRun(const std::string &hintstr, * @param extensionsToAdd :: a vector of extensions to add * @param uniqueExts :: a vector of currently included extensions */ -void FileFinderImpl::getUniqueExtensions( - const std::vector &extensionsToAdd, - std::vector &uniqueExts) const { +void FileFinderImpl::getUniqueExtensions(const std::vector &extensionsToAdd, + std::vector &uniqueExts) const { const bool isCaseSensitive = getCaseSensitive(); for (const auto &cit : extensionsToAdd) { std::string transformed(cit); if (!isCaseSensitive) { std::transform(cit.begin(), cit.end(), transformed.begin(), tolower); } - const auto searchItr = - std::find(uniqueExts.begin(), uniqueExts.end(), transformed); + const auto searchItr = std::find(uniqueExts.begin(), uniqueExts.end(), transformed); if (searchItr == uniqueExts.end()) { uniqueExts.emplace_back(transformed); } } } +/** + * Performs validation on the search text entered into the File Finder. It will + * return an error message if a problem is found. + * @param searchText :: The text to validate. + * @return An error message if something is invalid. + */ +std::string FileFinderImpl::validateRuns(const std::string &searchText) const { + if (!isASCII(searchText)) + return "An unsupported non-ASCII character was found in the search text."; + return ""; +} + /** * Find a list of files file given a hint. Calls findRun internally. * @param hintstr :: Comma separated list of hints to findRun method. @@ -548,20 +525,21 @@ void FileFinderImpl::getUniqueExtensions( * @throw std::invalid_argument if the argument is malformed * @throw Exception::NotFoundError if a file could not be found */ -std::vector -FileFinderImpl::findRuns(const std::string &hintstr, - const std::vector &exts, - const bool useExtsOnly) const { +std::vector FileFinderImpl::findRuns(const std::string &hintstr, const std::vector &exts, + const bool useExtsOnly) const { + auto const error = validateRuns(hintstr); + if (!error.empty()) + throw std::invalid_argument(error); + std::string hint = Kernel::Strings::strip(hintstr); g_log.debug() << "findRuns hint = " << hint << "\n"; std::vector res; Mantid::Kernel::StringTokenizer hints( - hint, ",", - Mantid::Kernel::StringTokenizer::TOK_TRIM | - Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY); + hint, ",", Mantid::Kernel::StringTokenizer::TOK_TRIM | Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY); static const boost::regex digits("[0-9]+"); auto h = hints.begin(); + std::string instrSName; for (; h != hints.end(); ++h) { // Quick check for a filename bool fileSuspected = false; @@ -577,13 +555,14 @@ FileFinderImpl::findRuns(const std::string &hintstr, } Mantid::Kernel::StringTokenizer range( - *h, "-", - Mantid::Kernel::StringTokenizer::TOK_TRIM | - Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY); + *h, "-", Mantid::Kernel::StringTokenizer::TOK_TRIM | Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY); if ((range.count() > 2) && (!fileSuspected)) { throw std::invalid_argument("Malformed range of runs: " + *h); } else if ((range.count() == 2) && (!fileSuspected)) { std::pair p1 = toInstrumentAndNumber(range[0]); + if (boost::algorithm::istarts_with(hint, "PG3")) { + instrSName = "PG3"; + } std::string run = p1.second; size_t nZero = run.size(); // zero padding if (range[1].size() > nZero) { @@ -605,19 +584,57 @@ FileFinderImpl::findRuns(const std::string &hintstr, if (runEndNumber < runNumber) { throw std::invalid_argument("Malformed range of runs: " + *h); } + std::string previousPath, previousExt; for (int irun = runNumber; irun <= runEndNumber; ++irun) { run = std::to_string(irun); while (run.size() < nZero) run.insert(0, "0"); - std::string path = findRun(p1.first + run, exts, useExtsOnly); + + // Quick check if file can be created from previous successfully found + // path/extension + if (!previousPath.empty() && !previousExt.empty()) { + try { + const Poco::File file(previousPath + p1.first + run + previousExt); + if (file.exists()) { + res.emplace_back(file.path()); + continue; + } + } catch (...) { + // Clear cached path and extension + previousPath = previousExt = ""; + } + } + + std::string path; + if (boost::algorithm::istarts_with(hint, "PG3")) { + path = findRun(instrSName + run, exts, useExtsOnly); + } else { + path = findRun(p1.first + run, exts, useExtsOnly); + } + if (!path.empty()) { + // Cache successfully found path and extension + auto tempPath = Poco::Path(path); + previousExt = "." + tempPath.getExtension(); + previousPath = tempPath.makeParent().toString(); res.emplace_back(path); } else { throw Kernel::Exception::NotFoundError("Unable to find file:", run); } } } else { - std::string path = findRun(*h, exts, useExtsOnly); + std::string path; + // Special check for "PG3", to cope with situation like '48314,48316'. + if (boost::algorithm::istarts_with(hint, "PG3")) { + if (h == hints.begin()) { + instrSName = "PG3"; + path = findRun(*h, exts, useExtsOnly); + } else { + path = findRun(instrSName + *h, exts, useExtsOnly); + } + } else { + path = findRun(*h, exts, useExtsOnly); + } if (!path.empty()) { res.emplace_back(path); } else { @@ -639,10 +656,9 @@ FileFinderImpl::findRuns(const std::string &hintstr, * search locations * or an empty string otherwise. */ -std::string -FileFinderImpl::getArchivePath(const std::vector &archs, - const std::set &filenames, - const std::vector &exts) const { +std::string FileFinderImpl::getArchivePath(const std::vector &archs, + const std::set &filenames, + const std::vector &exts) const { g_log.debug() << "getArchivePath([IArchiveSearch_sptr], [ "; for (const auto &iter : filenames) g_log.debug() << iter << " "; @@ -676,22 +692,18 @@ FileFinderImpl::getArchivePath(const std::vector &archs, * search locations * or an empty string otherwise. */ -std::string -FileFinderImpl::getPath(const std::vector &archs, - const std::set &filenames, - const std::vector &exts) const { +std::string FileFinderImpl::getPath(const std::vector &archs, + const std::set &filenames, + const std::vector &exts) const { std::string path; std::vector extensions; extensions.assign(exts.begin(), exts.end()); // Remove wild cards. - extensions.erase( - std::remove_if(extensions.begin(), extensions.end(), containsWildCard), - extensions.end()); + extensions.erase(std::remove_if(extensions.begin(), extensions.end(), containsWildCard), extensions.end()); - const std::vector &searchPaths = - Kernel::ConfigService::Instance().getDataSearchDirs(); + const std::vector &searchPaths = Kernel::ConfigService::Instance().getDataSearchDirs(); // Before we try any globbing, make sure we exhaust all reasonable attempts at // constructing the possible filename. @@ -719,13 +731,11 @@ FileFinderImpl::getPath(const std::vector &archs, path = getFullPath(filename + extension); try { if (!path.empty() && Poco::File(path).exists()) { - g_log.debug() << "path returned from getFullPath() = " << path - << '\n'; + g_log.debug() << "path returned from getFullPath() = " << path << '\n'; return path; } } catch (std::exception &e) { - g_log.error() << "Cannot open file " << path << ": " << e.what() - << '\n'; + g_log.error() << "Cannot open file " << path << ": " << e.what() << '\n'; return ""; } } @@ -740,8 +750,7 @@ FileFinderImpl::getPath(const std::vector &archs, return archivePath; } } catch (std::exception &e) { - g_log.error() << "Cannot open file " << archivePath << ": " << e.what() - << '\n'; + g_log.error() << "Cannot open file " << archivePath << ": " << e.what() << '\n'; return ""; } diff --git a/Framework/API/src/FileLoaderRegistry.cpp b/Framework/API/src/FileLoaderRegistry.cpp index 42fbf7790f20298e02e553e52a1dfcd302cc7dca..10c895d15625100ca117c8f9522454040864dd0b 100644 --- a/Framework/API/src/FileLoaderRegistry.cpp +++ b/Framework/API/src/FileLoaderRegistry.cpp @@ -21,21 +21,17 @@ template struct DescriptorCallback { void apply(std::shared_ptr & /*unused*/) {} // general one does nothing }; template <> struct DescriptorCallback { - void apply(std::shared_ptr &descriptor) { - descriptor->resetStreamToStart(); - } + void apply(std::shared_ptr &descriptor) { descriptor->resetStreamToStart(); } }; /// @endcond /// @cond template struct DescriptorSetter { // general one does nothing - void apply(std::shared_ptr & /*unused*/, - std::shared_ptr & /*unused*/) {} + void apply(std::shared_ptr & /*unused*/, std::shared_ptr & /*unused*/) {} }; template <> struct DescriptorSetter { - void apply(std::shared_ptr &loader, - std::shared_ptr &descriptor) { + void apply(std::shared_ptr &loader, std::shared_ptr &descriptor) { loader->setFileInfo(descriptor); } }; @@ -50,10 +46,8 @@ template <> struct DescriptorSetter { * was found */ template -const IAlgorithm_sptr -searchForLoader(const std::string &filename, - const std::multimap &names, - Kernel::Logger &logger) { +const IAlgorithm_sptr searchForLoader(const std::string &filename, const std::multimap &names, + Kernel::Logger &logger) { const auto &factory = AlgorithmFactory::Instance(); IAlgorithm_sptr bestLoader; int maxConfidence(0); @@ -69,20 +63,17 @@ searchForLoader(const std::string &filename, // Use static cast for speed. Checks have been done at registration to check // the types - auto alg = std::static_pointer_cast( - factory.create(name, version)); // highest version + auto alg = std::static_pointer_cast(factory.create(name, version)); // highest version try { const int confidence = alg->confidence(*(descriptor.get())); - logger.debug() << name << " returned with confidence=" << confidence - << '\n'; + logger.debug() << name << " returned with confidence=" << confidence << '\n'; if (confidence > maxConfidence) // strictly greater { bestLoader = alg; maxConfidence = confidence; } } catch (std::exception &exc) { - logger.warning() << "Checking loader '" << name << "' raised an error: '" - << exc.what() << "'. Loader skipped.\n"; + logger.warning() << "Checking loader '" << name << "' raised an error: '" << exc.what() << "'. Loader skipped.\n"; } callback.apply(descriptor); } @@ -105,8 +96,7 @@ searchForLoader(const std::string &filename, * @param version An optional version to remove. -1 indicates remove all * (Default=-1) */ -void FileLoaderRegistryImpl::unsubscribe(const std::string &name, - const int version) { +void FileLoaderRegistryImpl::unsubscribe(const std::string &name, const int version) { auto iend = m_names.end(); for (auto it = m_names.begin(); it != iend; ++it) { removeAlgorithm(name, version, *it); @@ -121,8 +111,7 @@ void FileLoaderRegistryImpl::unsubscribe(const std::string &name, * @return A string containing the name of an algorithm to load the file * @throws Exception::NotFoundError if an algorithm cannot be found */ -const std::shared_ptr -FileLoaderRegistryImpl::chooseLoader(const std::string &filename) const { +const std::shared_ptr FileLoaderRegistryImpl::chooseLoader(const std::string &filename) const { using Kernel::FileDescriptor; using Kernel::NexusDescriptor; using Kernel::NexusHDF5Descriptor; @@ -130,39 +119,31 @@ FileLoaderRegistryImpl::chooseLoader(const std::string &filename) const { IAlgorithm_sptr bestLoader; if (NexusDescriptor::isReadable(filename)) { - m_log.debug() - << filename - << " looks like a Nexus file. Checking registered Nexus loaders\n"; + m_log.debug() << filename << " looks like a Nexus file. Checking registered Nexus loaders\n"; // a large subset of NeXus files are actually HDF5 based if (NexusHDF5Descriptor::isReadable(filename)) { try { - bestLoader = searchForLoader>( - filename, m_names[NexusHDF5], m_log); + bestLoader = + searchForLoader>(filename, m_names[NexusHDF5], m_log); } catch (const std::invalid_argument &e) { - m_log.debug() << "Error in looking for HDF5 based NeXus files: " - << e.what() << '\n'; + m_log.debug() << "Error in looking for HDF5 based NeXus files: " << e.what() << '\n'; } } // try generic nexus loaders if (!bestLoader) { - bestLoader = - searchForLoader>( - filename, m_names[Nexus], m_log); + bestLoader = searchForLoader>(filename, m_names[Nexus], m_log); } } else { m_log.debug() << "Checking registered non-HDF loaders\n"; - bestLoader = searchForLoader>( - filename, m_names[Generic], m_log); + bestLoader = searchForLoader>(filename, m_names[Generic], m_log); } if (!bestLoader) { throw Kernel::Exception::NotFoundError(filename, "Unable to find loader"); } - m_log.debug() << "Found loader " << bestLoader->name() << " for file '" - << filename << "'\n"; + m_log.debug() << "Found loader " << bestLoader->name() << " for file '" << filename << "'\n"; return bestLoader; } @@ -173,46 +154,36 @@ FileLoaderRegistryImpl::chooseLoader(const std::string &filename) const { * @returns True if the algorithm can load the file, false otherwise * @throws std::invalid_argument if the loader does not exist */ -bool FileLoaderRegistryImpl::canLoad(const std::string &algorithmName, - const std::string &filename) const { +bool FileLoaderRegistryImpl::canLoad(const std::string &algorithmName, const std::string &filename) const { using Kernel::FileDescriptor; using Kernel::NexusDescriptor; using Kernel::NexusHDF5Descriptor; // Check if it is in one of our lists - const bool nexus = - (m_names[Nexus].find(algorithmName) != m_names[Nexus].end()); - const bool nexusHDF5 = - (m_names[NexusHDF5].find(algorithmName) != m_names[NexusHDF5].end()); - const bool nonHDF = - (m_names[Generic].find(algorithmName) != m_names[Generic].end()); + const bool nexus = (m_names[Nexus].find(algorithmName) != m_names[Nexus].end()); + const bool nexusHDF5 = (m_names[NexusHDF5].find(algorithmName) != m_names[NexusHDF5].end()); + const bool nonHDF = (m_names[Generic].find(algorithmName) != m_names[Generic].end()); if (!(nexus || nexusHDF5 || nonHDF)) - throw std::invalid_argument( - "FileLoaderRegistryImpl::canLoad - Algorithm '" + algorithmName + - "' is not registered as a loader."); + throw std::invalid_argument("FileLoaderRegistryImpl::canLoad - Algorithm '" + algorithmName + + "' is not registered as a loader."); std::multimap names{{algorithmName, -1}}; IAlgorithm_sptr loader; if (nexus) { if (NexusDescriptor::isReadable(filename)) { - loader = searchForLoader>( - filename, names, m_log); + loader = searchForLoader>(filename, names, m_log); } } else if (nexusHDF5) { if (NexusHDF5Descriptor::isReadable(filename)) { try { - loader = searchForLoader>( - filename, names, m_log); + loader = searchForLoader>(filename, names, m_log); } catch (const std::invalid_argument &e) { - m_log.debug() << "Error in looking for HDF5 based NeXus files: " - << e.what() << '\n'; + m_log.debug() << "Error in looking for HDF5 based NeXus files: " << e.what() << '\n'; } } } else if (nonHDF) { - loader = searchForLoader>( - filename, names, m_log); + loader = searchForLoader>(filename, names, m_log); } return static_cast(loader); } @@ -225,8 +196,7 @@ bool FileLoaderRegistryImpl::canLoad(const std::string &algorithmName, * * m_names is initialized in the header */ -FileLoaderRegistryImpl::FileLoaderRegistryImpl() - : m_totalSize(0), m_log("FileLoaderRegistry") {} +FileLoaderRegistryImpl::FileLoaderRegistryImpl() : m_totalSize(0), m_log("FileLoaderRegistry") {} FileLoaderRegistryImpl::~FileLoaderRegistryImpl() = default; @@ -235,9 +205,8 @@ FileLoaderRegistryImpl::~FileLoaderRegistryImpl() = default; * @param version The version to remove. -1 indicates all instances * @param typedLoaders A map of names to version numbers **/ -void FileLoaderRegistryImpl::removeAlgorithm( - const std::string &name, const int version, - std::multimap &typedLoaders) { +void FileLoaderRegistryImpl::removeAlgorithm(const std::string &name, const int version, + std::multimap &typedLoaders) { if (version == -1) // remove all { typedLoaders.erase(name); diff --git a/Framework/API/src/FileProperty.cpp b/Framework/API/src/FileProperty.cpp index d6129409c6fb7c94e7de87f34627bf0cb6a699df..6106865d2e28f91f2f57022544a9e7588306d276 100644 --- a/Framework/API/src/FileProperty.cpp +++ b/Framework/API/src/FileProperty.cpp @@ -37,15 +37,11 @@ namespace { * @param exts A list of extensions, only use for File-type actions and are * passed to the validator */ -IValidator_sptr createValidator(unsigned int action, - const std::vector &exts) { - if (action == FileProperty::Directory || - action == FileProperty::OptionalDirectory) { - return std::make_shared(action == - FileProperty::Directory); +IValidator_sptr createValidator(unsigned int action, const std::vector &exts) { + if (action == FileProperty::Directory || action == FileProperty::OptionalDirectory) { + return std::make_shared(action == FileProperty::Directory); } else { - return std::make_shared(exts, - (action == FileProperty::Load)); + return std::make_shared(exts, (action == FileProperty::Load)); } } @@ -54,10 +50,8 @@ IValidator_sptr createValidator(unsigned int action, * @param extension A string listing the extension * @param extensions The existing collection */ -void addExtension(const std::string &extension, - std::vector &extensions) { - if (std::find(extensions.begin(), extensions.end(), extension) != - extensions.end()) +void addExtension(const std::string &extension, std::vector &extensions) { + if (std::find(extensions.begin(), extensions.end(), extension) != extensions.end()) return; else extensions.emplace_back(extension); @@ -108,8 +102,7 @@ std::string expandUser(const std::string &filepath) { return filepath; // Position of the first slash after the variable - auto nextSlash = - find_if(start, end, [](const char &c) { return c == '/' || c == '\\'; }); + auto nextSlash = find_if(start, end, [](const char &c) { return c == '/' || c == '\\'; }); // ~user/blah format - no support for this as yet if (std::distance(start, nextSlash) != 1) @@ -136,8 +129,7 @@ std::string createDirectory(const std::string &path) { stem.createDirectories(); } catch (Poco::Exception &e) { std::stringstream msg; - msg << "Failed to create directory \"" << stempath.toString() - << "\": " << e.what(); + msg << "Failed to create directory \"" << stempath.toString() << "\": " << e.what(); return msg.str(); } } @@ -161,14 +153,10 @@ std::string createDirectory(const std::string &path) { * will be the default extension * @param direction An optional direction (default=Input) */ -FileProperty::FileProperty(const std::string &name, - const std::string &defaultValue, unsigned int action, - const std::vector &exts, - unsigned int direction) - : PropertyWithValue(name, defaultValue, - createValidator(action, exts), direction), - m_action(action), m_defaultExt((!exts.empty()) ? exts.front() : ""), - m_runFileProp(isLoadProperty() && extsMatchRunFiles()), +FileProperty::FileProperty(const std::string &name, const std::string &defaultValue, unsigned int action, + const std::vector &exts, unsigned int direction) + : PropertyWithValue(name, defaultValue, createValidator(action, exts), direction), m_action(action), + m_defaultExt((!exts.empty()) ? exts.front() : ""), m_runFileProp(isLoadProperty() && extsMatchRunFiles()), m_oldLoadPropValue(""), m_oldLoadFoundFile("") {} /** @@ -180,12 +168,9 @@ FileProperty::FileProperty(const std::string &name, * property * @param direction :: An optional direction (default=Input) */ -FileProperty::FileProperty(const std::string &name, - const std::string &default_value, - unsigned int action, const std::string &ext, - unsigned int direction) - : FileProperty(name, default_value, action, - std::vector(1, ext), direction) {} +FileProperty::FileProperty(const std::string &name, const std::string &default_value, unsigned int action, + const std::string &ext, unsigned int direction) + : FileProperty(name, default_value, action, std::vector(1, ext), direction) {} /** * Constructor @@ -196,45 +181,34 @@ FileProperty::FileProperty(const std::string &name, * property * @param direction :: An optional direction (default=Input) */ -FileProperty::FileProperty(const std::string &name, - const std::string &default_value, - unsigned int action, - std::initializer_list exts, - unsigned int direction) - : FileProperty(name, default_value, action, std::vector(exts), - direction) {} +FileProperty::FileProperty(const std::string &name, const std::string &default_value, unsigned int action, + std::initializer_list exts, unsigned int direction) + : FileProperty(name, default_value, action, std::vector(exts), direction) {} /** * Check if this is a load property * @returns True if the property is a Load property and false otherwise */ -bool FileProperty::isLoadProperty() const { - return m_action == Load || m_action == OptionalLoad; -} +bool FileProperty::isLoadProperty() const { return m_action == Load || m_action == OptionalLoad; } /** * Check if this is a Save property * @returns True if the property is a Save property and false otherwise */ -bool FileProperty::isSaveProperty() const { - return m_action == Save || m_action == OptionalSave; -} +bool FileProperty::isSaveProperty() const { return m_action == Save || m_action == OptionalSave; } /** * Check if this is a directory selection property * @returns True if the property is a Directory property */ -bool FileProperty::isDirectoryProperty() const { - return m_action == Directory || m_action == OptionalDirectory; -} +bool FileProperty::isDirectoryProperty() const { return m_action == Directory || m_action == OptionalDirectory; } /** * Check if this property is optional * @returns True if the property is optinal, false otherwise */ bool FileProperty::isOptional() const { - return (m_action == OptionalLoad || m_action == OptionalSave || - m_action == OptionalDirectory); + return (m_action == OptionalLoad || m_action == OptionalSave || m_action == OptionalDirectory); } /** @@ -316,16 +290,14 @@ std::string FileProperty::isEmptyValueValid() const { bool FileProperty::extsMatchRunFiles() { bool match(false); try { - Kernel::FacilityInfo facilityInfo = - Kernel::ConfigService::Instance().getFacility(); + Kernel::FacilityInfo facilityInfo = Kernel::ConfigService::Instance().getFacility(); const std::vector facilityExts = facilityInfo.extensions(); auto facilityExtsBegin = facilityExts.cbegin(); auto facilityExtsEnd = facilityExts.cend(); const std::vector allowedExts = this->allowedValues(); for (const auto &ext : allowedExts) { - if (std::find(facilityExtsBegin, facilityExtsEnd, ext) != - facilityExtsEnd) { + if (std::find(facilityExtsBegin, facilityExtsEnd, ext) != facilityExtsEnd) { match = true; break; } @@ -410,8 +382,7 @@ std::string FileProperty::setSaveProperty(const std::string &propValue) { // 'defaultsave.directory' // Note that this catches the Poco::NotFoundException and returns an empty // string in that case - std::string save_path = - ConfigService::Instance().getString("defaultsave.directory"); + std::string save_path = ConfigService::Instance().getString("defaultsave.directory"); Poco::Path save_dir; if (save_path.empty()) { save_dir = Poco::Path(propValue).parent(); diff --git a/Framework/API/src/FrameworkManager.cpp b/Framework/API/src/FrameworkManager.cpp index b2110a53fed0e19f907b2877a41d1acec8893a15..90e220f0e1d5bc89b46c3e8a026bf367ba7b02b1 100644 --- a/Framework/API/src/FrameworkManager.cpp +++ b/Framework/API/src/FrameworkManager.cpp @@ -29,8 +29,8 @@ // The below can be replaced with global_control when all platforms // have 2019U4 +#if __has_include("tbb/tbb_stddef.h") #include "tbb/tbb_stddef.h" - #if TBB_INTERFACE_VERSION_MAJOR < 11 #include "tbb/task_scheduler_init.h" #include @@ -38,6 +38,10 @@ #define TBB_HAS_GLOBAL_CONTROL #include "tbb/global_control.h" #endif +#else +#define TBB_HAS_GLOBAL_CONTROL +#include "tbb/global_control.h" +#endif #ifdef _WIN32 #include @@ -155,8 +159,7 @@ FrameworkManagerImpl::FrameworkManagerImpl() setNumOMPThreadsToConfigValue(); #ifdef MPI_BUILD - g_log.notice() << "This MPI process is rank: " - << boost::mpi::communicator().rank() << '\n'; + g_log.notice() << "This MPI process is rank: " << boost::mpi::communicator().rank() << '\n'; #endif g_log.debug() << "FrameworkManager created.\n"; @@ -167,17 +170,14 @@ FrameworkManagerImpl::FrameworkManagerImpl() /** * Load all plugins from the framework */ -void FrameworkManagerImpl::loadPlugins() { - loadPluginsUsingKey(PLUGINS_DIR_KEY, PLUGINS_EXCLUDE_KEY); -} +void FrameworkManagerImpl::loadPlugins() { loadPluginsUsingKey(PLUGINS_DIR_KEY, PLUGINS_EXCLUDE_KEY); } /** * Set the number of OpenMP cores to use based on the config value */ void FrameworkManagerImpl::setNumOMPThreadsToConfigValue() { // Set the number of threads to use for this process - auto maxCores = - Kernel::ConfigService::Instance().getValue("MultiThreaded.MaxCores"); + auto maxCores = Kernel::ConfigService::Instance().getValue("MultiThreaded.MaxCores"); if (maxCores.get_value_or(0) > 0) { setNumOMPThreads(maxCores.get()); } @@ -191,13 +191,11 @@ void FrameworkManagerImpl::setNumOMPThreads(const int nthreads) { g_log.debug() << "Setting maximum number of threads to " << nthreads << "\n"; PARALLEL_SET_NUM_THREADS(nthreads); if (m_globalTbbControl) { - m_globalTbbControl - .reset(); // Have to reset to change the number of threads at runtime + m_globalTbbControl.reset(); // Have to reset to change the number of threads at runtime } #ifdef TBB_HAS_GLOBAL_CONTROL - m_globalTbbControl = std::make_unique( - tbb::global_control::max_allowed_parallelism, nthreads); + m_globalTbbControl = std::make_unique(tbb::global_control::max_allowed_parallelism, nthreads); #else m_globalTbbControl = std::make_unique(nthreads); #endif @@ -209,9 +207,7 @@ void FrameworkManagerImpl::setNumOMPThreads(const int nthreads) { * parallel * call */ -int FrameworkManagerImpl::getNumOMPThreads() const { - return PARALLEL_GET_MAX_THREADS; -} +int FrameworkManagerImpl::getNumOMPThreads() const { return PARALLEL_GET_MAX_THREADS; } /** Clears all memory associated with the AlgorithmManager * and with the Analysis & Instrument data services. @@ -233,23 +229,17 @@ void FrameworkManagerImpl::shutdown() { /** * Clear memory associated with the AlgorithmManager */ -void FrameworkManagerImpl::clearAlgorithms() { - AlgorithmManager::Instance().clear(); -} +void FrameworkManagerImpl::clearAlgorithms() { AlgorithmManager::Instance().clear(); } /** * Clear memory associated with the ADS */ -void FrameworkManagerImpl::clearData() { - AnalysisDataService::Instance().clear(); -} +void FrameworkManagerImpl::clearData() { AnalysisDataService::Instance().clear(); } /** * Clear memory associated with the IDS */ -void FrameworkManagerImpl::clearInstruments() { - InstrumentDataService::Instance().clear(); -} +void FrameworkManagerImpl::clearInstruments() { InstrumentDataService::Instance().clear(); } /** * Clear memory associated with the PropertyManagers @@ -265,16 +255,13 @@ void FrameworkManagerImpl::clearPropertyManagers() { * @param count :: number of arguments given. * @return the algorithm created */ -IAlgorithm_sptr FrameworkManagerImpl::exec(const std::string &algorithmName, - int count, ...) { +IAlgorithm_sptr FrameworkManagerImpl::exec(const std::string &algorithmName, int count, ...) { if (count % 2 == 1) { - throw std::runtime_error( - "Must have an even number of parameter/value string arguments"); + throw std::runtime_error("Must have an even number of parameter/value string arguments"); } // Create the algorithm - IAlgorithm_sptr alg = - AlgorithmManager::Instance().createUnmanaged(algorithmName, -1); + auto alg = AlgorithmManager::Instance().createUnmanaged(algorithmName, -1); alg->initialize(); if (!alg->isInitialized()) throw std::runtime_error(algorithmName + " was not initialized."); @@ -305,8 +292,7 @@ Workspace *FrameworkManagerImpl::getWorkspace(const std::string &wsName) { try { space = AnalysisDataService::Instance().retrieve(wsName).get(); } catch (Kernel::Exception::NotFoundError &) { - throw Kernel::Exception::NotFoundError("Unable to retrieve workspace", - wsName); + throw Kernel::Exception::NotFoundError("Unable to retrieve workspace", wsName); } return space; } @@ -328,8 +314,7 @@ bool FrameworkManagerImpl::deleteWorkspace(const std::string &wsName) { return false; } - std::shared_ptr ws_grpsptr = - std::dynamic_pointer_cast(ws_sptr); + std::shared_ptr ws_grpsptr = std::dynamic_pointer_cast(ws_sptr); if (ws_grpsptr) { // selected workspace is a group workspace AnalysisDataService::Instance().deepRemoveGroup(wsName); @@ -355,18 +340,15 @@ bool FrameworkManagerImpl::deleteWorkspace(const std::string &wsName) { * ConfigService * @param excludeKey A string */ -void FrameworkManagerImpl::loadPluginsUsingKey(const std::string &locationKey, - const std::string &excludeKey) { +void FrameworkManagerImpl::loadPluginsUsingKey(const std::string &locationKey, const std::string &excludeKey) { const auto &cfgSvc = Kernel::ConfigService::Instance(); const auto pluginDir = cfgSvc.getString(locationKey); if (pluginDir.length() > 0) { std::vector excludes; const auto excludeStr = cfgSvc.getString(excludeKey); boost::split(excludes, excludeStr, boost::is_any_of(";")); - g_log.debug("Loading libraries from '" + pluginDir + "', excluding '" + - excludeStr + "'"); - LibraryManager::Instance().openLibraries( - pluginDir, LibraryManagerImpl::NonRecursive, excludes); + g_log.debug("Loading libraries from '" + pluginDir + "', excluding '" + excludeStr + "'"); + LibraryManager::Instance().openLibraries(pluginDir, LibraryManagerImpl::NonRecursive, excludes); } else { g_log.debug("No library directory found in key \"" + locationKey + "\""); } @@ -388,14 +370,11 @@ void FrameworkManagerImpl::setGlobalNumericLocaleToC() { } /// Silence NeXus output -void FrameworkManagerImpl::disableNexusOutput() { - NXMSetError(nullptr, NexusErrorFunction); -} +void FrameworkManagerImpl::disableNexusOutput() { NXMSetError(nullptr, NexusErrorFunction); } /// Starts asynchronous tasks that are done as part of Start-up. void FrameworkManagerImpl::asynchronousStartupTasks() { - auto instrumentUpdates = Kernel::ConfigService::Instance().getValue( - "UpdateInstrumentDefinitions.OnStartup"); + auto instrumentUpdates = Kernel::ConfigService::Instance().getValue("UpdateInstrumentDefinitions.OnStartup"); if (instrumentUpdates.get_value_or(false)) { updateInstrumentDefinitions(); @@ -404,8 +383,7 @@ void FrameworkManagerImpl::asynchronousStartupTasks() { "instrument definitions.\n"; } - auto newVersionCheck = Kernel::ConfigService::Instance().getValue( - "CheckMantidVersion.OnStartup"); + auto newVersionCheck = Kernel::ConfigService::Instance().getValue("CheckMantidVersion.OnStartup"); if (newVersionCheck.get_value_or(false)) { checkIfNewerVersionIsAvailable(); } else { @@ -430,8 +408,7 @@ void FrameworkManagerImpl::setupUsageReporting() { /// Update instrument definitions from github void FrameworkManagerImpl::updateInstrumentDefinitions() { try { - auto algDownloadInstrument = - Mantid::API::AlgorithmManager::Instance().create("DownloadInstrument"); + auto algDownloadInstrument = Mantid::API::AlgorithmManager::Instance().create("DownloadInstrument"); algDownloadInstrument->setAlgStartupLogging(false); algDownloadInstrument->executeAsync(); } catch (Kernel::Exception::NotFoundError &) { @@ -443,8 +420,7 @@ void FrameworkManagerImpl::updateInstrumentDefinitions() { /// Check if a newer release of Mantid is available void FrameworkManagerImpl::checkIfNewerVersionIsAvailable() { try { - auto algCheckVersion = - Mantid::API::AlgorithmManager::Instance().create("CheckMantidVersion"); + auto algCheckVersion = Mantid::API::AlgorithmManager::Instance().create("CheckMantidVersion"); algCheckVersion->setAlgStartupLogging(false); algCheckVersion->executeAsync(); } catch (Kernel::Exception::NotFoundError &) { diff --git a/Framework/API/src/FuncMinimizerFactory.cpp b/Framework/API/src/FuncMinimizerFactory.cpp index 6a8ee61c1172275e2acacb1bea9b2cd3f5a6cccd..968f5521d1f7b14b0673bc3636aafdcb15c21fcc 100644 --- a/Framework/API/src/FuncMinimizerFactory.cpp +++ b/Framework/API/src/FuncMinimizerFactory.cpp @@ -14,8 +14,7 @@ namespace Mantid { namespace API { -FuncMinimizerFactoryImpl::FuncMinimizerFactoryImpl() - : Kernel::DynamicFactory() { +FuncMinimizerFactoryImpl::FuncMinimizerFactoryImpl() : Kernel::DynamicFactory() { // we need to make sure the library manager has been loaded before we // are constructed so that it is destroyed after us and thus does // not close any loaded DLLs with loaded algorithms in them @@ -28,11 +27,9 @@ FuncMinimizerFactoryImpl::FuncMinimizerFactoryImpl() * and optionally properties: "type,prop1=value1,prop2=value2" * @return A pointer to the created minimizer */ -std::shared_ptr -FuncMinimizerFactoryImpl::createMinimizer(const std::string &str) const { +std::shared_ptr FuncMinimizerFactoryImpl::createMinimizer(const std::string &str) const { // check if there are any properties defined - look for a comma - if (str.find(',') == - std::string::npos) { // no properties - create minimizer and return + if (str.find(',') == std::string::npos) { // no properties - create minimizer and return return create(str); } diff --git a/Framework/API/src/FunctionDomain1D.cpp b/Framework/API/src/FunctionDomain1D.cpp index ed7dd5632834312ff64b8918468d649d6a7e9559..67096582f1f43946c98dece8cf78513e7a94f6ab 100644 --- a/Framework/API/src/FunctionDomain1D.cpp +++ b/Framework/API/src/FunctionDomain1D.cpp @@ -13,8 +13,7 @@ namespace Mantid { namespace API { /// The constructor -FunctionDomain1D::FunctionDomain1D(const double *x, size_t n) - : m_data(x), m_n(n), m_peakRadius(0) {} +FunctionDomain1D::FunctionDomain1D(const double *x, size_t n) : m_data(x), m_n(n), m_peakRadius(0) {} /// Convert to a vector std::vector FunctionDomain1D::toVector() const { @@ -40,9 +39,7 @@ int FunctionDomain1D::getPeakRadius() const { return m_peakRadius; } * Create a domain from a vector. * @param xvalues :: Vector with function arguments to be copied from. */ -FunctionDomain1DVector::FunctionDomain1DVector( - const std::vector &xvalues) - : FunctionDomain1D(nullptr, 0) { +FunctionDomain1DVector::FunctionDomain1DVector(const std::vector &xvalues) : FunctionDomain1D(nullptr, 0) { if (xvalues.empty()) { throw std::invalid_argument("FunctionDomain1D cannot have zero size."); } @@ -50,14 +47,27 @@ FunctionDomain1DVector::FunctionDomain1DVector( resetData(&m_X[0], m_X.size()); } +/** + * Create a domain from a vector using move semantics - no copy overhead. + * @param xvalues :: Vector with function arguments to be moved from. + */ +FunctionDomain1DVector::FunctionDomain1DVector(std::vector &&xvalues) : FunctionDomain1D(nullptr, 0) { + if (xvalues.empty()) { + throw std::invalid_argument("FunctionDomain1D cannot have zero size."); + } + m_X = std::move(xvalues); + /* clear the invalidated object */ + xvalues.clear(); + resetData(&m_X[0], m_X.size()); +} + /** * Create a domain from a part of a vector. * @param from :: Iterator to start copying values from. * @param to :: Iterator to the end of the data. */ -FunctionDomain1DVector::FunctionDomain1DVector( - std::vector::const_iterator from, - std::vector::const_iterator to) +FunctionDomain1DVector::FunctionDomain1DVector(std::vector::const_iterator from, + std::vector::const_iterator to) : FunctionDomain1D(nullptr, 0) { if (from == to) { throw std::invalid_argument("FunctionDomain1D cannot have zero size."); @@ -74,9 +84,7 @@ FunctionDomain1DVector::FunctionDomain1DVector( * @param endX :: The end of an interval. * @param n :: Number of values to create. */ -FunctionDomain1DVector::FunctionDomain1DVector(const double startX, - const double endX, - const size_t n) +FunctionDomain1DVector::FunctionDomain1DVector(const double startX, const double endX, const size_t n) : FunctionDomain1D(nullptr, 0) { if (n == 0) { throw std::invalid_argument("FunctionDomain1D cannot have zero size."); @@ -97,8 +105,7 @@ FunctionDomain1DVector::FunctionDomain1DVector(const double startX, * Create a domain with a single value. * @param x :: The argument value. */ -FunctionDomain1DVector::FunctionDomain1DVector(const double x) - : FunctionDomain1D(nullptr, 0) { +FunctionDomain1DVector::FunctionDomain1DVector(const double x) : FunctionDomain1D(nullptr, 0) { m_X.resize(1); m_X[0] = x; resetData(&m_X[0], m_X.size()); @@ -108,9 +115,7 @@ FunctionDomain1DVector::FunctionDomain1DVector(const double x) * Copy constructor. * @param right :: The other domain. */ -FunctionDomain1DVector::FunctionDomain1DVector( - const FunctionDomain1DVector &right) - : FunctionDomain1D(nullptr, 0) { +FunctionDomain1DVector::FunctionDomain1DVector(const FunctionDomain1DVector &right) : FunctionDomain1D(nullptr, 0) { *this = right; } @@ -118,8 +123,7 @@ FunctionDomain1DVector::FunctionDomain1DVector( * Copy assignment operator. * @param right :: The other domain. */ -FunctionDomain1DVector &FunctionDomain1DVector:: -operator=(const FunctionDomain1DVector &right) { +FunctionDomain1DVector &FunctionDomain1DVector::operator=(const FunctionDomain1DVector &right) { if (right.m_X.empty()) { throw std::invalid_argument("FunctionDomain1D cannot have zero size."); } @@ -133,8 +137,7 @@ operator=(const FunctionDomain1DVector &right) { * @param wi :: The workspace index of a spectrum the xvalues come from. * @param xvalues :: Vector with function arguments to be copied from. */ -FunctionDomain1DSpectrum::FunctionDomain1DSpectrum( - size_t wi, const std::vector &xvalues) +FunctionDomain1DSpectrum::FunctionDomain1DSpectrum(size_t wi, const std::vector &xvalues) : FunctionDomain1DVector(xvalues), m_workspaceIndex(wi) {} /** @@ -143,15 +146,13 @@ FunctionDomain1DSpectrum::FunctionDomain1DSpectrum( * @param from :: Iterator to start copying values from. * @param to :: Iterator to the end of the data. */ -FunctionDomain1DSpectrum::FunctionDomain1DSpectrum( - size_t wi, std::vector::const_iterator from, - std::vector::const_iterator to) +FunctionDomain1DSpectrum::FunctionDomain1DSpectrum(size_t wi, std::vector::const_iterator from, + std::vector::const_iterator to) : FunctionDomain1DVector(from, to), m_workspaceIndex(wi) {} /// Constructor. /// @param bins :: A vector with bin boundaries. -FunctionDomain1DHistogram::FunctionDomain1DHistogram( - const std::vector &bins) +FunctionDomain1DHistogram::FunctionDomain1DHistogram(const std::vector &bins) : FunctionDomain1DHistogram(bins.begin(), bins.end()) {} /** @@ -159,9 +160,8 @@ FunctionDomain1DHistogram::FunctionDomain1DHistogram( * @param from :: Iterator to start copying values from. * @param to :: Iterator to the end of the data. */ -FunctionDomain1DHistogram::FunctionDomain1DHistogram( - std::vector::const_iterator from, - std::vector::const_iterator to) +FunctionDomain1DHistogram::FunctionDomain1DHistogram(std::vector::const_iterator from, + std::vector::const_iterator to) : FunctionDomain1D(nullptr, 0), m_bins(from, to) { if (m_bins.size() < 2) { throw std::runtime_error("Cannot initialize FunctionDomain1DHistogram with " @@ -171,9 +171,7 @@ FunctionDomain1DHistogram::FunctionDomain1DHistogram( } /// Get the leftmost boundary -double FunctionDomain1DHistogram::leftBoundary() const { - return m_bins.front(); -} +double FunctionDomain1DHistogram::leftBoundary() const { return m_bins.front(); } } // namespace API } // namespace Mantid diff --git a/Framework/API/src/FunctionDomainGeneral.cpp b/Framework/API/src/FunctionDomainGeneral.cpp index f4c611dc67b787a71f5e279dfc893e311bf0eef8..fb4c4abf03ae4588d123e08aae1d723449420190 100644 --- a/Framework/API/src/FunctionDomainGeneral.cpp +++ b/Framework/API/src/FunctionDomainGeneral.cpp @@ -14,9 +14,7 @@ namespace Mantid { namespace API { /// Return the number of arguments in the domain -size_t FunctionDomainGeneral::size() const { - return m_columns.empty() ? 0 : m_columns.front()->size(); -} +size_t FunctionDomainGeneral::size() const { return m_columns.empty() ? 0 : m_columns.front()->size(); } /// Get the number of columns size_t FunctionDomainGeneral::columnCount() const { return m_columns.size(); } @@ -24,8 +22,7 @@ size_t FunctionDomainGeneral::columnCount() const { return m_columns.size(); } /// Add a new column. All columns must have the same size. void FunctionDomainGeneral::addColumn(const std::shared_ptr &column) { if (!column) { - throw std::runtime_error( - "Cannot add null column to FunctionDomainGeneral."); + throw std::runtime_error("Cannot add null column to FunctionDomainGeneral."); } if (!m_columns.empty() && size() != column->size()) { throw std::runtime_error("Cannot add a column to FunctionDomainGeneral. " @@ -37,9 +34,7 @@ void FunctionDomainGeneral::addColumn(const std::shared_ptr &column) { /// Get i-th column. /// @param i :: Index of a column to get. -std::shared_ptr FunctionDomainGeneral::getColumn(size_t i) const { - return m_columns.at(i); -} +std::shared_ptr FunctionDomainGeneral::getColumn(size_t i) const { return m_columns.at(i); } } // namespace API } // namespace Mantid diff --git a/Framework/API/src/FunctionDomainMD.cpp b/Framework/API/src/FunctionDomainMD.cpp index 51cf298b927935a356f514a04d026627daa0e297..ca945b7d0ab65560123c8fe239c8028c532e325b 100644 --- a/Framework/API/src/FunctionDomainMD.cpp +++ b/Framework/API/src/FunctionDomainMD.cpp @@ -21,10 +21,8 @@ namespace API { * @param start :: Index of the first iterator in this domain. * @param length :: Size of this domain. If 0 use all workspace. */ -FunctionDomainMD::FunctionDomainMD(const IMDWorkspace_const_sptr &ws, - size_t start, size_t length) - : m_iterator(ws->createIterator()), m_startIndex(start), m_currentIndex(0), - m_justReset(true), m_workspace(ws) { +FunctionDomainMD::FunctionDomainMD(const IMDWorkspace_const_sptr &ws, size_t start, size_t length) + : m_iterator(ws->createIterator()), m_startIndex(start), m_currentIndex(0), m_justReset(true), m_workspace(ws) { size_t dataSize = m_iterator->getDataSize(); m_size = length == 0 ? dataSize : length; if (start >= dataSize) { @@ -70,9 +68,7 @@ const IMDIterator *FunctionDomainMD::getNextIterator() const { } /// Returns the pointer to the original workspace -IMDWorkspace_const_sptr FunctionDomainMD::getWorkspace() const { - return m_workspace; -} +IMDWorkspace_const_sptr FunctionDomainMD::getWorkspace() const { return m_workspace; } } // namespace API } // namespace Mantid diff --git a/Framework/API/src/FunctionFactory.cpp b/Framework/API/src/FunctionFactory.cpp index c0f18ad6d6b5c0c0da2f150354f765e0a577f3af..1bac8c554925ed4fe6763f7b4e7db0c0af2dd1ba 100644 --- a/Framework/API/src/FunctionFactory.cpp +++ b/Framework/API/src/FunctionFactory.cpp @@ -12,6 +12,7 @@ #include "MantidAPI/IConstraint.h" #include "MantidAPI/IFunction.h" #include "MantidAPI/IFunction1D.h" +#include "MantidAPI/ImmutableCompositeFunction.h" #include "MantidAPI/MultiDomainFunction.h" #include "MantidAPI/Workspace.h" #include "MantidKernel/ConfigService.h" @@ -23,16 +24,14 @@ namespace Mantid { namespace API { -FunctionFactoryImpl::FunctionFactoryImpl() - : Kernel::DynamicFactory() { +FunctionFactoryImpl::FunctionFactoryImpl() : Kernel::DynamicFactory() { // we need to make sure the library manager has been loaded before we // are constructed so that it is destroyed after us and thus does // not close any loaded DLLs with loaded algorithms in them Mantid::Kernel::LibraryManager::Instance(); } -IFunction_sptr -FunctionFactoryImpl::createFunction(const std::string &type) const { +IFunction_sptr FunctionFactoryImpl::createFunction(const std::string &type) const { IFunction_sptr fun = create(type); fun->initialize(); return fun; @@ -50,8 +49,7 @@ FunctionFactoryImpl::createFunction(const std::string &type) const { * PeakCentre=10.,Sigma=1" * @return A pointer to the created function */ -IFunction_sptr -FunctionFactoryImpl::createInitialized(const std::string &input) const { +IFunction_sptr FunctionFactoryImpl::createInitialized(const std::string &input) const { Expression expr; try { expr.parse(input); @@ -87,8 +85,7 @@ FunctionFactoryImpl::createInitialized(const std::string &input) const { * @return A pointer to the created function. */ std::shared_ptr -FunctionFactoryImpl::createInitializedMultiDomainFunction( - const std::string &input, size_t domainNumber) const { +FunctionFactoryImpl::createInitializedMultiDomainFunction(const std::string &input, size_t domainNumber) const { auto singleFunction = createInitialized(input); auto multiDomainFunction = std::make_shared(); @@ -111,9 +108,8 @@ FunctionFactoryImpl::createInitializedMultiDomainFunction( * values of the parent function * @return A pointer to the created function */ -IFunction_sptr FunctionFactoryImpl::createSimple( - const Expression &expr, - std::map &parentAttributes) const { +IFunction_sptr FunctionFactoryImpl::createSimple(const Expression &expr, + std::map &parentAttributes) const { if (expr.name() == "=" && expr.size() > 1) { return createFunction(expr.terms()[1].name()); } @@ -127,16 +123,13 @@ IFunction_sptr FunctionFactoryImpl::createSimple( if (term->name() != "=") inputError(expr.str()); - if (term->terms()[0].name() != "name" && - term->terms()[0].name() != "composite") { - throw std::invalid_argument( - "Function name must be defined before its parameters"); + if (term->terms()[0].name() != "name" && term->terms()[0].name() != "composite") { + throw std::invalid_argument("Function name must be defined before its parameters"); } std::string fnName = term->terms()[1].name(); IFunction_sptr fun = createFunction(fnName); - for (++term; term != terms.end(); - ++term) { // loop over function's parameters/attributes + for (++term; term != terms.end(); ++term) { // loop over function's parameters/attributes if (term->name() != "=") inputError(expr.str()); std::string parName = term->terms()[0].name(); @@ -163,12 +156,11 @@ IFunction_sptr FunctionFactoryImpl::createSimple( try { fun->setParameter(parName, boost::lexical_cast(parValue)); } catch (boost::bad_lexical_cast &) { - throw std::runtime_error( - std::string("Error in value of parameter ") - .append(parName) - .append(".\n") - .append(parValue) - .append(" cannot be interpreted as a floating point value.")); + throw std::runtime_error(std::string("Error in value of parameter ") + .append(parName) + .append(".\n") + .append(parValue) + .append(" cannot be interpreted as a floating point value.")); } } } // for term @@ -184,9 +176,9 @@ IFunction_sptr FunctionFactoryImpl::createSimple( * values of the parent function * @return A pointer to the created function */ -CompositeFunction_sptr FunctionFactoryImpl::createComposite( - const Expression &expr, - std::map &parentAttributes) const { +CompositeFunction_sptr +FunctionFactoryImpl::createComposite(const Expression &expr, + std::map &parentAttributes) const { if (expr.name() != ";") inputError(expr.str()); @@ -201,14 +193,12 @@ CompositeFunction_sptr FunctionFactoryImpl::createComposite( CompositeFunction_sptr cfun; if (term.name() == "=") { if (term.terms()[0].name() == "composite") { - cfun = std::dynamic_pointer_cast( - createFunction(term.terms()[1].name())); + cfun = std::dynamic_pointer_cast(createFunction(term.terms()[1].name())); if (!cfun) inputError(expr.str()); ++it; } else if (term.terms()[0].name() == "name") { - cfun = std::dynamic_pointer_cast( - createFunction("CompositeFunction")); + cfun = std::dynamic_pointer_cast(createFunction("CompositeFunction")); if (!cfun) inputError(expr.str()); } else { @@ -218,14 +208,12 @@ CompositeFunction_sptr FunctionFactoryImpl::createComposite( auto firstTerm = term.terms().cbegin(); if (firstTerm->name() == "=") { if (firstTerm->terms()[0].name() == "composite") { - cfun = std::dynamic_pointer_cast( - createSimple(term, parentAttributes)); + cfun = std::dynamic_pointer_cast(createSimple(term, parentAttributes)); if (!cfun) inputError(expr.str()); ++it; } else if (firstTerm->terms()[0].name() == "name") { - cfun = std::dynamic_pointer_cast( - createFunction("CompositeFunction")); + cfun = std::dynamic_pointer_cast(createFunction("CompositeFunction")); if (!cfun) inputError(expr.str()); } else { @@ -233,8 +221,7 @@ CompositeFunction_sptr FunctionFactoryImpl::createComposite( } } } else if (term.name() == ";") { - cfun = std::dynamic_pointer_cast( - createFunction("CompositeFunction")); + cfun = std::dynamic_pointer_cast(createFunction("CompositeFunction")); if (!cfun) inputError(expr.str()); } else { @@ -302,8 +289,7 @@ void FunctionFactoryImpl::inputError(const std::string &str) const { * separated by commas ',' * and enclosed in brackets "(...)" . */ -void FunctionFactoryImpl::addConstraints(const IFunction_sptr &fun, - const Expression &expr) const { +void FunctionFactoryImpl::addConstraints(const IFunction_sptr &fun, const Expression &expr) const { if (expr.name() == ",") { for (auto it = expr.begin(); it != expr.end(); ++it) { // If this is a penalty term, we used it on the previous iteration @@ -336,10 +322,8 @@ void FunctionFactoryImpl::addConstraints(const IFunction_sptr &fun, * @param fun :: The function * @param expr :: The constraint expression. */ -void FunctionFactoryImpl::addConstraint(const std::shared_ptr &fun, - const Expression &expr) const { - auto c = std::unique_ptr( - ConstraintFactory::Instance().createInitialized(fun.get(), expr)); +void FunctionFactoryImpl::addConstraint(const std::shared_ptr &fun, const Expression &expr) const { + auto c = std::unique_ptr(ConstraintFactory::Instance().createInitialized(fun.get(), expr)); c->setPenaltyFactor(c->getDefaultPenaltyFactor()); fun->addConstraint(std::move(c)); } @@ -350,12 +334,9 @@ void FunctionFactoryImpl::addConstraint(const std::shared_ptr &fun, * @param constraint_expr :: The constraint expression. * @param penalty_expr :: The penalty expression. */ -void FunctionFactoryImpl::addConstraint(const std::shared_ptr &fun, - const Expression &constraint_expr, +void FunctionFactoryImpl::addConstraint(const std::shared_ptr &fun, const Expression &constraint_expr, const Expression &penalty_expr) const { - auto c = std::unique_ptr( - ConstraintFactory::Instance().createInitialized(fun.get(), - constraint_expr)); + auto c = std::unique_ptr(ConstraintFactory::Instance().createInitialized(fun.get(), constraint_expr)); double penalty_factor = std::stof(penalty_expr.terms()[1].str(), NULL); c->setPenaltyFactor(penalty_factor); fun->addConstraint(std::move(c)); @@ -366,8 +347,7 @@ void FunctionFactoryImpl::addConstraint(const std::shared_ptr &fun, * @param expr :: The tie expression: either parName = TieString or a list * of name = string pairs */ -void FunctionFactoryImpl::addTies(const IFunction_sptr &fun, - const Expression &expr) const { +void FunctionFactoryImpl::addTies(const IFunction_sptr &fun, const Expression &expr) const { if (expr.name() == "=") { addTie(fun, expr); } else if (expr.name() == ",") { @@ -381,8 +361,7 @@ void FunctionFactoryImpl::addTies(const IFunction_sptr &fun, * @param fun :: The function * @param expr :: The tie expression: parName = TieString */ -void FunctionFactoryImpl::addTie(const IFunction_sptr &fun, - const Expression &expr) const { +void FunctionFactoryImpl::addTie(const IFunction_sptr &fun, const Expression &expr) const { if (expr.size() > 1) { // if size > 2 it is interpreted as setting a tie (last // expr.term) to multiple parameters, e.g // f1.alpha = f2.alpha = f3.alpha = f0.beta^2/2 @@ -396,32 +375,27 @@ void FunctionFactoryImpl::addTie(const IFunction_sptr &fun, std::vector FunctionFactoryImpl::getFunctionNamesGUI() const { auto allNames = getFunctionNames(); + auto ImmutableCompositeFunctions = getFunctionNames(); + allNames.insert(allNames.end(), ImmutableCompositeFunctions.begin(), ImmutableCompositeFunctions.end()); allNames.emplace_back("ProductFunction"); allNames.emplace_back("CompositeFunction"); allNames.emplace_back("Convolution"); std::sort(allNames.begin(), allNames.end()); std::vector names; names.reserve(allNames.size()); - auto excludes = - Kernel::ConfigService::Instance().getString("curvefitting.guiExclude"); - Kernel::StringTokenizer tokenizer(excludes, ";", - Kernel::StringTokenizer::TOK_TRIM); + auto excludes = Kernel::ConfigService::Instance().getString("curvefitting.guiExclude"); + Kernel::StringTokenizer tokenizer(excludes, ";", Kernel::StringTokenizer::TOK_TRIM); std::set excludeList(tokenizer.begin(), tokenizer.end()); std::copy_if(allNames.cbegin(), allNames.cend(), std::back_inserter(names), - [&excludeList](const auto &name) { - return excludeList.count(name) == 0; - }); + [&excludeList](const auto &name) { return excludeList.count(name) == 0; }); return names; } -void FunctionFactoryImpl::subscribe( - const std::string &className, - std::unique_ptr pAbstractFactory, - Kernel::DynamicFactory::SubscribeAction replace) { +void FunctionFactoryImpl::subscribe(const std::string &className, std::unique_ptr pAbstractFactory, + Kernel::DynamicFactory::SubscribeAction replace) { // Clear the cache, then do all the work in the base class method m_cachedFunctionNames.clear(); - Kernel::DynamicFactory::subscribe( - className, std::move(pAbstractFactory), replace); + Kernel::DynamicFactory::subscribe(className, std::move(pAbstractFactory), replace); } void FunctionFactoryImpl::unsubscribe(const std::string &className) { diff --git a/Framework/API/src/FunctionGenerator.cpp b/Framework/API/src/FunctionGenerator.cpp index 00b27e2d3b0268bb1c02e62fecdbd3bde2ebd5d3..ffcc5f096294187a3ac9a7db20c6eb7795ffd6a8 100644 --- a/Framework/API/src/FunctionGenerator.cpp +++ b/Framework/API/src/FunctionGenerator.cpp @@ -16,8 +16,7 @@ namespace API { using namespace Kernel; /// Constructor -FunctionGenerator::FunctionGenerator(const IFunction_sptr &source) - : m_source(source), m_dirty(true) { +FunctionGenerator::FunctionGenerator(const IFunction_sptr &source) : m_source(source), m_dirty(true) { if (source) { m_nOwnParams = source->nParams(); } @@ -28,13 +27,10 @@ void FunctionGenerator::init() {} /// Set the source function /// @param source :: New source function. -void FunctionGenerator::setSource(IFunction_sptr source) const { - m_source = std::move(source); -} +void FunctionGenerator::setSource(IFunction_sptr source) const { m_source = std::move(source); } /// Set i-th parameter -void FunctionGenerator::setParameter(size_t i, const double &value, - bool explicitlySet) { +void FunctionGenerator::setParameter(size_t i, const double &value, bool explicitlySet) { if (i < m_nOwnParams) { m_source->setParameter(i, value, explicitlySet); m_dirty = true; @@ -45,8 +41,7 @@ void FunctionGenerator::setParameter(size_t i, const double &value, } /// Set i-th parameter description -void FunctionGenerator::setParameterDescription( - size_t i, const std::string &description) { +void FunctionGenerator::setParameterDescription(size_t i, const std::string &description) { if (i < m_nOwnParams) { m_source->setParameterDescription(i, description); } else { @@ -76,15 +71,13 @@ bool FunctionGenerator::hasParameter(const std::string &name) const { } /// Set parameter by name. -void FunctionGenerator::setParameter(const std::string &name, - const double &value, bool explicitlySet) { +void FunctionGenerator::setParameter(const std::string &name, const double &value, bool explicitlySet) { auto i = parameterIndex(name); setParameter(i, value, explicitlySet); } /// Set description of parameter by name. -void FunctionGenerator::setParameterDescription( - const std::string &name, const std::string &description) { +void FunctionGenerator::setParameterDescription(const std::string &name, const std::string &description) { auto i = parameterIndex(name); setParameterDescription(i, description); } @@ -174,8 +167,7 @@ void FunctionGenerator::setError(const std::string &name, double err) { } /// Change status of parameter -void FunctionGenerator::setParameterStatus(size_t i, - IFunction::ParameterStatus status) { +void FunctionGenerator::setParameterStatus(size_t i, IFunction::ParameterStatus status) { if (i < m_nOwnParams) { m_source->setParameterStatus(i, status); } else { @@ -185,8 +177,7 @@ void FunctionGenerator::setParameterStatus(size_t i, } /// Get status of parameter -IFunction::ParameterStatus -FunctionGenerator::getParameterStatus(size_t i) const { +IFunction::ParameterStatus FunctionGenerator::getParameterStatus(size_t i) const { if (i < m_nOwnParams) { return m_source->getParameterStatus(i); } else { @@ -196,8 +187,7 @@ FunctionGenerator::getParameterStatus(size_t i) const { } /// Return parameter index from a parameter reference. -size_t -FunctionGenerator::getParameterIndex(const ParameterReference &ref) const { +size_t FunctionGenerator::getParameterIndex(const ParameterReference &ref) const { if (ref.getLocalFunction() == this) { auto index = ref.getLocalIndex(); auto np = nParams(); @@ -217,18 +207,15 @@ void FunctionGenerator::setUpForFit() { } /// Declare a new parameter -void FunctionGenerator::declareParameter(const std::string & /*name*/, - double /*initValue*/, +void FunctionGenerator::declareParameter(const std::string & /*name*/, double /*initValue*/, const std::string & /*description*/) { - throw Kernel::Exception::NotImplementedError( - "FunctionGenerator cannot not have its own parameters."); + throw Kernel::Exception::NotImplementedError("FunctionGenerator cannot not have its own parameters."); } /// Returns the number of attributes associated with the function size_t FunctionGenerator::nAttributes() const { checkTargetFunction(); - return IFunction::nAttributes() + m_source->nAttributes() + - m_target->nAttributes(); + return IFunction::nAttributes() + m_source->nAttributes() + m_target->nAttributes(); } /// Returns a list of attribute names @@ -238,8 +225,7 @@ std::vector FunctionGenerator::getAttributeNames() const { } /// Return a value of attribute attName -IFunction::Attribute -FunctionGenerator::getAttribute(const std::string &attName) const { +IFunction::Attribute FunctionGenerator::getAttribute(const std::string &attName) const { if (IFunction::hasAttribute(attName)) { return IFunction::getAttribute(attName); } else if (isSourceName(attName)) { @@ -251,8 +237,7 @@ FunctionGenerator::getAttribute(const std::string &attName) const { } /// Set a value to attribute attName -void FunctionGenerator::setAttribute(const std::string &attName, - const IFunction::Attribute &att) { +void FunctionGenerator::setAttribute(const std::string &attName, const IFunction::Attribute &att) { if (IFunction::hasAttribute(attName)) { IFunction::setAttribute(attName, att); m_dirty = true; @@ -292,20 +277,17 @@ std::string FunctionGenerator::attributeName(size_t i) const { } else if (i < IFunction::nAttributes() + m_source->nAttributes()) { return m_source->attributeName(i - IFunction::nAttributes()); } else if (i < nAttributes()) { - return m_target->attributeName( - i - (IFunction::nAttributes() + m_source->nAttributes())); + return m_target->attributeName(i - (IFunction::nAttributes() + m_source->nAttributes())); } else { throw(std::runtime_error("Attribute index out of range")); } } // Evaluates the function -void FunctionGenerator::function(const FunctionDomain &domain, - FunctionValues &values) const { +void FunctionGenerator::function(const FunctionDomain &domain, FunctionValues &values) const { updateTargetFunction(); if (!m_target) { - throw std::logic_error( - "FunctionGenerator failed to generate target function."); + throw std::logic_error("FunctionGenerator failed to generate target function."); } m_target->function(domain, values); } @@ -314,8 +296,7 @@ void FunctionGenerator::function(const FunctionDomain &domain, /// @param aName :: A name to test. bool FunctionGenerator::isSourceName(const std::string &aName) const { if (aName.empty()) { - throw std::invalid_argument( - "Parameter or attribute name cannot be empty string."); + throw std::invalid_argument("Parameter or attribute name cannot be empty string."); } return (aName.front() != 'f' || aName.find('.') == std::string::npos); } @@ -326,8 +307,7 @@ void FunctionGenerator::checkTargetFunction() const { updateTargetFunction(); } if (!m_target) { - throw std::logic_error( - "FunctionGenerator failed to generate target function."); + throw std::logic_error("FunctionGenerator failed to generate target function."); } } diff --git a/Framework/API/src/FunctionParameterDecorator.cpp b/Framework/API/src/FunctionParameterDecorator.cpp index d76c55abd5a489235c7dbaaa5f2cac15f4f2dd7d..410821531e8a5aaf193b90e4f0397625bc732a47 100644 --- a/Framework/API/src/FunctionParameterDecorator.cpp +++ b/Framework/API/src/FunctionParameterDecorator.cpp @@ -14,28 +14,22 @@ namespace Mantid { namespace API { -void FunctionParameterDecorator::setDecoratedFunction( - const std::string &wrappedFunctionName) { - IFunction_sptr fn = - FunctionFactory::Instance().createFunction(wrappedFunctionName); +void FunctionParameterDecorator::setDecoratedFunction(const std::string &wrappedFunctionName) { + IFunction_sptr fn = FunctionFactory::Instance().createFunction(wrappedFunctionName); beforeDecoratedFunctionSet(fn); setDecoratedFunctionPrivate(fn); } -IFunction_sptr FunctionParameterDecorator::getDecoratedFunction() const { - return m_wrappedFunction; -} +IFunction_sptr FunctionParameterDecorator::getDecoratedFunction() const { return m_wrappedFunction; } IFunction_sptr FunctionParameterDecorator::clone() const { FunctionParameterDecorator_sptr cloned = - std::dynamic_pointer_cast( - FunctionFactory::Instance().createFunction(name())); + std::dynamic_pointer_cast(FunctionFactory::Instance().createFunction(name())); if (!cloned) { - throw std::runtime_error( - "Cloned function is not of type FunctionParameterDecorator, aborting."); + throw std::runtime_error("Cloned function is not of type FunctionParameterDecorator, aborting."); } IFunction_sptr decoratedFn = getDecoratedFunction(); @@ -47,30 +41,26 @@ IFunction_sptr FunctionParameterDecorator::clone() const { return cloned; } -void FunctionParameterDecorator::setWorkspace( - std::shared_ptr ws) { +void FunctionParameterDecorator::setWorkspace(std::shared_ptr ws) { throwIfNoFunctionSet(); m_wrappedFunction->setWorkspace(ws); } -void FunctionParameterDecorator::setMatrixWorkspace( - std::shared_ptr workspace, size_t wi, double startX, - double endX) { +void FunctionParameterDecorator::setMatrixWorkspace(std::shared_ptr workspace, size_t wi, + double startX, double endX) { throwIfNoFunctionSet(); m_wrappedFunction->setMatrixWorkspace(workspace, wi, startX, endX); } -void FunctionParameterDecorator::setParameter(size_t i, const double &value, - bool explicitlySet) { +void FunctionParameterDecorator::setParameter(size_t i, const double &value, bool explicitlySet) { throwIfNoFunctionSet(); m_wrappedFunction->setParameter(i, value, explicitlySet); } -void FunctionParameterDecorator::setParameterDescription( - size_t i, const std::string &description) { +void FunctionParameterDecorator::setParameterDescription(size_t i, const std::string &description) { throwIfNoFunctionSet(); m_wrappedFunction->setParameterDescription(i, description); @@ -82,16 +72,13 @@ double FunctionParameterDecorator::getParameter(size_t i) const { return m_wrappedFunction->getParameter(i); } -void FunctionParameterDecorator::setParameter(const std::string &name, - const double &value, - bool explicitlySet) { +void FunctionParameterDecorator::setParameter(const std::string &name, const double &value, bool explicitlySet) { throwIfNoFunctionSet(); m_wrappedFunction->setParameter(name, value, explicitlySet); } -void FunctionParameterDecorator::setParameterDescription( - const std::string &name, const std::string &description) { +void FunctionParameterDecorator::setParameterDescription(const std::string &name, const std::string &description) { throwIfNoFunctionSet(); m_wrappedFunction->setParameterDescription(name, description); @@ -128,8 +115,7 @@ size_t FunctionParameterDecorator::nParams() const { return m_wrappedFunction->nParams(); } -size_t -FunctionParameterDecorator::parameterIndex(const std::string &name) const { +size_t FunctionParameterDecorator::parameterIndex(const std::string &name) const { throwIfNoFunctionSet(); return m_wrappedFunction->parameterIndex(name); @@ -175,8 +161,7 @@ void FunctionParameterDecorator::setError(const std::string &name, double err) { setError(index, err); } -size_t FunctionParameterDecorator::getParameterIndex( - const ParameterReference &ref) const { +size_t FunctionParameterDecorator::getParameterIndex(const ParameterReference &ref) const { throwIfNoFunctionSet(); if (std::dynamic_pointer_cast(m_wrappedFunction)) { @@ -204,35 +189,30 @@ std::vector FunctionParameterDecorator::getAttributeNames() const { return m_wrappedFunction->getAttributeNames(); } -IFunction::Attribute -FunctionParameterDecorator::getAttribute(const std::string &attName) const { +IFunction::Attribute FunctionParameterDecorator::getAttribute(const std::string &attName) const { throwIfNoFunctionSet(); return m_wrappedFunction->getAttribute(attName); } -void FunctionParameterDecorator::setAttribute( - const std::string &attName, const IFunction::Attribute &attValue) { +void FunctionParameterDecorator::setAttribute(const std::string &attName, const IFunction::Attribute &attValue) { throwIfNoFunctionSet(); m_wrappedFunction->setAttribute(attName, attValue); } -bool FunctionParameterDecorator::hasAttribute( - const std::string &attName) const { +bool FunctionParameterDecorator::hasAttribute(const std::string &attName) const { throwIfNoFunctionSet(); return m_wrappedFunction->hasAttribute(attName); } -void FunctionParameterDecorator::setParameterStatus( - size_t i, IFunction::ParameterStatus status) { +void FunctionParameterDecorator::setParameterStatus(size_t i, IFunction::ParameterStatus status) { throwIfNoFunctionSet(); m_wrappedFunction->setParameterStatus(i, status); } -IFunction::ParameterStatus -FunctionParameterDecorator::getParameterStatus(size_t i) const { +IFunction::ParameterStatus FunctionParameterDecorator::getParameterStatus(size_t i) const { throwIfNoFunctionSet(); return m_wrappedFunction->getParameterStatus(i); } @@ -267,8 +247,7 @@ ParameterTie *FunctionParameterDecorator::getTie(size_t i) const { return m_wrappedFunction->getTie(i); } -void FunctionParameterDecorator::addConstraint( - std::unique_ptr ic) { +void FunctionParameterDecorator::addConstraint(std::unique_ptr ic) { throwIfNoFunctionSet(); m_wrappedFunction->addConstraint(std::move(ic)); @@ -300,15 +279,14 @@ void FunctionParameterDecorator::throwIfNoFunctionSet() const { } /// Does nothing, function does not have parameters. -void FunctionParameterDecorator::declareParameter( - const std::string &name, double initValue, const std::string &description) { +void FunctionParameterDecorator::declareParameter(const std::string &name, double initValue, + const std::string &description) { UNUSED_ARG(name); UNUSED_ARG(initValue); UNUSED_ARG(description); } -void FunctionParameterDecorator::tie(const std::string &parName, - const std::string &expr, bool isDefault) { +void FunctionParameterDecorator::tie(const std::string &parName, const std::string &expr, bool isDefault) { throwIfNoFunctionSet(); m_wrappedFunction->tie(parName, expr, isDefault); } @@ -330,15 +308,9 @@ void FunctionParameterDecorator::addTie(std::unique_ptr tie) { * * @param fn :: Function that is going to be decorated. */ -void FunctionParameterDecorator::beforeDecoratedFunctionSet( - const IFunction_sptr &fn) { - UNUSED_ARG(fn); -} +void FunctionParameterDecorator::beforeDecoratedFunctionSet(const IFunction_sptr &fn) { UNUSED_ARG(fn); } -void FunctionParameterDecorator::setDecoratedFunctionPrivate( - const IFunction_sptr &fn) { - m_wrappedFunction = fn; -} +void FunctionParameterDecorator::setDecoratedFunctionPrivate(const IFunction_sptr &fn) { m_wrappedFunction = fn; } } // namespace API } // namespace Mantid diff --git a/Framework/API/src/FunctionProperty.cpp b/Framework/API/src/FunctionProperty.cpp index f04bfbf3eabead8cee11881479b02c7b29efe3f8..e09e11b5cd442190664727d8a992548eb1ab79b7 100644 --- a/Framework/API/src/FunctionProperty.cpp +++ b/Framework/API/src/FunctionProperty.cpp @@ -16,42 +16,28 @@ namespace API { * Sets the property names but initialises the function pointer to null. * @param name :: The name to assign to the property * @param direction :: The direction of the function (i.e. input or output) + * @param optional :: A flag indicating whether the property is optional or mandatory. */ -FunctionProperty::FunctionProperty(const std::string &name, - const unsigned int direction) - : Kernel::PropertyWithValue>( - name, std::shared_ptr(), - Kernel::IValidator_sptr(new Kernel::NullValidator()), direction) {} - -/// Copy constructor -FunctionProperty::FunctionProperty(const FunctionProperty &right) - : Kernel::PropertyWithValue>(right) {} - -/// Copy assignment operator. Copies the pointer to the function. -FunctionProperty &FunctionProperty::operator=(const FunctionProperty &right) { - if (&right == this) - return *this; - Kernel::PropertyWithValue>::operator=(right); - return *this; -} +FunctionProperty::FunctionProperty(const std::string &name, const unsigned int direction, + const PropertyMode::Type optional) + : Kernel::PropertyWithValue>(name, std::shared_ptr(), + std::make_shared(), direction), + m_optional(optional) {} /** Bring in the PropertyWithValue assignment operator explicitly (avoids VSC++ * warning) * @param value :: The value to set to * @return assigned PropertyWithValue */ -FunctionProperty &FunctionProperty:: -operator=(const std::shared_ptr &value) { +FunctionProperty &FunctionProperty::operator=(const std::shared_ptr &value) { Kernel::PropertyWithValue>::operator=(value); return *this; } //-------------------------------------------------------------------------------------- /// Add the value of another property -FunctionProperty &FunctionProperty:: -operator+=(Kernel::Property const * /*right*/) { - throw Kernel::Exception::NotImplementedError( - "+= operator is not implemented for FunctionProperty."); +FunctionProperty &FunctionProperty::operator+=(Kernel::Property const * /*right*/) { + throw Kernel::Exception::NotImplementedError("+= operator is not implemented for FunctionProperty."); return *this; } @@ -69,15 +55,18 @@ std::string FunctionProperty::value() const { * @return A Json::Value object encoding the string representation of the * function */ -Json::Value FunctionProperty::valueAsJson() const { - return Json::Value(value()); -} +Json::Value FunctionProperty::valueAsJson() const { return Json::Value(value()); } /** Get the value the property was initialised with -its default value * @return The default value */ std::string FunctionProperty::getDefault() const { return ""; } +/** Returns true if this property is optional. + * @return true if this property is optional. + */ +bool FunctionProperty::isOptional() const { return (m_optional == PropertyMode::Optional); } + /** Set the function definition. * Also tries to create the function with FunctionFactory. * @param value :: The function definition string. @@ -85,9 +74,16 @@ std::string FunctionProperty::getDefault() const { return ""; } */ std::string FunctionProperty::setValue(const std::string &value) { std::string error; + + if (isOptional() && value.empty()) { + // No error message when the function string is empty and the function is optional + m_value = std::shared_ptr(); + m_definition = value; + return error; + } + try { - m_value = std::shared_ptr( - FunctionFactory::Instance().createInitialized(value)); + m_value = std::shared_ptr(FunctionFactory::Instance().createInitialized(value)); m_definition = value; } catch (std::exception &e) { error = e.what(); @@ -114,7 +110,7 @@ std::string FunctionProperty::setValueFromJson(const Json::Value &value) { * @returns A user level description of the problem or "" if it is valid. */ std::string FunctionProperty::isValid() const { - if (direction() == Kernel::Direction::Output) { + if (isOptional() || direction() == Kernel::Direction::Output) { return ""; } else { return isDefault() ? "Function is empty." : ""; @@ -124,15 +120,11 @@ std::string FunctionProperty::isValid() const { /** Indicates if the function has not been created yet. * @return true if the function has not been created yet. */ -bool FunctionProperty::isDefault() const { - return m_value == std::shared_ptr(); -} +bool FunctionProperty::isDefault() const { return m_value == std::shared_ptr(); } /// Create a history record /// @return A populated PropertyHistory for this class -const Kernel::PropertyHistory FunctionProperty::createHistory() const { - return Kernel::PropertyHistory(this); -} +const Kernel::PropertyHistory FunctionProperty::createHistory() const { return Kernel::PropertyHistory(this); } } // namespace API } // namespace Mantid diff --git a/Framework/API/src/FunctionValues.cpp b/Framework/API/src/FunctionValues.cpp index 3801bdac0413ba83b33c4f7b0d53cc6f82c4b49b..a4940db61375ed0487b2a29be4330e9e94cc5dc1 100644 --- a/Framework/API/src/FunctionValues.cpp +++ b/Framework/API/src/FunctionValues.cpp @@ -57,9 +57,7 @@ void FunctionValues::expand(size_t n) { /** Set all calculated values to same number. * @param value :: A new value. */ -void FunctionValues::setCalculated(double value) { - std::fill(m_calculated.begin(), m_calculated.end(), value); -} +void FunctionValues::setCalculated(double value) { std::fill(m_calculated.begin(), m_calculated.end(), value); } /** * Get a pointer to calculated data at index i @@ -79,16 +77,13 @@ void FunctionValues::zeroCalculated() { setCalculated(0.0); } * Copy calculated values to a buffer * @param to :: Pointer to the buffer */ -void FunctionValues::copyTo(double *to) const { - std::copy(m_calculated.begin(), m_calculated.end(), to); -} +void FunctionValues::copyTo(double *to) const { std::copy(m_calculated.begin(), m_calculated.end(), to); } /** Add calculated values to values in a buffer and save result to the buffer * @param to :: Pointer to the buffer, it must be large enough */ void FunctionValues::add(double *to) const { - std::transform(m_calculated.begin(), m_calculated.end(), to, to, - std::plus()); + std::transform(m_calculated.begin(), m_calculated.end(), to, to, std::plus()); } /** Multiply calculated values by values in a buffer and save result to the @@ -96,8 +91,7 @@ void FunctionValues::add(double *to) const { * @param to :: Pointer to the buffer, it must be large enough */ void FunctionValues::multiply(double *to) const { - std::transform(m_calculated.begin(), m_calculated.end(), to, to, - std::multiplies()); + std::transform(m_calculated.begin(), m_calculated.end(), to, to, std::multiplies()); } /** @@ -136,8 +130,7 @@ FunctionValues &FunctionValues::operator*=(const FunctionValues &values) { * values in this from start to the end. * @return A reference to this values. */ -void FunctionValues::addToCalculated(size_t start, - const FunctionValues &values) { +void FunctionValues::addToCalculated(size_t start, const FunctionValues &values) { if (start + size() < values.size()) { throw std::runtime_error("Cannot add values: sizes do not match"); } @@ -207,9 +200,7 @@ void FunctionValues::setFitWeights(const std::vector &values) { * Set all weights to the same value. * @param value :: The value to set. */ -void FunctionValues::setFitWeights(const double &value) { - m_weights.resize(m_calculated.size(), value); -} +void FunctionValues::setFitWeights(const double &value) { m_weights.resize(m_calculated.size(), value); } /** * Get a fitting weight. diff --git a/Framework/API/src/GridDomain.cpp b/Framework/API/src/GridDomain.cpp index 569e019a77d35ccd23b2ee21a66980184ad4a8f2..40696d0f164b9e5e9b843b2e1f21442525f7ebb5 100644 --- a/Framework/API/src/GridDomain.cpp +++ b/Framework/API/src/GridDomain.cpp @@ -25,19 +25,14 @@ size_t GridDomain::size() const { if (m_grids.empty()) return 0; else - return std::accumulate( - m_grids.begin(), m_grids.end(), size_t{1}, - [](size_t n, const std::shared_ptr &grid) { - return n * grid->size(); - }); + return std::accumulate(m_grids.begin(), m_grids.end(), size_t{1}, + [](size_t n, const std::shared_ptr &grid) { return n * grid->size(); }); } /// number of dimensions of the grid size_t GridDomain::nDimensions() { return std::accumulate(m_grids.begin(), m_grids.end(), size_t{0}, - [](size_t n, std::shared_ptr &grid) { - return n + grid->nDimensions(); - }); + [](size_t n, std::shared_ptr &grid) { return n + grid->nDimensions(); }); } /* return item of member m_grids diff --git a/Framework/API/src/GridDomain1D.cpp b/Framework/API/src/GridDomain1D.cpp index 3f076e75acaccff830558fb19ce019053d38c821..6d97fd086bfcaa32c9f8b83541f82ae5425c037b 100644 --- a/Framework/API/src/GridDomain1D.cpp +++ b/Framework/API/src/GridDomain1D.cpp @@ -16,8 +16,7 @@ namespace Mantid { namespace API { -void GridDomain1D::initialize(double &startX, double &endX, size_t &n, - const std::string &scaling) { +void GridDomain1D::initialize(double &startX, double &endX, size_t &n, const std::string &scaling) { m_points.resize(n); m_points.front() = startX; m_points.back() = endX; @@ -25,8 +24,7 @@ void GridDomain1D::initialize(double &startX, double &endX, size_t &n, } void GridDomain1D::reScale(const std::string &scaling) { - ITransformScale_sptr fx = - Mantid::API::TransformScaleFactory::Instance().create(scaling); + ITransformScale_sptr fx = Mantid::API::TransformScaleFactory::Instance().create(scaling); fx->transform(m_points); m_scaling = scaling; } diff --git a/Framework/API/src/GroupingLoader.cpp b/Framework/API/src/GroupingLoader.cpp index 48e64f779d5ad27739708e889b0a4e2b3fe2668d..8cf89451f26b4c48d6d5fe9cefd9acf0ac52489a 100644 --- a/Framework/API/src/GroupingLoader.cpp +++ b/Framework/API/src/GroupingLoader.cpp @@ -27,17 +27,14 @@ namespace API { /** Constructor without field direction * @param instrument :: [input] Instrument */ -GroupingLoader::GroupingLoader(Geometry::Instrument_const_sptr instrument) - : m_instrument(std::move(instrument)) {} +GroupingLoader::GroupingLoader(Geometry::Instrument_const_sptr instrument) : m_instrument(std::move(instrument)) {} /** Constructor with field direction * @param instrument :: [input] Instrument * @param mainFieldDirection :: [input] Direction of main field (for MUSR) */ -GroupingLoader::GroupingLoader(Geometry::Instrument_const_sptr instrument, - const std::string &mainFieldDirection) - : m_instrument(std::move(instrument)), - m_mainFieldDirection(mainFieldDirection) {} +GroupingLoader::GroupingLoader(Geometry::Instrument_const_sptr instrument, const std::string &mainFieldDirection) + : m_instrument(std::move(instrument)), m_mainFieldDirection(mainFieldDirection) {} //---------------------------------------------------------------------------------------------- /** Destructor @@ -53,20 +50,17 @@ std::shared_ptr GroupingLoader::getGroupingFromIDF() const { auto loadedGrouping = std::make_shared(); // Special case for MUSR or CHRONUS, because it has two possible groupings - if (m_instrument->getName() == "MUSR" || - m_instrument->getName() == "CHRONUS") { + if (m_instrument->getName() == "MUSR" || m_instrument->getName() == "CHRONUS") { parameterName.append(" - " + m_mainFieldDirection); } - std::vector groupingFiles = - m_instrument->getStringParameter(parameterName); + std::vector groupingFiles = m_instrument->getStringParameter(parameterName); if (groupingFiles.size() == 1) { const std::string groupingFile = groupingFiles[0]; // Get search directory for XML instrument definition files (IDFs) - std::string directoryName = - Kernel::ConfigService::Instance().getInstrumentDirectory(); + std::string directoryName = Kernel::ConfigService::Instance().getInstrumentDirectory(); loadGroupingFromXML(directoryName + groupingFile, *loadedGrouping); } else { @@ -81,48 +75,41 @@ std::shared_ptr GroupingLoader::getGroupingFromIDF() const { * @param filename :: XML filename to load grouping information from * @param grouping :: Struct to store grouping information to */ -void GroupingLoader::loadGroupingFromXML(const std::string &filename, - Grouping &grouping) { +void GroupingLoader::loadGroupingFromXML(const std::string &filename, Grouping &grouping) { // Set up the DOM parser and parse xml file DOMParser pParser; Poco::AutoPtr pDoc; try { pDoc = pParser.parse(filename); } catch (...) { - throw Mantid::Kernel::Exception::FileError("Unable to parse File", - filename); + throw Mantid::Kernel::Exception::FileError("Unable to parse File", filename); } // Get pointer to root element Element *pRootElem = pDoc->documentElement(); if (!pRootElem->hasChildNodes()) - throw Mantid::Kernel::Exception::FileError( - "No root element in XML grouping file", filename); + throw Mantid::Kernel::Exception::FileError("No root element in XML grouping file", filename); // Parse information for groups Poco::AutoPtr groups = pRootElem->getElementsByTagName("group"); if (groups->length() == 0) - throw Mantid::Kernel::Exception::FileError( - "No groups specified in XML grouping file", filename); + throw Mantid::Kernel::Exception::FileError("No groups specified in XML grouping file", filename); // Resize vectors grouping.groupNames.resize(groups->length()); grouping.groups.resize(groups->length()); for (size_t ig = 0; ig < groups->length(); ig++) { - auto *pGroupElem = - static_cast(groups->item(static_cast(ig))); + auto *pGroupElem = static_cast(groups->item(static_cast(ig))); if (!pGroupElem->hasAttribute("name")) - throw Mantid::Kernel::Exception::FileError("Group element without name", - filename); + throw Mantid::Kernel::Exception::FileError("Group element without name", filename); grouping.groupNames[ig] = pGroupElem->getAttribute("name"); Element *idlistElement = pGroupElem->getChildElement("ids"); if (!idlistElement) - throw Mantid::Kernel::Exception::FileError("Group element without ", - filename); + throw Mantid::Kernel::Exception::FileError("Group element without ", filename); grouping.groups[ig] = idlistElement->getAttribute("val"); } @@ -136,12 +123,10 @@ void GroupingLoader::loadGroupingFromXML(const std::string &filename, grouping.pairAlphas.resize(pairs->length()); for (size_t ip = 0; ip < pairs->length(); ip++) { - auto *pPairElem = - static_cast(pairs->item(static_cast(ip))); + auto *pPairElem = static_cast(pairs->item(static_cast(ip))); if (!pPairElem->hasAttribute("name")) - throw Mantid::Kernel::Exception::FileError("Pair element without name", - filename); + throw Mantid::Kernel::Exception::FileError("Pair element without name", filename); grouping.pairNames[ip] = pPairElem->getAttribute("name"); @@ -150,45 +135,35 @@ void GroupingLoader::loadGroupingFromXML(const std::string &filename, // Try to get id of the first group if (Element *fwdElement = pPairElem->getChildElement("forward-group")) { if (!fwdElement->hasAttribute("val")) - throw Mantid::Kernel::Exception::FileError( - "Pair forward-group without ", filename); + throw Mantid::Kernel::Exception::FileError("Pair forward-group without ", filename); // Find the group with the given name - auto it = - std::find(grouping.groupNames.begin(), grouping.groupNames.end(), - fwdElement->getAttribute("val")); + auto it = std::find(grouping.groupNames.begin(), grouping.groupNames.end(), fwdElement->getAttribute("val")); if (it == grouping.groupNames.end()) - throw Mantid::Kernel::Exception::FileError( - "Pair forward-group name not recognized", filename); + throw Mantid::Kernel::Exception::FileError("Pair forward-group name not recognized", filename); // Get index of the iterator fwdGroupId = it - grouping.groupNames.begin(); } else { - throw Mantid::Kernel::Exception::FileError( - "Pair element without ", filename); + throw Mantid::Kernel::Exception::FileError("Pair element without ", filename); } // Try to get id of the second group if (Element *bwdElement = pPairElem->getChildElement("backward-group")) { if (!bwdElement->hasAttribute("val")) - throw Mantid::Kernel::Exception::FileError( - "Pair backward-group without ", filename); + throw Mantid::Kernel::Exception::FileError("Pair backward-group without ", filename); // Find the group with the given name - auto it = - std::find(grouping.groupNames.begin(), grouping.groupNames.end(), - bwdElement->getAttribute("val")); + auto it = std::find(grouping.groupNames.begin(), grouping.groupNames.end(), bwdElement->getAttribute("val")); if (it == grouping.groupNames.end()) - throw Mantid::Kernel::Exception::FileError( - "Pair backward-group name not recognized", filename); + throw Mantid::Kernel::Exception::FileError("Pair backward-group name not recognized", filename); // Get index of the iterator bwdGroupId = it - grouping.groupNames.begin(); } else { - throw Mantid::Kernel::Exception::FileError( - "Pair element without ", filename); + throw Mantid::Kernel::Exception::FileError("Pair element without ", filename); } grouping.pairs[ip] = std::make_pair(fwdGroupId, bwdGroupId); @@ -196,16 +171,14 @@ void GroupingLoader::loadGroupingFromXML(const std::string &filename, // Try to get alpha element if (Element *aElement = pPairElem->getChildElement("alpha")) { if (!aElement->hasAttribute("val")) - throw Mantid::Kernel::Exception::FileError( - "Pair alpha element with no ", filename); + throw Mantid::Kernel::Exception::FileError("Pair alpha element with no ", filename); try // ... to convert value to double { - grouping.pairAlphas[ip] = - boost::lexical_cast(aElement->getAttribute("val")); - } catch (boost::bad_lexical_cast &) { - throw Mantid::Kernel::Exception::FileError( - "Pair alpha value is not a number", filename); + grouping.pairAlphas[ip] = boost::lexical_cast(aElement->getAttribute("val")); + } + catch (boost::bad_lexical_cast &) { + throw Mantid::Kernel::Exception::FileError("Pair alpha value is not a number", filename); } } // If alpha element not there, default it to 1.0 @@ -222,8 +195,7 @@ void GroupingLoader::loadGroupingFromXML(const std::string &filename, // Try to get default group/pair name if (Element *defaultElement = pRootElem->getChildElement("default")) { if (!defaultElement->hasAttribute("name")) - throw Mantid::Kernel::Exception::FileError( - "Default element with no ", filename); + throw Mantid::Kernel::Exception::FileError("Default element with no ", filename); grouping.defaultName = defaultElement->getAttribute("name"); } @@ -279,8 +251,8 @@ Grouping::Grouping(const ITableWorkspace_sptr &table) { * @return A grouping table as accepted by MuonGroupDetectors */ ITableWorkspace_sptr Grouping::toTable() const { - auto newTable = std::dynamic_pointer_cast( - WorkspaceFactory::Instance().createTable("TableWorkspace")); + auto newTable = + std::dynamic_pointer_cast(WorkspaceFactory::Instance().createTable("TableWorkspace")); newTable->addColumn("vector_int", "Detectors"); diff --git a/Framework/API/src/HistogramValidator.cpp b/Framework/API/src/HistogramValidator.cpp index 4bb788ac9f736321a624260e7a74f1bda136860c..b43a2bfc7e5d9d040b6e15ced50b08ba0f67b41d 100644 --- a/Framework/API/src/HistogramValidator.cpp +++ b/Framework/API/src/HistogramValidator.cpp @@ -20,17 +20,14 @@ HistogramValidator::HistogramValidator(const bool &mustBeHistogram) : MatrixWorkspaceValidator(), m_mustBeHistogram(mustBeHistogram) {} /// Clone the current state -Kernel::IValidator_sptr HistogramValidator::clone() const { - return std::make_shared(*this); -} +Kernel::IValidator_sptr HistogramValidator::clone() const { return std::make_shared(*this); } /** Checks if the workspace contains a histogram when it shouldn't and * vice-versa * @param value :: The workspace to test * @return A user level description if a problem exists or "" */ -std::string -HistogramValidator::checkValidity(const MatrixWorkspace_sptr &value) const { +std::string HistogramValidator::checkValidity(const MatrixWorkspace_sptr &value) const { if (m_mustBeHistogram) { if (value->isHistogramData()) return ""; diff --git a/Framework/API/src/HistoryView.cpp b/Framework/API/src/HistoryView.cpp index 818cff625f06baed069d93dae44b412924f67a36..fc234b8c1f7b60c73f6bff34e3574c196a712694 100644 --- a/Framework/API/src/HistoryView.cpp +++ b/Framework/API/src/HistoryView.cpp @@ -14,12 +14,10 @@ namespace Mantid { namespace API { -HistoryView::HistoryView(const WorkspaceHistory &wsHist) - : m_wsHist(wsHist), m_historyItems() { +HistoryView::HistoryView(const WorkspaceHistory &wsHist) : m_wsHist(wsHist), m_historyItems() { // add all of the top level algorithms to the view by default const auto &algorithms = wsHist.getAlgorithmHistories(); - m_historyItems = - std::vector(algorithms.begin(), algorithms.end()); + m_historyItems = std::vector(algorithms.begin(), algorithms.end()); } /** @@ -65,8 +63,7 @@ void HistoryView::unroll(std::vector::iterator &it) { it->unrolled(true); // insert each of the records, in order, at this position - std::vector tmpHistory(childHistories.cbegin(), - childHistories.cend()); + std::vector tmpHistory(childHistories.cbegin(), childHistories.cend()); // since we are using a std::vector, do all insertions at the same time. ++it; // move iterator forward to insertion position it = m_historyItems.insert(it, tmpHistory.begin(), tmpHistory.end()); @@ -184,15 +181,11 @@ void HistoryView::roll(std::vector::iterator &it) { * @param start Start of time range * @param end End of time range */ -void HistoryView::filterBetweenExecDate(Mantid::Types::Core::DateAndTime start, - Mantid::Types::Core::DateAndTime end) { - auto lastItem = std::remove_if( - m_historyItems.begin(), m_historyItems.end(), - [&start, &end](const HistoryItem &item) { - Mantid::Types::Core::DateAndTime algExecutionDate = - item.getAlgorithmHistory()->executionDate(); - return algExecutionDate < start || algExecutionDate > end; - }); +void HistoryView::filterBetweenExecDate(Mantid::Types::Core::DateAndTime start, Mantid::Types::Core::DateAndTime end) { + auto lastItem = std::remove_if(m_historyItems.begin(), m_historyItems.end(), [&start, &end](const HistoryItem &item) { + Mantid::Types::Core::DateAndTime algExecutionDate = item.getAlgorithmHistory()->executionDate(); + return algExecutionDate < start || algExecutionDate > end; + }); m_historyItems.erase(lastItem, m_historyItems.end()); } diff --git a/Framework/API/src/IDomainCreator.cpp b/Framework/API/src/IDomainCreator.cpp index 5634237e05a6df0a808e7ebf08a9187a3bf9e749..44e64a20daa1f9bea3d037f9827ca8eb943446f3 100644 --- a/Framework/API/src/IDomainCreator.cpp +++ b/Framework/API/src/IDomainCreator.cpp @@ -22,13 +22,10 @@ namespace API { * @param domainType :: Type of domain to create: Simple, Sequential, or * Parallel. */ -IDomainCreator::IDomainCreator( - Kernel::IPropertyManager *manager, - const std::vector &workspacePropertyNames, - DomainType domainType) - : m_manager(manager), m_workspacePropertyNames(workspacePropertyNames), - m_domainType(domainType), m_outputCompositeMembers(false), - m_convolutionCompositeMembers(false), m_ignoreInvalidData(false) {} +IDomainCreator::IDomainCreator(Kernel::IPropertyManager *manager, + const std::vector &workspacePropertyNames, DomainType domainType) + : m_manager(manager), m_workspacePropertyNames(workspacePropertyNames), m_domainType(domainType), + m_outputCompositeMembers(false), m_convolutionCompositeMembers(false), m_ignoreInvalidData(false) {} /** * @param value If true then each composite is unrolled and its output is @@ -40,8 +37,7 @@ IDomainCreator::IDomainCreator( * the * resolution (function index 0). */ -void IDomainCreator::separateCompositeMembersInOutput(const bool value, - const bool conv) { +void IDomainCreator::separateCompositeMembersInOutput(const bool value, const bool conv) { m_outputCompositeMembers = value; m_convolutionCompositeMembers = conv; } @@ -51,8 +47,7 @@ void IDomainCreator::separateCompositeMembersInOutput(const bool value, * @param prop :: A new property. * @param doc :: A doc string. */ -void IDomainCreator::declareProperty(Kernel::Property *prop, - const std::string &doc) { +void IDomainCreator::declareProperty(Kernel::Property *prop, const std::string &doc) { if (!m_manager) { throw std::runtime_error("IDomainCreator: property manager isn't defined."); } @@ -65,8 +60,7 @@ void IDomainCreator::declareProperty(Kernel::Property *prop, */ void IDomainCreator::initFunction(API::IFunction_sptr function) { if (!function) { - throw std::runtime_error( - "IDomainCreator: cannot initialize empty function."); + throw std::runtime_error("IDomainCreator: cannot initialize empty function."); } if (!m_manager) { throw std::runtime_error("IDomainCreator: property manager isn't defined."); @@ -74,8 +68,7 @@ void IDomainCreator::initFunction(API::IFunction_sptr function) { if (m_manager->existsProperty("InputWorkspace")) { API::Workspace_sptr workspace = m_manager->getProperty("InputWorkspace"); if (!workspace) { - throw std::runtime_error( - "IDomainCreator: cannot initialize function: workspace undefined."); + throw std::runtime_error("IDomainCreator: cannot initialize function: workspace undefined."); } function->setWorkspace(workspace); } diff --git a/Framework/API/src/IEventWorkspace.cpp b/Framework/API/src/IEventWorkspace.cpp index 9564fc75dc300ece04f0217de1b692ed488a8cfc..74eb1bef2e326e24ac4d56f4fbfd449cae68dcb3 100644 --- a/Framework/API/src/IEventWorkspace.cpp +++ b/Framework/API/src/IEventWorkspace.cpp @@ -41,34 +41,26 @@ namespace Kernel { template <> MANTID_API_DLL Mantid::API::IEventWorkspace_sptr -IPropertyManager::getValue( - const std::string &name) const { - auto *prop = - dynamic_cast *>( - getPointerToProperty(name)); +IPropertyManager::getValue(const std::string &name) const { + auto *prop = dynamic_cast *>(getPointerToProperty(name)); if (prop) { return *prop; } else { std::string message = - "Attempt to assign property " + name + - " to incorrect type. Expected shared_ptr."; + "Attempt to assign property " + name + " to incorrect type. Expected shared_ptr."; throw std::runtime_error(message); } } template <> MANTID_API_DLL Mantid::API::IEventWorkspace_const_sptr -IPropertyManager::getValue( - const std::string &name) const { - auto *prop = - dynamic_cast *>( - getPointerToProperty(name)); +IPropertyManager::getValue(const std::string &name) const { + auto *prop = dynamic_cast *>(getPointerToProperty(name)); if (prop) { return prop->operator()(); } else { std::string message = - "Attempt to assign property " + name + - " to incorrect type. Expected const shared_ptr."; + "Attempt to assign property " + name + " to incorrect type. Expected const shared_ptr."; throw std::runtime_error(message); } } diff --git a/Framework/API/src/IFuncMinimizer.cpp b/Framework/API/src/IFuncMinimizer.cpp index 989fe1fd64b97da549759934cffff3516467e64e..e8075ffdb9793c23f414b1c890166e78286be2a3 100644 --- a/Framework/API/src/IFuncMinimizer.cpp +++ b/Framework/API/src/IFuncMinimizer.cpp @@ -38,8 +38,7 @@ bool IFuncMinimizer::minimize(size_t maxIterations) { if (!m_errorString.empty()) { m_errorString += '\n'; } - m_errorString += "Failed to converge after " + - std::to_string(maxIterations) + " iterations."; + m_errorString += "Failed to converge after " + std::to_string(maxIterations) + " iterations."; } return success; diff --git a/Framework/API/src/IFunction.cpp b/Framework/API/src/IFunction.cpp index 4980fd11db9844abc35cde43fe27aa53807daf6e..5b89cd6560e5d5318951a10f2b5758219d1d6922 100644 --- a/Framework/API/src/IFunction.cpp +++ b/Framework/API/src/IFunction.cpp @@ -30,6 +30,7 @@ #include "MantidKernel/ProgressBase.h" #include "MantidKernel/Strings.h" #include "MantidKernel/UnitFactory.h" +#include "MantidKernel/UsageService.h" #include @@ -57,23 +58,38 @@ struct TieNode { // This tie must be applied before the other if the RHS of the other // contains this (left) parameter. bool operator<(TieNode const &other) const { - return std::find(other.right.begin(), other.right.end(), left) != - other.right.end(); + return std::find(other.right.begin(), other.right.end(), left) != other.right.end(); } }; +const std::vector EXCLUDEUSAGE = {"CompositeFunction"}; } // namespace +/** + * Constructor + */ +IFunction ::IFunction() : m_isParallel(false), m_handler(nullptr), m_chiSquared(0.0) {} /** * Destructor */ IFunction::~IFunction() { m_attrs.clear(); } +/** +Registers the usage of the function with the UsageService + */ +void IFunction::registerFunctionUsage(bool internal) { + if (!Kernel::UsageService::Instance().isEnabled()) { + return; + } + if (std::find(EXCLUDEUSAGE.cbegin(), EXCLUDEUSAGE.cend(), name()) == EXCLUDEUSAGE.cend() && !m_isRegistered) { + m_isRegistered = true; + Kernel::UsageService::Instance().registerFeatureUsage(Kernel::FeatureType::Function, name(), internal); + } +} /** * Virtual copy constructor */ std::shared_ptr IFunction::clone() const { - auto clonedFunction = - FunctionFactory::Instance().createInitialized(this->asString()); + auto clonedFunction = FunctionFactory::Instance().createInitialized(this->asString()); for (size_t i = 0; i < this->nParams(); i++) { double error = this->getError(i); clonedFunction->setError(i, error); @@ -86,8 +102,7 @@ std::shared_ptr IFunction::clone() const { * @param reporter :: A pointer to a progress reporter that can be called during * function evaluation */ -void IFunction::setProgressReporter( - std::shared_ptr reporter) { +void IFunction::setProgressReporter(std::shared_ptr reporter) { m_progReporter = std::move(reporter); m_progReporter->setNotifyStep(0.01); } @@ -119,17 +134,12 @@ bool IFunction::cancellationRequestReceived() const { * @param jacobian :: A Jacobian matrix. It is expected to have dimensions of * domain.size() by nParams(). */ -void IFunction::functionDeriv(const FunctionDomain &domain, - Jacobian &jacobian) { - calNumericalDeriv(domain, jacobian); -} +void IFunction::functionDeriv(const FunctionDomain &domain, Jacobian &jacobian) { calNumericalDeriv(domain, jacobian); } /** Check if an active parameter i is actually active * @param i :: Index of a parameter. */ -bool IFunction::isActive(size_t i) const { - return getParameterStatus(i) == Active; -} +bool IFunction::isActive(size_t i) const { return getParameterStatus(i) == Active; } /** * Query if the parameter is fixed @@ -144,9 +154,7 @@ bool IFunction::isFixed(size_t i) const { /// Check if a parameter i is fixed by default (not by user). /// @param i :: The index of a parameter /// @return true if parameter i is fixed by default -bool IFunction::isFixedByDefault(size_t i) const { - return getParameterStatus(i) == FixedByDefault; -} +bool IFunction::isFixedByDefault(size_t i) const { return getParameterStatus(i) == FixedByDefault; } /// This method doesn't create a tie /// @param i :: A declared parameter index to be fixed @@ -155,8 +163,8 @@ bool IFunction::isFixedByDefault(size_t i) const { void IFunction::fix(size_t i, bool isDefault) { auto status = getParameterStatus(i); if (status == Tied) { - throw std::runtime_error("Cannot fix parameter " + std::to_string(i) + - " (" + parameterName(i) + "): it has a tie."); + throw std::runtime_error("Cannot fix parameter " + std::to_string(i) + " (" + parameterName(i) + + "): it has a tie."); } if (isDefault) { setParameterStatus(i, FixedByDefault); @@ -171,8 +179,8 @@ void IFunction::fix(size_t i, bool isDefault) { void IFunction::unfix(size_t i) { auto status = getParameterStatus(i); if (status == Tied) { - throw std::runtime_error("Cannot unfix parameter " + std::to_string(i) + - " (" + parameterName(i) + "): it has a tie."); + throw std::runtime_error("Cannot unfix parameter " + std::to_string(i) + " (" + parameterName(i) + + "): it has a tie."); } setParameterStatus(i, Active); } @@ -185,8 +193,7 @@ void IFunction::unfix(size_t i) { * with this reference: a tie or a constraint. * @return newly ties parameters */ -void IFunction::tie(const std::string &parName, const std::string &expr, - bool isDefault) { +void IFunction::tie(const std::string &parName, const std::string &expr, bool isDefault) { auto ti = std::make_unique(this, parName, expr, isDefault); if (!isDefault && ti->isConstant()) { setParameter(parName, ti->eval()); @@ -304,14 +311,11 @@ class ReferenceEqual { public: /// Constructor - explicit ReferenceEqual(const IFunction &fun, size_t i) - : m_fun(fun), m_i(i) {} + explicit ReferenceEqual(const IFunction &fun, size_t i) : m_fun(fun), m_i(i) {} /// Bracket operator /// @param p :: the element you are looking for /// @return True if found - template bool operator()(const std::unique_ptr &p) { - return m_fun.getParameterIndex(*p) == m_i; - } + template bool operator()(const std::unique_ptr &p) { return m_fun.getParameterIndex(*p) == m_i; } }; /** Removes i-th parameter's tie if it is tied or does nothing. @@ -322,8 +326,7 @@ bool IFunction::removeTie(size_t i) { if (i >= nParams()) { throw std::out_of_range("Function parameter index out of range."); } - auto it = - std::find_if(m_ties.begin(), m_ties.end(), ReferenceEqual(*this, i)); + auto it = std::find_if(m_ties.begin(), m_ties.end(), ReferenceEqual(*this, i)); if (it != m_ties.end()) { m_ties.erase(it); setParameterStatus(i, Active); @@ -338,8 +341,7 @@ bool IFunction::removeTie(size_t i) { * @return A pointer to the tie */ ParameterTie *IFunction::getTie(size_t i) const { - auto it = - std::find_if(m_ties.cbegin(), m_ties.cend(), ReferenceEqual(*this, i)); + auto it = std::find_if(m_ties.cbegin(), m_ties.cend(), ReferenceEqual(*this, i)); if (it != m_ties.cend()) { return it->get(); } @@ -378,8 +380,7 @@ void IFunction::addConstraint(std::unique_ptr ic) { * @return A pointer to the constraint or NULL */ IConstraint *IFunction::getConstraint(size_t i) const { - auto it = std::find_if(m_constraints.cbegin(), m_constraints.cend(), - ReferenceEqual(*this, i)); + auto it = std::find_if(m_constraints.cbegin(), m_constraints.cend(), ReferenceEqual(*this, i)); if (it != m_constraints.cend()) { return it->get(); } @@ -403,8 +404,7 @@ void IFunction::removeConstraint(const std::string &parName) { * @param parName :: The name of a constraint * @param c :: The penalty */ -void IFunction::setConstraintPenaltyFactor(const std::string &parName, - const double &c) { +void IFunction::setConstraintPenaltyFactor(const std::string &parName, const double &c) { size_t iPar = parameterIndex(parName); for (auto &constraint : m_constraints) { if (iPar == constraint->getLocalIndex()) { @@ -412,10 +412,8 @@ void IFunction::setConstraintPenaltyFactor(const std::string &parName, return; } } - g_log.warning() - << parName - << " does not have constraint so setConstraintPenaltyFactor failed" - << "\n"; + g_log.warning() << parName << " does not have constraint so setConstraintPenaltyFactor failed" + << "\n"; } /// Remove all constraints. @@ -459,8 +457,7 @@ std::string IFunction::asString() const { return writeToString(); } * CompositeFunction (eg MultiDomainFunction). * @return string representation of the function */ -std::string -IFunction::writeToString(const std::string &parentLocalAttributesStr) const { +std::string IFunction::writeToString(const std::string &parentLocalAttributesStr) const { std::ostringstream ostr; ostr << "name=" << this->name(); // print the attributes @@ -497,8 +494,7 @@ IFunction::writeToString(const std::string &parentLocalAttributesStr) const { } // print the ties if (!ties.empty()) { - ostr << ",ties=(" << Kernel::Strings::join(ties.begin(), ties.end(), ",") - << ")"; + ostr << ",ties=(" << Kernel::Strings::join(ties.begin(), ties.end(), ",") << ")"; } // "local" attributes of a parent composite function ostr << parentLocalAttributesStr; @@ -523,22 +519,16 @@ void IFunction::addConstraints(const std::string &str, bool isDefault) { if ((it + 1) != list.end()) { auto next_expr = *(it + 1); if (next_expr.terms()[0].str().compare("penalty") == 0) { - auto c = std::unique_ptr( - ConstraintFactory::Instance().createInitialized(this, expr, - isDefault)); + auto c = std::unique_ptr(ConstraintFactory::Instance().createInitialized(this, expr, isDefault)); double penalty_factor = std::stof(next_expr.terms()[1].str(), NULL); c->setPenaltyFactor(penalty_factor); this->addConstraint(std::move(c)); } else { - auto c = std::unique_ptr( - ConstraintFactory::Instance().createInitialized(this, expr, - isDefault)); + auto c = std::unique_ptr(ConstraintFactory::Instance().createInitialized(this, expr, isDefault)); this->addConstraint(std::move(c)); } } else { - auto c = std::unique_ptr( - ConstraintFactory::Instance().createInitialized(this, expr, - isDefault)); + auto c = std::unique_ptr(ConstraintFactory::Instance().createInitialized(this, expr, isDefault)); this->addConstraint(std::move(c)); } } @@ -569,10 +559,9 @@ void IFunction::setHandler(std::unique_ptr handler) { /// Function to return all of the categories that contain this function const std::vector IFunction::categories() const { - Mantid::Kernel::StringTokenizer tokenizer( - category(), categorySeparator(), - Mantid::Kernel::StringTokenizer::TOK_TRIM | - Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY); + Mantid::Kernel::StringTokenizer tokenizer(category(), categorySeparator(), + Mantid::Kernel::StringTokenizer::TOK_TRIM | + Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY); return tokenizer.asVector(); } @@ -593,9 +582,7 @@ namespace { class AttType : public IFunction::ConstAttributeVisitor { protected: /// Apply if string - std::string apply(const std::string & /*str*/) const override { - return "std::string"; - } + std::string apply(const std::string & /*str*/) const override { return "std::string"; } /// Apply if int std::string apply(const int & /*i*/) const override { return "int"; } /// Apply if double @@ -603,9 +590,7 @@ protected: /// Apply if bool std::string apply(const bool & /*i*/) const override { return "bool"; } /// Apply if vector - std::string apply(const std::vector & /*unused*/) const override { - return "std::vector"; - } + std::string apply(const std::vector & /*unused*/) const override { return "std::vector"; } }; } // namespace @@ -621,8 +606,7 @@ namespace { class AttValue : public IFunction::ConstAttributeVisitor { public: explicit AttValue(bool quoteString = false) - : IFunction::ConstAttributeVisitor(), - m_quoteString(quoteString) {} + : IFunction::ConstAttributeVisitor(), m_quoteString(quoteString) {} protected: /// Apply if string @@ -632,13 +616,9 @@ protected: /// Apply if int std::string apply(const int &i) const override { return std::to_string(i); } /// Apply if double - std::string apply(const double &d) const override { - return boost::lexical_cast(d); - } + std::string apply(const double &d) const override { return boost::lexical_cast(d); } /// Apply if bool - std::string apply(const bool &b) const override { - return b ? "true" : "false"; - } + std::string apply(const bool &b) const override { return b ? "true" : "false"; } /// Apply if vector std::string apply(const std::vector &v) const override { std::string res = "("; @@ -858,8 +838,7 @@ bool IFunction::Attribute::isEmpty() const { try { return boost::get(m_data).empty(); } catch (...) { - throw std::runtime_error("Trying to access a " + type() + - " attribute as string"); + throw std::runtime_error("Trying to access a " + type() + " attribute as string"); } } @@ -897,9 +876,7 @@ protected: m_value); } /// Apply if bool - void apply(bool &b) const override { - b = (m_value == "true" || m_value == "TRUE" || m_value == "1"); - } + void apply(bool &b) const override { b = (m_value == "true" || m_value == "TRUE" || m_value == "1"); } /// Apply if vector void apply(std::vector &v) const override { if (m_value.empty() || m_value == "EMPTY") { @@ -913,8 +890,7 @@ protected: m_value.erase(m_value.size() - 1); } } - Mantid::Kernel::StringTokenizer tokenizer( - m_value, ",", Mantid::Kernel::StringTokenizer::TOK_TRIM); + Mantid::Kernel::StringTokenizer tokenizer(m_value, ",", Mantid::Kernel::StringTokenizer::TOK_TRIM); v.resize(tokenizer.count()); for (size_t i = 0; i < v.size(); ++i) { v[i] = boost::lexical_cast(tokenizer[i]); @@ -938,8 +914,7 @@ void IFunction::Attribute::fromString(const std::string &str) { /// parameters different from the declared double IFunction::activeParameter(size_t i) const { if (!isActive(i)) { - throw std::runtime_error("Attempt to use an inactive parameter " + - parameterName(i)); + throw std::runtime_error("Attempt to use an inactive parameter " + parameterName(i)); } return getParameter(i); } @@ -948,8 +923,7 @@ double IFunction::activeParameter(size_t i) const { /// parameters different from the declared void IFunction::setActiveParameter(size_t i, double value) { if (!isActive(i)) { - throw std::runtime_error("Attempt to use an inactive parameter " + - parameterName(i)); + throw std::runtime_error("Attempt to use an inactive parameter " + parameterName(i)); } setParameter(i, value); } @@ -960,8 +934,7 @@ void IFunction::setActiveParameter(size_t i, double value) { */ std::string IFunction::nameOfActive(size_t i) const { if (!isActive(i)) { - throw std::runtime_error("Attempt to use an inactive parameter " + - parameterName(i)); + throw std::runtime_error("Attempt to use an inactive parameter " + parameterName(i)); } return parameterName(i); } @@ -972,8 +945,7 @@ std::string IFunction::nameOfActive(size_t i) const { */ std::string IFunction::descriptionOfActive(size_t i) const { if (!isActive(i)) { - throw std::runtime_error("Attempt to use an inactive parameter " + - parameterName(i)); + throw std::runtime_error("Attempt to use an inactive parameter " + parameterName(i)); } return parameterDescription(i); } @@ -983,8 +955,7 @@ std::string IFunction::descriptionOfActive(size_t i) const { * @param jacobian :: A Jacobian matrix. It is expected to have dimensions of * domain.size() by nParams(). */ -void IFunction::calNumericalDeriv(const FunctionDomain &domain, - Jacobian &jacobian) { +void IFunction::calNumericalDeriv(const FunctionDomain &domain, Jacobian &jacobian) { /* * There is a similar more specialized method for 1D functions in IFunction1D * but the method takes different parameters and uses slightly different @@ -994,8 +965,7 @@ void IFunction::calNumericalDeriv(const FunctionDomain &domain, constexpr double epsilon = std::numeric_limits::epsilon() * 100; constexpr double stepPercentage = 0.001; - constexpr double cutoff = - 100.0 * std::numeric_limits::min() / stepPercentage; + constexpr double cutoff = 100.0 * std::numeric_limits::min() / stepPercentage; const size_t nParam = nParams(); size_t nData = getValuesSize(domain); @@ -1028,9 +998,7 @@ void IFunction::calNumericalDeriv(const FunctionDomain &domain, step = paramPstep - val; for (size_t i = 0; i < nData; i++) { - jacobian.set(i, iP, - (plusStep.getCalculated(i) - minusStep.getCalculated(i)) / - step); + jacobian.set(i, iP, (plusStep.getCalculated(i) - minusStep.getCalculated(i)) / step); } } } @@ -1042,9 +1010,8 @@ void IFunction::calNumericalDeriv(const FunctionDomain &domain, * @param startX :: The lower bin index * @param endX :: The upper bin index */ -void IFunction::setMatrixWorkspace( - std::shared_ptr workspace, size_t wi, - double startX, double endX) { +void IFunction::setMatrixWorkspace(std::shared_ptr workspace, size_t wi, double startX, + double endX) { UNUSED_ARG(startX); UNUSED_ARG(endX); @@ -1064,8 +1031,7 @@ void IFunction::setMatrixWorkspace( // the first detector // Note JZ oct 2011 - I'm not sure why the code uses the first detector // and not the group. Ask Roman. - auto firstDetectorId = - *workspace->getSpectrum(wi).getDetectorIDs().begin(); + auto firstDetectorId = *workspace->getSpectrum(wi).getDetectorIDs().begin(); const auto &detectorInfo = workspace->detectorInfo(); const auto detectorIndex = detectorInfo.indexOf(firstDetectorId); @@ -1080,8 +1046,7 @@ void IFunction::setMatrixWorkspace( for (size_t i = 0; i < nParams(); i++) { if (!isExplicitlySet(i)) { - Geometry::Parameter_sptr param = - paramMap.getRecursive(detectorPtr, parameterName(i), "fitting"); + Geometry::Parameter_sptr param = paramMap.getRecursive(detectorPtr, parameterName(i), "fitting"); if (param != Geometry::Parameter_sptr()) { // get FitParameter const auto &fitParam = param->value(); @@ -1090,11 +1055,9 @@ void IFunction::setMatrixWorkspace( // function if (name() == fitParam.getFunction()) { // update value - auto *testWithLocation = - dynamic_cast(this); + auto *testWithLocation = dynamic_cast(this); if (testWithLocation == nullptr || - (!fitParam.getLookUpTable().containData() && - fitParam.getFormula().empty())) { + (!fitParam.getLookUpTable().containData() && fitParam.getFormula().empty())) { setParameter(i, fitParam.getValue()); } else { double centreValue = testWithLocation->centre(); @@ -1105,13 +1068,10 @@ void IFunction::setMatrixWorkspace( else { if (!fitParam.getFormulaUnit().empty()) { try { - centreUnit = Kernel::UnitFactory::Instance().create( - fitParam.getFormulaUnit()); // from formula + centreUnit = Kernel::UnitFactory::Instance().create(fitParam.getFormulaUnit()); // from formula } catch (...) { - g_log.warning() - << fitParam.getFormulaUnit() - << " Is not an recognised formula unit for parameter " - << fitParam.getName() << "\n"; + g_log.warning() << fitParam.getFormulaUnit() << " Is not an recognised formula unit for parameter " + << fitParam.getName() << "\n"; } } } @@ -1119,15 +1079,11 @@ void IFunction::setMatrixWorkspace( // if unit specified convert centre value to unit required by // formula or look-up-table if (centreUnit) { - g_log.debug() - << "For FitParameter " << parameterName(i) - << " centre of peak before any unit convertion is " - << centreValue << '\n'; - centreValue = - convertValue(centreValue, centreUnit, workspace, wi); g_log.debug() << "For FitParameter " << parameterName(i) - << " centre of peak after any unit convertion is " - << centreValue << '\n'; + << " centre of peak before any unit conversion is " << centreValue << '\n'; + centreValue = convertValue(centreValue, centreUnit, workspace, wi); + g_log.debug() << "For FitParameter " << parameterName(i) + << " centre of peak after any unit conversion is " << centreValue << '\n'; } double paramValue = fitParam.getValue(centreValue); @@ -1139,30 +1095,25 @@ void IFunction::setMatrixWorkspace( // www.mantidproject.org/IDF if (fitParam.getFormula().empty()) { // so from look up table - Kernel::Unit_sptr resultUnit = - fitParam.getLookUpTable().getYUnit(); // from table - g_log.debug() - << "The FitParameter " << parameterName(i) << " = " - << paramValue << " before y-unit convertion\n"; + Kernel::Unit_sptr resultUnit = fitParam.getLookUpTable().getYUnit(); // from table + g_log.debug() << "The FitParameter " << parameterName(i) << " = " << paramValue + << " before y-unit conversion\n"; paramValue /= convertValue(1.0, resultUnit, workspace, wi); - g_log.debug() - << "The FitParameter " << parameterName(i) << " = " - << paramValue << " after y-unit convertion\n"; + g_log.debug() << "The FitParameter " << parameterName(i) << " = " << paramValue + << " after y-unit conversion\n"; } else { // so from formula std::string resultUnitStr = fitParam.getResultUnit(); if (!resultUnitStr.empty()) { - std::vector allUnitStr = - Kernel::UnitFactory::Instance().getKeys(); + std::vector allUnitStr = Kernel::UnitFactory::Instance().getKeys(); for (auto &iUnit : allUnitStr) { size_t found = resultUnitStr.find(iUnit); if (found != std::string::npos) { size_t len = iUnit.size(); std::stringstream readDouble; - Kernel::Unit_sptr unt = - Kernel::UnitFactory::Instance().create(iUnit); + Kernel::Unit_sptr unt = Kernel::UnitFactory::Instance().create(iUnit); readDouble << 1.0 / convertValue(1.0, unt, workspace, wi); resultUnitStr.replace(found, len, readDouble.str()); } @@ -1171,24 +1122,18 @@ void IFunction::setMatrixWorkspace( try { mu::Parser p; p.SetExpr(resultUnitStr); - g_log.debug() << "The FitParameter " << parameterName(i) - << " = " << paramValue - << " before result-unit convertion (using " - << resultUnitStr << ")\n"; + g_log.debug() << "The FitParameter " << parameterName(i) << " = " << paramValue + << " before result-unit conversion (using " << resultUnitStr << ")\n"; paramValue *= p.Eval(); - g_log.debug() - << "The FitParameter " << parameterName(i) << " = " - << paramValue << " after result-unit convertion\n"; + g_log.debug() << "The FitParameter " << parameterName(i) << " = " << paramValue + << " after result-unit conversion\n"; } catch (mu::Parser::exception_type &e) { - g_log.error() - << "Cannot convert formula unit to workspace unit" - << " Formula unit which cannot be passed is " - << resultUnitStr - << ". Muparser error message is: " << e.GetMsg() - << '\n'; + g_log.error() << "Cannot convert formula unit to workspace unit" + << " Formula unit which cannot be passed is " << resultUnitStr + << ". Muparser error message is: " << e.GetMsg() << '\n'; } } // end if - } // end trying to convert result-unit from formula or y-unit for + } // end trying to convert result-unit from formula or y-unit for // lookuptable setParameter(i, paramValue); @@ -1205,17 +1150,13 @@ void IFunction::setMatrixWorkspace( // add constraint if specified for this parameter in instrument // definition file if (!fitParam.getConstraint().empty()) { - IConstraint *constraint = - ConstraintFactory::Instance().createInitialized( - this, fitParam.getConstraint()); + IConstraint *constraint = ConstraintFactory::Instance().createInitialized(this, fitParam.getConstraint()); if (!fitParam.getConstraintPenaltyFactor().empty()) { try { - double penalty = - std::stod(fitParam.getConstraintPenaltyFactor()); + double penalty = std::stod(fitParam.getConstraintPenaltyFactor()); constraint->setPenaltyFactor(penalty); } catch (...) { - g_log.warning() - << "Can't set penalty factor for constraint\n"; + g_log.warning() << "Can't set penalty factor for constraint\n"; } } addConstraint(std::unique_ptr(constraint)); @@ -1237,8 +1178,7 @@ void IFunction::setMatrixWorkspace( * @return converted value */ double IFunction::convertValue(double value, Kernel::Unit_sptr &outUnit, - const std::shared_ptr &ws, - size_t wsIndex) const { + const std::shared_ptr &ws, size_t wsIndex) const { // only required if formula or look-up-table different from ws unit const auto &wsUnit = ws->getAxis(0)->unit(); if (outUnit->unitID() == wsUnit->unitID()) @@ -1264,10 +1204,8 @@ double IFunction::convertValue(double value, Kernel::Unit_sptr &outUnit, * @param ws :: workspace * @param wsIndex :: workspace index */ -void IFunction::convertValue(std::vector &values, - Kernel::Unit_sptr &outUnit, - const std::shared_ptr &ws, - size_t wsIndex) const { +void IFunction::convertValue(std::vector &values, Kernel::Unit_sptr &outUnit, + const std::shared_ptr &ws, size_t wsIndex) const { // only required if formula or look-up-table different from ws unit const auto &wsUnit = ws->getAxis(0)->unit(); if (outUnit->unitID() == wsUnit->unitID()) @@ -1284,33 +1222,24 @@ void IFunction::convertValue(std::vector &values, Instrument_const_sptr instrument = ws->getInstrument(); Geometry::IComponent_const_sptr sample = instrument->getSample(); if (sample == nullptr) { - g_log.error() - << "No sample defined instrument. Cannot convert units for function\n" - << "Ignore convertion."; + g_log.error() << "No sample defined instrument. Cannot convert units for function\n" + << "Ignore conversion."; return; } const auto &spectrumInfo = ws->spectrumInfo(); double l1 = spectrumInfo.l1(); // If this is a monitor then l1+l2 = source-detector distance and twoTheta=0 - double l2 = spectrumInfo.l2(wsIndex); - double twoTheta(0.0); - if (!spectrumInfo.isMonitor(wsIndex)) - twoTheta = spectrumInfo.twoTheta(wsIndex); - auto emode = static_cast(ws->getEMode()); - double efixed(0.0); + auto emode = ws->getEMode(); + + Kernel::UnitParametersMap pmap{}; + spectrumInfo.getDetectorValues(*wsUnit, *outUnit, emode, false, wsIndex, pmap); + std::vector emptyVec; try { - std::shared_ptr det( - &spectrumInfo.detector(wsIndex), NoDeleting()); - efixed = ws->getEFixed(det); + wsUnit->toTOF(values, emptyVec, l1, emode, pmap); + outUnit->fromTOF(values, emptyVec, l1, emode, pmap); } catch (std::exception &) { - // assume elastic - efixed = 0.0; - emode = 0; + throw std::runtime_error("Unable to perform unit conversion to " + outUnit->unitID()); } - - std::vector emptyVec; - wsUnit->toTOF(values, emptyVec, l1, l2, twoTheta, emode, efixed, 0.0); - outUnit->fromTOF(values, emptyVec, l1, l2, twoTheta, emode, efixed, 0.0); } } @@ -1320,17 +1249,14 @@ void IFunction::convertValue(std::vector &values, size_t IFunction::nAttributes() const { return m_attrs.size(); } /// Check if attribute named exists -bool IFunction::hasAttribute(const std::string &name) const { - return m_attrs.find(name) != m_attrs.end(); -} +bool IFunction::hasAttribute(const std::string &name) const { return m_attrs.find(name) != m_attrs.end(); } /** * Overload for const char* values. * @param attName :: Attribute name * @param value :: New attribute value to set */ -void IFunction::setAttributeValue(const std::string &attName, - const char *value) { +void IFunction::setAttributeValue(const std::string &attName, const char *value) { std::string str(value); setAttributeValue(attName, str); } @@ -1340,8 +1266,7 @@ void IFunction::setAttributeValue(const std::string &attName, * @param attName :: Attribute name * @param value :: New attribute value to set */ -void IFunction::setAttributeValue(const std::string &attName, - const std::string &value) { +void IFunction::setAttributeValue(const std::string &attName, const std::string &value) { Attribute att = getAttribute(attName); att.setString(value); setAttribute(attName, att); @@ -1379,14 +1304,11 @@ std::string IFunction::attributeName(size_t index) const { * Return a value of attribute attName * @param name :: Returns the named attribute */ -API::IFunction::Attribute -IFunction::getAttribute(const std::string &name) const { +API::IFunction::Attribute IFunction::getAttribute(const std::string &name) const { if (hasAttribute(name)) { return m_attrs.at(name); } else { - throw std::invalid_argument( - "ParamFunctionAttributeHolder::getAttribute - Unknown attribute '" + - name + "'"); + throw std::invalid_argument("ParamFunctionAttributeHolder::getAttribute - Unknown attribute '" + name + "'"); } } @@ -1397,8 +1319,7 @@ IFunction::getAttribute(const std::string &name) const { * @param name :: The name of the attribute * @param value :: The value of the attribute */ -void IFunction::setAttribute(const std::string &name, - const API::IFunction::Attribute &value) { +void IFunction::setAttribute(const std::string &name, const API::IFunction::Attribute &value) { storeAttributeValue(name, value); } @@ -1407,8 +1328,7 @@ void IFunction::setAttribute(const std::string &name, * @param name :: The name of the attribute * @param defaultValue :: A default value */ -void IFunction::declareAttribute( - const std::string &name, const API::IFunction::Attribute &defaultValue) { +void IFunction::declareAttribute(const std::string &name, const API::IFunction::Attribute &defaultValue) { m_attrs.emplace(name, defaultValue); } @@ -1423,14 +1343,11 @@ void IFunction::init() { * @param name :: The name of the attribute * @param value :: The value of the attribute */ -void IFunction::storeAttributeValue(const std::string &name, - const API::IFunction::Attribute &value) { +void IFunction::storeAttributeValue(const std::string &name, const API::IFunction::Attribute &value) { if (hasAttribute(name)) { m_attrs[name] = value; } else { - throw std::invalid_argument( - "ParamFunctionAttributeHolder::setAttribute - Unknown attribute '" + - name + "'"); + throw std::invalid_argument("ParamFunctionAttributeHolder::setAttribute - Unknown attribute '" + name + "'"); } } @@ -1440,8 +1357,7 @@ void IFunction::storeAttributeValue(const std::string &name, * @param name :: The name of the attribute * @param value :: The value of the attribute */ -void IFunction::storeReadOnlyAttribute( - const std::string &name, const API::IFunction::Attribute &value) const { +void IFunction::storeReadOnlyAttribute(const std::string &name, const API::IFunction::Attribute &value) const { const_cast(this)->storeAttributeValue(name, value); } @@ -1454,26 +1370,21 @@ void IFunction::storeReadOnlyAttribute( * this function. * @param covar :: A matrix to set. */ -void IFunction::setCovarianceMatrix( - const std::shared_ptr> &covar) { +void IFunction::setCovarianceMatrix(const std::shared_ptr> &covar) { // the matrix shouldn't be empty if (!covar) { - throw std::invalid_argument( - "IFunction: Cannot set an empty covariance matrix"); + throw std::invalid_argument("IFunction: Cannot set an empty covariance matrix"); } // the matrix should relate to this function if (covar->numRows() != nParams() || covar->numCols() != nParams()) { - throw std::invalid_argument( - "IFunction: Covariance matrix has a wrong size"); + throw std::invalid_argument("IFunction: Covariance matrix has a wrong size"); } m_covar = covar; } /// Get number of values for a given domain. /// @param domain :: A domain. -size_t IFunction::getValuesSize(const FunctionDomain &domain) const { - return domain.size(); -} +size_t IFunction::getValuesSize(const FunctionDomain &domain) const { return domain.size(); } /// Fix a parameter /// @param name :: A name of a parameter to fix @@ -1543,8 +1454,7 @@ size_t IFunction::getNumberDomains() const { return 1; } /// created functions on their domains must be the same as if this function /// was evaluated on the composition of those domains. std::vector IFunction::createEquivalentFunctions() const { - return std::vector( - 1, FunctionFactory::Instance().createInitialized(asString())); + return std::vector(1, FunctionFactory::Instance().createInitialized(asString())); } /// Put all ties in order in which they will be applied correctly. @@ -1564,8 +1474,7 @@ void IFunction::sortTies() { newNode.right.emplace_back(this->getParameterIndex(p)); } if (newNode < newNode) { - throw std::runtime_error("Parameter is tied to itself: " + - tie->asString(this)); + throw std::runtime_error("Parameter is tied to itself: " + tie->asString(this)); } bool before(false), after(false); size_t indexBefore(0), indexAfter(0); @@ -1581,8 +1490,7 @@ void IFunction::sortTies() { } if (before) { if (after) { - std::string message = - "Circular dependency in ties:\n" + tie->asString(this) + '\n'; + std::string message = "Circular dependency in ties:\n" + tie->asString(this) + '\n'; message += getTie(indexBefore)->asString(this); if (indexAfter != indexBefore) { message += '\n' + getTie(indexAfter)->asString(this); @@ -1609,33 +1517,25 @@ namespace Kernel { template <> MANTID_API_DLL std::shared_ptr -IPropertyManager::getValue>( - const std::string &name) const { - auto *prop = dynamic_cast< - PropertyWithValue> *>( - getPointerToProperty(name)); +IPropertyManager::getValue>(const std::string &name) const { + auto *prop = dynamic_cast> *>(getPointerToProperty(name)); if (prop) { return *prop; } else { - std::string message = "Attempt to assign property " + name + - " to incorrect type. Expected shared_ptr."; + std::string message = "Attempt to assign property " + name + " to incorrect type. Expected shared_ptr."; throw std::runtime_error(message); } } template <> MANTID_API_DLL std::shared_ptr -IPropertyManager::getValue>( - const std::string &name) const { - auto *prop = dynamic_cast< - PropertyWithValue> *>( - getPointerToProperty(name)); +IPropertyManager::getValue>(const std::string &name) const { + auto *prop = dynamic_cast> *>(getPointerToProperty(name)); if (prop) { return prop->operator()(); } else { std::string message = - "Attempt to assign property " + name + - " to incorrect type. Expected const shared_ptr."; + "Attempt to assign property " + name + " to incorrect type. Expected const shared_ptr."; throw std::runtime_error(message); } } diff --git a/Framework/API/src/IFunction1D.cpp b/Framework/API/src/IFunction1D.cpp index 27e686585cf5c01158da96eb2ae7bf51d1cb7f47..451f4a1d05eec66815d18e5cf177f16e66ffb1cd 100644 --- a/Framework/API/src/IFunction1D.cpp +++ b/Framework/API/src/IFunction1D.cpp @@ -36,28 +36,24 @@ using namespace Geometry; /// init logger Kernel::Logger IFunction1D::g_log("IFunction1D"); -void IFunction1D::function(const FunctionDomain &domain, - FunctionValues &values) const { +void IFunction1D::function(const FunctionDomain &domain, FunctionValues &values) const { auto histoDomain = dynamic_cast(&domain); if (histoDomain) { - histogram1D(values.getPointerToCalculated(0), histoDomain->leftBoundary(), - histoDomain->getPointerAt(0), histoDomain->size()); + histogram1D(values.getPointerToCalculated(0), histoDomain->leftBoundary(), histoDomain->getPointerAt(0), + histoDomain->size()); return; } const auto *d1d = dynamic_cast(&domain); if (!d1d) { throw std::invalid_argument("Unexpected domain in IFunction1D"); } - function1D(values.getPointerToCalculated(0), d1d->getPointerAt(0), - d1d->size()); + function1D(values.getPointerToCalculated(0), d1d->getPointerAt(0), d1d->size()); } -void IFunction1D::functionDeriv(const FunctionDomain &domain, - Jacobian &jacobian) { +void IFunction1D::functionDeriv(const FunctionDomain &domain, Jacobian &jacobian) { auto histoDomain = dynamic_cast(&domain); if (histoDomain) { - histogramDerivative1D(&jacobian, histoDomain->leftBoundary(), - histoDomain->getPointerAt(0), histoDomain->size()); + histogramDerivative1D(&jacobian, histoDomain->leftBoundary(), histoDomain->getPointerAt(0), histoDomain->size()); return; } const auto *d1d = dynamic_cast(&domain); @@ -67,35 +63,28 @@ void IFunction1D::functionDeriv(const FunctionDomain &domain, functionDeriv1D(&jacobian, d1d->getPointerAt(0), d1d->size()); } -void IFunction1D::derivative(const FunctionDomain &domain, - FunctionValues &values, const size_t order) const { +void IFunction1D::derivative(const FunctionDomain &domain, FunctionValues &values, const size_t order) const { const auto *d1d = dynamic_cast(&domain); if (!d1d) { throw std::invalid_argument("Unexpected domain in IFunction1D"); } - derivative1D(values.getPointerToCalculated(0), d1d->getPointerAt(0), - d1d->size(), order); + derivative1D(values.getPointerToCalculated(0), d1d->getPointerAt(0), d1d->size(), order); } -void IFunction1D::derivative1D(double *out, const double *xValues, size_t nData, - const size_t order) const { +void IFunction1D::derivative1D(double *out, const double *xValues, size_t nData, const size_t order) const { UNUSED_ARG(out); UNUSED_ARG(xValues); UNUSED_ARG(nData); UNUSED_ARG(order); - throw Kernel::Exception::NotImplementedError( - "Derivative is not implemented for this function."); + throw Kernel::Exception::NotImplementedError("Derivative is not implemented for this function."); } -void IFunction1D::functionDeriv1D(Jacobian *jacobian, const double *xValues, - const size_t nData) { - auto evalMethod = [this](double *out, const double *xValues, - const size_t nData) { +void IFunction1D::functionDeriv1D(Jacobian *jacobian, const double *xValues, const size_t nData) { + auto evalMethod = [this](double *out, const double *xValues, const size_t nData) { this->function1D(out, xValues, nData); }; - this->calcNumericalDerivative1D(jacobian, std::move(evalMethod), xValues, - nData); + this->calcNumericalDerivative1D(jacobian, std::move(evalMethod), xValues, nData); } /// Calculate histogram data for the given bin boundaries. @@ -105,14 +94,12 @@ void IFunction1D::functionDeriv1D(Jacobian *jacobian, const double *xValues, /// @param right :: A pointer to an array of successive right bin boundaries /// (size = nBins). /// @param nBins :: Number of bins. -void IFunction1D::histogram1D(double *out, double left, const double *right, - const size_t nBins) const { +void IFunction1D::histogram1D(double *out, double left, const double *right, const size_t nBins) const { UNUSED_ARG(out); UNUSED_ARG(left); UNUSED_ARG(right); UNUSED_ARG(nBins); - throw Kernel::Exception::NotImplementedError( - "Integration is not implemented for this function."); + throw Kernel::Exception::NotImplementedError("Integration is not implemented for this function."); } /// Derivatives of the histogram. @@ -121,15 +108,13 @@ void IFunction1D::histogram1D(double *out, double left, const double *right, /// @param right :: A pointer to an array of successive right bin boundaries /// (size = nBins). /// @param nBins :: Number of bins. -void IFunction1D::histogramDerivative1D(Jacobian *jacobian, double left, - const double *right, +void IFunction1D::histogramDerivative1D(Jacobian *jacobian, double left, const double *right, const size_t nBins) const { UNUSED_ARG(jacobian); UNUSED_ARG(left); UNUSED_ARG(right); UNUSED_ARG(nBins); - throw Kernel::Exception::NotImplementedError( - "Integration is not implemented for this function."); + throw Kernel::Exception::NotImplementedError("Integration is not implemented for this function."); } } // namespace API diff --git a/Framework/API/src/IFunction1DSpectrum.cpp b/Framework/API/src/IFunction1DSpectrum.cpp index 086796ccb985132553e3adc17a9a37e677b99ca8..b25bc9b2a01a6bce21f5c4bb9cd54e41f16ac826 100644 --- a/Framework/API/src/IFunction1DSpectrum.cpp +++ b/Framework/API/src/IFunction1DSpectrum.cpp @@ -11,32 +11,25 @@ namespace API { Kernel::Logger IFunction1DSpectrum::g_log("IFunction1DSpectrum"); -void IFunction1DSpectrum::function(const FunctionDomain &domain, - FunctionValues &values) const { +void IFunction1DSpectrum::function(const FunctionDomain &domain, FunctionValues &values) const { try { - const auto &spectrumDomain = - dynamic_cast(domain); + const auto &spectrumDomain = dynamic_cast(domain); function1DSpectrum(spectrumDomain, values); } catch (const std::bad_cast &) { - throw std::invalid_argument( - "Provided domain is not of type FunctionDomain1DSpectrum."); + throw std::invalid_argument("Provided domain is not of type FunctionDomain1DSpectrum."); } } -void IFunction1DSpectrum::functionDeriv(const FunctionDomain &domain, - Jacobian &jacobian) { +void IFunction1DSpectrum::functionDeriv(const FunctionDomain &domain, Jacobian &jacobian) { try { - const auto &spectrumDomain = - dynamic_cast(domain); + const auto &spectrumDomain = dynamic_cast(domain); functionDeriv1DSpectrum(spectrumDomain, jacobian); } catch (const std::bad_cast &) { - throw std::invalid_argument( - "Provided domain is not of type FunctionDomain1DSpectrum."); + throw std::invalid_argument("Provided domain is not of type FunctionDomain1DSpectrum."); } } -void IFunction1DSpectrum::functionDeriv1DSpectrum( - const FunctionDomain1DSpectrum &domain, Jacobian &jacobian) { +void IFunction1DSpectrum::functionDeriv1DSpectrum(const FunctionDomain1DSpectrum &domain, Jacobian &jacobian) { calNumericalDeriv(domain, jacobian); } diff --git a/Framework/API/src/IFunctionGeneral.cpp b/Framework/API/src/IFunctionGeneral.cpp index 6920051433f90bb048c55650ce22473cf757037b..60c525b12ba0027402fb8b236514abad2243e590 100644 --- a/Framework/API/src/IFunctionGeneral.cpp +++ b/Framework/API/src/IFunctionGeneral.cpp @@ -11,26 +11,21 @@ namespace API { Kernel::Logger IFunctionGeneral::g_log("IFunctionGeneral"); -void IFunctionGeneral::function(const FunctionDomain &domain, - FunctionValues &values) const { +void IFunctionGeneral::function(const FunctionDomain &domain, FunctionValues &values) const { auto actualValuesSize = values.size(); auto requiredValuesSize = getValuesSize(domain); - if (actualValuesSize > 0 && requiredValuesSize > 0 && - actualValuesSize != requiredValuesSize) { - throw std::runtime_error( - "IFunctionGeneral: values object doesn't match domain."); + if (actualValuesSize > 0 && requiredValuesSize > 0 && actualValuesSize != requiredValuesSize) { + throw std::runtime_error("IFunctionGeneral: values object doesn't match domain."); } try { auto &generalDomain = dynamic_cast(domain); functionGeneral(generalDomain, values); } catch (const std::bad_cast &) { - throw std::invalid_argument( - "Provided domain is not of type FunctionDomainGeneral."); + throw std::invalid_argument("Provided domain is not of type FunctionDomainGeneral."); } } -void IFunctionGeneral::functionDeriv(const FunctionDomain &domain, - Jacobian &jacobian) { +void IFunctionGeneral::functionDeriv(const FunctionDomain &domain, Jacobian &jacobian) { calNumericalDeriv(domain, jacobian); } diff --git a/Framework/API/src/IFunctionMD.cpp b/Framework/API/src/IFunctionMD.cpp index 385df66585e02da26d23fd6a366f6df5bba389fc..e103231c1a4fe32acccfd963ad6f4d5c756dea9b 100644 --- a/Framework/API/src/IFunctionMD.cpp +++ b/Framework/API/src/IFunctionMD.cpp @@ -40,11 +40,9 @@ std::shared_ptr IFunctionMD::clone() const { */ void IFunctionMD::setWorkspace(std::shared_ptr ws) { try { - IMDWorkspace_const_sptr workspace = - std::dynamic_pointer_cast(ws); + IMDWorkspace_const_sptr workspace = std::dynamic_pointer_cast(ws); if (!workspace) { - throw std::invalid_argument( - "Workspace has a wrong type (not a IMDWorkspace)"); + throw std::invalid_argument("Workspace has a wrong type (not a IMDWorkspace)"); } if (m_dimensionIndexMap.empty()) { @@ -52,17 +50,12 @@ void IFunctionMD::setWorkspace(std::shared_ptr ws) { } m_dimensions.resize(m_dimensionIndexMap.size()); - std::map::const_iterator it = - m_dimensionIndexMap.begin(); - std::map::const_iterator end = - m_dimensionIndexMap.end(); + std::map::const_iterator it = m_dimensionIndexMap.begin(); + std::map::const_iterator end = m_dimensionIndexMap.end(); for (; it != end; ++it) { - std::shared_ptr dim = - workspace->getDimensionWithId(it->first); + std::shared_ptr dim = workspace->getDimensionWithId(it->first); if (!dim) { - throw std::invalid_argument("Dimension " + it->first + - " dos not exist in workspace " + - ws->getName()); + throw std::invalid_argument("Dimension " + it->first + " dos not exist in workspace " + ws->getName()); } m_dimensions[it->second] = dim; } @@ -76,8 +69,7 @@ void IFunctionMD::setWorkspace(std::shared_ptr ws) { * @param domain :: The input domain over which to calculate the function * @param values :: A result holder to store the output of the calculation */ -void IFunctionMD::function(const FunctionDomain &domain, - FunctionValues &values) const { +void IFunctionMD::function(const FunctionDomain &domain, FunctionValues &values) const { const auto *dmd = dynamic_cast(&domain); if (!dmd) { throw std::invalid_argument("Unexpected domain in IFunctionMD"); @@ -91,14 +83,11 @@ void IFunctionMD::function(const FunctionDomain &domain, * @param domain :: The MD domain to evaluate the function * @param values :: The computed values */ -void IFunctionMD::evaluateFunction(const FunctionDomainMD &domain, - FunctionValues &values) const { +void IFunctionMD::evaluateFunction(const FunctionDomainMD &domain, FunctionValues &values) const { domain.reset(); size_t i = 0; - for (const IMDIterator *r = domain.getNextIterator(); r != nullptr; - r = domain.getNextIterator()) { - this->reportProgress("Evaluating function for box " + - std::to_string(i + 1)); + for (const IMDIterator *r = domain.getNextIterator(); r != nullptr; r = domain.getNextIterator()) { + this->reportProgress("Evaluating function for box " + std::to_string(i + 1)); values.setCalculated(i, functionMD(*r)); i++; }; diff --git a/Framework/API/src/IFunctionMW.cpp b/Framework/API/src/IFunctionMW.cpp index 7053a51b94b80d6aa0a234095d95d92cbd2de294..8e7f4e2d83f8f46ee0c0374e32a97ff4dc5acb55 100644 --- a/Framework/API/src/IFunctionMW.cpp +++ b/Framework/API/src/IFunctionMW.cpp @@ -20,9 +20,8 @@ using namespace Geometry; * @param startX :: The lower bin index * @param endX :: The upper bin index */ -void IFunctionMW::setMatrixWorkspace( - std::shared_ptr workspace, size_t wi, - double startX, double endX) { +void IFunctionMW::setMatrixWorkspace(std::shared_ptr workspace, size_t wi, double startX, + double endX) { m_workspace = workspace; m_workspaceIndex = wi; @@ -32,10 +31,7 @@ void IFunctionMW::setMatrixWorkspace( /** * Get a shared pointer to the saved matrix workspace. */ -std::shared_ptr -IFunctionMW::getMatrixWorkspace() const { - return m_workspace.lock(); -} +std::shared_ptr IFunctionMW::getMatrixWorkspace() const { return m_workspace.lock(); } } // namespace API } // namespace Mantid diff --git a/Framework/API/src/ILatticeFunction.cpp b/Framework/API/src/ILatticeFunction.cpp index 19fcd97cee4ac1fb798a37d4305e7a485b08760a..bf3800f4d6770404e36346d1f5df7db5e47f5319 100644 --- a/Framework/API/src/ILatticeFunction.cpp +++ b/Framework/API/src/ILatticeFunction.cpp @@ -22,15 +22,13 @@ ILatticeFunction::ILatticeFunction() : FunctionParameterDecorator() {} * @param domain :: A FunctionDomain of type LatticeDomain * @param values :: Function values. */ -void ILatticeFunction::function(const FunctionDomain &domain, - FunctionValues &values) const { +void ILatticeFunction::function(const FunctionDomain &domain, FunctionValues &values) const { try { const auto &latticeDomain = dynamic_cast(domain); functionLattice(latticeDomain, values); } catch (const std::bad_cast &) { - throw std::invalid_argument( - "ILatticeFunction expects domain of type LatticeDomain."); + throw std::invalid_argument("ILatticeFunction expects domain of type LatticeDomain."); } } @@ -44,28 +42,24 @@ void ILatticeFunction::function(const FunctionDomain &domain, * @param domain :: A FunctionDomain of type LatticeDomain * @param jacobian :: Jacobian matrix */ -void ILatticeFunction::functionDeriv(const FunctionDomain &domain, - Jacobian &jacobian) { +void ILatticeFunction::functionDeriv(const FunctionDomain &domain, Jacobian &jacobian) { try { const auto &latticeDomain = dynamic_cast(domain); functionDerivLattice(latticeDomain, jacobian); } catch (const std::bad_cast &) { - throw std::invalid_argument( - "ILatticeFunction expects domain of type LatticeDomain."); + throw std::invalid_argument("ILatticeFunction expects domain of type LatticeDomain."); } catch (const Kernel::Exception::NotImplementedError &) { calNumericalDeriv(domain, jacobian); } } /// Default implementation, throws NotImplementedError. -void ILatticeFunction::functionDerivLattice(const LatticeDomain &latticeDomain, - Jacobian &jacobian) { +void ILatticeFunction::functionDerivLattice(const LatticeDomain &latticeDomain, Jacobian &jacobian) { UNUSED_ARG(latticeDomain); UNUSED_ARG(jacobian); - throw Kernel::Exception::NotImplementedError( - "FunctionLatticeDeriv is not implemented for this function."); + throw Kernel::Exception::NotImplementedError("FunctionLatticeDeriv is not implemented for this function."); } } // namespace API diff --git a/Framework/API/src/IMDEventWorkspace.cpp b/Framework/API/src/IMDEventWorkspace.cpp index 8b553feb4bda25b69206d7c2e9c3501fc2f3e3dc..24a9ef7988eb98302d01bd7c0ae94d9e5b52084d 100644 --- a/Framework/API/src/IMDEventWorkspace.cpp +++ b/Framework/API/src/IMDEventWorkspace.cpp @@ -18,25 +18,20 @@ namespace API { //----------------------------------------------------------------------------------------------- /** Empty constructor */ -IMDEventWorkspace::IMDEventWorkspace() - : IMDWorkspace(), MultipleExperimentInfos(), m_fileNeedsUpdating(false) {} +IMDEventWorkspace::IMDEventWorkspace() : IMDWorkspace(), MultipleExperimentInfos(), m_fileNeedsUpdating(false) {} //----------------------------------------------------------------------------------------------- /** @return the marker set to true when a file-backed workspace needs its * back-end file updated (by calling SaveMD(UpdateFileBackEnd=1) ) */ -bool IMDEventWorkspace::fileNeedsUpdating() const { - return m_fileNeedsUpdating; -} +bool IMDEventWorkspace::fileNeedsUpdating() const { return m_fileNeedsUpdating; } //----------------------------------------------------------------------------------------------- /** Sets the marker set to true when a file-backed workspace needs its back-end * file updated (by calling SaveMD(UpdateFileBackEnd=1) ) * @param value :: marker value */ -void IMDEventWorkspace::setFileNeedsUpdating(bool value) { - m_fileNeedsUpdating = value; -} +void IMDEventWorkspace::setFileNeedsUpdating(bool value) { m_fileNeedsUpdating = value; } //----------------------------------------------------------------------------------------------- /** Is the workspace thread-safe. For MDEventWorkspaces, this means operations @@ -75,17 +70,13 @@ namespace Kernel { * for the PropertyWithValue is required */ template <> MANTID_API_DLL Mantid::API::IMDEventWorkspace_sptr -IPropertyManager::getValue( - const std::string &name) const { - auto *prop = - dynamic_cast *>( - getPointerToProperty(name)); +IPropertyManager::getValue(const std::string &name) const { + auto *prop = dynamic_cast *>(getPointerToProperty(name)); if (prop) { return *prop; } else { std::string message = - "Attempt to assign property " + name + - " to incorrect type. Expected shared_ptr."; + "Attempt to assign property " + name + " to incorrect type. Expected shared_ptr."; throw std::runtime_error(message); } } @@ -94,11 +85,8 @@ IPropertyManager::getValue( * for the PropertyWithValue is required */ template <> MANTID_API_DLL Mantid::API::IMDEventWorkspace_const_sptr -IPropertyManager::getValue( - const std::string &name) const { - auto *prop = dynamic_cast< - PropertyWithValue *>( - getPointerToProperty(name)); +IPropertyManager::getValue(const std::string &name) const { + auto *prop = dynamic_cast *>(getPointerToProperty(name)); if (prop) { return prop->operator()(); } else { @@ -106,14 +94,12 @@ IPropertyManager::getValue( // property as a shared_ptr. This class should be consistent, so // try that: auto *nonConstProp = - dynamic_cast *>( - getPointerToProperty(name)); + dynamic_cast *>(getPointerToProperty(name)); if (nonConstProp) { return nonConstProp->operator()(); } else { std::string message = - "Attempt to assign property " + name + - " to incorrect type. Expected const shared_ptr."; + "Attempt to assign property " + name + " to incorrect type. Expected const shared_ptr."; throw std::runtime_error(message); } } diff --git a/Framework/API/src/IMDHistoWorkspace.cpp b/Framework/API/src/IMDHistoWorkspace.cpp index d683d7eac2a8dc34c5611f837bdb58455b66a8af..cd3a6373eb39d1b2da82b838525bb1df31f3ad56 100644 --- a/Framework/API/src/IMDHistoWorkspace.cpp +++ b/Framework/API/src/IMDHistoWorkspace.cpp @@ -38,17 +38,13 @@ namespace Kernel { * for the PropertyWithValue is required */ template <> MANTID_API_DLL Mantid::API::IMDHistoWorkspace_sptr -IPropertyManager::getValue( - const std::string &name) const { - auto *prop = - dynamic_cast *>( - getPointerToProperty(name)); +IPropertyManager::getValue(const std::string &name) const { + auto *prop = dynamic_cast *>(getPointerToProperty(name)); if (prop) { return *prop; } else { std::string message = - "Attempt to assign property " + name + - " to incorrect type. Expected shared_ptr."; + "Attempt to assign property " + name + " to incorrect type. Expected shared_ptr."; throw std::runtime_error(message); } } @@ -57,17 +53,13 @@ IPropertyManager::getValue( * for the PropertyWithValue is required */ template <> MANTID_API_DLL Mantid::API::IMDHistoWorkspace_const_sptr -IPropertyManager::getValue( - const std::string &name) const { - auto *prop = - dynamic_cast *>( - getPointerToProperty(name)); +IPropertyManager::getValue(const std::string &name) const { + auto *prop = dynamic_cast *>(getPointerToProperty(name)); if (prop) { return prop->operator()(); } else { std::string message = - "Attempt to assign property " + name + - " to incorrect type. Expected const shared_ptr."; + "Attempt to assign property " + name + " to incorrect type. Expected const shared_ptr."; throw std::runtime_error(message); } } diff --git a/Framework/API/src/IMDIterator.cpp b/Framework/API/src/IMDIterator.cpp index 870c410e7a2147741b5fdafdedb264a79c3b1e9d..9d6239651fa11ede0098609a854496010c808075 100644 --- a/Framework/API/src/IMDIterator.cpp +++ b/Framework/API/src/IMDIterator.cpp @@ -13,22 +13,17 @@ namespace Mantid { namespace API { /** Default constructor */ -IMDIterator::IMDIterator() - : m_normalization(Mantid::API::VolumeNormalization) {} +IMDIterator::IMDIterator() : m_normalization(Mantid::API::VolumeNormalization) {} /** Set how the signal will be normalized when calling getNormalizedSignal() * * @param normalization :: method to use */ -void IMDIterator::setNormalization(Mantid::API::MDNormalization normalization) { - m_normalization = normalization; -} +void IMDIterator::setNormalization(Mantid::API::MDNormalization normalization) { m_normalization = normalization; } /** @return how the signal will be normalized when calling getNormalizedSignal() */ -Mantid::API::MDNormalization IMDIterator::getNormalization() const { - return m_normalization; -} +Mantid::API::MDNormalization IMDIterator::getNormalization() const { return m_normalization; } } // namespace API } // namespace Mantid diff --git a/Framework/API/src/IMDWorkspace.cpp b/Framework/API/src/IMDWorkspace.cpp index 4e84206a2f8bab302f14d857b61751c1cfc0a740..b06da7b821224cdc9670322e0aad7e3f3ddccaf7 100644 --- a/Framework/API/src/IMDWorkspace.cpp +++ b/Framework/API/src/IMDWorkspace.cpp @@ -33,10 +33,8 @@ IMDWorkspace::IMDWorkspace(const Parallel::StorageMode storageMode) * @param function :: Implicit function limiting space to look at * @return a single IMDIterator pointer */ -std::unique_ptr IMDWorkspace::createIterator( - Mantid::Geometry::MDImplicitFunction *function) const { - std::vector> iterators = - this->createIterators(1, function); +std::unique_ptr IMDWorkspace::createIterator(Mantid::Geometry::MDImplicitFunction *function) const { + std::vector> iterators = this->createIterators(1, function); if (iterators.empty()) throw std::runtime_error("IMDWorkspace::createIterator(): iterator " "creation was not successful. No iterators " @@ -53,9 +51,7 @@ std::string IMDWorkspace::getConvention() const { return m_convention; } //--------------------------------------------------------------------------------------------- /** @return the convention */ -void IMDWorkspace::setConvention(std::string convention) { - m_convention = std::move(convention); -} +void IMDWorkspace::setConvention(std::string convention) { m_convention = std::move(convention); } //--------------------------------------------------------------------------------------------- /** @return the convention @@ -75,9 +71,8 @@ std::string IMDWorkspace::changeQConvention() { * @param normalization :: how to normalize the signal returned * @return normalized signal */ -signal_t IMDWorkspace::getSignalAtVMD( - const Mantid::Kernel::VMD &coords, - const Mantid::API::MDNormalization &normalization) const { +signal_t IMDWorkspace::getSignalAtVMD(const Mantid::Kernel::VMD &coords, + const Mantid::API::MDNormalization &normalization) const { return this->getSignalAtCoord(coords.getBareArray(), normalization); } @@ -89,9 +84,8 @@ signal_t IMDWorkspace::getSignalAtVMD( * @param normalization :: how to normalize the signal returned * @return normalized signal */ -signal_t IMDWorkspace::getSignalWithMaskAtVMD( - const Mantid::Kernel::VMD &coords, - const Mantid::API::MDNormalization &normalization) const { +signal_t IMDWorkspace::getSignalWithMaskAtVMD(const Mantid::Kernel::VMD &coords, + const Mantid::API::MDNormalization &normalization) const { return this->getSignalWithMaskAtCoord(coords.getBareArray(), normalization); } @@ -103,8 +97,8 @@ const std::string IMDWorkspace::toString() const { << "Title: " + getTitle() << "\n"; for (size_t i = 0; i < getNumDims(); i++) { const auto &dim = getDimension(i); - os << "Dim " << i << ": (" << dim->getName() << ") " << dim->getMinimum() - << " to " << dim->getMaximum() << " in " << dim->getNBins() << " bins"; + os << "Dim " << i << ": (" << dim->getName() << ") " << dim->getMinimum() << " to " << dim->getMaximum() << " in " + << dim->getNBins() << " bins"; // Also show the dimension ID string, if different than name if (dim->getDimensionId() != dim->getName()) os << ". Id=" << dim->getDimensionId(); @@ -131,8 +125,7 @@ const std::string IMDWorkspace::toString() const { * @param y :: signal value * @param e :: error value */ -void IMDWorkspace::makeSinglePointWithNaN(std::vector &x, - std::vector &y, +void IMDWorkspace::makeSinglePointWithNaN(std::vector &x, std::vector &y, std::vector &e) const { x.emplace_back(0.f); y.emplace_back(std::numeric_limits::quiet_NaN()); @@ -153,10 +146,8 @@ void IMDWorkspace::makeSinglePointWithNaN(std::vector &x, * each bin with Length = length(x) - 1 and e is set to the normalized * errors for each bin with Length = length(x) - 1. */ -IMDWorkspace::LinePlot -IMDWorkspace::getLinePlot(const Mantid::Kernel::VMD &start, - const Mantid::Kernel::VMD &end, - Mantid::API::MDNormalization normalize) const { +IMDWorkspace::LinePlot IMDWorkspace::getLinePlot(const Mantid::Kernel::VMD &start, const Mantid::Kernel::VMD &end, + Mantid::API::MDNormalization normalize) const { // TODO: Don't use a fixed number of points later size_t numPoints = 200; @@ -184,17 +175,13 @@ IMDWorkspace::getLinePlot(const Mantid::Kernel::VMD &start, @return normalization preferred for visualization. Set to none for the generic case, but overriden elsewhere. */ -MDNormalization IMDWorkspace::displayNormalization() const { - return NoNormalization; -} +MDNormalization IMDWorkspace::displayNormalization() const { return NoNormalization; } /** @return normalization preferred for visualization of histo workspaces. Set to none for the generic case, but overriden elsewhere. */ -MDNormalization IMDWorkspace::displayNormalizationHisto() const { - return NoNormalization; -} +MDNormalization IMDWorkspace::displayNormalizationHisto() const { return NoNormalization; } } // namespace API } // namespace Mantid @@ -204,17 +191,13 @@ namespace Kernel { * for the PropertyWithValue is required */ template <> MANTID_API_DLL Mantid::API::IMDWorkspace_sptr -IPropertyManager::getValue( - const std::string &name) const { - auto *prop = - dynamic_cast *>( - getPointerToProperty(name)); +IPropertyManager::getValue(const std::string &name) const { + auto *prop = dynamic_cast *>(getPointerToProperty(name)); if (prop) { return *prop; } else { std::string message = - "Attempt to assign property " + name + - " to incorrect type. Expected shared_ptr."; + "Attempt to assign property " + name + " to incorrect type. Expected shared_ptr."; throw std::runtime_error(message); } } @@ -223,17 +206,13 @@ IPropertyManager::getValue( * for the PropertyWithValue is required */ template <> MANTID_API_DLL Mantid::API::IMDWorkspace_const_sptr -IPropertyManager::getValue( - const std::string &name) const { - auto *prop = - dynamic_cast *>( - getPointerToProperty(name)); +IPropertyManager::getValue(const std::string &name) const { + auto *prop = dynamic_cast *>(getPointerToProperty(name)); if (prop) { return prop->operator()(); } else { std::string message = - "Attempt to assign property " + name + - " to incorrect type. Expected const shared_ptr."; + "Attempt to assign property " + name + " to incorrect type. Expected const shared_ptr."; throw std::runtime_error(message); } } diff --git a/Framework/API/src/IPeakFunction.cpp b/Framework/API/src/IPeakFunction.cpp index 07c51beb4f96d1d36c6bffc88057b285aa9f42c4..3b03d4d677d36af2dd5b004c859922d8bc095311 100644 --- a/Framework/API/src/IPeakFunction.cpp +++ b/Framework/API/src/IPeakFunction.cpp @@ -14,6 +14,7 @@ #include "MantidAPI/Jacobian.h" #include "MantidAPI/PeakFunctionIntegrator.h" #include "MantidKernel/Exception.h" +#include "boost/make_shared.hpp" #include #include @@ -41,9 +42,7 @@ public: * @param iP :: The parameter index of an individual function. * @param value :: The derivative value */ - void set(size_t iY, size_t iP, double value) override { - m_J->set(m_iY0 + iY, iP, value); - } + void set(size_t iY, size_t iP, double value) override { m_J->set(m_iY0 + iY, iP, value); } /** * Overridden Jacobian::get(...). * @param iY :: The index of the data point @@ -53,37 +52,8 @@ public: /** Zero all matrix elements. */ void zero() override { - throw Kernel::Exception::NotImplementedError( - "zero() is not implemented for PartialJacobian1"); - } -}; - -class TempJacobian : public Jacobian { -public: - TempJacobian(size_t y, size_t p) : m_y(y), m_p(p), m_J(y * p) {} - void set(size_t iY, size_t iP, double value) override { - m_J[iY * m_p + iP] = value; + throw Kernel::Exception::NotImplementedError("zero() is not implemented for PartialJacobian1"); } - double get(size_t iY, size_t iP) override { return m_J[iY * m_p + iP]; } - size_t maxParam(size_t iY) { - double max = -DBL_MAX; - size_t maxIndex = 0; - for (size_t i = 0; i < m_p; ++i) { - double current = get(iY, i); - if (current > max) { - maxIndex = i; - max = current; - } - } - - return maxIndex; - } - void zero() override { m_J.assign(m_J.size(), 0.0); } - -protected: - size_t m_y; - size_t m_p; - std::vector m_J; }; /// Tolerance for determining the smallest significant value on the peak @@ -98,10 +68,8 @@ const int MAX_PEAK_RADIUS = std::numeric_limits::max(); */ IPeakFunction::IPeakFunction() : m_peakRadius(MAX_PEAK_RADIUS) {} -void IPeakFunction::function(const FunctionDomain &domain, - FunctionValues &values) const { - auto peakRadius = - dynamic_cast(domain).getPeakRadius(); +void IPeakFunction::function(const FunctionDomain &domain, FunctionValues &values) const { + auto peakRadius = dynamic_cast(domain).getPeakRadius(); setPeakRadius(peakRadius); IFunction1D::function(domain, values); } @@ -116,8 +84,7 @@ void IPeakFunction::function(const FunctionDomain &domain, * @param xValues :: X values for data points * @param nData :: Number of data points */ -void IPeakFunction::function1D(double *out, const double *xValues, - const size_t nData) const { +void IPeakFunction::function1D(double *out, const double *xValues, const size_t nData) const { double c = this->centre(); double dx = fabs(m_peakRadius * this->fwhm()); int i0 = -1; @@ -147,8 +114,7 @@ void IPeakFunction::function1D(double *out, const double *xValues, * @param xValues :: X values for data points * @param nData :: Number of data points */ -void IPeakFunction::functionDeriv1D(Jacobian *out, const double *xValues, - const size_t nData) { +void IPeakFunction::functionDeriv1D(Jacobian *out, const double *xValues, const size_t nData) { double c = this->centre(); double dx = fabs(m_peakRadius * this->fwhm()); int i0 = -1; @@ -178,20 +144,45 @@ void IPeakFunction::setPeakRadius(int r) const { } } -/// Returns the integral intensity of the peak function, using the peak radius -/// to determine integration borders. -double IPeakFunction::intensity() const { - auto interval = getDomainInterval(); +void IPeakFunction::setParameter(size_t i, const double &value, bool explicitlySet) { + m_parameterContextDirty = true; + ParamFunction::setParameter(i, value, explicitlySet); +} - PeakFunctionIntegrator integrator; - IntegrationResult result = - integrator.integrate(*this, interval.first, interval.second); +void IPeakFunction::setParameter(const std::string &name, const double &value, bool explicitlySet) { + m_parameterContextDirty = true; + ParamFunction::setParameter(name, value, explicitlySet); +} - if (!result.success) { - return 0.0; +/* + * @brief Integrate based on dirty parameters then cache the result + * @details Returns the integrated intensity of the peak function, using the peak radius + * to determine integration borders. + */ +IntegrationResultCache IPeakFunction::integrate() const { + if (!integrationResult || m_parameterContextDirty) { + auto const interval = getDomainInterval(); + + PeakFunctionIntegrator integrator; + + auto const result = integrator.integrate(*this, interval.first, interval.second); + if (result.success) + integrationResult = boost::make_shared(result.result, result.error); + else + integrationResult = boost::make_shared(std::nan(""), std