diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5d5c14d896..9031ee177e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,6 +11,7 @@ jobs: fail-fast: false matrix: env: [environment_a, environment_b, conda-forge] + steps: - uses: actions/checkout@v4 - uses: actions/cache@v4 @@ -18,6 +19,7 @@ jobs: with: path: /usr/share/miniconda/envs/im${{ matrix.env }} key: ${{ format('{0}-conda-improver-{1}-{2}', runner.os, matrix.env, hashFiles(format('envs/{0}.yml', matrix.env))) }} + - name: conda env update if: steps.cache.outputs.cache-hit != 'true' run: | @@ -26,29 +28,34 @@ jobs: conda install -q -n base -c conda-forge -c nodefaults mamba rm -f /usr/share/miniconda/pkgs/cache/*.json # workaround for mamba-org/mamba#488 mamba env create -q --file envs/${{ matrix.env }}.yml --name im${{ matrix.env }} + - name: conda info run: | source '/usr/share/miniconda/etc/profile.d/conda.sh' conda activate im${{ matrix.env }} conda info conda list + - name: sphinx documentation run: | source '/usr/share/miniconda/etc/profile.d/conda.sh' conda activate im${{ matrix.env }} make -C doc html SPHINXOPTS="-W --keep-going" + - name: pytest without coverage if: matrix.env == 'conda-forge' run: | source '/usr/share/miniconda/etc/profile.d/conda.sh' conda activate im${{ matrix.env }} pytest + - name: pytest with coverage if: matrix.env != 'conda-forge' run: | source '/usr/share/miniconda/etc/profile.d/conda.sh' conda activate im${{ matrix.env }} pytest --cov=improver --cov-report xml:coverage.xml + - name: codacy upload if: env.CODACY_PROJECT_TOKEN && matrix.env == 'environment_a' run: | @@ -57,63 +64,65 @@ jobs: python-codacy-coverage -v -r coverage.xml env: CODACY_PROJECT_TOKEN: ${{ secrets.CODACY_PROJECT_TOKEN }} + - name: codecov upload uses: codecov/codecov-action@v4 with: name: ${{ matrix.env }} if: matrix.env != 'conda_forge' - Codestyle-and-flake8: + + pre-commit-checks: runs-on: ubuntu-22.04 strategy: fail-fast: false - matrix: - env: [environment_a] steps: - - uses: actions/checkout@v4 - - uses: actions/cache@v4 - id: cache + + - name: improver checkout + uses: actions/checkout@v4 with: - path: /usr/share/miniconda/envs/im${{ matrix.env }} - key: ${{ format('{0}-conda-improver-{1}-{2}', runner.os, matrix.env, hashFiles(format('envs/{0}.yml', matrix.env))) }} - - name: conda env update - if: steps.cache.outputs.cache-hit != 'true' - run: | - source '/usr/share/miniconda/etc/profile.d/conda.sh' - conda update -q -n base -c defaults conda - conda install -q -n base -c conda-forge -c nodefaults mamba - rm -f /usr/share/miniconda/pkgs/cache/*.json # workaround for mamba-org/mamba#488 - mamba env create -q --file envs/${{ matrix.env }}.yml --name im${{ matrix.env }} - - name: conda info - run: | - source '/usr/share/miniconda/etc/profile.d/conda.sh' - conda activate im${{ matrix.env }} - conda info - conda list - - name: isort + fetch-depth: 0 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: 3.7 + cache: 'pip' + + - name: pip install pre-commit run: | - source '/usr/share/miniconda/etc/profile.d/conda.sh' - conda activate im${{ matrix.env }} - isort --check-only . - - name: black + pip install pre-commit + + - name: Python interpreter version sha (PYSHA) + run: echo "PYSHA=$(python -VV | sha256sum | cut -d' ' -f1)" >> $GITHUB_ENV + + - name: Cache pre-commit + uses: actions/cache@v3 + id: pre-commit-cache + with: + path: ~/.cache/pre-commit + key: pre-commit|${{ env.PYSHA }}|${{ hashFiles('.pre-commit-config.yaml') }} + + - name: pre-commit install run: | - source '/usr/share/miniconda/etc/profile.d/conda.sh' - conda activate im${{ matrix.env }} - black --check . - - name: flake8 + pre-commit install + + - name: pre-commit run run: | - source '/usr/share/miniconda/etc/profile.d/conda.sh' - conda activate im${{ matrix.env }} - flake8 improver improver_tests + pre-commit run --verbose --color=always --all-files + PR-standards: runs-on: ubuntu-22.04 timeout-minutes: 10 steps: + - name: Checkout uses: actions/checkout@v4 with: fetch-depth: 0 + - name: Check CONTRIBUTING.md uses: cylc/release-actions/check-shortlog@v1 + Safety-Bandit: runs-on: ubuntu-22.04 strategy: @@ -121,12 +130,15 @@ jobs: matrix: env: [environment_a, environment_b, conda-forge] steps: + - uses: actions/checkout@v4 + - uses: actions/cache@v4 id: cache with: path: /usr/share/miniconda/envs/im${{ matrix.env }} key: ${{ format('{0}-conda-improver-{1}-{2}', runner.os, matrix.env, hashFiles(format('envs/{0}.yml', matrix.env))) }} + - name: conda env update if: steps.cache.outputs.cache-hit != 'true' run: | @@ -135,17 +147,20 @@ jobs: conda install -q -n base -c conda-forge mamba rm -f /usr/share/miniconda/pkgs/cache/*.json # workaround for mamba-org/mamba#488 mamba env create -q --file envs/${{ matrix.env }}.yml --name im${{ matrix.env }} + - name: conda info run: | source '/usr/share/miniconda/etc/profile.d/conda.sh' conda activate im${{ matrix.env }} conda info conda list + - name: safety run: | source '/usr/share/miniconda/etc/profile.d/conda.sh' conda activate im${{ matrix.env }} safety check || true + - name: bandit run: | source '/usr/share/miniconda/etc/profile.d/conda.sh' diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000000..851c514ddb --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,24 @@ +repos: +- repo: https://github.com/astral-sh/ruff-pre-commit + # Ruff version. + rev: v0.4.8 + hooks: + # Run the linter (must come before any formatter, black/ruff when --fix). + - id: ruff + args: [ --fix ] + # Run the formatter. + - id: ruff-format +- repo: local + hooks: + - id: copyright_check + name: Check copyright header + types: [python] + args: [ --fix ] + language: system + entry: ./copyright_check + - id: init_check + name: Check for missing __init__.py files + types: [python] + language: system + entry: ./init_check + files: ^(improver/|improver_tests/) diff --git a/README.md b/README.md index 670c475abd..2de74d8d6b 100644 --- a/README.md +++ b/README.md @@ -42,3 +42,10 @@ activate your new improver environment ``` conda activate improver ``` + +## Pre-commit Hook +OPTIONAL: A pre-commit hook can be added to facilitate the development of this code base. +Ensure that you have python available on the path, then install the pre-commit hook by running `pre-commit install` from within your working copy. +pre-commit checks will run against modified files when you commit from then on. + +These pre-commit hooks will run as part of continuous integration to maintain standard in the project. \ No newline at end of file diff --git a/bin/improver b/bin/improver index 9bc8a208e8..790238a204 100755 --- a/bin/improver +++ b/bin/improver @@ -1,7 +1,7 @@ #!/bin/bash -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. #------------------------------------------------------------------------------ # NAME diff --git a/bin/improver-tests b/bin/improver-tests index 9029206ab3..68a68b4c6f 100755 --- a/bin/improver-tests +++ b/bin/improver-tests @@ -1,7 +1,7 @@ #!/bin/bash -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. #------------------------------------------------------------------------------ # NAME @@ -31,19 +31,9 @@ function get_python_files { ! -name '*~' \)` } -function improver_test_black { - ${BLACK:-black} $FILES_TO_TEST - echo_ok "black" -} - -function improver_test_isort { - ${ISORT:-isort} $FILES_TO_TEST - echo_ok "isort" -} - -function improver_test_flake8 { - ${FLAKE8:-flake8} $FILES_TO_TEST - echo_ok "flake8" +function improver_test_pre_commit { + pre-commit run --all-files + echo_ok "pre-commit" } function improver_test_doc { @@ -105,7 +95,7 @@ function print_usage { cat <<'__USAGE__' improver tests [OPTIONS] [SUBTEST...] [SUBCLI...] -Run black, isort, flake8, documentation, unit and CLI acceptance tests. +Run pre-commit, documentation, unit and CLI acceptance tests. Optional arguments: --debug Run in verbose mode (may take longer for CLI) @@ -113,11 +103,11 @@ Optional arguments: Arguments: SUBTEST Name(s) of a subtest to run without running the rest. - Valid names are: black, isort, flake8, doc, unit, cli, - and recreate_checksums. The default tests are black, - isort, flake8, doc, unit, and cli. Using - recreate_checksums will regenerate the test data - checksum file which is used as part of the cli tests. + Valid names are: pre_commit, doc, unit, cli, + and recreate_checksums. The default tests are pre_commit, + doc, unit, and cli. Using recreate_checksums will + regenerate the test data checksum file which is used as + part of the cli tests. __USAGE__ } @@ -158,7 +148,7 @@ for arg in "$@"; do print_usage exit 0 ;; - black|isort|flake8|doc|unit|cli|recreate_checksums) + pre_commit|doc|unit|cli|recreate_checksums) SUBTESTS="$SUBTESTS $arg" ;; $cli_tasks) @@ -176,7 +166,7 @@ if [[ -n "$SUBTESTS" ]]; then TESTS="$SUBTESTS" else # Default tests. - TESTS="isort black flake8 doc unit cli" + TESTS="pre_commit doc unit cli" fi # If cli sub test is not specified by user, do all cli tests. diff --git a/copyright_check b/copyright_check new file mode 100755 index 0000000000..80a4165984 --- /dev/null +++ b/copyright_check @@ -0,0 +1,121 @@ +#!/bin/bash + +copyright_header="\ +# (C) Crown Copyright, Met Office. All rights reserved.\n\ +#\n\ +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license.\n\ +# See LICENSE in the root of the repository for full licensing details.\ +" + +show_help() { + echo "info: Check the copyright header in the specified files." + echo " If the non-empty file does not contain the copyright header, it " + echo " will be added. If a file looks like it does contain a copyright " + echo " header, it will verified that it matches exactly." + echo " Hash bangs are preserved." + echo '' + echo "usage: $0 FILEPATH..." + echo '' + echo 'positional arguments:' + echo ' FILEPATH... The file(s) to check' + echo "" + echo "options:" + echo " -h|--help Show this help message and exit." + echo " -v|--verbose Print verbose output." + echo " -f|--fix Fix files with missing copyright header by adding it." + echo "" +} + +VERBOSE=false +FIX=false +ARGS="" +DEBUG=false + +while :; do + case $1 in + --help|-h) + show_help + exit 0 + ;; + --verbose|-v) + VERBOSE=true + ;; + --fix|-f) + FIX=true + ;; + -*) + echo "Unknown option: $1" + show_help + exit 1 + ;; + *) + ARGS+="$1"$'\n' + ;; + esac + shift + [ -z "$1" ] && break # Exit loop when there are no more arguments +done + + +contains_copyright() { + grep -qi '# .*copyright' $1 +} + + +defines_hash_bang() { + grep -q '^#!' $1 +} + + +correct_copyright() { + python -c 'import sys; sys.exit(0 if "'"$1"'" in open("'"$2"'", "r").read() else 1)' +} + + +# Function to delete temporary files +cleanup() { + for filepath in "$@"; do + tmp_file="${filepath}.tmp" + if [ -f "$tmp_file" ]; then + [[ ${DEBUG} == true ]] && echo "problem occurred while adding Copyright header, deleting temporary file: $tmp_file" >&2 + rm -f "$tmp_file" 2&> /dev/null + fi + done +} + +# Trap the EXIT signal to call the cleanup function +trap 'cleanup $ARGS' EXIT + +found_error=0 +for filepath in $ARGS; do + [[ ${VERBOSE} == true ]] && echo checking ${filepath} + if contains_copyright "${filepath}"; then + [[ ${VERBOSE} == true ]] && echo "File '${filepath}' appears to already contain a Copyright header" + if correct_copyright "${copyright_header}" "${filepath}"; then + [[ ${VERBOSE} == true ]] && echo "Copyright verified" + continue + else + echo "Incorrect Copyright header in '${filepath}'" >&2 + [[ ${VERBOSE} == true ]] && (diff <(echo -e $copyright_header) <(grep -i -A3 '# .*copyright' ${filepath}) >&2; echo >&2) + found_error=1 + fi + elif [ -s "${filepath}" ]; then # skip empty files + echo "File '${filepath}' is missing a copyright header." >&2 + if [[ ${FIX} == true ]]; then + echo "Adding missing Copyright to '${filepath}'" + tmp_file="${filepath}.tmp" + if defines_hash_bang "${filepath}"; then + head -n 1 ${filepath} > ${tmp_file} + echo -e ${copyright_header} >> ${tmp_file} + tail -n +2 ${filepath} >> ${tmp_file} + else + echo -e ${copyright_header} > ${tmp_file} + cat ${filepath} >> ${tmp_file} + fi + mv ${tmp_file} ${filepath} + found_error=1 + fi + fi +done + +exit ${found_error} diff --git a/doc/source/Code-Style-Guide.rst b/doc/source/Code-Style-Guide.rst index 28d3046b73..11a8c89566 100644 --- a/doc/source/Code-Style-Guide.rst +++ b/doc/source/Code-Style-Guide.rst @@ -68,11 +68,56 @@ In general, follow the very sensible `Google style guide `_. Code format should match that produced by the -`black `_ code formatter - this is -checked as part of the test suite on Github Actions. Codacy will give -you a mark based around ``pylint`` (with some caveats). A pylint score -of >8 is OK, >9 is good - skip pylint-misled errors for e.g. numpy -(e.g. with ``pylint --extension-pkg-whitelist=numpy``). +`ruff `_ code formatter - this is +checked as part of the pre-commit which is itself also executed on Github +Actions. +Codacy will give you a mark based around ``pylint`` (with some caveats). A +pylint score of >8 is OK, >9 is good - skip pylint-misled errors for e.g. +numpy (e.g. with ``pylint --extension-pkg-whitelist=numpy``). + +Pre-commit Hook +~~~~~~~~~~~~~~~ +A `pre-commit `_ hook can be added to facilitate the +development of this code base. Ensure that you have python available on the +path, then install the pre-commit hook by running: + +:: + + pip install pre-commit + +From this you will want to install the pre-commit hook. Do so from within your +working copy: + +:: + + pre-commit install + +pre-commit checks will run against modified files when you commit from then on. + +These pre-commit hooks will also run as part of continuous integration to +maintain standards in the project. +Numerous code QOL checks are performed including checking for copyright headers, +presence of python init files and ensuring that code passes rules set by both +`ruff linter `_ (providing similar +purpose to tools like isort, flake8, etc.) and +`ruff formatter `_ (providing similar +purpose to black). + +You can run pre-commit manually without commiting: + +All files: + +:: + + pre-commit run --all-files + +Specific files: + +:: + + pre-commit run --files + +See `pre=commit official docs `_ for more information. Modular code ~~~~~~~~~~~~ @@ -738,7 +783,7 @@ The following licence information should be added to each new file: :: - # (C) Crown copyright, Met Office. All rights reserved. + # (C) Crown Copyright, Met Office. All rights reserved. # # This file is part of IMPROVER and is released under a BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. diff --git a/doc/source/conf.py b/doc/source/conf.py index 276abba953..a7a54b7e2d 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. # # IMPROVER documentation build configuration file, created by @@ -286,7 +286,7 @@ # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, "Improver.tex", "IMPROVER Documentation", "Met Office", "manual"), + (master_doc, "Improver.tex", "IMPROVER Documentation", "Met Office", "manual") ] # The name of an image file (relative to this directory) to place at the top of @@ -347,7 +347,7 @@ "IMPROVER", "One line description of project.", "Miscellaneous", - ), + ) ] # Documents to append as an appendix to all manuals. diff --git a/envs/environment_a.yml b/envs/environment_a.yml index 3adafdb33d..6c48d2994a 100644 --- a/envs/environment_a.yml +++ b/envs/environment_a.yml @@ -27,12 +27,8 @@ dependencies: # Development - astroid - bandit - - black=19.10b0 - - click=8.0.2 - codacy-coverage - filelock - - flake8 - - isort=5.7.0 - mock - mypy - pytest diff --git a/envs/environment_b.yml b/envs/environment_b.yml index 6ee85984ff..05e88d9929 100644 --- a/envs/environment_b.yml +++ b/envs/environment_b.yml @@ -30,11 +30,7 @@ dependencies: # Development - astroid - bandit - - black=19.10b0 - - click=8.0.2 - filelock - - flake8 - - isort=5 - mock - mypy - pytest diff --git a/envs/latest.yml b/envs/latest.yml index dbe90fc694..e08ff168e8 100644 --- a/envs/latest.yml +++ b/envs/latest.yml @@ -31,11 +31,8 @@ dependencies: # Development - astroid - bandit - - black - codacy-coverage - filelock - - flake8 - - isort - mock - mypy - pytest diff --git a/improver/__init__.py b/improver/__init__.py index fdf837db16..6e839fccea 100644 --- a/improver/__init__.py +++ b/improver/__init__.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing plugin base class.""" diff --git a/improver/api/__init__.py b/improver/api/__init__.py index 366f4dbdff..60bd5cd67c 100644 --- a/improver/api/__init__.py +++ b/improver/api/__init__.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. # flake8: noqa """ @@ -8,6 +8,7 @@ by making them available to a single flat namespace. This also protects end-users from changes in structure to IMPROVER impacting their use of the plugins. """ + from importlib import import_module # alphabetically sorted IMPROVER plugin lookup diff --git a/improver/between_thresholds.py b/improver/between_thresholds.py index 50edb67935..9b765e6852 100644 --- a/improver/between_thresholds.py +++ b/improver/between_thresholds.py @@ -1,9 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -"""Plugin to calculate probabilities of occurrence between specified thresholds -""" +"""Plugin to calculate probabilities of occurrence between specified thresholds""" from typing import List @@ -46,8 +45,9 @@ def __init__( threshold_diffs = np.diff(threshold_ranges) if any(diff < 1e-5 for diff in threshold_diffs): raise ValueError( - "Plugin cannot distinguish between thresholds at " - "{} {}".format(threshold_ranges, threshold_units) + "Plugin cannot distinguish between thresholds at " "{} {}".format( + threshold_ranges, threshold_units + ) ) self.threshold_ranges = threshold_ranges self.threshold_units = threshold_units @@ -137,7 +137,7 @@ def _calculate_probabilities(self) -> Cube: thresh_name = self.thresh_coord.name() cubelist = iris.cube.CubeList([]) - for (lower_cube, upper_cube) in self.cube_slices: + for lower_cube, upper_cube in self.cube_slices: # construct difference cube between_thresholds_data = (lower_cube.data - upper_cube.data) * multiplier between_thresholds_cube = upper_cube.copy(between_thresholds_data) diff --git a/improver/blending/__init__.py b/improver/blending/__init__.py index f422b5fe64..0c09b8aec5 100644 --- a/improver/blending/__init__.py +++ b/improver/blending/__init__.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Constants used internally to the blending plugins""" diff --git a/improver/blending/blend_across_adjacent_points.py b/improver/blending/blend_across_adjacent_points.py index 80fe7dfb58..320963a81b 100644 --- a/improver/blending/blend_across_adjacent_points.py +++ b/improver/blending/blend_across_adjacent_points.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing Blending classes that blend over adjacent points, as opposed to collapsing the whole dimension.""" diff --git a/improver/blending/calculate_weights_and_blend.py b/improver/blending/calculate_weights_and_blend.py index 527232373f..42000ecb5e 100644 --- a/improver/blending/calculate_weights_and_blend.py +++ b/improver/blending/calculate_weights_and_blend.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Plugin to calculate blend weights and blend data across a dimension""" diff --git a/improver/blending/spatial_weights.py b/improver/blending/spatial_weights.py index 4aaafff9fd..1d4d50652a 100644 --- a/improver/blending/spatial_weights.py +++ b/improver/blending/spatial_weights.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to adjust weights spatially based on missing data in input cubes.""" diff --git a/improver/blending/utilities.py b/improver/blending/utilities.py index 196e9fcd2c..4beaf688ca 100644 --- a/improver/blending/utilities.py +++ b/improver/blending/utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Utilities to support weighted blending""" diff --git a/improver/blending/weighted_blend.py b/improver/blending/weighted_blend.py index d3c8c0663d..4f9cb6d402 100644 --- a/improver/blending/weighted_blend.py +++ b/improver/blending/weighted_blend.py @@ -1,9 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing classes for doing weighted blending by collapsing a - whole dimension.""" +whole dimension.""" import warnings from typing import List, Optional, Union @@ -204,8 +204,9 @@ def process( for cube in cubelist: if "model" not in self.blend_coord and not cube.coords(self.blend_coord): raise ValueError( - "{} coordinate is not present on all input " - "cubes".format(self.blend_coord) + "{} coordinate is not present on all input " "cubes".format( + self.blend_coord + ) ) # create model ID and model configuration coordinates if blending @@ -221,29 +222,29 @@ def process( class PercentileBlendingAggregator: """Class for the percentile blending aggregator - This class implements the method described by Combining Probabilities - by Caroline Jones, 2017. This method implements blending in probability - space. - - The steps are: - 1. At each geographic point in the cube we take the percentile - threshold's values across the percentile dimensional coordinate. - We recalculate, using linear interpolation, their probabilities - in the pdf of the other points across the coordinate we are - blending over. Thus at each point we have a set of thresholds - and their corresponding probability values in each of the - probability spaces across the blending coordinate. - 2. We do a weighted blend across all the probability spaces, - combining all the thresholds in all the points in the coordinate - we are blending over. This gives us an array of thresholds and an - array of blended probabilities for each of the grid points. - 3. We convert back to the original percentile values, again using - linear interpolation, resulting in blended values at each of the - original percentiles. - - References: - :download:`Combining Probabilities by Caroline Jones, 2017 - <../files/Combining_Probabilities.pdf>` + This class implements the method described by Combining Probabilities + by Caroline Jones, 2017. This method implements blending in probability + space. + + The steps are: + 1. At each geographic point in the cube we take the percentile + threshold's values across the percentile dimensional coordinate. + We recalculate, using linear interpolation, their probabilities + in the pdf of the other points across the coordinate we are + blending over. Thus at each point we have a set of thresholds + and their corresponding probability values in each of the + probability spaces across the blending coordinate. + 2. We do a weighted blend across all the probability spaces, + combining all the thresholds in all the points in the coordinate + we are blending over. This gives us an array of thresholds and an + array of blended probabilities for each of the grid points. + 3. We convert back to the original percentile values, again using + linear interpolation, resulting in blended values at each of the + original percentiles. + + References: + :download:`Combining Probabilities by Caroline Jones, 2017 + <../files/Combining_Probabilities.pdf>` """ @staticmethod @@ -311,7 +312,7 @@ def aggregate( def blend_percentiles( perc_values: ndarray, percentiles: ndarray, weights: ndarray ) -> ndarray: - """ Blend percentiles function, to calculate the weighted blend across + """Blend percentiles function, to calculate the weighted blend across a given axis of percentile data for a single grid point. Args: @@ -362,8 +363,8 @@ def blend_percentiles( class WeightedBlendAcrossWholeDimension(PostProcessingPlugin): """Apply a Weighted blend to a cube, collapsing across the whole - dimension. Uses one of two methods, either weighted average, or - the maximum of the weighted probabilities.""" + dimension. Uses one of two methods, either weighted average, or + the maximum of the weighted probabilities.""" def __init__(self, blend_coord: str, timeblending: bool = False) -> None: """Set up for a Weighted Blending plugin diff --git a/improver/blending/weights.py b/improver/blending/weights.py index 042de87922..8a44ec9329 100644 --- a/improver/blending/weights.py +++ b/improver/blending/weights.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to create the weights used to blend data.""" @@ -25,7 +25,7 @@ class WeightsUtilities: - """ Utilities for Weight processing. """ + """Utilities for Weight processing.""" def __repr__(self) -> str: """Represent the configured plugin instance as a string.""" @@ -67,7 +67,7 @@ def normalise_weights(weights: ndarray, axis: Optional[int] = None) -> ndarray: return normalised_weights @staticmethod - def build_weights_cube(cube: Cube, weights: ndarray, blending_coord: str,) -> Cube: + def build_weights_cube(cube: Cube, weights: ndarray, blending_coord: str) -> Cube: """Build a cube containing weights for use in blending. Args: @@ -386,12 +386,9 @@ def _calculate_weights(self, cube: Cube) -> Cube: has been renamed using the self.weights_key_name but otherwise matches the input cube. """ - ( - source_points, - target_points, - source_weights, - fill_value, - ) = self._get_interpolation_inputs_from_dict(cube) + (source_points, target_points, source_weights, fill_value) = ( + self._get_interpolation_inputs_from_dict(cube) + ) axis = 0 weights = self._interpolate_to_find_weights( @@ -499,7 +496,7 @@ def process(self, cubes: Union[Cube, CubeList]) -> Cube: class ChooseDefaultWeightsLinear(BasePlugin): - """ Calculate Default Weights using Linear Function. """ + """Calculate Default Weights using Linear Function.""" def __init__(self, y0val: float, ynval: float) -> None: """ @@ -592,7 +589,7 @@ def __repr__(self): class ChooseDefaultWeightsNonLinear(BasePlugin): - """ Calculate Default Weights using NonLinear Function. """ + """Calculate Default Weights using NonLinear Function.""" def __init__(self, cval: float) -> None: """ @@ -645,7 +642,7 @@ def nonlinear_weights(self, num_of_weights: int) -> ndarray: return weights def process( - self, cube: Cube, coord_name: str, inverse_ordering: bool = False, + self, cube: Cube, coord_name: str, inverse_ordering: bool = False ) -> Cube: """ Calculate nonlinear weights for a given cube and coord. @@ -703,7 +700,7 @@ def __repr__(self): class ChooseDefaultWeightsTriangular(BasePlugin): - """ Calculate Default Weights using a Triangular Function. """ + """Calculate Default Weights using a Triangular Function.""" def __init__(self, width: float, units: Union[Unit, str] = "no_unit") -> None: """Set up for calculating default weights using triangular function. diff --git a/improver/calibration/__init__.py b/improver/calibration/__init__.py index d85ee1c244..db23e43628 100644 --- a/improver/calibration/__init__.py +++ b/improver/calibration/__init__.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """init for calibration that contains functionality to split forecast, truth and coefficient inputs. @@ -95,7 +95,7 @@ def split_forecasts_and_truth( def split_forecasts_and_coeffs( - cubes: CubeList, land_sea_mask_name: Optional[str] = None, + cubes: CubeList, land_sea_mask_name: Optional[str] = None ): """Split the input forecast, coefficients, static additional predictors, land sea-mask and probability template, if provided. The coefficients diff --git a/improver/calibration/dataframe_utilities.py b/improver/calibration/dataframe_utilities.py index ac5b5f9251..bc103eb983 100644 --- a/improver/calibration/dataframe_utilities.py +++ b/improver/calibration/dataframe_utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Functionality to convert a pandas DataFrame in the expected format @@ -11,6 +11,7 @@ """ + import warnings from typing import List, Optional, Sequence, Tuple @@ -28,10 +29,7 @@ from improver.metadata.constants.time_types import TIME_COORDS from improver.spotdata.build_spotdata_cube import build_spotdata_cube -REPRESENTATION_COLUMNS = [ - "percentile", - "realization", -] +REPRESENTATION_COLUMNS = ["percentile", "realization"] FORECAST_DATAFRAME_COLUMNS = [ "altitude", @@ -219,7 +217,6 @@ def _ensure_consistent_static_cols( # Check if any of the assumed static columns are actually not static when # the DataFrame is grouped by the site_id_col. if (forecast_df.groupby(site_id_col)[static_cols].nunique().nunique() > 1).any(): - for static_col in static_cols: # For each static column, find the last value from the list of unique # values for each site. The last value corresponds to the most recent value @@ -236,7 +233,7 @@ def _ensure_consistent_static_cols( def _define_time_coord( - adate: pd.Timestamp, time_bounds: Optional[Sequence[pd.Timestamp]] = None, + adate: pd.Timestamp, time_bounds: Optional[Sequence[pd.Timestamp]] = None ) -> DimCoord: """Define a time coordinate. The coordinate will have bounds, if bounds are provided. @@ -254,12 +251,14 @@ def _define_time_coord( return DimCoord( np.array(adate.timestamp(), dtype=TIME_COORDS["time"].dtype), "time", - bounds=time_bounds - if time_bounds is None - else [ - np.array(t.timestamp(), dtype=TIME_COORDS["time"].dtype) - for t in time_bounds - ], + bounds=( + time_bounds + if time_bounds is None + else [ + np.array(t.timestamp(), dtype=TIME_COORDS["time"].dtype) + for t in time_bounds + ] + ), units=TIME_COORDS["time"].units, ) @@ -274,7 +273,7 @@ def _define_height_coord(height) -> AuxCoord: Returns: The height coordinate. """ - return AuxCoord(np.array(height, dtype=np.float32), "height", units="m",) + return AuxCoord(np.array(height, dtype=np.float32), "height", units="m") def _training_dates_for_calibration( @@ -573,7 +572,7 @@ def _prepare_dataframes( def forecast_dataframe_to_cube( - df: DataFrame, training_dates: DatetimeIndex, forecast_period: int, + df: DataFrame, training_dates: DatetimeIndex, forecast_period: int ) -> Cube: """Convert a forecast DataFrame into an iris Cube. The percentiles within the forecast DataFrame are rebadged as realizations. @@ -629,12 +628,16 @@ def forecast_dataframe_to_cube( fp_point.total_seconds(), dtype=TIME_COORDS["forecast_period"].dtype ), "forecast_period", - bounds=fp_bounds - if fp_bounds is None - else [ - np.array(f.total_seconds(), dtype=TIME_COORDS["forecast_period"].dtype) - for f in fp_bounds - ], + bounds=( + fp_bounds + if fp_bounds is None + else [ + np.array( + f.total_seconds(), dtype=TIME_COORDS["forecast_period"].dtype + ) + for f in fp_bounds + ] + ), units=TIME_COORDS["forecast_period"].units, ) frt_coord = AuxCoord( @@ -694,7 +697,7 @@ def forecast_dataframe_to_cube( return cube -def truth_dataframe_to_cube(df: DataFrame, training_dates: DatetimeIndex,) -> Cube: +def truth_dataframe_to_cube(df: DataFrame, training_dates: DatetimeIndex) -> Cube: """Convert a truth DataFrame into an iris Cube. Args: diff --git a/improver/calibration/dz_rescaling.py b/improver/calibration/dz_rescaling.py index d006dfaed7..aafa21d3fa 100644 --- a/improver/calibration/dz_rescaling.py +++ b/improver/calibration/dz_rescaling.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Estimate and apply a rescaling of the input forecast based on the difference in altitude between the grid point and the site.""" @@ -23,7 +23,6 @@ class EstimateDzRescaling(PostProcessingPlugin): - """Estimate a rescaling of the input forecasts based on the difference in altitude between the grid point and the site.""" @@ -143,7 +142,7 @@ def _compute_scaled_dz(self, scale_factor: float, dz: np.ndarray) -> np.ndarray: return np.clip(scaled_dz.data, scaled_dz_lower, scaled_dz_upper) def _compute_scaled_dz_cube( - self, forecast: Cube, dz: Cube, scale_factor: float, + self, forecast: Cube, dz: Cube, scale_factor: float ) -> Cube: """Compute the scaled difference in altitude and ensure that the output cube has the correct metadata. @@ -289,7 +288,6 @@ def process(self, forecasts: Cube, truths: Cube, neighbour_cube: Cube) -> Cube: class ApplyDzRescaling(PostProcessingPlugin): - """Apply rescaling of the forecast using the difference in altitude between the grid point and the site.""" diff --git a/improver/calibration/ensemble_calibration.py b/improver/calibration/ensemble_calibration.py index 200137ecb9..2856f74ed0 100644 --- a/improver/calibration/ensemble_calibration.py +++ b/improver/calibration/ensemble_calibration.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ This module defines all the "plugins" specific for Ensemble Model Output @@ -11,6 +11,7 @@ ensemble_calibration.rst """ + import warnings from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union @@ -351,7 +352,7 @@ def _minimise_caller( optimised_coeffs = minimize( minimisation_function, initial_guess, - args=(forecast_predictor_data, truth_data, forecast_var_data, sqrt_pi,), + args=(forecast_predictor_data, truth_data, forecast_var_data, sqrt_pi), method="Nelder-Mead", tol=self.tolerance, options={"maxiter": self.max_iterations, "return_all": True}, @@ -422,10 +423,7 @@ def _process_points_independently( are provided. """ fp_template = forecast_predictors[0] - sindex = [ - fp_template.coord(axis="y"), - fp_template.coord(axis="x"), - ] + sindex = [fp_template.coord(axis="y"), fp_template.coord(axis="x")] y_name = truth.coord(axis="y").name() x_name = truth.coord(axis="x").name() @@ -468,7 +466,7 @@ def _process_points_independently( x_coord = fp_template.coord(axis="x") if fp_template.coord_dims(y_coord) == fp_template.coord_dims(x_coord): return np.transpose(np.array(optimised_coeffs)).reshape( - (len(initial_guess[0]), len(fp_template.coord(axis="y").points),) + (len(initial_guess[0]), len(fp_template.coord(axis="y").points)) ) else: return np.transpose(np.array(optimised_coeffs)).reshape( @@ -810,7 +808,7 @@ def _get_spatial_associated_coordinates( if self.point_by_point: spatial_coords = [historic_forecasts.coord(axis=axis) for axis in "yx"] spatial_dims = { - n for n, in [historic_forecasts.coord_dims(c) for c in spatial_coords] + n for (n,) in [historic_forecasts.coord_dims(c) for c in spatial_coords] } template_dims = [x for x in spatial_dims] spatial_associated_coords = [ @@ -850,7 +848,7 @@ def _add_predictor_coords( for index, fp in enumerate(forecast_predictors): template_cube_copy = template_cube.copy() predictor_index = iris.coords.DimCoord( - np.array(index, dtype=np.int8), long_name="predictor_index", units="1", + np.array(index, dtype=np.int8), long_name="predictor_index", units="1" ) template_cube_copy.add_aux_coord(predictor_index) template_cube_copy = iris.util.new_axis(template_cube_copy, predictor_index) @@ -861,7 +859,7 @@ def _add_predictor_coords( fp_names, long_name="predictor_name", units="no_unit" ) template_cube.add_aux_coord( - predictor_name, data_dims=template_cube.coord_dims("predictor_index"), + predictor_name, data_dims=template_cube.coord_dims("predictor_index") ) return iris.util.squeeze(template_cube) @@ -887,10 +885,9 @@ def _create_cubelist( cubelist is for a separate EMOS coefficient e.g. alpha, beta, gamma, delta. """ - ( - template_dims, - spatial_associated_coords, - ) = self._get_spatial_associated_coordinates(historic_forecasts) + (template_dims, spatial_associated_coords) = ( + self._get_spatial_associated_coordinates(historic_forecasts) + ) coords_to_replace = ( self._create_temporal_coordinates(historic_forecasts) + spatial_associated_coords @@ -1436,15 +1433,12 @@ def _spatial_domain_match(self) -> None: for axis in ["x", "y"]: for coeff_cube in self.coefficients_cubelist: if ( - ( - self.current_forecast.coord(axis=axis).collapsed().points - != coeff_cube.coord(axis=axis).collapsed().points - ).all() - or ( - self.current_forecast.coord(axis=axis).collapsed().bounds - != coeff_cube.coord(axis=axis).collapsed().bounds - ).all() - ): + self.current_forecast.coord(axis=axis).collapsed().points + != coeff_cube.coord(axis=axis).collapsed().points + ).all() or ( + self.current_forecast.coord(axis=axis).collapsed().bounds + != coeff_cube.coord(axis=axis).collapsed().bounds + ).all(): raise ValueError( msg.format( axis, @@ -1899,9 +1893,9 @@ def _format_forecast( self.distribution["location"], self.distribution["scale"], template, - percentiles=self.percentiles - if self.percentiles - else perc_coord.points, + percentiles=( + self.percentiles if self.percentiles else perc_coord.points + ), ) else: no_of_percentiles = len(template.coord("realization").points) diff --git a/improver/calibration/rainforest_calibration.py b/improver/calibration/rainforest_calibration.py index 1529e8d9c0..b63645a98a 100644 --- a/improver/calibration/rainforest_calibration.py +++ b/improver/calibration/rainforest_calibration.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """RainForests calibration Plugins. @@ -10,7 +10,6 @@ """ - import warnings from collections import OrderedDict from pathlib import Path @@ -50,7 +49,6 @@ def __new__( threads: int = 1, bin_data: bool = False, ): - """Initialise class object based on package and model file availability. Args: @@ -281,15 +279,15 @@ def __init__( "24": { "0.000010": { "lightgbm_model": "", - "treelite_model": "" + "treelite_model": "", }, "0.000050": { "lightgbm_model": "", - "treelite_model": "" + "treelite_model": "", }, "0.000100": { "lightgbm_model": "", - "treelite_model": "" + "treelite_model": "", }, } } @@ -446,7 +444,7 @@ def _prepare_threshold_probability_cube(self, forecast_cube, thresholds): attributes={"spp__relative_to_threshold": "greater_than_or_equal_to"}, ) probability_cube = add_coordinate_to_cube( - probability_cube, new_coord=threshold_coord, + probability_cube, new_coord=threshold_coord ) return probability_cube @@ -507,7 +505,7 @@ def _make_decreasing(self, probability_data: ndarray) -> ndarray: return 0.5 * (upper + lower) def _evaluate_probabilities( - self, input_data: ndarray, lead_time_hours: int, output_data: ndarray, + self, input_data: ndarray, lead_time_hours: int, output_data: ndarray ) -> None: """Evaluate probability that forecast exceeds thresholds. @@ -573,7 +571,7 @@ def _evaluate_probabilities( ) def _calculate_threshold_probabilities( - self, forecast_cube: Cube, feature_cubes: CubeList, + self, forecast_cube: Cube, feature_cubes: CubeList ) -> Cube: """Evaluate the threshold exceedence probabilities for each ensemble member in forecast_cube using the tree_models, with the associated feature_cubes taken as @@ -605,7 +603,7 @@ def _calculate_threshold_probabilities( ) self._evaluate_probabilities( - input_dataset, lead_time_hours, threshold_probability_cube.data, + input_dataset, lead_time_hours, threshold_probability_cube.data ) # Enforcing monotonicity @@ -780,7 +778,6 @@ def __new__( threads: int = 1, bin_data: bool = False, ): - """Check required dependency and all model files are available before initialising.""" # Try and initialise the treelite_runtime library to test if the package # is available. @@ -816,15 +813,15 @@ def __init__( "24": { "0.000010": { "lightgbm_model": "", - "treelite_model": "" + "treelite_model": "", }, "0.000050": { "lightgbm_model": "", - "treelite_model": "" + "treelite_model": "", }, "0.000100": { "lightgbm_model": "", - "treelite_model": "" + "treelite_model": "", }, } } diff --git a/improver/calibration/reliability_calibration.py b/improver/calibration/reliability_calibration.py index 7d291f7434..861131fd0b 100644 --- a/improver/calibration/reliability_calibration.py +++ b/improver/calibration/reliability_calibration.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Reliability calibration plugins.""" @@ -37,7 +37,6 @@ class ConstructReliabilityCalibrationTables(BasePlugin): - """A plugin for creating and populating reliability calibration tables.""" def __init__( @@ -231,7 +230,7 @@ def _create_reliability_table_cube( A reliability table cube. """ - def _get_coords_and_dims(coord_names: List[str],) -> List[Tuple[DimCoord, int]]: + def _get_coords_and_dims(coord_names: List[str]) -> List[Tuple[DimCoord, int]]: """Obtain the requested coordinates and their dimension index from the forecast slice cube.""" coords_and_dims = [] @@ -252,10 +251,9 @@ def _get_coords_and_dims(coord_names: List[str],) -> List[Tuple[DimCoord, int]]: # Define reliability table specific coordinates probability_bins_coord = self._create_probability_bins_coord() - ( - reliability_index_coord, - reliability_name_coord, - ) = self._create_reliability_table_coords() + (reliability_index_coord, reliability_name_coord) = ( + self._create_reliability_table_coords() + ) frt_coord = create_unified_frt_coord(forecast.coord("forecast_reference_time")) # List of required non-spatial coordinates from the forecast @@ -414,7 +412,7 @@ def _add_reliability_tables( # as being masked within the resulting reliability table. mask = threshold_reliability.mask & table.mask threshold_reliability = np.ma.array( - threshold_reliability.data + table.data, mask=mask, dtype=np.float32, + threshold_reliability.data + table.data, mask=mask, dtype=np.float32 ) else: np.add( @@ -503,7 +501,6 @@ def process( truths.slices_over(threshold_coord), ) for forecast_slice, truth_slice in threshold_slices: - time_slices = zip( forecast_slice.slices_over(time_coord), truth_slice.slices_over(time_coord), @@ -528,7 +525,6 @@ def process( class AggregateReliabilityCalibrationTables(BasePlugin): - """This plugin enables the aggregation of multiple reliability calibration tables, and/or the aggregation over coordinates in the tables.""" @@ -1065,7 +1061,6 @@ def process(self, reliability_table: Cube) -> CubeList: class ApplyReliabilityCalibration(PostProcessingPlugin): - """ A plugin for the application of reliability calibration to probability forecasts. This calibration is designed to improve the reliability of @@ -1287,7 +1282,7 @@ def _interpolate( return np.clip(interpolated, 0, 1) def _apply_calibration( - self, forecast: Cube, reliability_table: Union[Cube, CubeList], + self, forecast: Cube, reliability_table: Union[Cube, CubeList] ) -> Cube: """ Apply reliability calibration to a forecast. @@ -1309,10 +1304,9 @@ def _apply_calibration( reliability_threshold = self._extract_matching_reliability_table( forecast_threshold, reliability_table ) - ( - reliability_probabilities, - observation_frequencies, - ) = self._calculate_reliability_probabilities(reliability_threshold) + (reliability_probabilities, observation_frequencies) = ( + self._calculate_reliability_probabilities(reliability_threshold) + ) if reliability_probabilities is None: calibrated_cubes.append(forecast_threshold) @@ -1343,7 +1337,7 @@ def _apply_calibration( return calibrated_forecast def _apply_point_by_point_calibration( - self, forecast: Cube, reliability_table: CubeList, + self, forecast: Cube, reliability_table: CubeList ) -> Cube: """ Apply point by point reliability calibration by iteratively picking a spatial @@ -1414,9 +1408,7 @@ def _apply_point_by_point_calibration( return calibrated_forecast - def process( - self, forecast: Cube, reliability_table: Union[Cube, CubeList], - ) -> Cube: + def process(self, forecast: Cube, reliability_table: Union[Cube, CubeList]) -> Cube: """ Apply reliability calibration to a forecast. The reliability table and the forecast cube must share an identical threshold coordinate. @@ -1440,7 +1432,7 @@ def process( else: calibrated_forecast = self._apply_calibration( - forecast=forecast, reliability_table=reliability_table, + forecast=forecast, reliability_table=reliability_table ) # enforce correct data type diff --git a/improver/calibration/simple_bias_correction.py b/improver/calibration/simple_bias_correction.py index a350ec3a77..fef04f976a 100644 --- a/improver/calibration/simple_bias_correction.py +++ b/improver/calibration/simple_bias_correction.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Simple bias correction plugins.""" @@ -395,7 +395,7 @@ def _check_forecast_bias_consistent( "Forecast period differ between forecast and bias datasets." ) - def process(self, *cubes: Union[Cube, CubeList],) -> Cube: + def process(self, *cubes: Union[Cube, CubeList]) -> Cube: """Split then apply bias correction using the specified bias values. Where the bias data is defined point-by-point, the bias-correction will also diff --git a/improver/calibration/utilities.py b/improver/calibration/utilities.py index 8463c80137..6e804e3a59 100644 --- a/improver/calibration/utilities.py +++ b/improver/calibration/utilities.py @@ -1,12 +1,13 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ This module defines all the utilities used by the "plugins" specific for ensemble calibration. """ + from typing import List, Set, Tuple, Union import iris @@ -140,7 +141,7 @@ def check_predictor(predictor: str) -> str: def filter_non_matching_cubes( - historic_forecast: Cube, truth: Cube, + historic_forecast: Cube, truth: Cube ) -> Tuple[Cube, Cube]: """ Provide filtering for the historic forecast and truth to make sure diff --git a/improver/categorical/decision_tree.py b/improver/categorical/decision_tree.py index b22e952ca2..3de32e21cf 100644 --- a/improver/categorical/decision_tree.py +++ b/improver/categorical/decision_tree.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing categorical decision tree implementation.""" - import copy import operator from typing import Dict, List, Optional, Tuple, Union @@ -49,12 +48,7 @@ def _define_invertible_conditions() -> Dict[str, str]: """Returns a dictionary of boolean comparator strings where the value is the logical inverse of the key.""" - invertible_conditions = { - ">=": "<", - ">": "<=", - "OR": "AND", - "": "", - } + invertible_conditions = {">=": "<", ">": "<=", "OR": "AND", "": ""} # Add reverse {value: key} entries to invertible_conditions reverse_inversions = {} for k, v in invertible_conditions.items(): @@ -197,7 +191,6 @@ def prepare_input_cubes( for diagnostic, threshold, condition in zip( diagnostics, thresholds, conditions ): - # First we check the diagnostic name and units, performing # a conversion is required and possible. test_condition = iris.Constraint(name=diagnostic) @@ -382,7 +375,6 @@ def create_condition_chain(self, test_conditions: Dict) -> List: for index, (diagnostic, p_threshold) in enumerate( zip(test_conditions["diagnostic_fields"], test_conditions[coord]) ): - d_threshold = test_conditions.get("diagnostic_thresholds") d_threshold = d_threshold[index] if d_threshold else None loop += 1 @@ -462,11 +454,11 @@ def construct_extract_constraint( threshold_val = threshold.points.item() if abs(threshold_val) < self.float_abs_tolerance: cell_constraint = lambda cell: np.isclose( - cell.point, threshold_val, rtol=0, atol=self.float_abs_tolerance, + cell.point, threshold_val, rtol=0, atol=self.float_abs_tolerance ) else: cell_constraint = lambda cell: np.isclose( - cell.point, threshold_val, rtol=self.float_tolerance, atol=0, + cell.point, threshold_val, rtol=self.float_tolerance, atol=0 ) kw_dict = {"{}".format(threshold_coord_name): cell_constraint} @@ -490,7 +482,6 @@ def remove_optional_missing(self, optional_node_data_missing: List[str]): is allowed. """ for missing in optional_node_data_missing: - # Get the name of the alternative node to bypass the missing one target = self.queries[missing]["if_diagnostic_missing"] alternative = self.queries[missing][target] @@ -506,7 +497,7 @@ def remove_optional_missing(self, optional_node_data_missing: List[str]): @staticmethod def find_all_routes( - graph: Dict, start: str, end: int, route: Optional[List[str]] = None, + graph: Dict, start: str, end: int, route: Optional[List[str]] = None ) -> List[str]: """ Function to trace all routes through the decision tree. @@ -820,9 +811,11 @@ def process(self, *cubes: Union[Cube, CubeList]) -> Cube: # Construct graph nodes dictionary graph = { - key: [self.queries[key]["leaf"]] - if "leaf" in self.queries[key].keys() - else [self.queries[key]["if_true"], self.queries[key]["if_false"]] + key: ( + [self.queries[key]["leaf"]] + if "leaf" in self.queries[key].keys() + else [self.queries[key]["if_true"], self.queries[key]["if_false"]] + ) for key in self.queries } # Search through tree for all leaves (category end points) @@ -836,7 +829,7 @@ def process(self, *cubes: Union[Cube, CubeList]) -> Cube: # Loop over possible categories for category_code in defined_categories: - routes = self.find_all_routes(graph, self.start_node, category_code,) + routes = self.find_all_routes(graph, self.start_node, category_code) # Loop over possible routes from root to leaf for route in routes: conditions = [] @@ -846,7 +839,6 @@ def process(self, *cubes: Union[Cube, CubeList]) -> Cube: next_node = route[i_node + 1] if current.get("if_false") == next_node: - ( current["threshold_condition"], current["condition_combination"], diff --git a/improver/categorical/modal_code.py b/improver/categorical/modal_code.py index 0c09b3a288..bad5358bb4 100644 --- a/improver/categorical/modal_code.py +++ b/improver/categorical/modal_code.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing a plugin to calculate the modal category in a period.""" diff --git a/improver/categorical/utilities.py b/improver/categorical/utilities.py index b0367e42fb..8e400a0167 100644 --- a/improver/categorical/utilities.py +++ b/improver/categorical/utilities.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -"""This module defines the utilities required for decision tree plugin """ +"""This module defines the utilities required for decision tree plugin""" from collections import OrderedDict from typing import Any, Dict, List, Optional, Union @@ -143,7 +143,7 @@ def expand_nested_lists(query: Dict[str, Any], key: str) -> List[Any]: def update_daynight(cube: Cube, day_night: Dict) -> Cube: - """ Update category depending on whether it is day or night + """Update category depending on whether it is day or night Args: cube: @@ -231,7 +231,7 @@ def interrogate_decision_tree(decision_tree: Dict[str, Dict[str, Any]]) -> str: ) if query.get("deterministic", False): for diagnostic in diagnostics: - output.append(f"\u26C5 {diagnostic} (deterministic)") + output.append(f"\u26c5 {diagnostic} (deterministic)") output.sort() else: thresholds = expand_nested_lists(query, "diagnostic_thresholds") @@ -241,7 +241,7 @@ def interrogate_decision_tree(decision_tree: Dict[str, Dict[str, Any]]) -> str: for requirement, uniq_thresh in sorted(requirements.items()): (units,) = {u.units for u in uniq_thresh} # enforces same units thresh_str = ", ".join(map(str, sorted({v.points[0] for v in uniq_thresh}))) - output.append("\u26C5 {} ({}): {}".format(requirement, units, thresh_str)) + output.append("\u26c5 {} ({}): {}".format(requirement, units, thresh_str)) n_files = len(output) formatted_string = "{}\n" * n_files diff --git a/improver/cli/__init__.py b/improver/cli/__init__.py index 22fbccf064..79542ad4cf 100644 --- a/improver/cli/__init__.py +++ b/improver/cli/__init__.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """init for cli and clize""" @@ -362,8 +362,7 @@ def with_output( def clizefy(obj=None, helper_class=DocutilizeClizeHelp, **kwargs): - """Decorator for creating CLI objects. - """ + """Decorator for creating CLI objects.""" if obj is None: return partial(clizefy, helper_class=helper_class, **kwargs) if hasattr(obj, "cli"): @@ -432,7 +431,7 @@ def _cli_items(): def unbracket(args): """Convert input list with bracketed items into nested lists. - >>> unbracket('foo [ bar a b ] [ baz c ] -o z'.split()) + >>> unbracket("foo [ bar a b ] [ baz c ] -o z".split()) ['foo', ['bar', 'a', 'b'], ['baz', 'c'], '-o', 'z'] """ diff --git a/improver/cli/__main__.py b/improver/cli/__main__.py index dca40c2f6e..3f69070152 100644 --- a/improver/cli/__main__.py +++ b/improver/cli/__main__.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Main to run clize on the cli""" + from improver import cli if __name__ == "__main__": diff --git a/improver/cli/aggregate_reliability_tables.py b/improver/cli/aggregate_reliability_tables.py index b6461735e0..8320f34243 100644 --- a/improver/cli/aggregate_reliability_tables.py +++ b/improver/cli/aggregate_reliability_tables.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to aggregate reliability tables.""" diff --git a/improver/cli/apply_bias_correction.py b/improver/cli/apply_bias_correction.py index 2b9ed5ae38..b87c71bd7b 100644 --- a/improver/cli/apply_bias_correction.py +++ b/improver/cli/apply_bias_correction.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to apply simple bias correction to ensemble members based on bias from the reference forecast dataset.""" diff --git a/improver/cli/apply_dz_rescaling.py b/improver/cli/apply_dz_rescaling.py index b63d215dfd..5f4abc1274 100755 --- a/improver/cli/apply_dz_rescaling.py +++ b/improver/cli/apply_dz_rescaling.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to apply a scaling factor to account for a correction linked to the difference in altitude between the grid point and the site location.""" diff --git a/improver/cli/apply_emos_coefficients.py b/improver/cli/apply_emos_coefficients.py index 80a7b78de9..ab714c4d05 100644 --- a/improver/cli/apply_emos_coefficients.py +++ b/improver/cli/apply_emos_coefficients.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to apply coefficients for Ensemble Model Output Statistics (EMOS), otherwise known as Non-homogeneous Gaussian @@ -121,13 +121,9 @@ def process( ResamplePercentiles, ) - ( - forecast, - coefficients, - additional_predictors, - land_sea_mask, - prob_template, - ) = split_forecasts_and_coeffs(cubes, land_sea_mask_name) + (forecast, coefficients, additional_predictors, land_sea_mask, prob_template) = ( + split_forecasts_and_coeffs(cubes, land_sea_mask_name) + ) if validity_times is not None and not validity_time_check(forecast, validity_times): if percentiles: diff --git a/improver/cli/apply_height_adjustment.py b/improver/cli/apply_height_adjustment.py index f5ec1141c6..814ce56b29 100644 --- a/improver/cli/apply_height_adjustment.py +++ b/improver/cli/apply_height_adjustment.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to apply height adjustments to spot data.""" diff --git a/improver/cli/apply_lapse_rate.py b/improver/cli/apply_lapse_rate.py index 03aebe020b..c85d1ba2b7 100755 --- a/improver/cli/apply_lapse_rate.py +++ b/improver/cli/apply_lapse_rate.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to apply lapse rates to temperature data.""" diff --git a/improver/cli/apply_mask.py b/improver/cli/apply_mask.py index 84f1c9959f..9efc51c5a5 100644 --- a/improver/cli/apply_mask.py +++ b/improver/cli/apply_mask.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to apply provided mask to cube data.""" diff --git a/improver/cli/apply_night_mask.py b/improver/cli/apply_night_mask.py index b33865435f..b8279dd583 100755 --- a/improver/cli/apply_night_mask.py +++ b/improver/cli/apply_night_mask.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to set night values to zero for UV index.""" diff --git a/improver/cli/apply_rainforests_calibration.py b/improver/cli/apply_rainforests_calibration.py index dc0ac62591..d7daee11ba 100644 --- a/improver/cli/apply_rainforests_calibration.py +++ b/improver/cli/apply_rainforests_calibration.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to apply rainforests calibration.""" diff --git a/improver/cli/apply_reliability_calibration.py b/improver/cli/apply_reliability_calibration.py index 6080007159..4b79b2f515 100644 --- a/improver/cli/apply_reliability_calibration.py +++ b/improver/cli/apply_reliability_calibration.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to apply reliability calibration.""" diff --git a/improver/cli/between_thresholds.py b/improver/cli/between_thresholds.py index 7bcf1196bf..805856acf5 100644 --- a/improver/cli/between_thresholds.py +++ b/improver/cli/between_thresholds.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate probabilities of occurrence between thresholds.""" diff --git a/improver/cli/blend_adjacent_points.py b/improver/cli/blend_adjacent_points.py index 190030a6c4..15bed96b60 100755 --- a/improver/cli/blend_adjacent_points.py +++ b/improver/cli/blend_adjacent_points.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run weighted blending across adjacent points""" diff --git a/improver/cli/blend_cycles_and_realizations.py b/improver/cli/blend_cycles_and_realizations.py index 2dda709c24..7bc70a1de2 100755 --- a/improver/cli/blend_cycles_and_realizations.py +++ b/improver/cli/blend_cycles_and_realizations.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run weighted blending to collapse realization and forecast_reference_time @@ -12,9 +12,7 @@ @cli.clizefy @cli.with_output -def process( - *cubes: cli.inputcube, cycletime: str = None, -): +def process(*cubes: cli.inputcube, cycletime: str = None): """Runs equal-weighted blending for a specific scenario. Calculates an equal-weighted blend of input cube data across the realization and @@ -42,6 +40,6 @@ def process( for cube in cubes: cubelist.append(collapse_realizations(cube)) - plugin = WeightAndBlend("forecast_reference_time", "linear", y0val=0.5, ynval=0.5,) - cube = plugin(cubelist, cycletime=cycletime,) + plugin = WeightAndBlend("forecast_reference_time", "linear", y0val=0.5, ynval=0.5) + cube = plugin(cubelist, cycletime=cycletime) return cube diff --git a/improver/cli/blend_with_vicinity_and_rename.py b/improver/cli/blend_with_vicinity_and_rename.py index 8ce9517ee6..cc08150007 100755 --- a/improver/cli/blend_with_vicinity_and_rename.py +++ b/improver/cli/blend_with_vicinity_and_rename.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run weighted blending, with mismatched vicinity coord and new output cube name.""" diff --git a/improver/cli/calculate_forecast_bias.py b/improver/cli/calculate_forecast_bias.py index fcb61547c1..0c7ff7b649 100644 --- a/improver/cli/calculate_forecast_bias.py +++ b/improver/cli/calculate_forecast_bias.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to calculate the bias values from the specified set of reference forecasts.""" diff --git a/improver/cli/categorical.py b/improver/cli/categorical.py index 22ca6d30dd..f5ee5c3286 100755 --- a/improver/cli/categorical.py +++ b/improver/cli/categorical.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to generate categorical data.""" diff --git a/improver/cli/categorical_modes.py b/improver/cli/categorical_modes.py index 4efddb0eea..6744129ee0 100644 --- a/improver/cli/categorical_modes.py +++ b/improver/cli/categorical_modes.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to generate modal categories over periods.""" @@ -46,5 +46,5 @@ def process( raise RuntimeError("Not enough input arguments. See help for more information.") return ModalCategory( - decision_tree, model_id_attr=model_id_attr, record_run_attr=record_run_attr, + decision_tree, model_id_attr=model_id_attr, record_run_attr=record_run_attr )(cubes) diff --git a/improver/cli/clip.py b/improver/cli/clip.py index 493529be36..52fae3d027 100644 --- a/improver/cli/clip.py +++ b/improver/cli/clip.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to clip the input cube's data to be between the specified values""" @@ -10,9 +10,7 @@ @cli.clizefy @cli.with_output -def process( - cube: cli.inputcube, *, min_value: float = None, max_value: float = None, -): +def process(cube: cli.inputcube, *, min_value: float = None, max_value: float = None): """Clip the data in the input cube such that any data above max_value is set equal to max_value and any data below min_value is set equal to min_value. diff --git a/improver/cli/cloud_condensation_level.py b/improver/cli/cloud_condensation_level.py index 98b36e2974..da2dd893d0 100755 --- a/improver/cli/cloud_condensation_level.py +++ b/improver/cli/cloud_condensation_level.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to generate cloud condensation level from near-surface temperature, pressure and humidity data.""" diff --git a/improver/cli/cloud_top_temperature.py b/improver/cli/cloud_top_temperature.py index 681adfec69..fde23e2142 100755 --- a/improver/cli/cloud_top_temperature.py +++ b/improver/cli/cloud_top_temperature.py @@ -1,9 +1,10 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to generate the convective cloud top temperature from CCL and temperature profile data.""" + from improver import cli diff --git a/improver/cli/collapse_realizations.py b/improver/cli/collapse_realizations.py index f6b0b96e38..3327d14298 100644 --- a/improver/cli/collapse_realizations.py +++ b/improver/cli/collapse_realizations.py @@ -1,19 +1,16 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to collapse the realizations dimension of a cube.""" - from improver import cli @cli.clizefy @cli.with_output -def process( - cube: cli.inputcube, *, method: str = "mean", new_name: str = None, -): +def process(cube: cli.inputcube, *, method: str = "mean", new_name: str = None): """Collapse the realization dimension of a cube. Args: diff --git a/improver/cli/combine.py b/improver/cli/combine.py index 0580b25103..a2c13cd6e7 100755 --- a/improver/cli/combine.py +++ b/improver/cli/combine.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to combine netcdf data.""" diff --git a/improver/cli/compare.py b/improver/cli/compare.py index f4e550ca52..e5b77e3591 100644 --- a/improver/cli/compare.py +++ b/improver/cli/compare.py @@ -1,11 +1,10 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to compare netcdf files""" - from improver import cli from improver.constants import DEFAULT_TOLERANCE diff --git a/improver/cli/construct_reliability_tables.py b/improver/cli/construct_reliability_tables.py index 3c70e9a721..e215429176 100644 --- a/improver/cli/construct_reliability_tables.py +++ b/improver/cli/construct_reliability_tables.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to construct reliability tables for use in reliability calibration.""" diff --git a/improver/cli/convection_ratio.py b/improver/cli/convection_ratio.py index 4d9164967e..4e1f566db9 100755 --- a/improver/cli/convection_ratio.py +++ b/improver/cli/convection_ratio.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate the ratio of convective precipitation to total precipitation.""" @@ -11,7 +11,7 @@ @cli.clizefy @cli.with_output def process(*cubes: cli.inputcube, model_id_attr: str = None): - """ Calculate the convection ratio from convective and dynamic (stratiform) + """Calculate the convection ratio from convective and dynamic (stratiform) precipitation rate components. Calculates the convective ratio as: diff --git a/improver/cli/copy_attributes.py b/improver/cli/copy_attributes.py index a89a3dfa4b..30081959a5 100755 --- a/improver/cli/copy_attributes.py +++ b/improver/cli/copy_attributes.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to copy attributes from template_cube to cube""" diff --git a/improver/cli/create_grid_with_halo.py b/improver/cli/create_grid_with_halo.py index 5399afa079..50c92b0e52 100755 --- a/improver/cli/create_grid_with_halo.py +++ b/improver/cli/create_grid_with_halo.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to generate an ancillary "grid_with_halo" file.""" diff --git a/improver/cli/enforce_consistent_forecasts.py b/improver/cli/enforce_consistent_forecasts.py index 52de2d726b..27c3a6c773 100644 --- a/improver/cli/enforce_consistent_forecasts.py +++ b/improver/cli/enforce_consistent_forecasts.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to enforce consistency between two forecasts.""" diff --git a/improver/cli/estimate_dz_rescaling.py b/improver/cli/estimate_dz_rescaling.py index 733a9c4dae..c77429c57e 100755 --- a/improver/cli/estimate_dz_rescaling.py +++ b/improver/cli/estimate_dz_rescaling.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to estimate a scaling factor to account for a correction linked to the difference in altitude between the grid point and the site location.""" diff --git a/improver/cli/estimate_emos_coefficients.py b/improver/cli/estimate_emos_coefficients.py index 88b60986bc..6175444e7b 100755 --- a/improver/cli/estimate_emos_coefficients.py +++ b/improver/cli/estimate_emos_coefficients.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to estimate coefficients for Ensemble Model Output Statistics (EMOS), otherwise known as Non-homogeneous Gaussian diff --git a/improver/cli/estimate_emos_coefficients_from_table.py b/improver/cli/estimate_emos_coefficients_from_table.py index fd32bbc2fd..d6bf71cf8f 100755 --- a/improver/cli/estimate_emos_coefficients_from_table.py +++ b/improver/cli/estimate_emos_coefficients_from_table.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to estimate coefficients for Ensemble Model Output Statistics (EMOS), otherwise known as Non-homogeneous Gaussian diff --git a/improver/cli/expected_value.py b/improver/cli/expected_value.py index af3f76984c..c3a8e36c05 100644 --- a/improver/cli/expected_value.py +++ b/improver/cli/expected_value.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to calculate expected value of probability distribution.""" diff --git a/improver/cli/extend_radar_mask.py b/improver/cli/extend_radar_mask.py index 6869318ff5..6c55375cbf 100755 --- a/improver/cli/extend_radar_mask.py +++ b/improver/cli/extend_radar_mask.py @@ -1,16 +1,17 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to extend a radar mask based on coverage data.""" + from improver import cli @cli.clizefy @cli.with_output def process(cube: cli.inputcube, coverage: cli.inputcube): - """ Extend radar mask based on coverage data. + """Extend radar mask based on coverage data. Extends the mask on radar data based on the radar coverage composite. Update the mask on the input cube to reflect where coverage is valid. diff --git a/improver/cli/extract.py b/improver/cli/extract.py index 7047158be9..c2cb810cec 100755 --- a/improver/cli/extract.py +++ b/improver/cli/extract.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to extract a subset of input file data, given constraints.""" @@ -18,7 +18,7 @@ def process( units: cli.comma_separated_list = None, ignore_failure=False, ): - """ Extract a subset of a single cube. + """Extract a subset of a single cube. Extracts subset of data from a single cube, subject to equality-based constraints. diff --git a/improver/cli/extract_from_table.py b/improver/cli/extract_from_table.py index 9cbfc770f6..6469974d38 100755 --- a/improver/cli/extract_from_table.py +++ b/improver/cli/extract_from_table.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to extract values from a table.""" @@ -11,9 +11,9 @@ @cli.clizefy @cli.with_output def process( - *cubes: cli.inputcube, table: cli.inputjson, row_name: str, new_name: str = None, + *cubes: cli.inputcube, table: cli.inputjson, row_name: str, new_name: str = None ): - """ Extract values from a table based on the provided row and column cubes. + """Extract values from a table based on the provided row and column cubes. The data from the row cube is compared to the labels of the rows in the table of which the nearest lower label is selected. The same is done for the columns using the column cube. diff --git a/improver/cli/feels_like_temp.py b/improver/cli/feels_like_temp.py index d4886133e8..79aa6fb8cb 100755 --- a/improver/cli/feels_like_temp.py +++ b/improver/cli/feels_like_temp.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run the feels like temperature plugin.""" diff --git a/improver/cli/field_texture.py b/improver/cli/field_texture.py index 6e5655201d..e58ad25f12 100644 --- a/improver/cli/field_texture.py +++ b/improver/cli/field_texture.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate whether or not the input field texture exceeds a given threshold.""" @@ -17,7 +17,6 @@ def process( diagnostic_threshold: float = 0.8125, model_id_attr: str = None, ): - """Calculates field texture for a given neighbourhood radius. The field texture is an assessment of the transitions/edges within a diff --git a/improver/cli/fill_radar_holes.py b/improver/cli/fill_radar_holes.py index 576220dfa2..46b34e818b 100644 --- a/improver/cli/fill_radar_holes.py +++ b/improver/cli/fill_radar_holes.py @@ -1,16 +1,17 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to fill in small holes in the radar composite""" + from improver import cli @cli.clizefy @cli.with_output def process(cube: cli.inputcube): - """ Fill in small "no data" holes in the radar composite + """Fill in small "no data" holes in the radar composite Args: cube (iris.cube.Cube): diff --git a/improver/cli/freezing_rain.py b/improver/cli/freezing_rain.py index 5b6e8403f6..4106d18cf3 100644 --- a/improver/cli/freezing_rain.py +++ b/improver/cli/freezing_rain.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to generate freezing rain probabilities.""" diff --git a/improver/cli/generate_clearsky_solar_radiation.py b/improver/cli/generate_clearsky_solar_radiation.py index e34e5113bb..cb57d1447d 100644 --- a/improver/cli/generate_clearsky_solar_radiation.py +++ b/improver/cli/generate_clearsky_solar_radiation.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run GenerateClearSkySolarRadiation ancillary generation.""" diff --git a/improver/cli/generate_landmask_ancillary.py b/improver/cli/generate_landmask_ancillary.py index 2570c52f59..921606cce9 100755 --- a/improver/cli/generate_landmask_ancillary.py +++ b/improver/cli/generate_landmask_ancillary.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run land_sea_mask ancillary generation.""" diff --git a/improver/cli/generate_metadata_cube.py b/improver/cli/generate_metadata_cube.py index cbe5e158f2..5fcc2cfa3a 100644 --- a/improver/cli/generate_metadata_cube.py +++ b/improver/cli/generate_metadata_cube.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to generate metadata cube for acceptance tests.""" @@ -24,7 +24,7 @@ def process( domain_corner: cli.comma_separated_list_of_float = None, npoints: int = 71, ): - """ Generate a cube with metadata only. + """Generate a cube with metadata only. Args: mandatory_attributes_json (Dict): @@ -85,10 +85,9 @@ def process( if "coords" in json_input: coord_data = json_input["coords"] - ( - json_input["leading_dimension"], - json_input["cube_type"], - ) = get_leading_dimension(coord_data) + (json_input["leading_dimension"], json_input["cube_type"]) = ( + get_leading_dimension(coord_data) + ) json_input["height_levels"], json_input["pressure"] = get_height_levels( coord_data ) diff --git a/improver/cli/generate_orographic_smoothing_coefficients.py b/improver/cli/generate_orographic_smoothing_coefficients.py index 9bb528683d..33305333fd 100644 --- a/improver/cli/generate_orographic_smoothing_coefficients.py +++ b/improver/cli/generate_orographic_smoothing_coefficients.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI for generating orographic smoothing_coefficients.""" diff --git a/improver/cli/generate_percentiles.py b/improver/cli/generate_percentiles.py index 57983fa3cb..505b875299 100755 --- a/improver/cli/generate_percentiles.py +++ b/improver/cli/generate_percentiles.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to collapse cube coordinates and calculate percentiled data.""" diff --git a/improver/cli/generate_realizations.py b/improver/cli/generate_realizations.py index 62e76c562d..657b0f3a92 100644 --- a/improver/cli/generate_realizations.py +++ b/improver/cli/generate_realizations.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Convert NetCDF files to realizations.""" diff --git a/improver/cli/generate_solar_time.py b/improver/cli/generate_solar_time.py index ff397fa288..8caf82e30d 100644 --- a/improver/cli/generate_solar_time.py +++ b/improver/cli/generate_solar_time.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run GenerateSolarTime ancillary generation.""" diff --git a/improver/cli/generate_topography_bands_mask.py b/improver/cli/generate_topography_bands_mask.py index 4665779f7f..e896c64f80 100755 --- a/improver/cli/generate_topography_bands_mask.py +++ b/improver/cli/generate_topography_bands_mask.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run topographic bands mask generation.""" diff --git a/improver/cli/generate_topography_bands_weights.py b/improver/cli/generate_topography_bands_weights.py index 17239291f3..887bcc1266 100755 --- a/improver/cli/generate_topography_bands_weights.py +++ b/improver/cli/generate_topography_bands_weights.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run topographic bands weights generation.""" diff --git a/improver/cli/gradient_between_vertical_levels.py b/improver/cli/gradient_between_vertical_levels.py index 96d655cdcc..896966ec4c 100644 --- a/improver/cli/gradient_between_vertical_levels.py +++ b/improver/cli/gradient_between_vertical_levels.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to calculate a gradient between two vertical levels.""" diff --git a/improver/cli/hail_fraction.py b/improver/cli/hail_fraction.py index ad174e3f7f..b6f87d7801 100644 --- a/improver/cli/hail_fraction.py +++ b/improver/cli/hail_fraction.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate a hail fraction.""" diff --git a/improver/cli/hail_size.py b/improver/cli/hail_size.py index fab8cd7c2e..aa94725139 100644 --- a/improver/cli/hail_size.py +++ b/improver/cli/hail_size.py @@ -1,9 +1,10 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to generate hail size.""" + from improver import cli diff --git a/improver/cli/height_of_max_vertical_velocity.py b/improver/cli/height_of_max_vertical_velocity.py index 67972877b4..9df01648e5 100644 --- a/improver/cli/height_of_max_vertical_velocity.py +++ b/improver/cli/height_of_max_vertical_velocity.py @@ -1,10 +1,10 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate the height at which the maximum vertical velocity -occurs. """ +occurs.""" from improver import cli diff --git a/improver/cli/integrate_time_bounds.py b/improver/cli/integrate_time_bounds.py index 84ae4739ed..3ba5aaa45e 100755 --- a/improver/cli/integrate_time_bounds.py +++ b/improver/cli/integrate_time_bounds.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to multiply period average values by the period.""" diff --git a/improver/cli/interpolate_using_difference.py b/improver/cli/interpolate_using_difference.py index ca3e0ec0fe..447c0aee84 100644 --- a/improver/cli/interpolate_using_difference.py +++ b/improver/cli/interpolate_using_difference.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to fill masked regions in a field using interpolation of the difference between it and a reference field.""" @@ -54,6 +54,6 @@ def process( from improver.utilities.interpolation import InterpolateUsingDifference result = InterpolateUsingDifference(limit_as_maximum=limit_as_maximum)( - cube, reference_cube=reference_cube, limit=limit, + cube, reference_cube=reference_cube, limit=limit ) return result diff --git a/improver/cli/interpret_metadata.py b/improver/cli/interpret_metadata.py index 45e7e567ce..f785d34461 100644 --- a/improver/cli/interpret_metadata.py +++ b/improver/cli/interpret_metadata.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to interpret the metadata of an IMPROVER output.""" diff --git a/improver/cli/lightning_from_cape_and_precip.py b/improver/cli/lightning_from_cape_and_precip.py index 0db79ec8bf..43d1d1d4e7 100755 --- a/improver/cli/lightning_from_cape_and_precip.py +++ b/improver/cli/lightning_from_cape_and_precip.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to apply latitude-dependent thresholding to a parameter dataset.""" @@ -10,9 +10,7 @@ @cli.clizefy @cli.with_output -def process( - *cubes: cli.inputcube, model_id_attr: str = None, -): +def process(*cubes: cli.inputcube, model_id_attr: str = None): """ Apply latitude-dependent thresholds to CAPE and precipitation rate to derive a probability-of-lightning cube. diff --git a/improver/cli/lightning_multivariate_probability_usaf2024.py b/improver/cli/lightning_multivariate_probability_usaf2024.py index 62ce745ff8..76dd77792d 100755 --- a/improver/cli/lightning_multivariate_probability_usaf2024.py +++ b/improver/cli/lightning_multivariate_probability_usaf2024.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to create lightning probabilities from multi-parameter datasets.""" @@ -10,9 +10,7 @@ @cli.clizefy @cli.with_output -def process( - *cubes: cli.inputcube, model_id_attr: str = None, -): +def process(*cubes: cli.inputcube, model_id_attr: str = None): """ From the supplied following cubes: Convective Available Potential Energy (CAPE in J/kg), diff --git a/improver/cli/manipulate_reliability_table.py b/improver/cli/manipulate_reliability_table.py index 2e1ccba1af..7198d4cf04 100644 --- a/improver/cli/manipulate_reliability_table.py +++ b/improver/cli/manipulate_reliability_table.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to manipulate a reliability table cube.""" @@ -45,6 +45,6 @@ def process( from improver.calibration.reliability_calibration import ManipulateReliabilityTable plugin = ManipulateReliabilityTable( - minimum_forecast_count=minimum_forecast_count, point_by_point=point_by_point, + minimum_forecast_count=minimum_forecast_count, point_by_point=point_by_point ) return plugin(reliability_table) diff --git a/improver/cli/max_in_height.py b/improver/cli/max_in_height.py index a868dadbdb..65ff91ca19 100644 --- a/improver/cli/max_in_height.py +++ b/improver/cli/max_in_height.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate the maximum over the height coordinate""" diff --git a/improver/cli/max_in_time_window.py b/improver/cli/max_in_time_window.py index 2d724bdd0d..5b0f1bc1b2 100755 --- a/improver/cli/max_in_time_window.py +++ b/improver/cli/max_in_time_window.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to compute the maximum within a time window for a period diagnostic.""" diff --git a/improver/cli/merge.py b/improver/cli/merge.py index eea62178e9..3d0747ff2f 100755 --- a/improver/cli/merge.py +++ b/improver/cli/merge.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to merge the input files into a single file.""" diff --git a/improver/cli/nbhood.py b/improver/cli/nbhood.py index fc4fe6df9a..010708ea3f 100755 --- a/improver/cli/nbhood.py +++ b/improver/cli/nbhood.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run neighbourhood processing.""" diff --git a/improver/cli/nbhood_iterate_with_mask.py b/improver/cli/nbhood_iterate_with_mask.py index c013db7bea..fdc3c1e08d 100755 --- a/improver/cli/nbhood_iterate_with_mask.py +++ b/improver/cli/nbhood_iterate_with_mask.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run neighbourhooding processing when iterating over a coordinate defining a series of masks.""" diff --git a/improver/cli/nbhood_land_and_sea.py b/improver/cli/nbhood_land_and_sea.py index c65acad6e6..f8cf21d222 100755 --- a/improver/cli/nbhood_land_and_sea.py +++ b/improver/cli/nbhood_land_and_sea.py @@ -1,11 +1,12 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run neighbourhooding processing over areas of land and sea separately before combining them to return unified fields. Topographic zones may also be employed, with the sea area being treated as a distinct zone.""" + from improver import cli @@ -21,7 +22,7 @@ def process( lead_times: cli.comma_separated_list = None, area_sum=False, ): - """ Module to process land and sea separately before combining them. + """Module to process land and sea separately before combining them. Neighbourhood the input dataset over two distinct regions of land and sea. If performed as a single level neighbourhood, a land-sea mask should be @@ -89,7 +90,6 @@ def process( if any( "topographic_zone" in coord.name() for coord in mask.coords(dim_coords=True) ): - if mask.attributes["topographic_zones_include_seapoints"] == "True": raise ValueError( "The topographic zones mask cube must have been " diff --git a/improver/cli/neighbour_finding.py b/improver/cli/neighbour_finding.py index e5beb59f85..c708654ec9 100755 --- a/improver/cli/neighbour_finding.py +++ b/improver/cli/neighbour_finding.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to create neighbour cubes for extracting spot data.""" diff --git a/improver/cli/normalise_to_reference.py b/improver/cli/normalise_to_reference.py index 049a51fc5f..3b6befebbc 100644 --- a/improver/cli/normalise_to_reference.py +++ b/improver/cli/normalise_to_reference.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to enforce the sum total of a set of forecasts to be equal to a reference.""" diff --git a/improver/cli/nowcast_accumulate.py b/improver/cli/nowcast_accumulate.py index 4c0a7a6944..5376333c3f 100755 --- a/improver/cli/nowcast_accumulate.py +++ b/improver/cli/nowcast_accumulate.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to accumulate input data given advection velocity fields.""" diff --git a/improver/cli/nowcast_extrapolate.py b/improver/cli/nowcast_extrapolate.py index eacee60098..95edbf2418 100755 --- a/improver/cli/nowcast_extrapolate.py +++ b/improver/cli/nowcast_extrapolate.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to extrapolate input data given advection velocity fields.""" diff --git a/improver/cli/nowcast_optical_flow.py b/improver/cli/nowcast_optical_flow.py index 95ff453e01..540a939dca 100755 --- a/improver/cli/nowcast_optical_flow.py +++ b/improver/cli/nowcast_optical_flow.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate optical flow advection velocities with option to extrapolate.""" @@ -11,9 +11,7 @@ @cli.clizefy @cli.with_output -def process( - orographic_enhancement: cli.inputcube, *cubes: cli.inputcube, -): +def process(orographic_enhancement: cli.inputcube, *cubes: cli.inputcube): """Calculate optical flow components from input fields. Args: diff --git a/improver/cli/nowcast_optical_flow_from_winds.py b/improver/cli/nowcast_optical_flow_from_winds.py index 90df1adeac..47f6c48a08 100644 --- a/improver/cli/nowcast_optical_flow_from_winds.py +++ b/improver/cli/nowcast_optical_flow_from_winds.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate optical flow components as perturbations from model steering flow""" @@ -10,7 +10,7 @@ # Creates the value_converter that clize needs. inputflow = cli.create_constrained_inputcubelist_converter( - "grid_eastward_wind", "grid_northward_wind", + "grid_eastward_wind", "grid_northward_wind" ) diff --git a/improver/cli/orographic_enhancement.py b/improver/cli/orographic_enhancement.py index ba436fcf48..beefd91dfd 100755 --- a/improver/cli/orographic_enhancement.py +++ b/improver/cli/orographic_enhancement.py @@ -1,11 +1,10 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate orographic enhancement.""" - from improver import cli diff --git a/improver/cli/phase_change_level.py b/improver/cli/phase_change_level.py index a8ba82157d..658e704bb4 100755 --- a/improver/cli/phase_change_level.py +++ b/improver/cli/phase_change_level.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate continuous phase change level.""" diff --git a/improver/cli/phase_mask.py b/improver/cli/phase_mask.py index d3ccc5128b..a3e5de8de7 100644 --- a/improver/cli/phase_mask.py +++ b/improver/cli/phase_mask.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Interface to significant_phase_mask.""" diff --git a/improver/cli/phase_probability.py b/improver/cli/phase_probability.py index b572de64de..44cd105b7f 100644 --- a/improver/cli/phase_probability.py +++ b/improver/cli/phase_probability.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Interface to precip_phase_probability.""" diff --git a/improver/cli/recursive_filter.py b/improver/cli/recursive_filter.py index 7148a40c25..f52c4792e6 100755 --- a/improver/cli/recursive_filter.py +++ b/improver/cli/recursive_filter.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to apply a recursive filter to neighbourhooded data.""" diff --git a/improver/cli/regrid.py b/improver/cli/regrid.py index 92f7f08d4e..3f1b51eabb 100644 --- a/improver/cli/regrid.py +++ b/improver/cli/regrid.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to regrid a NetCDF file""" diff --git a/improver/cli/relabel_to_period.py b/improver/cli/relabel_to_period.py index 7e46d6ff24..09c95c0d6c 100644 --- a/improver/cli/relabel_to_period.py +++ b/improver/cli/relabel_to_period.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to relabel a diagnostic as a period diagnostic.""" diff --git a/improver/cli/remake_as_shower_condition.py b/improver/cli/remake_as_shower_condition.py index ac1ebcd43b..6dac8eeb72 100644 --- a/improver/cli/remake_as_shower_condition.py +++ b/improver/cli/remake_as_shower_condition.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to modify a suitable shower condition proxy diagnostic into a shower condition cube.""" diff --git a/improver/cli/resolve_wind_components.py b/improver/cli/resolve_wind_components.py index 223de7c7ac..17f09cb733 100644 --- a/improver/cli/resolve_wind_components.py +++ b/improver/cli/resolve_wind_components.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Convert wind speed and direction into individual velocity components.""" diff --git a/improver/cli/shower_condition_probability.py b/improver/cli/shower_condition_probability.py index 9e0086ef15..34fa72ca00 100644 --- a/improver/cli/shower_condition_probability.py +++ b/improver/cli/shower_condition_probability.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate a probability of precipitation being showery if present.""" diff --git a/improver/cli/sleet_probability.py b/improver/cli/sleet_probability.py index 8a56d689ca..992e5e2563 100644 --- a/improver/cli/sleet_probability.py +++ b/improver/cli/sleet_probability.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate sleet probability.""" diff --git a/improver/cli/snow_fraction.py b/improver/cli/snow_fraction.py index 1ffa208826..8e6389a54a 100644 --- a/improver/cli/snow_fraction.py +++ b/improver/cli/snow_fraction.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Interface to snow_fraction.""" diff --git a/improver/cli/snow_splitter.py b/improver/cli/snow_splitter.py index ff78126297..984bcd7514 100644 --- a/improver/cli/snow_splitter.py +++ b/improver/cli/snow_splitter.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI for SnowSplitter""" diff --git a/improver/cli/spot_extract.py b/improver/cli/spot_extract.py index 69b5daf88b..6fe168940c 100755 --- a/improver/cli/spot_extract.py +++ b/improver/cli/spot_extract.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run spotdata extraction.""" diff --git a/improver/cli/standardise.py b/improver/cli/standardise.py index c0ba513440..e51ae2b6ca 100755 --- a/improver/cli/standardise.py +++ b/improver/cli/standardise.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to standardise a NetCDF file by updating metadata and demoting float64 data to float32""" diff --git a/improver/cli/temp_lapse_rate.py b/improver/cli/temp_lapse_rate.py index f9daa47dc8..ea16c0da30 100755 --- a/improver/cli/temp_lapse_rate.py +++ b/improver/cli/temp_lapse_rate.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate temperature lapse rates for given temperature and orogrophy datasets.""" diff --git a/improver/cli/temporal_interpolate.py b/improver/cli/temporal_interpolate.py index f3ed9341f3..c36a000256 100755 --- a/improver/cli/temporal_interpolate.py +++ b/improver/cli/temporal_interpolate.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to interpolate data between validity times""" diff --git a/improver/cli/threshold.py b/improver/cli/threshold.py index f2dd37fa8f..6294d6cc8c 100755 --- a/improver/cli/threshold.py +++ b/improver/cli/threshold.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to apply thresholding to a parameter dataset.""" diff --git a/improver/cli/time_lagged_ensembles.py b/improver/cli/time_lagged_ensembles.py index f76c1c77e2..22fde44e19 100755 --- a/improver/cli/time_lagged_ensembles.py +++ b/improver/cli/time_lagged_ensembles.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run time-lagged ensembles.""" diff --git a/improver/cli/uv_index.py b/improver/cli/uv_index.py index 45af0c4d38..257525e139 100755 --- a/improver/cli/uv_index.py +++ b/improver/cli/uv_index.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run the UV index plugin.""" diff --git a/improver/cli/vertical_updraught.py b/improver/cli/vertical_updraught.py index d2fafb9571..2c1212d08e 100755 --- a/improver/cli/vertical_updraught.py +++ b/improver/cli/vertical_updraught.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to generate maximum vertical updraught from CAPE and max precip rate data.""" diff --git a/improver/cli/vicinity.py b/improver/cli/vicinity.py index 4f4515a714..80312e505a 100755 --- a/improver/cli/vicinity.py +++ b/improver/cli/vicinity.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to apply vicinity neighbourhoods to data.""" diff --git a/improver/cli/visibility_combine_cloud_base.py b/improver/cli/visibility_combine_cloud_base.py index 8a21729718..cea5db300d 100644 --- a/improver/cli/visibility_combine_cloud_base.py +++ b/improver/cli/visibility_combine_cloud_base.py @@ -1,9 +1,10 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to combine visibility and cloud bases""" + from improver import cli diff --git a/improver/cli/weighted_blending.py b/improver/cli/weighted_blending.py index 32abb7ae31..e8da71b290 100755 --- a/improver/cli/weighted_blending.py +++ b/improver/cli/weighted_blending.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run weighted blending.""" diff --git a/improver/cli/wet_bulb_freezing_level.py b/improver/cli/wet_bulb_freezing_level.py index e8447c3286..d86038cd5c 100644 --- a/improver/cli/wet_bulb_freezing_level.py +++ b/improver/cli/wet_bulb_freezing_level.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to extract wet-bulb freezing level from wet-bulb temperature on height levels""" diff --git a/improver/cli/wet_bulb_temperature.py b/improver/cli/wet_bulb_temperature.py index bd8b74248a..f7b51b4556 100755 --- a/improver/cli/wet_bulb_temperature.py +++ b/improver/cli/wet_bulb_temperature.py @@ -1,10 +1,10 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """CLI to generate wet bulb temperatures from air temperature, relative - humidity, and pressure data. """ +humidity, and pressure data.""" from improver import cli diff --git a/improver/cli/wet_bulb_temperature_integral.py b/improver/cli/wet_bulb_temperature_integral.py index 9e1c8ee806..a0e16385c5 100644 --- a/improver/cli/wet_bulb_temperature_integral.py +++ b/improver/cli/wet_bulb_temperature_integral.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate wet bulb temperature integral.""" diff --git a/improver/cli/wind_direction.py b/improver/cli/wind_direction.py index f58f35e8f0..1f2c36e27d 100755 --- a/improver/cli/wind_direction.py +++ b/improver/cli/wind_direction.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to calculate mean wind direction from ensemble realizations.""" diff --git a/improver/cli/wind_downscaling.py b/improver/cli/wind_downscaling.py index 5c59d2ccfc..6e2e17121d 100755 --- a/improver/cli/wind_downscaling.py +++ b/improver/cli/wind_downscaling.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to run wind downscaling.""" diff --git a/improver/cli/wind_gust_diagnostic.py b/improver/cli/wind_gust_diagnostic.py index 6131d4166e..1b84f197d4 100755 --- a/improver/cli/wind_gust_diagnostic.py +++ b/improver/cli/wind_gust_diagnostic.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Script to create wind-gust data.""" diff --git a/improver/constants.py b/improver/constants.py index 6b8e7cc05c..78e31fb17b 100644 --- a/improver/constants.py +++ b/improver/constants.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to contain generally useful constants.""" diff --git a/improver/cube_combiner.py b/improver/cube_combiner.py index 6968ed8146..d4b26febd0 100644 --- a/improver/cube_combiner.py +++ b/improver/cube_combiner.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing plugins for combining cubes""" @@ -206,7 +206,7 @@ def __init__( @staticmethod def _check_dimensions_match( - cube_list: Union[List[Cube], CubeList], comparators: List[Callable] = [eq], + cube_list: Union[List[Cube], CubeList], comparators: List[Callable] = [eq] ) -> None: """ Check all coordinate dimensions on the input cubes match according to @@ -400,7 +400,7 @@ def _coords_are_broadcastable(coord1: DimCoord, coord2: DimCoord) -> bool: ) def process( - self, cube_list: Union[List[Cube], CubeList], new_diagnostic_name: str, + self, cube_list: Union[List[Cube], CubeList], new_diagnostic_name: str ) -> Cube: """ Combine data and metadata from a list of input cubes into a single diff --git a/improver/developer_tools/metadata_interpreter.py b/improver/developer_tools/metadata_interpreter.py index 3fc532cc61..b03e4bdd12 100644 --- a/improver/developer_tools/metadata_interpreter.py +++ b/improver/developer_tools/metadata_interpreter.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing classes for metadata interpretation""" diff --git a/improver/ensemble_copula_coupling/_scipy_continuous_distns.py b/improver/ensemble_copula_coupling/_scipy_continuous_distns.py index c78d21264e..bcd6bd02aa 100644 --- a/improver/ensemble_copula_coupling/_scipy_continuous_distns.py +++ b/improver/ensemble_copula_coupling/_scipy_continuous_distns.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ This module defines the truncnorm as per scipy v1.3.3 to overcome performance @@ -9,6 +9,7 @@ - https://github.com/scipy/scipy/issues/12733 """ + import numpy as np import scipy.special as sc from scipy.stats._distn_infrastructure import rv_continuous @@ -61,11 +62,11 @@ def _norm_pdf(x): - return np.exp(-(x ** 2) / 2.0) / _norm_pdf_C + return np.exp(-(x**2) / 2.0) / _norm_pdf_C def _norm_logpdf(x): - return -(x ** 2) / 2.0 - _norm_pdf_logC + return -(x**2) / 2.0 - _norm_pdf_logC def _norm_cdf(x): diff --git a/improver/ensemble_copula_coupling/constants.py b/improver/ensemble_copula_coupling/constants.py index 6d6587e1fd..b7497290bb 100644 --- a/improver/ensemble_copula_coupling/constants.py +++ b/improver/ensemble_copula_coupling/constants.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to contain constants used for Ensemble Copula Coupling.""" diff --git a/improver/ensemble_copula_coupling/ensemble_copula_coupling.py b/improver/ensemble_copula_coupling/ensemble_copula_coupling.py index f49fd47b73..56be3c33ee 100644 --- a/improver/ensemble_copula_coupling/ensemble_copula_coupling.py +++ b/improver/ensemble_copula_coupling/ensemble_copula_coupling.py @@ -1,11 +1,12 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ This module defines the plugins required for Ensemble Copula Coupling. """ + import warnings from typing import List, Optional, Tuple @@ -352,11 +353,12 @@ def _interpolate_percentiles( bounds_pairing = get_bounds_of_distribution( forecast_at_percentiles.name(), cube_units ) - ( - original_percentiles, - forecast_at_reshaped_percentiles, - ) = self._add_bounds_to_percentiles_and_forecast_at_percentiles( - original_percentiles, forecast_at_reshaped_percentiles, bounds_pairing + (original_percentiles, forecast_at_reshaped_percentiles) = ( + self._add_bounds_to_percentiles_and_forecast_at_percentiles( + original_percentiles, + forecast_at_reshaped_percentiles, + bounds_pairing, + ) ) forecast_at_interpolated_percentiles = interpolate_multiple_rows_same_x( @@ -379,7 +381,7 @@ def _interpolate_percentiles( template_cube = next(forecast_at_percentiles.slices_over(percentile_coord_name)) template_cube.remove_coord(percentile_coord_name) percentile_cube = create_cube_with_percentiles( - desired_percentiles, template_cube, forecast_at_percentiles_data, + desired_percentiles, template_cube, forecast_at_percentiles_data ) if original_mask is not None: original_mask = np.broadcast_to(original_mask, percentile_cube.shape) @@ -449,7 +451,7 @@ def process( ) forecast_at_percentiles = self._interpolate_percentiles( - forecast_at_percentiles, percentiles, percentile_coord.name(), + forecast_at_percentiles, percentiles, percentile_coord.name() ) return forecast_at_percentiles @@ -577,15 +579,17 @@ def _add_bounds_to_thresholds_and_probabilities( upper_bound = max(threshold_points_with_endpoints) if lower_bound > min(threshold_points_with_endpoints): lower_bound = min(threshold_points_with_endpoints) - threshold_points_with_endpoints = insert_lower_and_upper_endpoint_to_1d_array( - threshold_points, lower_bound, upper_bound + threshold_points_with_endpoints = ( + insert_lower_and_upper_endpoint_to_1d_array( + threshold_points, lower_bound, upper_bound + ) ) else: raise ValueError(msg) return threshold_points_with_endpoints, probabilities_for_cdf def _probabilities_to_percentiles( - self, forecast_probabilities: Cube, percentiles: ndarray, + self, forecast_probabilities: Cube, percentiles: ndarray ) -> Cube: """ Conversion of probabilities to percentiles through the construction @@ -654,11 +658,10 @@ def _probabilities_to_percentiles( ) cube_units = forecast_probabilities.coord(threshold_coord.name()).units bounds_pairing = get_bounds_of_distribution(phenom_name, cube_units) - ( - threshold_points, - probabilities_for_cdf, - ) = self._add_bounds_to_thresholds_and_probabilities( - threshold_points, probabilities_for_cdf, bounds_pairing + (threshold_points, probabilities_for_cdf) = ( + self._add_bounds_to_thresholds_and_probabilities( + threshold_points, probabilities_for_cdf, bounds_pairing + ) ) if np.any(np.diff(probabilities_for_cdf) < 0): @@ -773,8 +776,9 @@ def process( """ if no_of_percentiles is not None and percentiles is not None: raise ValueError( - "Cannot specify both no_of_percentiles and percentiles to " - "{}".format(self.__class__.__name__) + "Cannot specify both no_of_percentiles and percentiles to " "{}".format( + self.__class__.__name__ + ) ) threshold_coord = find_threshold_coordinate(forecast_probabilities) @@ -820,7 +824,7 @@ class ConvertLocationAndScaleParameters: """ def __init__( - self, distribution: str = "norm", shape_parameters: Optional[ndarray] = None, + self, distribution: str = "norm", shape_parameters: Optional[ndarray] = None ) -> None: """ Initialise the class. @@ -1087,8 +1091,10 @@ def process( if no_of_percentiles: percentiles = choose_set_of_percentiles(no_of_percentiles) - calibrated_forecast_percentiles = self._location_and_scale_parameters_to_percentiles( - location_parameter, scale_parameter, template_cube, percentiles + calibrated_forecast_percentiles = ( + self._location_and_scale_parameters_to_percentiles( + location_parameter, scale_parameter, template_cube, percentiles + ) ) return calibrated_forecast_percentiles @@ -1472,7 +1478,6 @@ def _check_input_cube_masks(post_processed_forecast, raw_forecast): ): for aslice in post_processed_forecast.data.mask[1:, ...]: if np.any(aslice != post_processed_forecast.data.mask[0]): - message = ( "The post_processed_forecast does not have same" " mask on all x-y slices" diff --git a/improver/ensemble_copula_coupling/numba_utilities.py b/improver/ensemble_copula_coupling/numba_utilities.py index 8d80d770b3..dccf2be21c 100644 --- a/improver/ensemble_copula_coupling/numba_utilities.py +++ b/improver/ensemble_copula_coupling/numba_utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ This module defines the optional numba utilities for Ensemble Copula Coupling diff --git a/improver/ensemble_copula_coupling/utilities.py b/improver/ensemble_copula_coupling/utilities.py index fbf228722a..1beb1e1a2c 100644 --- a/improver/ensemble_copula_coupling/utilities.py +++ b/improver/ensemble_copula_coupling/utilities.py @@ -1,12 +1,13 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ This module defines the utilities required for Ensemble Copula Coupling plugins. """ + import warnings from typing import List, Optional, Union @@ -21,7 +22,7 @@ def concatenate_2d_array_with_2d_array_endpoints( - array_2d: ndarray, low_endpoint: float, high_endpoint: float, + array_2d: ndarray, low_endpoint: float, high_endpoint: float ) -> ndarray: """ For a 2d array, add a 2d array as the lower and upper endpoints. diff --git a/improver/expected_value.py b/improver/expected_value.py index 1d0264e74f..e217a360a1 100644 --- a/improver/expected_value.py +++ b/improver/expected_value.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Calculation of expected value from a probability distribution.""" diff --git a/improver/feels_like_temperature.py b/improver/feels_like_temperature.py index e0460d107b..e28a9a525e 100644 --- a/improver/feels_like_temperature.py +++ b/improver/feels_like_temperature.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing feels like temperature calculation plugins""" diff --git a/improver/generate_ancillaries/__init__.py b/improver/generate_ancillaries/__init__.py index f11a0270d7..4cc15b9341 100644 --- a/improver/generate_ancillaries/__init__.py +++ b/improver/generate_ancillaries/__init__.py @@ -1,4 +1,4 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. diff --git a/improver/generate_ancillaries/generate_ancillary.py b/improver/generate_ancillaries/generate_ancillary.py index 37e21cdf86..bb1cd5f68b 100644 --- a/improver/generate_ancillaries/generate_ancillary.py +++ b/improver/generate_ancillaries/generate_ancillary.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing ancillary generation utilities for Improver""" @@ -299,7 +299,7 @@ def process( "bounds": list of list of pairs of bounds for each band and "units":"string containing units of bounds", for example:: - {'bounds':[[0,100], [100,200]], 'units': "m"} + {"bounds": [[0, 100], [100, 200]], "units": "m"} landmask: land mask on standard grid, with land points set to one and diff --git a/improver/generate_ancillaries/generate_derived_solar_fields.py b/improver/generate_ancillaries/generate_derived_solar_fields.py index 2f55d7cf73..f05e486db7 100644 --- a/improver/generate_ancillaries/generate_derived_solar_fields.py +++ b/improver/generate_ancillaries/generate_derived_solar_fields.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module for generating derived solar fields.""" + import warnings from datetime import datetime, timedelta, timezone from typing import List, Optional, Tuple, Union @@ -387,7 +388,6 @@ def _calc_clearsky_solar_radiation_data( ) for time_index, time_step in enumerate(irradiance_times): - day_of_year = get_day_of_year(time_step) utc_hour = get_hour_of_day(time_step) diff --git a/improver/generate_ancillaries/generate_orographic_smoothing_coefficients.py b/improver/generate_ancillaries/generate_orographic_smoothing_coefficients.py index 904f74a02a..57fdd4238b 100644 --- a/improver/generate_ancillaries/generate_orographic_smoothing_coefficients.py +++ b/improver/generate_ancillaries/generate_orographic_smoothing_coefficients.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """A module for creating orographic smoothing coefficients""" @@ -20,7 +20,6 @@ class OrographicSmoothingCoefficients(BasePlugin): - """ Class to generate smoothing coefficients for recursive filtering based on orography gradients. diff --git a/improver/generate_ancillaries/generate_svp_table.py b/improver/generate_ancillaries/generate_svp_table.py index 152c86443f..101ede34f8 100644 --- a/improver/generate_ancillaries/generate_svp_table.py +++ b/improver/generate_ancillaries/generate_svp_table.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """A module for creating a saturated vapour pressure table""" @@ -16,7 +16,6 @@ class SaturatedVapourPressureTable(BasePlugin): - """ Plugin to create a saturated vapour pressure lookup table. """ diff --git a/improver/generate_ancillaries/generate_topographic_zone_weights.py b/improver/generate_ancillaries/generate_topographic_zone_weights.py index abe99e6ef7..43c4bae0d4 100644 --- a/improver/generate_ancillaries/generate_topographic_zone_weights.py +++ b/improver/generate_ancillaries/generate_topographic_zone_weights.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module for generating the weights for topographic zones.""" @@ -22,7 +22,6 @@ class GenerateTopographicZoneWeights(BasePlugin): - """Generate weights generated by determining where the orography lies within the topographic zones.""" diff --git a/improver/grids.py b/improver/grids.py index 6c9f17e0c4..b73f0129aa 100644 --- a/improver/grids.py +++ b/improver/grids.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to contain standard grid projection definitions.""" diff --git a/improver/lapse_rate.py b/improver/lapse_rate.py index 7c562a6d7c..394d643e18 100644 --- a/improver/lapse_rate.py +++ b/improver/lapse_rate.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing lapse rate calculation plugins.""" diff --git a/improver/lightning.py b/improver/lightning.py index 3fb93528f4..2a01afc87d 100644 --- a/improver/lightning.py +++ b/improver/lightning.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing lightning classes.""" + from datetime import timedelta from typing import Tuple, Union @@ -164,7 +165,7 @@ def process(self, *cubes: Union[Cube, CubeList]) -> Cube: def latitude_to_threshold( - latitude: np.ndarray, midlatitude: float, tropics: float, + latitude: np.ndarray, midlatitude: float, tropics: float ) -> np.ndarray: """ Rescale a latitude range into a range of threshold values suitable for @@ -277,7 +278,7 @@ def _get_inputs(self, cubes: CubeList) -> Tuple[Cube, Cube]: for input_name, units in input_names.items(): output_cubes.append(self._extract_input(cubes, input_name)) - if not output_cubes[-1].units in units: + if output_cubes[-1].units not in units: expected_unit_string = " or ".join(map(str, units)) received_unit_string = str(output_cubes[-1].units) raise ValueError( diff --git a/improver/memprofile.py b/improver/memprofile.py index 9182033499..93bdfa8b01 100644 --- a/improver/memprofile.py +++ b/improver/memprofile.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing maximum memory profiling utilities.""" diff --git a/improver/metadata/amend.py b/improver/metadata/amend.py index f4c0b8fe9e..5d9da6741e 100644 --- a/improver/metadata/amend.py +++ b/improver/metadata/amend.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing utilities for modifying cube metadata""" + import re from datetime import datetime, timedelta, timezone from typing import Any, Dict, List, Tuple, Union @@ -148,7 +149,7 @@ def update_diagnostic_name(source_cube: Cube, new_diagnostic_name: str, result: def _update_cell_methods( - cell_methods: Tuple[CellMethod], original_name: str, new_diagnostic_name: str, + cell_methods: Tuple[CellMethod], original_name: str, new_diagnostic_name: str ) -> List[CellMethod]: """ Update any cell methods that include a comment that refers to the diff --git a/improver/metadata/check_datatypes.py b/improver/metadata/check_datatypes.py index cfbaa982f7..5143536575 100644 --- a/improver/metadata/check_datatypes.py +++ b/improver/metadata/check_datatypes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Utilities for mandatory datatype and units checking""" diff --git a/improver/metadata/constants/__init__.py b/improver/metadata/constants/__init__.py index ab3112ba36..bb255347c1 100644 --- a/improver/metadata/constants/__init__.py +++ b/improver/metadata/constants/__init__.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Constants associated with metadata""" diff --git a/improver/metadata/constants/attributes.py b/improver/metadata/constants/attributes.py index e24f82ba10..d5ea2f47da 100644 --- a/improver/metadata/constants/attributes.py +++ b/improver/metadata/constants/attributes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Defaults for mandatory attributes""" diff --git a/improver/metadata/constants/mo_attributes.py b/improver/metadata/constants/mo_attributes.py index 97927340a1..548b4b662d 100644 --- a/improver/metadata/constants/mo_attributes.py +++ b/improver/metadata/constants/mo_attributes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module defining Met Office specific attributes""" diff --git a/improver/metadata/constants/time_types.py b/improver/metadata/constants/time_types.py index 874dfd9078..a6ebb4fa84 100644 --- a/improver/metadata/constants/time_types.py +++ b/improver/metadata/constants/time_types.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Expected datatypes and units for time-type coordinates""" diff --git a/improver/metadata/forecast_times.py b/improver/metadata/forecast_times.py index f05c9ec6ce..b22946cf76 100644 --- a/improver/metadata/forecast_times.py +++ b/improver/metadata/forecast_times.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Utilities to manipulate forecast time coordinates""" diff --git a/improver/metadata/probabilistic.py b/improver/metadata/probabilistic.py index 6d85bc8358..3478be1110 100644 --- a/improver/metadata/probabilistic.py +++ b/improver/metadata/probabilistic.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Utilities for interrogating IMPROVER probabilistic metadata""" @@ -144,8 +144,9 @@ def find_threshold_coordinate(cube: Cube) -> Coord: """ if not isinstance(cube, iris.cube.Cube): msg = ( - "Expecting data to be an instance of " - "iris.cube.Cube but is {0}.".format(type(cube)) + "Expecting data to be an instance of " "iris.cube.Cube but is {0}.".format( + type(cube) + ) ) raise TypeError(msg) @@ -225,8 +226,9 @@ def find_percentile_coordinate(cube: Cube) -> Coord: """ if not isinstance(cube, iris.cube.Cube): msg = ( - "Expecting data to be an instance of " - "iris.cube.Cube but is {0}.".format(type(cube)) + "Expecting data to be an instance of " "iris.cube.Cube but is {0}.".format( + type(cube) + ) ) raise TypeError(msg) standard_name = cube.name() diff --git a/improver/metadata/utilities.py b/improver/metadata/utilities.py index ffbd131f0a..3de37a85c9 100644 --- a/improver/metadata/utilities.py +++ b/improver/metadata/utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """General IMPROVER metadata utilities""" diff --git a/improver/nbhood/__init__.py b/improver/nbhood/__init__.py index 9b2ea569ce..88a0b20c97 100644 --- a/improver/nbhood/__init__.py +++ b/improver/nbhood/__init__.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """init for nbhood""" diff --git a/improver/nbhood/nbhood.py b/improver/nbhood/nbhood.py index d69a799895..c88b8d0a13 100644 --- a/improver/nbhood/nbhood.py +++ b/improver/nbhood/nbhood.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing neighbourhood processing utilities.""" @@ -83,11 +83,11 @@ def circular_kernel(ranges: int, weighted_mode: bool) -> ndarray: # Create a kernel, such that the central grid point has the # highest weighting, with the weighting decreasing with distance # away from the central grid point. - open_grid_summed_squared = np.sum(open_grid ** 2.0).astype(float) + open_grid_summed_squared = np.sum(open_grid**2.0).astype(float) kernel[:] = (area - open_grid_summed_squared) / area mask = kernel < 0.0 else: - mask = np.reshape(np.sum(open_grid ** 2) > area, np.shape(kernel)) + mask = np.reshape(np.sum(open_grid**2) > area, np.shape(kernel)) kernel[mask] = 0.0 return kernel @@ -99,7 +99,7 @@ class BaseNeighbourhoodProcessing(PostProcessingPlugin): """ def __init__( - self, radii: Union[float, List[float]], lead_times: Optional[List] = None, + self, radii: Union[float, List[float]], lead_times: Optional[List] = None ) -> None: """ Create a base neighbourhood processing plugin that processes radii @@ -317,7 +317,7 @@ def _calculate_neighbourhood( return data.astype(out_data_dtype) def _do_nbhood_sum( - self, data: np.ndarray, max_extreme: Optional[np.ndarray] = None, + self, data: np.ndarray, max_extreme: Optional[np.ndarray] = None ) -> np.ndarray: """Calculate the sum-in-area from an array. As this can be expensive, the method first checks for the extreme cases where the data are: @@ -466,7 +466,6 @@ def process(self, cube: Cube, mask_cube: Optional[Cube] = None) -> Cube: class GeneratePercentilesFromANeighbourhood(BaseNeighbourhoodProcessing): - """Class for generating percentiles from a circular neighbourhood.""" def __init__( @@ -521,56 +520,78 @@ def pad_and_unpad_cube(self, slice_2d: Cube, kernel: ndarray) -> Cube: 1. Take the input slice_2d cube with the data, where 1 is an occurrence and 0 is an non-occurrence:: - [[1., 1., 1.,], - [1., 0., 1.], - [1., 1., 1.]] + # fmt: off + [ + [1., 1., 1.], + [1., 0., 1.], + [1., 1., 1.], + ] + # fmt: on 2. Define a kernel. This kernel is effectively placed over each point within the input data. Note that the input data is padded prior to placing the kernel over each point, so that the kernel does not exceed the bounds of the padded data:: - [[ 0., 0., 1., 0., 0.], - [ 0., 1., 1., 1., 0.], - [ 1., 1., 1., 1., 1.], - [ 0., 1., 1., 1., 0.], - [ 0., 0., 1., 0., 0.]] + # fmt: off + [ + [0., 0., 1., 0., 0.], + [0., 1., 1., 1., 0.], + [1., 1., 1., 1., 1.], + [0., 1., 1., 1., 0.], + [0., 0., 1., 0., 0.], + ] + # fmt: on 3. Pad the input data. The extent of the padding is given by the shape of the kernel. The number of values included within the calculation of the mean is determined by the size of the kernel:: - [[ 0.75, 0.75, 1. , 0.5 , 1. , 0.75, 0.75], - [ 0.75, 0.75, 1. , 0.5 , 1. , 0.75, 0.75], - [ 1. , 1. , 1. , 1. , 1. , 1. , 1. ], - [ 0.5 , 0.5 , 1. , 0. , 1. , 0.5 , 0.5 ], - [ 1. , 1. , 1. , 1. , 1. , 1. , 1. ], - [ 0.75, 0.75, 1. , 0.5 , 1. , 0.75, 0.75], - [ 0.75, 0.75, 1. , 0.5 , 1. , 0.75, 0.75]] + # fmt: off + [ + [0.75, 0.75, 1. , 0.5, 1., 0.75, 0.75], + [0.75, 0.75, 1. , 0.5, 1., 0.75, 0.75], + [1. , 1. , 1. , 1. , 1., 1. , 1. ], + [0.5 , 0.5 , 1. , 0. , 1., 0.5 , 0.5 ], + [1. , 1. , 1. , 1. , 1., 1. , 1. ], + [0.75, 0.75, 1. , 0.5, 1., 0.75, 0.75], + [0.75, 0.75, 1. , 0.5, 1., 0.75, 0.75], + ] + # fmt: on 4. Calculate the values at the percentiles: [10]. For the point in the upper right corner within the original input data e.g. :: - [[->1.<-, 1., 1.,], - [ 1., 0., 1.], - [ 1., 1., 1.]] + # fmt: off + [ + [->1.<-, 1., 1.], + [ 1. , 0., 1.], + [ 1. , 1., 1.], + ] + # fmt: on When the kernel is placed over this point within the padded data, then the following points are included:: - [[ 0.75, 0.75, ->1.<-, 0.5 , 1. , 0.75, 0.75], - [ 0.75, ->0.75, 1. , 0.5<-, 1. , 0.75, 0.75], - [ ->1. , 1. , 1. , 1. , 1.<-, 1. , 1. ], - [ 0.5 , ->0.5 , 1. , 0.<-, 1. , 0.5 , 0.5 ], - [ 1. , 1. , ->1.<-, 1. , 1. , 1. , 1. ], - [ 0.75, 0.75, 1. , 0.5 , 1. , 0.75, 0.75], - [ 0.75, 0.75, 1. , 0.5 , 1. , 0.75, 0.75]] + # fmt: off + [ + [ 0.75, 0.75, ->1.<-, 0.5 , 1. , 0.75, 0.75], + [ 0.75, ->0.75, 1. , 0.5<-, 1. , 0.75, 0.75], + [->1. , 1. , 1. , 1. , 1.<-, 1. , 1. ], + [ 0.5 , ->0.5 , 1. , 0.<- , 1. , 0.5 , 0.5 ], + [ 1. , 1. , ->1.<-, 1. , 1. , 1. , 1. ], + [ 0.75, 0.75, 1. , 0.5 , 1. , 0.75, 0.75], + [ 0.75, 0.75, 1. , 0.5 , 1. , 0.75, 0.75], + ] + # fmt: on This gives:: + # fmt: off [0, 0.5, 0.5, 0.75, 1., 1., 1., 1., 1., 1., 1., 1., 1.] + # fmt: on As there are 13 points within the kernel, this gives the following relationship between percentiles and values. @@ -599,19 +620,31 @@ def pad_and_unpad_cube(self, slice_2d: Cube, kernel: ndarray) -> Cube: When this process is applied to every point within the original input data, the result is:: - [[[ 0.75, 0.75, 0.5 , 0.5 , 0.5 , 0.75, 0.75], - [ 0.75, 0.55, 0.55, 0.5 , 0.55, 0.55, 0.55], - [ 0.55, 0.55, 0.5 , 0.5 , 0.5 , 0.5 , 0.5 ], - [ 0.5 , 0.5 , 0.5 , 0.5 , 0.5 , 0.5 , 0.5 ], - [ 0.5 , 0.5 , 0.5 , 0.5 , 0.5 , 0.55, 0.55], - [ 0.55, 0.55, 0.55, 0.5 , 0.55, 0.55, 0.75], - [ 0.75, 0.75, 0.5 , 0.5 , 0.5 , 0.75, 0.75]]], + # fmt: off + [ + [ + [0.75, 0.75, 0.5 , 0.5, 0.5 , 0.75, 0.75], + [0.75, 0.55, 0.55, 0.5, 0.55, 0.55, 0.55], + [0.55, 0.55, 0.5 , 0.5, 0.5 , 0.5 , 0.5 ], + [0.5, 0.5 , 0.5 , 0.5, 0.5 , 0.5 , 0.5 ], + [0.5, 0.5 , 0.5 , 0.5, 0.5 , 0.55, 0.55], + [0.55, 0.55, 0.55, 0.5, 0.55, 0.55, 0.75], + [0.75, 0.75, 0.5 , 0.5, 0.5 , 0.75, 0.75], + ] + ] + # fmt: on 5. The padding is then removed to give:: - [[[ 0.5, 0.5, 0.5], - [ 0.5, 0.5, 0.5], - [ 0.5, 0.5, 0.5]]] + # fmt: off + [ + [ + [0.5, 0.5, 0.5], + [0.5, 0.5, 0.5], + [0.5, 0.5, 0.5], + ] + ] + # fmt: on """ kernel_mask = kernel > 0 nb_slices = pad_and_roll( diff --git a/improver/nbhood/recursive_filter.py b/improver/nbhood/recursive_filter.py index a9c391fc37..479bf3bacc 100644 --- a/improver/nbhood/recursive_filter.py +++ b/improver/nbhood/recursive_filter.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to apply a recursive filter to neighbourhooded data.""" @@ -226,7 +226,6 @@ def _validate_coefficients( axes = ["x", "y"] for axis, smoothing_coefficient in zip(axes, smoothing_coefficients): - # Check the smoothing coefficient cube name is as expected expected_name = self.smoothing_coefficient_name_format.format(axis) if smoothing_coefficient.name() != expected_name: @@ -279,7 +278,7 @@ def _pad_coefficients(self, coeff_x, coeff_y): """Pad smoothing coefficients""" pad_x, pad_y = [ pad_cube_with_halo( - coeff, 2 * self.edge_width, 2 * self.edge_width, pad_method="symmetric", + coeff, 2 * self.edge_width, 2 * self.edge_width, pad_method="symmetric" ) for coeff in [coeff_x, coeff_y] ] @@ -371,7 +370,7 @@ def process(self, cube: Cube, smoothing_coefficients: CubeList) -> Cube: mask_cube = cube_format.copy(data=cube_format.data.mask) coeffs_x, coeffs_y = self._update_coefficients_from_mask( - coeffs_x, coeffs_y, mask_cube, + coeffs_x, coeffs_y, mask_cube ) padded_coefficients_x, padded_coefficients_y = self._pad_coefficients( @@ -380,7 +379,6 @@ def process(self, cube: Cube, smoothing_coefficients: CubeList) -> Cube: recursed_cube = iris.cube.CubeList() for output in cube.slices([cube.coord(axis="y"), cube.coord(axis="x")]): - padded_cube = pad_cube_with_halo( output, 2 * self.edge_width, 2 * self.edge_width, pad_method="symmetric" ) diff --git a/improver/nbhood/use_nbhood.py b/improver/nbhood/use_nbhood.py index f1c4c3344f..9122ef01ce 100644 --- a/improver/nbhood/use_nbhood.py +++ b/improver/nbhood/use_nbhood.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Utilities for using neighbourhood processing.""" @@ -21,7 +21,6 @@ class ApplyNeighbourhoodProcessingWithAMask(PostProcessingPlugin): - r"""Class for applying neighbourhood processing when passing in a mask cube that is iterated over. diff --git a/improver/nowcasting/accumulation.py b/improver/nowcasting/accumulation.py index 4e59842c2e..efd5ac2fc7 100644 --- a/improver/nowcasting/accumulation.py +++ b/improver/nowcasting/accumulation.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ This module defines the Accumulation class for calculating precipitation diff --git a/improver/nowcasting/forecasting.py b/improver/nowcasting/forecasting.py index 0dda7f299a..3c2d647f94 100644 --- a/improver/nowcasting/forecasting.py +++ b/improver/nowcasting/forecasting.py @@ -1,12 +1,13 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ DEPRECATED MODULE. This module has been replaced by pysteps_advection.py and is no longer called by any CLI. This module defines plugins used to create nowcast extrapolation forecasts. """ + import datetime import warnings from datetime import timedelta diff --git a/improver/nowcasting/lightning.py b/improver/nowcasting/lightning.py index f9cf2bc1e4..12db11a86a 100644 --- a/improver/nowcasting/lightning.py +++ b/improver/nowcasting/lightning.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module for NowcastLightning class and associated functions.""" + from math import isclose from typing import Optional diff --git a/improver/nowcasting/optical_flow.py b/improver/nowcasting/optical_flow.py index 22b79231eb..bccb894492 100644 --- a/improver/nowcasting/optical_flow.py +++ b/improver/nowcasting/optical_flow.py @@ -1,11 +1,12 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ This module defines the optical flow velocity calculation and extrapolation classes for advection nowcasting. """ + import warnings from typing import List, Optional, Tuple @@ -172,8 +173,9 @@ def check_input_coords(cube: Cube, require_time: bool = False) -> None: non_scalar_coords = np.sum(np.where(data_shape > 1, 1, 0)) if non_scalar_coords > 2: raise InvalidCubeError( - "Cube has {:d} (more than 2) non-scalar " - "coordinates".format(non_scalar_coords) + "Cube has {:d} (more than 2) non-scalar " "coordinates".format( + non_scalar_coords + ) ) if require_time: @@ -228,8 +230,9 @@ def __init__( """ if iterations < 20: raise ValueError( - "Got {} iterations; minimum requirement 20 " - "iterations".format(iterations) + "Got {} iterations; minimum requirement 20 " "iterations".format( + iterations + ) ) self.data_smoothing_radius_km = data_smoothing_radius_km @@ -441,7 +444,7 @@ def _make_subboxes(self, field: ndarray) -> Tuple[List[ndarray], ndarray]: """ boxes = [] weights = [] - weighting_factor = 0.5 / self.boxsize ** 2.0 + weighting_factor = 0.5 / self.boxsize**2.0 for i in range(0, field.shape[0], self.boxsize): for j in range(0, field.shape[1], self.boxsize): boxes.append(field[i : i + self.boxsize, j : j + self.boxsize]) @@ -707,7 +710,6 @@ def calculate_displacement_vectors( # (b) Solve optical flow displacement calculation on each subbox velocity = ([], []) for deriv_x, deriv_y, deriv_t in zip(dx_boxed, dy_boxed, dt_boxed): - # Flatten arrays to create the system of linear simultaneous # equations to solve for this subbox deriv_x = deriv_x.flatten() diff --git a/improver/nowcasting/pysteps_advection.py b/improver/nowcasting/pysteps_advection.py index 6680a8a6dd..ea9386fe7e 100644 --- a/improver/nowcasting/pysteps_advection.py +++ b/improver/nowcasting/pysteps_advection.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Semi-Lagrangian backward advection plugin using pysteps""" @@ -124,9 +124,9 @@ def _reformat_analysis_cube(self, attribute_changes): [self.analysis_cube] ) self.analysis_cube.attributes["source"] = "MONOW" - self.analysis_cube.attributes[ - "title" - ] = "MONOW Extrapolation Nowcast on UK 2 km Standard Grid" + self.analysis_cube.attributes["title"] = ( + "MONOW Extrapolation Nowcast on UK 2 km Standard Grid" + ) set_history_attribute(self.analysis_cube, "Nowcast") if attribute_changes is not None: amend_attributes(self.analysis_cube, attribute_changes) diff --git a/improver/nowcasting/utilities.py b/improver/nowcasting/utilities.py index 0a3234e541..0f85ac34ce 100644 --- a/improver/nowcasting/utilities.py +++ b/improver/nowcasting/utilities.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module with utilities required for nowcasting.""" @@ -54,8 +54,9 @@ def process(self, radar_data: Cube, coverage: Cube) -> Cube: for crd in radar_data.coords(): if coverage.coord(crd.name()) != crd: raise ValueError( - "Rain rate and coverage composites unmatched " - "- coord {}".format(crd.name()) + "Rain rate and coverage composites unmatched " "- coord {}".format( + crd.name() + ) ) # accommodate data from multiple times @@ -187,9 +188,8 @@ def process(self, masked_radar: Cube) -> Cube: class ApplyOrographicEnhancement(BasePlugin): - """Apply orographic enhancement to precipitation rate input, either to - add or subtract an orographic enhancement component.""" + add or subtract an orographic enhancement component.""" def __init__(self, operation: str) -> None: """Initialise class. diff --git a/improver/orographic_enhancement.py b/improver/orographic_enhancement.py index 04c3cc05cb..da8a8dac7a 100644 --- a/improver/orographic_enhancement.py +++ b/improver/orographic_enhancement.py @@ -1,11 +1,12 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ This module contains a plugin to calculate the enhancement of precipitation over orography. """ + from typing import Tuple import iris diff --git a/improver/percentile.py b/improver/percentile.py index 563f615a88..4c328e4e03 100644 --- a/improver/percentile.py +++ b/improver/percentile.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing percentiling classes.""" @@ -18,7 +18,6 @@ class PercentileConverter(BasePlugin): - """Plugin for converting from a set of values to a PDF. Generate percentiles together with min, max, mean, stdev. diff --git a/improver/precipitation_type/calculate_sleet_prob.py b/improver/precipitation_type/calculate_sleet_prob.py index 82ed1c23fa..bfb075ca39 100644 --- a/improver/precipitation_type/calculate_sleet_prob.py +++ b/improver/precipitation_type/calculate_sleet_prob.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """A plugin to calculate probability of sleet""" diff --git a/improver/precipitation_type/convection.py b/improver/precipitation_type/convection.py index 3a7baee311..534e2370bf 100644 --- a/improver/precipitation_type/convection.py +++ b/improver/precipitation_type/convection.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing convection diagnosis utilities.""" diff --git a/improver/precipitation_type/freezing_rain.py b/improver/precipitation_type/freezing_rain.py index 94675a332a..ecdcda1de4 100644 --- a/improver/precipitation_type/freezing_rain.py +++ b/improver/precipitation_type/freezing_rain.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing the FreezingRain class.""" diff --git a/improver/precipitation_type/hail_fraction.py b/improver/precipitation_type/hail_fraction.py index 308eb403c6..5fa602a8e7 100644 --- a/improver/precipitation_type/hail_fraction.py +++ b/improver/precipitation_type/hail_fraction.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing the HailFraction class.""" @@ -87,9 +87,9 @@ def _compute_hail_fraction( | (convective_cloud_top.data > cct_limit) | (hail_melting_level.data > orography.data) ] = 0 - hail_fraction[ - (hail_size.data > hail_size_limit) & (hail_fraction < 0.05) - ] = 0.05 + hail_fraction[(hail_size.data > hail_size_limit) & (hail_fraction < 0.05)] = ( + 0.05 + ) return hail_fraction def process(self, *cubes: Union[Cube, CubeList]) -> Cube: diff --git a/improver/precipitation_type/shower_condition_probability.py b/improver/precipitation_type/shower_condition_probability.py index ddf192a140..d0f1dc7cdc 100644 --- a/improver/precipitation_type/shower_condition_probability.py +++ b/improver/precipitation_type/shower_condition_probability.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Plugin to construct a shower conditions probability""" @@ -81,7 +81,7 @@ def _create_shower_condition_cube(self, data: ndarray, cube: Cube) -> Cube: ) result = create_new_diagnostic_cube( - template.name(), "1", template, mandatory_attributes=attributes, data=data, + template.name(), "1", template, mandatory_attributes=attributes, data=data ) return result diff --git a/improver/precipitation_type/snow_fraction.py b/improver/precipitation_type/snow_fraction.py index 0f0727bb0e..785f754586 100644 --- a/improver/precipitation_type/snow_fraction.py +++ b/improver/precipitation_type/snow_fraction.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing the SnowFraction class.""" diff --git a/improver/precipitation_type/snow_splitter.py b/improver/precipitation_type/snow_splitter.py index 2ea312d8c2..ddb942dc42 100644 --- a/improver/precipitation_type/snow_splitter.py +++ b/improver/precipitation_type/snow_splitter.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to separate snow and rain contributions from a precipitation diagnostic""" @@ -21,7 +21,7 @@ class SnowSplitter(BasePlugin): rate/accumulation. This is calculated using the probability of rain and snow at the surface to determine what fraction of the precipitation rate/accumulation is rain or snow. - """ + """ def __init__(self, output_is_rain: bool): """ diff --git a/improver/precipitation_type/utilities.py b/improver/precipitation_type/utilities.py index f77977dd58..6373db75b7 100644 --- a/improver/precipitation_type/utilities.py +++ b/improver/precipitation_type/utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Utilities for use by precipitation_type plugins / functions.""" diff --git a/improver/profile.py b/improver/profile.py index b13c027f4f..0ec5e0aa73 100644 --- a/improver/profile.py +++ b/improver/profile.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing profiling utilities.""" diff --git a/improver/psychrometric_calculations/cloud_condensation_level.py b/improver/psychrometric_calculations/cloud_condensation_level.py index 2881d11f10..24859753a1 100644 --- a/improver/psychrometric_calculations/cloud_condensation_level.py +++ b/improver/psychrometric_calculations/cloud_condensation_level.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to contain CloudCondensationLevel plugin.""" + from typing import Tuple, Union import numpy as np diff --git a/improver/psychrometric_calculations/cloud_top_temperature.py b/improver/psychrometric_calculations/cloud_top_temperature.py index 8219cc669c..20e47ef22c 100644 --- a/improver/psychrometric_calculations/cloud_top_temperature.py +++ b/improver/psychrometric_calculations/cloud_top_temperature.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing the CloudTopTemperature plugin""" + from typing import Union import numpy as np @@ -69,7 +70,7 @@ def _calculate_cct(self) -> ndarray: (pressure,) = t.coord("pressure").points t_dry_parcel = dry_adiabatic_temperature( - self.t_at_ccl.data[mask], self.p_at_ccl.data[mask], pressure, + self.t_at_ccl.data[mask], self.p_at_ccl.data[mask], pressure ) t_parcel = np.full_like(t.data, np.nan) diff --git a/improver/psychrometric_calculations/hail_size.py b/improver/psychrometric_calculations/hail_size.py index 16dcf2f120..c92b2178a1 100644 --- a/improver/psychrometric_calculations/hail_size.py +++ b/improver/psychrometric_calculations/hail_size.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """module to calculate hail_size""" @@ -77,23 +77,20 @@ class HailSize(BasePlugin): def __init__(self, model_id_attr: str = None): """Sets up Class - Args: - model_id_attr: - Name of model ID attribute to be copied from source cubes to output cube + Args: + model_id_attr: + Name of model ID attribute to be copied from source cubes to output cube """ self.final_order = None self.model_id_attr = model_id_attr - ( - self._wbzh_keys, - self._hail_groups, - self._updated_values, - ) = self.updated_nomogram() + (self._wbzh_keys, self._hail_groups, self._updated_values) = ( + self.updated_nomogram() + ) @staticmethod def nomogram_values() -> np.ndarray: - """Sets-up an array of a table containing possible diameter of hail stones(mm). It is a transposed version of the table in Hand and Cappelluti (2011). @@ -149,7 +146,6 @@ def nomogram_values() -> np.ndarray: @staticmethod def updated_nomogram() -> Tuple[List, List, np.array]: - """Sets up a dictionary of updated hail diameter values (mm). The dictionary keys are the height of the wet bulb freezing level (m) where, @@ -190,17 +186,17 @@ def check_cubes( ) -> None: """Checks the size and units of input cubes and enforces the standard coord order - Args: - ccl_temperature: - Cube of cloud condensation level temperature - ccl_pressure: - Cube of cloud condensation level pressure - temperature_on_pressure: - Cube of environment temperature on pressure levels - wet_bulb_zero_asl: - Cube of the height of the wet bulb freezing level above sea level - orography: - Cube of the orography height. + Args: + ccl_temperature: + Cube of cloud condensation level temperature + ccl_pressure: + Cube of cloud condensation level pressure + temperature_on_pressure: + Cube of environment temperature on pressure levels + wet_bulb_zero_asl: + Cube of the height of the wet bulb freezing level above sea level + orography: + Cube of the orography height. """ coord_order = ["realization", "pressure"] + [ temperature_on_pressure.coord(axis=axis).name() for axis in "yx" @@ -407,10 +403,7 @@ def hail_size_data( # temp_saturated_ascent is little-b in Hand (2011). temp_saturated_ascent = self.temperature_after_saturated_ascent_from_ccl( - ccl_temperature, - ccl_pressure, - pressure_at_268, - humidity_mixing_ratio_at_ccl, + ccl_temperature, ccl_pressure, pressure_at_268, humidity_mixing_ratio_at_ccl ) # horizontal is c - B in Hand (2011). @@ -519,7 +512,7 @@ def process(self, *cubes: Union[Cube, CubeList]) -> Cube: temperature_at_268.rename("temperature_of_atmosphere_at_268.15K") temperature_at_268.remove_coord("pressure") temperature = np.full_like( - temperature_at_268.data, extract_pressure.value_of_level, dtype=np.float32, + temperature_at_268.data, extract_pressure.value_of_level, dtype=np.float32 ) temperature = np.ma.masked_where(np.ma.getmask(pressure_at_268), temperature) temperature_at_268.data = temperature diff --git a/improver/psychrometric_calculations/precip_phase_probability.py b/improver/psychrometric_calculations/precip_phase_probability.py index 96cff0d5a6..a6be97ac37 100644 --- a/improver/psychrometric_calculations/precip_phase_probability.py +++ b/improver/psychrometric_calculations/precip_phase_probability.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module for calculating the probability of specific precipitation phases.""" @@ -168,7 +168,7 @@ def process(self, *cubes: Union[CubeList, List[Cube]]) -> Cube: self._extract_input_cubes(cubes) result_data = np.where( - self.comparator(self.altitudes, self.falling_level_cube.data), 1, 0, + self.comparator(self.altitudes, self.falling_level_cube.data), 1, 0 ).astype(np.int8) mandatory_attributes = generate_mandatory_attributes([self.falling_level_cube]) diff --git a/improver/psychrometric_calculations/psychrometric_calculations.py b/improver/psychrometric_calculations/psychrometric_calculations.py index 3c15416bc9..43d7143f44 100644 --- a/improver/psychrometric_calculations/psychrometric_calculations.py +++ b/improver/psychrometric_calculations/psychrometric_calculations.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to contain Psychrometric Calculations.""" @@ -105,7 +105,7 @@ def calculate_svp_in_air(temperature: ndarray, pressure: ndarray) -> ndarray: def dry_adiabatic_temperature( - initial_temperature: ndarray, initial_pressure: ndarray, final_pressure: ndarray, + initial_temperature: ndarray, initial_pressure: ndarray, final_pressure: ndarray ) -> ndarray: """ Calculate temperature at final_pressure after adiabatic adjustment of dry air from the @@ -132,7 +132,7 @@ def dry_adiabatic_temperature( def dry_adiabatic_pressure( - initial_temperature: ndarray, initial_pressure: ndarray, final_temperature: ndarray, + initial_temperature: ndarray, initial_pressure: ndarray, final_temperature: ndarray ) -> ndarray: """ Calculate pressure at final_temperature after adiabatic adjustment of dry air from the @@ -328,7 +328,7 @@ def process(self, *cubes: Union[Cube, CubeList]) -> Cube: """ cubes = as_cubelist(*cubes) - (self.temperature, self.pressure, self.rel_humidity,) = cubes.extract_cubes( + (self.temperature, self.pressure, self.rel_humidity) = cubes.extract_cubes( ["air_temperature", "surface_air_pressure", "relative_humidity"] ) @@ -825,7 +825,7 @@ def _horizontally_interpolate_phase( if np.isnan(phase_change_data).any(): # This should be rare. phase_change_data = interpolate_missing_data( - phase_change_data, method="nearest", limit=orography, + phase_change_data, method="nearest", limit=orography ) return phase_change_data diff --git a/improver/psychrometric_calculations/significant_phase_mask.py b/improver/psychrometric_calculations/significant_phase_mask.py index 6f2545285a..fd5a821894 100644 --- a/improver/psychrometric_calculations/significant_phase_mask.py +++ b/improver/psychrometric_calculations/significant_phase_mask.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module for calculating the significant phase mask.""" diff --git a/improver/psychrometric_calculations/wet_bulb_temperature.py b/improver/psychrometric_calculations/wet_bulb_temperature.py index 9286b467c9..687cacb9b3 100644 --- a/improver/psychrometric_calculations/wet_bulb_temperature.py +++ b/improver/psychrometric_calculations/wet_bulb_temperature.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to contain wet-bulb temperature plugins.""" + from typing import List, Union import iris @@ -216,7 +217,6 @@ def _calculate_wet_bulb_temperature( to_update = np.arange(temperature.size) update_to_update = slice(None) while to_update.size and iteration < self.maximum_iterations: - if iteration > 0: wbt_data_upd = wbt_data[to_update] pressure = pressure[update_to_update] @@ -351,9 +351,9 @@ def process(self, wet_bulb_temperature: Cube) -> Cube: wbt.data wet_bulb_temperature_integral = self.integration_plugin(wbt) if self.model_id_attr: - wet_bulb_temperature_integral.attributes[ - self.model_id_attr - ] = wbt.attributes[self.model_id_attr] + wet_bulb_temperature_integral.attributes[self.model_id_attr] = ( + wbt.attributes[self.model_id_attr] + ) # although the integral is computed over degC the standard unit is # 'K m', and these are equivalent wet_bulb_temperature_integral.units = Unit("K m") diff --git a/improver/regrid/bilinear.py b/improver/regrid/bilinear.py index 6b1301873b..7b41002a4c 100644 --- a/improver/regrid/bilinear.py +++ b/improver/regrid/bilinear.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ .. Further information is available in: @@ -8,6 +8,7 @@ bilinear_land_sea.rst """ + from typing import Tuple, Union import numpy as np @@ -566,16 +567,10 @@ def lakes_islands( # If the expanded search area hasn't found any same surface type matches anywhere # just ignore surface type, use normal bilinear approach if points_with_no_match.shape[0] > 0: - # revert back to the basic bilinear weights, indexes unchanged no_match_indexes = lake_island_indexes[points_with_no_match] weights[no_match_indexes] = basic_weights( - no_match_indexes, - indexes, - out_latlons, - in_latlons, - lat_spacing, - lon_spacing, + no_match_indexes, indexes, out_latlons, in_latlons, lat_spacing, lon_spacing ) points_with_match = np.where(count_matching_surface > 0)[0] diff --git a/improver/regrid/grid.py b/improver/regrid/grid.py index 0157acae63..19363ffc08 100644 --- a/improver/regrid/grid.py +++ b/improver/regrid/grid.py @@ -1,10 +1,11 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Grid handling for regridding """ + from typing import List, Tuple, Union import iris diff --git a/improver/regrid/idw.py b/improver/regrid/idw.py index d97781ff81..52b320fc43 100644 --- a/improver/regrid/idw.py +++ b/improver/regrid/idw.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Inverse distance weighting interpolation functions diff --git a/improver/regrid/landsea.py b/improver/regrid/landsea.py index 5eefa38b20..830b97a4ac 100644 --- a/improver/regrid/landsea.py +++ b/improver/regrid/landsea.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Plugin to regrid with land-sea awareness""" @@ -331,8 +331,9 @@ def process(self, cube: Cube, input_land: Cube, output_land: Cube) -> Cube: # Check cube and output_land are on the same grid: if not spatial_coords_match([cube, output_land]): raise ValueError( - "X and Y coordinates do not match for cubes {}" - "and {}".format(repr(cube), repr(output_land)) + "X and Y coordinates do not match for cubes {}" "and {}".format( + repr(cube), repr(output_land) + ) ) self.output_land = output_land diff --git a/improver/regrid/landsea2.py b/improver/regrid/landsea2.py index e2685f4a43..a9ad80996e 100644 --- a/improver/regrid/landsea2.py +++ b/improver/regrid/landsea2.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Plugin to regrid using custom nearest and bilinear methods, both with @@ -128,10 +128,9 @@ def process(self, cube_in: Cube, cube_in_mask: Cube, cube_out_mask: Cube) -> Cub ) # group cube_out's grid points into outside or inside cube_in's domain - ( - outside_input_domain_index, - inside_input_domain_index, - ) = group_target_points_with_source_domain(cube_in, out_latlons) + (outside_input_domain_index, inside_input_domain_index) = ( + group_target_points_with_source_domain(cube_in, out_latlons) + ) # exclude out-of-input-domain target point here if len(outside_input_domain_index) > 0: @@ -197,7 +196,7 @@ def process(self, cube_in: Cube, cube_in_mask: Cube, cube_out_mask: Cube) -> Cub # These will be updated for mask/mismatched surface type further below index_range = np.arange(weights.shape[0]) weights[index_range] = basic_weights( - index_range, indexes, out_latlons, in_latlons, lat_spacing, lon_spacing, + index_range, indexes, out_latlons, in_latlons, lat_spacing, lon_spacing ) if WITH_MASK in self.regrid_mode: diff --git a/improver/regrid/nearest.py b/improver/regrid/nearest.py index 759d9926e5..81ede05247 100644 --- a/improver/regrid/nearest.py +++ b/improver/regrid/nearest.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Nearest neighbour interpolation functions diff --git a/improver/spotdata/__init__.py b/improver/spotdata/__init__.py index 52dae3234f..eba5d684d6 100644 --- a/improver/spotdata/__init__.py +++ b/improver/spotdata/__init__.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Top level constants""" diff --git a/improver/spotdata/apply_lapse_rate.py b/improver/spotdata/apply_lapse_rate.py index 8e20a01df4..2675f818ac 100644 --- a/improver/spotdata/apply_lapse_rate.py +++ b/improver/spotdata/apply_lapse_rate.py @@ -1,9 +1,10 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Apply temperature lapse rate adjustments to a spot data cube.""" + from typing import Optional import iris @@ -40,10 +41,10 @@ def __init__( The methods available will be all, or a subset, of the following:: - - nearest - - nearest_land - - nearest_land_minimum_dz - - nearest_minimum_dz + -nearest + -nearest_land + -nearest_land_minimum_dz + -nearest_minimum_dz The method available in a neighbour cube will depend on the options that were specified when it was created. diff --git a/improver/spotdata/build_spotdata_cube.py b/improver/spotdata/build_spotdata_cube.py index 8eec7fb7a4..aedcc1fa3f 100644 --- a/improver/spotdata/build_spotdata_cube.py +++ b/improver/spotdata/build_spotdata_cube.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Functions to create spotdata cubes.""" diff --git a/improver/spotdata/height_adjustment.py b/improver/spotdata/height_adjustment.py index 9335f00fe9..0effebe68a 100644 --- a/improver/spotdata/height_adjustment.py +++ b/improver/spotdata/height_adjustment.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Applies height adjustment for height above ground level spot forecasts.""" @@ -36,7 +36,7 @@ class SpotHeightAdjustment(BasePlugin): or lowest threshold's probability from the original cube respectively for that spot. """ - def __init__(self, neighbour_selection_method: str = "nearest",) -> None: + def __init__(self, neighbour_selection_method: str = "nearest") -> None: """ Args: neighbour_selection_method: @@ -93,7 +93,7 @@ def adjust_prob_cube(self, spot_cube: Cube, vertical_displacement: Cube) -> Cube broadcast_thresholds = np.broadcast_to(thresholds, (n_sites, n_thresholds)) broadcast_vertical_displacement = np.transpose( - np.broadcast_to(vertical_displacement.data, (n_thresholds, n_sites),) + np.broadcast_to(vertical_displacement.data, (n_thresholds, n_sites)) ) desired_thresholds = broadcast_thresholds + broadcast_vertical_displacement.data @@ -120,7 +120,7 @@ def adjust_prob_cube(self, spot_cube: Cube, vertical_displacement: Cube) -> Cube spot_cube.data = spot_data return spot_cube - def process(self, spot_cube: Cube, neighbour: Cube,) -> Cube: + def process(self, spot_cube: Cube, neighbour: Cube) -> Cube: """ Adjusts spot forecast data to be relative to site height rather than grid square orography height. diff --git a/improver/spotdata/neighbour_finding.py b/improver/spotdata/neighbour_finding.py index 1f345a912e..7cf2620ac9 100644 --- a/improver/spotdata/neighbour_finding.py +++ b/improver/spotdata/neighbour_finding.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Neighbour finding for the Improver site specific process chain.""" @@ -485,13 +485,10 @@ def process( # Exclude any sites falling outside the domain given by the cube and # notify the user. - ( - sites, - site_coords, - site_x_coords, - site_y_coords, - ) = self.check_sites_are_within_domain( - sites, site_coords, site_x_coords, site_y_coords, orography + (sites, site_coords, site_x_coords, site_y_coords) = ( + self.check_sites_are_within_domain( + sites, site_coords, site_x_coords, site_y_coords, orography + ) ) # Find nearest neighbour point using quick iris method. diff --git a/improver/spotdata/spot_extraction.py b/improver/spotdata/spot_extraction.py index 6cf91b7b9d..de1344337e 100644 --- a/improver/spotdata/spot_extraction.py +++ b/improver/spotdata/spot_extraction.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Spot data extraction from diagnostic fields using neighbour cubes.""" @@ -113,7 +113,7 @@ def check_for_unique_id(neighbour_cube: Cube) -> Optional[Tuple[ndarray, str]]: return (unique_id_coord.points, unique_id_coord.name()) def get_aux_coords( - self, diagnostic_cube: Cube, x_indices: ndarray, y_indices: ndarray, + self, diagnostic_cube: Cube, x_indices: ndarray, y_indices: ndarray ) -> Tuple[List[AuxCoord], List[AuxCoord]]: """ Extract scalar and non-scalar auxiliary coordinates from the diagnostic diff --git a/improver/spotdata/spot_manipulation.py b/improver/spotdata/spot_manipulation.py index 859e555fa6..70eea8cc98 100644 --- a/improver/spotdata/spot_manipulation.py +++ b/improver/spotdata/spot_manipulation.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Spot data extraction from diagnostic fields using neighbour cubes.""" @@ -165,7 +165,6 @@ def process(self, cubes: CubeList) -> Cube: # which to constrain is provided, e.g. wmo_id. Otherwise pass the # spot forecast cube forwards unchanged. if cube.coords("spot_index"): - if ( self.apply_lapse_rate_correction is not False or self.fixed_lapse_rate is not None diff --git a/improver/spotdata/utilities.py b/improver/spotdata/utilities.py index 80b9154117..f76f708f9e 100644 --- a/improver/spotdata/utilities.py +++ b/improver/spotdata/utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Spot data utilities.""" diff --git a/improver/standardise.py b/improver/standardise.py index 5e70fd57ae..d1a655a964 100644 --- a/improver/standardise.py +++ b/improver/standardise.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Plugin to standardise metadata""" @@ -227,9 +227,7 @@ def _discard_redundant_cell_methods(cube: Cube) -> None: """ if not cube.cell_methods: return - removable_cms = [ - CellMethod(method="point", coords="time"), - ] + removable_cms = [CellMethod(method="point", coords="time")] updated_cms = [] for cm in cube.cell_methods: if cm in removable_cms: diff --git a/improver/synthetic_data/generate_metadata.py b/improver/synthetic_data/generate_metadata.py index 8ddc6cf287..4efb7aa4b9 100644 --- a/improver/synthetic_data/generate_metadata.py +++ b/improver/synthetic_data/generate_metadata.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to generate a metadata cube.""" @@ -27,7 +27,7 @@ def _get_units(name: str) -> str: - """ Get output variable units from iris.std_names.STD_NAMES """ + """Get output variable units from iris.std_names.STD_NAMES""" try: units = STD_NAMES[name]["canonical_units"] except KeyError: @@ -37,7 +37,7 @@ def _get_units(name: str) -> str: def _create_time_bounds(time: datetime, time_period: int) -> Tuple[datetime, datetime]: - """ Create time bounds using time - time_period as the lower bound and time as the + """Create time bounds using time - time_period as the lower bound and time as the upper bound""" lower_bound = time - timedelta(minutes=time_period) upper_bound = time @@ -51,7 +51,7 @@ def _create_data_array( npoints: int, height_levels: Optional[List[float]], ) -> ndarray: - """ Create data array of specified shape filled with zeros """ + """Create data array of specified shape filled with zeros""" if leading_dimension is not None: nleading_dimension = len(leading_dimension) else: @@ -87,7 +87,7 @@ def generate_metadata( npoints: int = 71, **kwargs: Any, ) -> Cube: - """ Generate a cube with metadata only. + """Generate a cube with metadata only. Args: mandatory_attributes: @@ -194,7 +194,7 @@ def generate_metadata( # Set up requested cube if cube_type == "percentile": metadata_cube = set_up_percentile_cube( - data, percentiles=leading_dimension, name=name, units=units, **kwargs, + data, percentiles=leading_dimension, name=name, units=units, **kwargs ) elif cube_type == "probability": metadata_cube = set_up_probability_cube( @@ -207,7 +207,7 @@ def generate_metadata( ) else: metadata_cube = set_up_variable_cube( - data, name=name, units=units, realizations=leading_dimension, **kwargs, + data, name=name, units=units, realizations=leading_dimension, **kwargs ) metadata_cube = squeeze(metadata_cube) diff --git a/improver/synthetic_data/set_up_test_cubes.py b/improver/synthetic_data/set_up_test_cubes.py index 85590c1fba..936be45830 100644 --- a/improver/synthetic_data/set_up_test_cubes.py +++ b/improver/synthetic_data/set_up_test_cubes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Functions to set up variable, multi-realization, percentile and probability @@ -267,10 +267,7 @@ def construct_scalar_time_coords( def _create_dimension_coord( - coord_array: Optional[List[float]], - data_length: int, - coord_name: str, - **kwargs: Any, + coord_array: Optional[List[float]], data_length: int, coord_name: str, **kwargs: Any ) -> DimCoord: """ Creates dimension coordinate from coord_array if not None, otherwise creating an @@ -279,8 +276,9 @@ def _create_dimension_coord( if coord_array is not None: if len(coord_array) != data_length: raise ValueError( - "Cannot generate {} {}s with data of length " - "{}".format(len(coord_array), coord_name, data_length) + "Cannot generate {} {}s with data of length " "{}".format( + len(coord_array), coord_name, data_length + ) ) coord_array = np.array(coord_array) @@ -704,7 +702,7 @@ def set_up_percentile_cube(*args, **kwargs): def _percentile_cube( - function, data: ndarray, percentiles: Union[List[float], ndarray], **kwargs: Any, + function, data: ndarray, percentiles: Union[List[float], ndarray], **kwargs: Any ) -> Cube: """ Set up a cube containing percentiles of a variable with: @@ -725,7 +723,7 @@ def _percentile_cube( Returns: Cube containing percentiles """ - cube = function(data, realizations=percentiles, **kwargs,) + cube = function(data, realizations=percentiles, **kwargs) cube.coord("realization").rename("percentile") cube.coord("percentile").units = Unit("%") if len(percentiles) == 1: @@ -816,7 +814,7 @@ def _probability_cube( ) raise ValueError(msg) - cube = function(data, name=name, units="1", realizations=thresholds, **kwargs,) + cube = function(data, name=name, units="1", realizations=thresholds, **kwargs) threshold_name = variable_name.replace("_in_vicinity", "") cube.coord("realization").rename(threshold_name) cube.coord(threshold_name).var_name = "threshold" @@ -888,7 +886,7 @@ def add_coordinate( for val in coord_points: temp_cube = cube.copy() coord = DimCoord( - np.array([val], dtype=dtype), units=coord_units, attributes=attributes, + np.array([val], dtype=dtype), units=coord_units, attributes=attributes ) coord.rename(coord_name) temp_cube.add_aux_coord(coord) diff --git a/improver/synthetic_data/utilities.py b/improver/synthetic_data/utilities.py index 6e793e6414..0d25e656af 100644 --- a/improver/synthetic_data/utilities.py +++ b/improver/synthetic_data/utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Functions required for additional processing in generate_metadata_cube CLI. diff --git a/improver/threshold.py b/improver/threshold.py index 5aba3af53a..e1d4f294af 100644 --- a/improver/threshold.py +++ b/improver/threshold.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing thresholding classes.""" @@ -34,7 +34,6 @@ class Threshold(PostProcessingPlugin): - """Apply a threshold truth criterion to a cube. Calculate the threshold truth values based on a linear membership function @@ -289,8 +288,9 @@ def _check_fuzzy_bounds(self) -> None: ) if bounds[0] > thr or bounds[1] < thr: bounds_msg = ( - "Threshold must be within bounds: " - "!( {} <= {} <= {} )".format(bounds[0], thr, bounds[1]) + "Threshold must be within bounds: " "!( {} <= {} <= {} )".format( + bounds[0], thr, bounds[1] + ) ) raise ValueError(bounds_msg) @@ -678,7 +678,6 @@ def process(self, input_cube: Cube, landmask: Cube = None) -> Cube: class LatitudeDependentThreshold(Threshold): - """Apply a latitude-dependent threshold truth criterion to a cube. Calculates the threshold truth values based on the threshold function provided. @@ -782,7 +781,7 @@ def process(self, input_cube: Cube) -> Cube: # Add a scalar axis for the longitude axis so that numpy's array- # broadcasting knows what we want to do truth_value = self.comparison_operator.function( - cube.data, np.expand_dims(threshold_over_latitude, 1), + cube.data, np.expand_dims(threshold_over_latitude, 1) ) truth_value = truth_value.astype(FLOAT_DTYPE) diff --git a/improver/utilities/cli_utilities.py b/improver/utilities/cli_utilities.py index bb5e33a378..cdc2937b6d 100644 --- a/improver/utilities/cli_utilities.py +++ b/improver/utilities/cli_utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Provides support utilities for cli scripts.""" diff --git a/improver/utilities/common_input_handle.py b/improver/utilities/common_input_handle.py index 1593f97975..046ddf94d4 100644 --- a/improver/utilities/common_input_handle.py +++ b/improver/utilities/common_input_handle.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. from typing import Union diff --git a/improver/utilities/compare.py b/improver/utilities/compare.py index 91a2368e5e..b96a6fc4e2 100644 --- a/improver/utilities/compare.py +++ b/improver/utilities/compare.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Compare netcdf files using python-netCDF4 library. @@ -258,7 +258,7 @@ def compare_vars( actual_var = actual_ds.variables[var] desired_var = desired_ds.variables[var] compare_attributes( - var_path, actual_var, desired_var, ignored_attributes, reporter, + var_path, actual_var, desired_var, ignored_attributes, reporter ) if var in coord_vars: compare_data(var_path, actual_var, desired_var, 0.0, 0.0, reporter) diff --git a/improver/utilities/complex_conversion.py b/improver/utilities/complex_conversion.py index b44ee601ea..3664c70869 100644 --- a/improver/utilities/complex_conversion.py +++ b/improver/utilities/complex_conversion.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. from typing import Union diff --git a/improver/utilities/copy_attributes.py b/improver/utilities/copy_attributes.py index b62488470a..81193f6473 100644 --- a/improver/utilities/copy_attributes.py +++ b/improver/utilities/copy_attributes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. from typing import List, Tuple, Union diff --git a/improver/utilities/cube_checker.py b/improver/utilities/cube_checker.py index af85cd958b..b133b6f959 100644 --- a/improver/utilities/cube_checker.py +++ b/improver/utilities/cube_checker.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Provides support utilities for checking cubes.""" +"""Provides support utilities for checking cubes.""" from typing import List, Optional, Union @@ -80,7 +80,6 @@ def check_cube_coordinates( new_cube_dim_names = [coord.name() for coord in new_cube.dim_coords] # If we have the wrong number of dimensions then raise an error. if len(cube.dim_coords) + len(exception_coordinates) != len(new_cube.dim_coords): - msg = ( "The number of dimension coordinates within the new cube " "do not match the number of dimension coordinates within the " diff --git a/improver/utilities/cube_constraints.py b/improver/utilities/cube_constraints.py index 51aeab6fa4..95f86c394f 100644 --- a/improver/utilities/cube_constraints.py +++ b/improver/utilities/cube_constraints.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module for helping to create Iris constraints.""" diff --git a/improver/utilities/cube_extraction.py b/improver/utilities/cube_extraction.py index ebf84d2185..9f221f3b4f 100644 --- a/improver/utilities/cube_extraction.py +++ b/improver/utilities/cube_extraction.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Utilities to parse a list of constraints and extract matching subcube """ +"""Utilities to parse a list of constraints and extract matching subcube""" from ast import literal_eval from typing import Callable, Dict, List, Optional, Tuple, Union @@ -351,9 +351,7 @@ class ExtractLevel(BasePlugin): Class for extracting a pressure or height surface from data-on-levels. """ - def __init__( - self, positive_correlation: bool, value_of_level: float, - ): + def __init__(self, positive_correlation: bool, value_of_level: float): """Sets up Class Args: @@ -403,7 +401,7 @@ def fill_invalid(self, cube: Cube): Args: cube: Cube of variable on levels (3D) (modified in-place). -""" + """ if np.isfinite(cube.data).all() and not np.ma.is_masked(cube.data): return data = np.ma.masked_invalid(cube.data) @@ -460,7 +458,7 @@ def _one_way_fill( c_slice = [slice(None)] * data.ndim c_slice[coordinate_axis] = slice(c, c + 1) data[c_slice] = np.ma.where( - data.mask[c_slice], data[last_slice] + local_increment, data[c_slice], + data.mask[c_slice], data[last_slice] + local_increment, data[c_slice] ) last_slice = c_slice diff --git a/improver/utilities/cube_manipulation.py b/improver/utilities/cube_manipulation.py index 6a94ce1b45..87e7475c74 100644 --- a/improver/utilities/cube_manipulation.py +++ b/improver/utilities/cube_manipulation.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Provides support utilities for cube manipulation.""" +"""Provides support utilities for cube manipulation.""" import warnings from typing import Any, Dict, List, Optional, Union @@ -563,7 +563,7 @@ def clip_cube_data(cube: Cube, minimum_value: float, maximum_value: float) -> Cu def expand_bounds( - result_cube: Cube, cubelist: Union[List[Cube], CubeList], coord_names: List[str], + result_cube: Cube, cubelist: Union[List[Cube], CubeList], coord_names: List[str] ) -> Cube: """Alter a coordinate on result_cube such that bounds are expanded to cover the entire range of the input cubes (cubelist). The input result_cube is @@ -586,7 +586,6 @@ def expand_bounds( Cube with coords expanded. """ for coord in coord_names: - if len(result_cube.coord(coord).points) != 1: emsg = ( "the expand bounds function should only be used on a" @@ -777,7 +776,7 @@ def maximum_in_height( def height_of_maximum( - cube: Cube, max_cube: Cube, find_lowest: bool = True, new_name: str = None, + cube: Cube, max_cube: Cube, find_lowest: bool = True, new_name: str = None ) -> Cube: """Calculates the height level at which the maximum value has been calculated. This takes in a cube with values at different heights, and also a cube with the maximum diff --git a/improver/utilities/extract_from_table.py b/improver/utilities/extract_from_table.py index a39af75b99..1247725254 100644 --- a/improver/utilities/extract_from_table.py +++ b/improver/utilities/extract_from_table.py @@ -1,9 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Provides ability to extract values from table.""" - +"""Provides ability to extract values from table.""" from typing import List @@ -18,7 +17,7 @@ class ExtractValueFromTable(BasePlugin): - """ Plugin to extract values from a table using the provided inputs cubes to select which + """Plugin to extract values from a table using the provided inputs cubes to select which rows and columns to extract. The table is expected to contain numerical labels for every row and column. These labels will be @@ -39,12 +38,12 @@ class ExtractValueFromTable(BasePlugin): def __init__(self, row_name: str, new_name: str = None) -> None: """Initialise the plugin - Args: - row_name: - Name of the cube used for indexing rows. - new_name: - Optional new name for the resulting cube. - """ + Args: + row_name: + Name of the cube used for indexing rows. + new_name: + Optional new name for the resulting cube. + """ self.row_name = row_name self.new_name = new_name @@ -53,13 +52,13 @@ def nearest_lower_index( values: np.array, sorted_table_labels: np.array ) -> np.array: """Returns the index of the nearest lower label for every element of values. - Args: - values: - Array of values to extract from table - table_label: - An array of the labels along an axis of the table. - Returns: - An array of indices of the nearest lower label for each value in values. + Args: + values: + Array of values to extract from table + table_label: + An array of the labels along an axis of the table. + Returns: + An array of indices of the nearest lower label for each value in values. """ sorted_index = np.searchsorted(sorted_table_labels, values, side="right") - 1 @@ -83,15 +82,15 @@ def extract_table_values( self, table: DataFrame, columns_cube: iris.cube.Cube, row_cube: iris.cube.Cube ) -> np.array: """Extract values from the table based on the provided row and column cubes. - Args: - table: - DataFrame representing the table from which values are extracted. - columns_cube: - Cube used to index the columns of the table. - row_cube: - Cube used to index the rows of the table. - Returns: - Array of values extracted from the table. + Args: + table: + DataFrame representing the table from which values are extracted. + columns_cube: + Cube used to index the columns of the table. + row_cube: + Cube used to index the rows of the table. + Returns: + Array of values extracted from the table. """ shape = columns_cube.shape diff --git a/improver/utilities/flatten.py b/improver/utilities/flatten.py index 762ed456d9..bf95e4e77a 100644 --- a/improver/utilities/flatten.py +++ b/improver/utilities/flatten.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Provides support utilities for flattening.""" +"""Provides support utilities for flattening.""" from typing import Any, Generator, Iterable, Union diff --git a/improver/utilities/forecast_reference_enforcement.py b/improver/utilities/forecast_reference_enforcement.py index 594dfa0253..c7a0886243 100644 --- a/improver/utilities/forecast_reference_enforcement.py +++ b/improver/utilities/forecast_reference_enforcement.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Provides utilities for updating a forecast or forecasts based on a reference.""" @@ -330,7 +330,7 @@ def normalise_to_reference( def split_cubes_by_name( - cubes: Union[Iterable[Cube], CubeList], cube_names: Union[str, List[str]] = None, + cubes: Union[Iterable[Cube], CubeList], cube_names: Union[str, List[str]] = None ) -> tuple: """Split a list of cubes into two lists; one containing all cubes with names which match cube_names, and the other containing all the other cubes. diff --git a/improver/utilities/gradient_between_vertical_levels.py b/improver/utilities/gradient_between_vertical_levels.py index 010d551804..80bddbfa0e 100644 --- a/improver/utilities/gradient_between_vertical_levels.py +++ b/improver/utilities/gradient_between_vertical_levels.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Calculate the gradient between two vertical levels.""" @@ -117,7 +117,6 @@ def gradient_over_vertical_levels( height_diff.data = np.ma.masked_where(height_diff.data == 0, height_diff.data) if "height" in coord_used and "pressure" in coord_used: - try: missing_coord = cubes[1].coord("pressure") except CoordinateNotFoundError: @@ -132,22 +131,22 @@ def gradient_over_vertical_levels( def process(self, *cubes: CubeList) -> Cube: """ - Process the input cubes to calculate the gradient between two vertical levels. - - Args: - cubes: - A cubelist of two cubes containing a diagnostic at two vertical levels. - The cubes must contain either a height or pressure scalar coordinate. - If exactly one of the cubes contain a height scalar coordinate this is assumed - to be a height above ground level and a cube with the name "surface_altitude" - must also be provided. If either cube contains a pressure scalar coordinate - a cube with the name "geopotential_height" must be provided.If both cubes are - on height levels then no additional cubes are required. - - Returns: - A cube containing the gradient between two vertical levels. The cube will be - named gradient of followed by the name of the input cubes. - """ + Process the input cubes to calculate the gradient between two vertical levels. + + Args: + cubes: + A cubelist of two cubes containing a diagnostic at two vertical levels. + The cubes must contain either a height or pressure scalar coordinate. + If exactly one of the cubes contain a height scalar coordinate this is assumed + to be a height above ground level and a cube with the name "surface_altitude" + must also be provided. If either cube contains a pressure scalar coordinate + a cube with the name "geopotential_height" must be provided.If both cubes are + on height levels then no additional cubes are required. + + Returns: + A cube containing the gradient between two vertical levels. The cube will be + named gradient of followed by the name of the input cubes. + """ cubes = as_cubelist(cubes) orography, cubes = self.extract_cube_from_list(cubes, "surface_altitude") geopotential_height, cubes = self.extract_cube_from_list( diff --git a/improver/utilities/indexing_operations.py b/improver/utilities/indexing_operations.py index 2321009ee1..7a6ce8cf30 100644 --- a/improver/utilities/indexing_operations.py +++ b/improver/utilities/indexing_operations.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to contain indexing operation functions.""" diff --git a/improver/utilities/interpolation.py b/improver/utilities/interpolation.py index 7e4e54c6d2..3f0c61c323 100644 --- a/improver/utilities/interpolation.py +++ b/improver/utilities/interpolation.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to contain interpolation functions.""" @@ -186,7 +186,6 @@ def process( for cslice, rslice in zip( cube.slices([yaxis, xaxis]), reference_cube.slices([yaxis, xaxis]) ): - invalid_points = cslice.data.mask.copy() valid_points = ~invalid_points diff --git a/improver/utilities/load.py b/improver/utilities/load.py index e47d06a4d2..55deb2b7a6 100644 --- a/improver/utilities/load.py +++ b/improver/utilities/load.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module for loading cubes.""" @@ -67,7 +67,6 @@ def load_cubelist( cubes = strip_var_names(cubes) for cube in cubes: - # Remove metadata attributes pointing to legacy prefix cube cube.attributes.pop("bald__isPrefixedBy", None) diff --git a/improver/utilities/mask.py b/improver/utilities/mask.py index db3b4af94a..49f72430fb 100644 --- a/improver/utilities/mask.py +++ b/improver/utilities/mask.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module for applying mask to a cube.""" diff --git a/improver/utilities/mathematical_operations.py b/improver/utilities/mathematical_operations.py index df6e16fd4c..b9f2398607 100644 --- a/improver/utilities/mathematical_operations.py +++ b/improver/utilities/mathematical_operations.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module to contain mathematical operations.""" @@ -263,7 +263,7 @@ def skip_slice(upper_bound, lower_bound, direction, start_point, end_point): lower_bounds_cube.slices_over(self.coord_name_to_integrate), ) - for (upper_bounds_slice, lower_bounds_slice) in levels_tuple: + for upper_bounds_slice, lower_bounds_slice in levels_tuple: (upper_bound,) = upper_bounds_slice.coord( self.coord_name_to_integrate ).points diff --git a/improver/utilities/neighbourhood_tools.py b/improver/utilities/neighbourhood_tools.py index 63f9dbf4ad..e994ae905e 100644 --- a/improver/utilities/neighbourhood_tools.py +++ b/improver/utilities/neighbourhood_tools.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Provides tools for neighbourhood generation""" diff --git a/improver/utilities/pad_spatial.py b/improver/utilities/pad_spatial.py index 7a381b6dd7..a2858aeacc 100644 --- a/improver/utilities/pad_spatial.py +++ b/improver/utilities/pad_spatial.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Utilities for spatial padding of iris cubes.""" diff --git a/improver/utilities/probability_manipulation.py b/improver/utilities/probability_manipulation.py index 9c8f3045c5..88a1942235 100644 --- a/improver/utilities/probability_manipulation.py +++ b/improver/utilities/probability_manipulation.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module for utilities that manipulate probabilities.""" @@ -36,21 +36,21 @@ def comparison_operator_dict() -> Dict[str, namedtuple]: comparison_operator_dict.update( dict.fromkeys( ["gt", "GT", ">"], - inequality(function=operator.gt, spp_string="greater_than", inverse="le",), + inequality(function=operator.gt, spp_string="greater_than", inverse="le"), ) ) comparison_operator_dict.update( dict.fromkeys( ["le", "LE", "<="], inequality( - function=operator.le, spp_string="less_than_or_equal_to", inverse="gt", + function=operator.le, spp_string="less_than_or_equal_to", inverse="gt" ), ) ) comparison_operator_dict.update( dict.fromkeys( ["lt", "LT", "<"], - inequality(function=operator.lt, spp_string="less_than", inverse="ge",), + inequality(function=operator.lt, spp_string="less_than", inverse="ge"), ) ) return comparison_operator_dict @@ -135,9 +135,9 @@ def invert_probabilities(cube: Cube) -> Cube: ) new_inequality = comparison_operator_lookup[inverse].spp_string inverted_probabilities = cube.copy(data=(1.0 - cube.data)) - inverted_probabilities.coord(threshold).attributes[ - "spp__relative_to_threshold" - ] = new_inequality + inverted_probabilities.coord(threshold).attributes["spp__relative_to_threshold"] = ( + new_inequality + ) new_name = ( cube.name().replace("above", "below") diff --git a/improver/utilities/redirect_stdout.py b/improver/utilities/redirect_stdout.py index 32ef1f87a2..9935843bde 100644 --- a/improver/utilities/redirect_stdout.py +++ b/improver/utilities/redirect_stdout.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Contains a class to trap stdout. Deprecated from PySteps v1.1.0 in favour of adding "silent_import=True" to the pyconfig file.""" diff --git a/improver/utilities/rescale.py b/improver/utilities/rescale.py index a84aa08b87..75a808f4b4 100644 --- a/improver/utilities/rescale.py +++ b/improver/utilities/rescale.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Provides support utility for rescaling data.""" diff --git a/improver/utilities/round.py b/improver/utilities/round.py index b45561baed..96f43ec851 100644 --- a/improver/utilities/round.py +++ b/improver/utilities/round.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Rounding utility""" diff --git a/improver/utilities/save.py b/improver/utilities/save.py index 98f3c4c17c..30d50d7b15 100644 --- a/improver/utilities/save.py +++ b/improver/utilities/save.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module for saving netcdf cubes with desired attribute types.""" diff --git a/improver/utilities/solar.py b/improver/utilities/solar.py index 1db25ece08..607668d68e 100644 --- a/improver/utilities/solar.py +++ b/improver/utilities/solar.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Utilities to find the relative position of the sun.""" +"""Utilities to find the relative position of the sun.""" + from datetime import datetime, timedelta from typing import Union @@ -257,7 +258,7 @@ class DayNightMask(BasePlugin): """ def __init__(self) -> None: - """ Initial the DayNightMask Object """ + """Initial the DayNightMask Object""" self.night = 0 self.day = 1 self.irregular = False diff --git a/improver/utilities/spatial.py b/improver/utilities/spatial.py index 5655e8e05d..024ad342de 100644 --- a/improver/utilities/spatial.py +++ b/improver/utilities/spatial.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Provides support utilities.""" +"""Provides support utilities.""" import copy from abc import ABC, abstractmethod @@ -636,7 +636,6 @@ def process(self, cube: Cube) -> Tuple[Cube, Cube]: class GradientBetweenAdjacentGridSquares(PostProcessingPlugin): - """Calculate the gradient between adjacent grid squares within a cube. The gradient is calculated along the x and y axis individually.""" @@ -827,7 +826,6 @@ def create_vicinity_coord( class OccurrenceWithinVicinity(PostProcessingPlugin): - """Calculate whether a phenomenon occurs within the specified radii about a point. These radii can be given in metres, or as numbers of grid points. Each radius provided will result in a distinct output, with these demarked diff --git a/improver/utilities/temporal.py b/improver/utilities/temporal.py index b2a9a210b5..133c2c7ff5 100644 --- a/improver/utilities/temporal.py +++ b/improver/utilities/temporal.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """General utilities for parsing and extracting cubes at times""" diff --git a/improver/utilities/temporal_interpolation.py b/improver/utilities/temporal_interpolation.py index d887c65e26..1e3f3e9412 100644 --- a/improver/utilities/temporal_interpolation.py +++ b/improver/utilities/temporal_interpolation.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Class for Temporal Interpolation calculations.""" @@ -25,7 +25,6 @@ class TemporalInterpolation(BasePlugin): - """ Interpolate data to intermediate times between the validity times of two cubes. This can be used to fill in missing data (e.g. for radar fields) or @@ -151,8 +150,9 @@ def __init__( known_interpolation_methods = ["linear", "solar", "daynight"] if interpolation_method not in known_interpolation_methods: raise ValueError( - "TemporalInterpolation: Unknown interpolation " - "method {}. ".format(interpolation_method) + "TemporalInterpolation: Unknown interpolation " "method {}. ".format( + interpolation_method + ) ) self.interpolation_method = interpolation_method self.period_inputs = False diff --git a/improver/utilities/textural.py b/improver/utilities/textural.py index 3a2fa04938..ecceac46ff 100644 --- a/improver/utilities/textural.py +++ b/improver/utilities/textural.py @@ -1,9 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Module containing plugin to calculate whether or not the input field texture - exceeds a given threshold.""" +"""Module containing plugin to calculate whether or not the input field texture +exceeds a given threshold.""" from typing import Optional diff --git a/improver/utilities/time_lagging.py b/improver/utilities/time_lagging.py index 96a6303668..0c9328b0b7 100644 --- a/improver/utilities/time_lagging.py +++ b/improver/utilities/time_lagging.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Provide support utilities for time lagging ensembles""" diff --git a/improver/uv_index.py b/improver/uv_index.py index 19d43632cd..0e06e4df8f 100644 --- a/improver/uv_index.py +++ b/improver/uv_index.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module for calculating the uv index using radiation flux in UV downward at the surface.""" @@ -17,7 +17,7 @@ def calculate_uv_index( - uv_downward: Cube, scale_factor: float = 3.6, model_id_attr: Optional[str] = None, + uv_downward: Cube, scale_factor: float = 3.6, model_id_attr: Optional[str] = None ) -> Cube: """ A plugin to calculate the uv index using radiation flux in UV downward diff --git a/improver/visibility/visibility_combine_cloud_base.py b/improver/visibility/visibility_combine_cloud_base.py index 323ee2d76a..a2c6ef6892 100644 --- a/improver/visibility/visibility_combine_cloud_base.py +++ b/improver/visibility/visibility_combine_cloud_base.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module for combining a visibility forecast with a scaled cloud base at ground level forecast""" @@ -123,7 +123,7 @@ def get_scaling_factors(self, vis_thresholds: np.ndarray) -> np.ndarray: in vis_thresholds. """ scaling_factors = (1 - self.initial_scaling_value) * ( - -1 / self.first_unscaled_threshold ** 4 + -1 / self.first_unscaled_threshold**4 ) * (vis_thresholds - self.first_unscaled_threshold) ** 4 + 1 scaling_factors = np.where( diff --git a/improver/wind_calculations/vertical_updraught.py b/improver/wind_calculations/vertical_updraught.py index b55f3e0652..0b5bd59221 100644 --- a/improver/wind_calculations/vertical_updraught.py +++ b/improver/wind_calculations/vertical_updraught.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """This module contains the VerticalUpdraught plugin""" diff --git a/improver/wind_calculations/wind_components.py b/improver/wind_calculations/wind_components.py index 9c6d8bbe86..52902351da 100644 --- a/improver/wind_calculations/wind_components.py +++ b/improver/wind_calculations/wind_components.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing plugin to resolve wind components.""" @@ -151,7 +151,6 @@ def resolve_wind_components( return [speed.copy(data=uspeed), speed.copy(data=vspeed)] def process(self, wind_speed: Cube, wind_dir: Cube) -> Tuple[Cube, Cube]: - """ Convert wind speed and direction into u,v components along input cube projection axes. diff --git a/improver/wind_calculations/wind_direction.py b/improver/wind_calculations/wind_direction.py index bd1f8cea3e..1ab2343e4d 100644 --- a/improver/wind_calculations/wind_direction.py +++ b/improver/wind_calculations/wind_direction.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing wind direction averaging plugins.""" + import iris import numpy as np from iris.coords import CellMethod @@ -25,8 +26,8 @@ class WindDirection(PostProcessingPlugin): find a useful numerical average. :: z = a + bi - a = r*Cos(theta) - b = r*Sin(theta) + a = r * Cos(theta) + b = r * Sin(theta) r = radius The average of two complex numbers is NOT the ANGLE between two points diff --git a/improver/wind_calculations/wind_downscaling.py b/improver/wind_calculations/wind_downscaling.py index 5a69a5f8cd..cd40afab9d 100644 --- a/improver/wind_calculations/wind_downscaling.py +++ b/improver/wind_calculations/wind_downscaling.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing wind downscaling plugins.""" diff --git a/improver/wind_calculations/wind_gust_diagnostic.py b/improver/wind_calculations/wind_gust_diagnostic.py index 4fa46df76d..5951dc077e 100644 --- a/improver/wind_calculations/wind_gust_diagnostic.py +++ b/improver/wind_calculations/wind_gust_diagnostic.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module containing plugin for WindGustDiagnostic.""" @@ -17,7 +17,6 @@ class WindGustDiagnostic(PostProcessingPlugin): - """Plugin for calculating wind-gust diagnostic. In the model a shear-driven turbulence parameterization is used to diff --git a/improver_tests/__init__.py b/improver_tests/__init__.py index d9000c0eed..17c8a8a982 100644 --- a/improver_tests/__init__.py +++ b/improver_tests/__init__.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Extends IrisTest class with additional useful tests.""" diff --git a/improver_tests/acceptance/acceptance.py b/improver_tests/acceptance/acceptance.py index 15be32d183..6837be01c8 100644 --- a/improver_tests/acceptance/acceptance.py +++ b/improver_tests/acceptance/acceptance.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Setup and checking of known good output for CLI tests""" @@ -169,7 +169,7 @@ def calculate_checksum(path): with open(path, mode="rb") as kgo_file: while True: # read 1 megabyte binary chunks from file and feed them to hasher - kgo_chunk = kgo_file.read(2 ** 20) + kgo_chunk = kgo_file.read(2**20) if not kgo_chunk: break hasher.update(kgo_chunk) diff --git a/improver_tests/acceptance/test_aggregate_reliability_tables.py b/improver_tests/acceptance/test_aggregate_reliability_tables.py index 9cd2c18511..753f694045 100644 --- a/improver_tests/acceptance/test_aggregate_reliability_tables.py +++ b/improver_tests/acceptance/test_aggregate_reliability_tables.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the aggregate-reliability-tables CLI.""" diff --git a/improver_tests/acceptance/test_apply_bias_correction.py b/improver_tests/acceptance/test_apply_bias_correction.py index d579559b90..0c91a4963b 100644 --- a/improver_tests/acceptance/test_apply_bias_correction.py +++ b/improver_tests/acceptance/test_apply_bias_correction.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the apply-bias-correction CLI.""" @@ -28,12 +28,7 @@ def test_single_bias_file(tmp_path): / "20220813T0300Z-PT0003H00M-wind_speed_at_10m.nc" ) output_path = tmp_path / "output.nc" - args = [ - fcst_path, - bias_file_path, - "--output", - output_path, - ] + args = [fcst_path, bias_file_path, "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) @@ -50,12 +45,7 @@ def test_multiple_bias_files(tmp_path): "202208*T0300Z-PT0003H00M-wind_speed_at_10m.nc" ) output_path = tmp_path / "output.nc" - args = [ - fcst_path, - *bias_file_paths, - "--output", - output_path, - ] + args = [fcst_path, *bias_file_paths, "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) @@ -103,12 +93,7 @@ def test_with_masked_bias_data(tmp_path): kgo_dir / "bias_data" / "20220813T0300Z-PT0003H00M-wind_speed_at_10m.nc" ) output_path = tmp_path / "output.nc" - args = [ - fcst_path, - bias_file_path, - "--output", - output_path, - ] + args = [fcst_path, bias_file_path, "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_apply_dz_rescaling.py b/improver_tests/acceptance/test_apply_dz_rescaling.py index b79548b82a..21b7afb78a 100644 --- a/improver_tests/acceptance/test_apply_dz_rescaling.py +++ b/improver_tests/acceptance/test_apply_dz_rescaling.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the apply-dz-rescaling CLI @@ -22,11 +22,6 @@ def test_apply_dz_rescaling(tmp_path): forecast_path = kgo_dir / "20230220T1200Z-PT0006H00M-wind_speed_at_10m.nc" scaled_dz_path = kgo_dir / "scaled_dz.nc" output_path = tmp_path / "output.nc" - args = [ - forecast_path, - scaled_dz_path, - "--output", - output_path, - ] + args = [forecast_path, scaled_dz_path, "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_apply_emos_coefficients.py b/improver_tests/acceptance/test_apply_emos_coefficients.py index 3343f7fe19..cbe02030a1 100644 --- a/improver_tests/acceptance/test_apply_emos_coefficients.py +++ b/improver_tests/acceptance/test_apply_emos_coefficients.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the apply-emos-coefficients CLI""" @@ -22,14 +22,7 @@ def test_normal(tmp_path): input_path = kgo_dir / "input.nc" emos_est_path = kgo_dir / "normal_coefficients.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - emos_est_path, - "--random-seed", - "0", - "--output", - output_path, - ] + args = [input_path, emos_est_path, "--random-seed", "0", "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path, atol=LOOSE_TOLERANCE) @@ -41,14 +34,7 @@ def test_truncated_normal(tmp_path): input_path = kgo_dir / "input.nc" emos_est_path = kgo_dir / "truncated_normal_coefficients.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - emos_est_path, - "--random-seed", - "0", - "--output", - output_path, - ] + args = [input_path, emos_est_path, "--random-seed", "0", "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path, atol=LOOSE_TOLERANCE) @@ -61,14 +47,7 @@ def test_normal_point_by_point_sites(tmp_path): input_path = kgo_dir / ".." / "realization_input.nc" emos_est_path = kgo_dir / "coefficients.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - emos_est_path, - "--random-seed", - "0", - "--output", - output_path, - ] + args = [input_path, emos_est_path, "--random-seed", "0", "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path, atol=LOOSE_TOLERANCE) @@ -82,14 +61,7 @@ def test_normal_sites_subhourly(tmp_path): input_path = kgo_dir / "offset_input.nc" emos_est_path = kgo_dir / "coefficients.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - emos_est_path, - "--random-seed", - "0", - "--output", - output_path, - ] + args = [input_path, emos_est_path, "--random-seed", "0", "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path, atol=LOOSE_TOLERANCE) @@ -186,12 +158,7 @@ def test_probabilities_error(tmp_path): input_path = kgo_dir / "input.nc" emos_est_path = kgo_dir / "../normal/normal_coefficients.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - emos_est_path, - "--output", - output_path, - ] + args = [input_path, emos_est_path, "--output", output_path] with pytest.raises(ValueError, match=".*provided as probabilities.*"): run_cli(args) @@ -266,12 +233,7 @@ def test_percentiles_error(tmp_path): input_path = kgo_dir / "input.nc" emos_est_path = kgo_dir / "../normal/normal_coefficients.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - emos_est_path, - "--output", - output_path, - ] + args = [input_path, emos_est_path, "--output", output_path] with pytest.raises(ValueError): run_cli(args) @@ -405,13 +367,7 @@ def test_no_coefficients(tmp_path): kgo_path = kgo_dir / "kgo_with_comment.nc" input_path = kgo_dir / "input.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - "--random-seed", - "0", - "--output", - output_path, - ] + args = [input_path, "--random-seed", "0", "--output", output_path] with pytest.warns(UserWarning, match=".*no coefficients provided.*"): run_cli(args) # Check output matches input excluding the comment attribute. @@ -478,9 +434,7 @@ def test_no_coefficients_with_prob_template(tmp_path): exclude_attributes="comment", ) # Check output matches kgo. - acc.compare( - output_path, kgo_path, atol=LOOSE_TOLERANCE, rtol=LOOSE_TOLERANCE, - ) + acc.compare(output_path, kgo_path, atol=LOOSE_TOLERANCE, rtol=LOOSE_TOLERANCE) def test_wrong_coefficients(tmp_path): @@ -488,14 +442,7 @@ def test_wrong_coefficients(tmp_path): kgo_dir = acc.kgo_root() / "apply-emos-coefficients/normal" input_path = kgo_dir / "input.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - input_path, - "--random-seed", - "0", - "--output", - output_path, - ] + args = [input_path, input_path, "--random-seed", "0", "--output", output_path] with pytest.raises(ValueError, match="Multiple items have been provided.*"): run_cli(args) diff --git a/improver_tests/acceptance/test_apply_height_adjustment.py b/improver_tests/acceptance/test_apply_height_adjustment.py index 5b6eed9a71..e47c6e7bfa 100644 --- a/improver_tests/acceptance/test_apply_height_adjustment.py +++ b/improver_tests/acceptance/test_apply_height_adjustment.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the apply-height-adjustment CLI""" diff --git a/improver_tests/acceptance/test_apply_lapse_rate.py b/improver_tests/acceptance/test_apply_lapse_rate.py index 1561282f6e..a064c23088 100644 --- a/improver_tests/acceptance/test_apply_lapse_rate.py +++ b/improver_tests/acceptance/test_apply_lapse_rate.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the apply-lapse-rate CLI""" diff --git a/improver_tests/acceptance/test_apply_mask.py b/improver_tests/acceptance/test_apply_mask.py index 050712bdbb..cc6dec726a 100644 --- a/improver_tests/acceptance/test_apply_mask.py +++ b/improver_tests/acceptance/test_apply_mask.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the apply-mask CLI diff --git a/improver_tests/acceptance/test_apply_night_mask.py b/improver_tests/acceptance/test_apply_night_mask.py index 91287a68b8..fcd93835e2 100644 --- a/improver_tests/acceptance/test_apply_night_mask.py +++ b/improver_tests/acceptance/test_apply_night_mask.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the apply-night-mask CLI""" diff --git a/improver_tests/acceptance/test_apply_rainforests_calibration.py b/improver_tests/acceptance/test_apply_rainforests_calibration.py index 37ab260c24..c6e608e0db 100644 --- a/improver_tests/acceptance/test_apply_rainforests_calibration.py +++ b/improver_tests/acceptance/test_apply_rainforests_calibration.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the apply-rainforests-calibration CLI.""" diff --git a/improver_tests/acceptance/test_apply_reliability_calibration.py b/improver_tests/acceptance/test_apply_reliability_calibration.py index 0e7d17b83b..85b11c0639 100644 --- a/improver_tests/acceptance/test_apply_reliability_calibration.py +++ b/improver_tests/acceptance/test_apply_reliability_calibration.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the apply-reliability-calibration CLI.""" diff --git a/improver_tests/acceptance/test_between_thresholds.py b/improver_tests/acceptance/test_between_thresholds.py index 3217fade01..abad640565 100644 --- a/improver_tests/acceptance/test_between_thresholds.py +++ b/improver_tests/acceptance/test_between_thresholds.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the between-thresholds CLI""" diff --git a/improver_tests/acceptance/test_blend_adjacent_points.py b/improver_tests/acceptance/test_blend_adjacent_points.py index ea0153485a..34d94a8eb9 100644 --- a/improver_tests/acceptance/test_blend_adjacent_points.py +++ b/improver_tests/acceptance/test_blend_adjacent_points.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the blend-adjacent-points CLI""" diff --git a/improver_tests/acceptance/test_blend_cycles_and_realizations.py b/improver_tests/acceptance/test_blend_cycles_and_realizations.py index 70635123e6..42a71077ea 100644 --- a/improver_tests/acceptance/test_blend_cycles_and_realizations.py +++ b/improver_tests/acceptance/test_blend_cycles_and_realizations.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the blend-cycles-and-realizations CLI @@ -22,12 +22,6 @@ def test_basic(tmp_path): input_dir = kgo_dir input_paths = sorted((input_dir.glob("??00Z_precip_rate.nc"))) output_path = tmp_path / "output.nc" - args = [ - "--cycletime", - "20190101T1000Z", - *input_paths, - "--output", - output_path, - ] + args = ["--cycletime", "20190101T1000Z", *input_paths, "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_blend_with_vicinity_and_rename.py b/improver_tests/acceptance/test_blend_with_vicinity_and_rename.py index 6de1261b46..65bea83ba7 100644 --- a/improver_tests/acceptance/test_blend_with_vicinity_and_rename.py +++ b/improver_tests/acceptance/test_blend_with_vicinity_and_rename.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the blend-with-vicinity-and-rename CLI diff --git a/improver_tests/acceptance/test_calculate_forecast_bias.py b/improver_tests/acceptance/test_calculate_forecast_bias.py index 79449daf06..4ed429691c 100644 --- a/improver_tests/acceptance/test_calculate_forecast_bias.py +++ b/improver_tests/acceptance/test_calculate_forecast_bias.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the calculate-forecast-bias CLI.""" diff --git a/improver_tests/acceptance/test_categorical.py b/improver_tests/acceptance/test_categorical.py index 7d3ffc1e6d..95a51ada34 100644 --- a/improver_tests/acceptance/test_categorical.py +++ b/improver_tests/acceptance/test_categorical.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the categorical CLI""" + import re import pytest @@ -193,13 +194,7 @@ def test_cubelist_input(tmp_path): wxtree = kgo_dir / "deterministic_decision_tree.json" output_path = tmp_path / "output.nc" - args = [ - *param_paths, - "--decision-tree", - wxtree, - "--output", - output_path, - ] + args = [*param_paths, "--decision-tree", wxtree, "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_categorical_modes.py b/improver_tests/acceptance/test_categorical_modes.py index 3d5875fe69..8e36dc9ad6 100644 --- a/improver_tests/acceptance/test_categorical_modes.py +++ b/improver_tests/acceptance/test_categorical_modes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the categorical-modes CLI""" @@ -60,11 +60,6 @@ def test_no_input(tmp_path): """Test an exceptions is raised by the CLI if no cubes are provided.""" wxtree = acc.kgo_root() / "categorical-modes" / "wx_decision_tree.json" output_path = tmp_path / "output.nc" - args = [ - "--decision-tree", - wxtree, - "--output", - output_path, - ] + args = ["--decision-tree", wxtree, "--output", output_path] with pytest.raises(RuntimeError, match="Not enough input arguments*"): run_cli(args) diff --git a/improver_tests/acceptance/test_checksums.py b/improver_tests/acceptance/test_checksums.py index 28bf266186..fbacdf99e8 100644 --- a/improver_tests/acceptance/test_checksums.py +++ b/improver_tests/acceptance/test_checksums.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Bulk checking and updating of checksum file""" diff --git a/improver_tests/acceptance/test_clip.py b/improver_tests/acceptance/test_clip.py index 5c793aae4d..8514a6d521 100644 --- a/improver_tests/acceptance/test_clip.py +++ b/improver_tests/acceptance/test_clip.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the clip CLI""" @@ -16,7 +16,7 @@ @pytest.mark.parametrize("cube_type", ("spot_data", "gridded_data")) @pytest.mark.parametrize("min_value,max_value", ((0, 4000), (None, 6000), (1000, None))) def test_basic(tmp_path, min_value, max_value, cube_type): - """Test clip functionality with different combinations of min and max values """ + """Test clip functionality with different combinations of min and max values""" kgo_dir = acc.kgo_root() / "clip" / cube_type kgo_path = kgo_dir / f"kgo_{min_value}_{max_value}.nc" output_path = tmp_path / "output.nc" diff --git a/improver_tests/acceptance/test_cloud_condensation_level.py b/improver_tests/acceptance/test_cloud_condensation_level.py index c064d15897..22b08dd09f 100644 --- a/improver_tests/acceptance/test_cloud_condensation_level.py +++ b/improver_tests/acceptance/test_cloud_condensation_level.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the vertical-updraught CLI""" diff --git a/improver_tests/acceptance/test_cloud_top_temperature.py b/improver_tests/acceptance/test_cloud_top_temperature.py index c8df7e0cad..0c396c5606 100644 --- a/improver_tests/acceptance/test_cloud_top_temperature.py +++ b/improver_tests/acceptance/test_cloud_top_temperature.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the cloud-top-temperature CLI""" diff --git a/improver_tests/acceptance/test_collapse_realizations.py b/improver_tests/acceptance/test_collapse_realizations.py index e310c3f4b1..5df44016d0 100644 --- a/improver_tests/acceptance/test_collapse_realizations.py +++ b/improver_tests/acceptance/test_collapse_realizations.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the collapse-realizations CLI""" - import pytest from . import acceptance as acc @@ -45,13 +44,7 @@ def test_no_rename(tmp_path): kgo_path = kgo_dir / "kgo_no_rename.nc" input_path = kgo_dir / "input.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - "--method", - "mean", - "--output", - output_path, - ] + args = [input_path, "--method", "mean", "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_combine.py b/improver_tests/acceptance/test_combine.py index cc520a45c7..2a1b84d746 100644 --- a/improver_tests/acceptance/test_combine.py +++ b/improver_tests/acceptance/test_combine.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the combine CLI""" diff --git a/improver_tests/acceptance/test_compare.py b/improver_tests/acceptance/test_compare.py index 80171f317b..425517f300 100644 --- a/improver_tests/acceptance/test_compare.py +++ b/improver_tests/acceptance/test_compare.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the compare CLI""" diff --git a/improver_tests/acceptance/test_construct_reliability_tables.py b/improver_tests/acceptance/test_construct_reliability_tables.py index 4b577a8489..00e2561641 100644 --- a/improver_tests/acceptance/test_construct_reliability_tables.py +++ b/improver_tests/acceptance/test_construct_reliability_tables.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the construct-reliability-tables CLI.""" diff --git a/improver_tests/acceptance/test_convection_ratio.py b/improver_tests/acceptance/test_convection_ratio.py index cd2a046fb9..0ccc938b93 100644 --- a/improver_tests/acceptance/test_convection_ratio.py +++ b/improver_tests/acceptance/test_convection_ratio.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the convection-ratio CLI""" @@ -12,10 +12,7 @@ CLI = acc.cli_name_with_dashes(__file__) run_cli = acc.run_cli(CLI) -ALL_PARAMS = [ - "lwe_convective_precipitation_rate", - "lwe_stratiform_precipitation_rate", -] +ALL_PARAMS = ["lwe_convective_precipitation_rate", "lwe_stratiform_precipitation_rate"] def test_basic(tmp_path): diff --git a/improver_tests/acceptance/test_copy_attributes.py b/improver_tests/acceptance/test_copy_attributes.py index 20d122c67f..55ad7bd832 100644 --- a/improver_tests/acceptance/test_copy_attributes.py +++ b/improver_tests/acceptance/test_copy_attributes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the copy-attributes CLI diff --git a/improver_tests/acceptance/test_create_grid_with_halo.py b/improver_tests/acceptance/test_create_grid_with_halo.py index ebe65bba79..a64b0e29b8 100644 --- a/improver_tests/acceptance/test_create_grid_with_halo.py +++ b/improver_tests/acceptance/test_create_grid_with_halo.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the create-grid-with-halo-points CLI""" diff --git a/improver_tests/acceptance/test_enforce_consistent_forecasts.py b/improver_tests/acceptance/test_enforce_consistent_forecasts.py index f294b44b5b..458c5c49d9 100644 --- a/improver_tests/acceptance/test_enforce_consistent_forecasts.py +++ b/improver_tests/acceptance/test_enforce_consistent_forecasts.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the enforce-consistent-forecasts CLI.""" @@ -104,7 +104,7 @@ def test_too_many_cubes(tmp_path): @pytest.mark.parametrize( "additive_amount, multiplicative_amount, comparison_operator", - (("0.0, 0.0", "1.0", ">="), ("0.0, 0.0, 0.0", "1.0, 1.0, 1.0", ">=, >=, <="),), + (("0.0, 0.0", "1.0", ">="), ("0.0, 0.0, 0.0", "1.0, 1.0, 1.0", ">=, >=, <=")), ) def test_bad_inputs( tmp_path, additive_amount, multiplicative_amount, comparison_operator diff --git a/improver_tests/acceptance/test_estimate_dz_rescaling.py b/improver_tests/acceptance/test_estimate_dz_rescaling.py index 75570e0930..3744b47057 100644 --- a/improver_tests/acceptance/test_estimate_dz_rescaling.py +++ b/improver_tests/acceptance/test_estimate_dz_rescaling.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the estimate-dz-rescaling CLI diff --git a/improver_tests/acceptance/test_estimate_emos_coefficients.py b/improver_tests/acceptance/test_estimate_emos_coefficients.py index fd0f7be794..12f272d177 100644 --- a/improver_tests/acceptance/test_estimate_emos_coefficients.py +++ b/improver_tests/acceptance/test_estimate_emos_coefficients.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the estimate-emos-coefficients CLI diff --git a/improver_tests/acceptance/test_estimate_emos_coefficients_from_table.py b/improver_tests/acceptance/test_estimate_emos_coefficients_from_table.py index 2cc725d030..8bda5fe896 100644 --- a/improver_tests/acceptance/test_estimate_emos_coefficients_from_table.py +++ b/improver_tests/acceptance/test_estimate_emos_coefficients_from_table.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the estimate-emos-coefficients-from-table CLI @@ -117,7 +117,7 @@ def test_basic( @pytest.mark.slow -def test_invalid_truth_filter(tmp_path,): +def test_invalid_truth_filter(tmp_path): """ Test using an invalid diagnostic name to filter the truth table. """ @@ -150,7 +150,7 @@ def test_invalid_truth_filter(tmp_path,): @pytest.mark.slow -def test_return_none(tmp_path,): +def test_return_none(tmp_path): """ Test that None is returned if a non-existent forecast period is requested. """ diff --git a/improver_tests/acceptance/test_expected_value.py b/improver_tests/acceptance/test_expected_value.py index c42d8b0f3d..d3ae9b2f8a 100644 --- a/improver_tests/acceptance/test_expected_value.py +++ b/improver_tests/acceptance/test_expected_value.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the expected-value CLI.""" - import iris import numpy as np import pytest diff --git a/improver_tests/acceptance/test_extend_radar_mask.py b/improver_tests/acceptance/test_extend_radar_mask.py index 0c6c2b68e5..1c9630b746 100644 --- a/improver_tests/acceptance/test_extend_radar_mask.py +++ b/improver_tests/acceptance/test_extend_radar_mask.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the extend-radar-mask CLI diff --git a/improver_tests/acceptance/test_extract.py b/improver_tests/acceptance/test_extract.py index 6ed24b0d6d..e928bfac71 100644 --- a/improver_tests/acceptance/test_extract.py +++ b/improver_tests/acceptance/test_extract.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the extract CLI diff --git a/improver_tests/acceptance/test_extract_from_table.py b/improver_tests/acceptance/test_extract_from_table.py index 6059fa69c1..4b5d557f25 100644 --- a/improver_tests/acceptance/test_extract_from_table.py +++ b/improver_tests/acceptance/test_extract_from_table.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the extract CLI diff --git a/improver_tests/acceptance/test_feels_like_temp.py b/improver_tests/acceptance/test_feels_like_temp.py index cc0f8ced71..8431646162 100644 --- a/improver_tests/acceptance/test_feels_like_temp.py +++ b/improver_tests/acceptance/test_feels_like_temp.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the feels-like-temp CLI diff --git a/improver_tests/acceptance/test_field_texture.py b/improver_tests/acceptance/test_field_texture.py index c9922fc6fc..9dbe273362 100644 --- a/improver_tests/acceptance/test_field_texture.py +++ b/improver_tests/acceptance/test_field_texture.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the field-texture CLI""" @@ -21,11 +21,7 @@ def test_basic(tmp_path): input_path = kgo_dir / "input.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - "--output", - output_path, - ] + args = [input_path, "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_fill_radar_holes.py b/improver_tests/acceptance/test_fill_radar_holes.py index b3f257a67d..f01a073aba 100644 --- a/improver_tests/acceptance/test_fill_radar_holes.py +++ b/improver_tests/acceptance/test_fill_radar_holes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the fill-radar-holes CLI diff --git a/improver_tests/acceptance/test_freezing_rain.py b/improver_tests/acceptance/test_freezing_rain.py index 328fd6e07d..27ab3d86b4 100644 --- a/improver_tests/acceptance/test_freezing_rain.py +++ b/improver_tests/acceptance/test_freezing_rain.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the freezing-rain CLI""" diff --git a/improver_tests/acceptance/test_generate_clearsky_solar_radiation.py b/improver_tests/acceptance/test_generate_clearsky_solar_radiation.py index 111bc58256..336a03462a 100644 --- a/improver_tests/acceptance/test_generate_clearsky_solar_radiation.py +++ b/improver_tests/acceptance/test_generate_clearsky_solar_radiation.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the generate-clearsky-solar-radiation CLI.""" diff --git a/improver_tests/acceptance/test_generate_landmask_ancillary.py b/improver_tests/acceptance/test_generate_landmask_ancillary.py index d732a1a35d..a6e47823b9 100644 --- a/improver_tests/acceptance/test_generate_landmask_ancillary.py +++ b/improver_tests/acceptance/test_generate_landmask_ancillary.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the generate-landmask-ancillary CLI diff --git a/improver_tests/acceptance/test_generate_metadata_cube.py b/improver_tests/acceptance/test_generate_metadata_cube.py index 696d27cfd2..b22f9c62f6 100644 --- a/improver_tests/acceptance/test_generate_metadata_cube.py +++ b/improver_tests/acceptance/test_generate_metadata_cube.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the generate-metadata-cube CLI.""" @@ -19,11 +19,7 @@ def test_default(tmp_path): """Test default metadata cube generation""" kgo_path = kgo_dir / "kgo_default.nc" output_path = tmp_path / "output.nc" - args = [ - mandatory_attributes_json, - "--output", - output_path, - ] + args = [mandatory_attributes_json, "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_generate_orographic_smoothing_coefficients.py b/improver_tests/acceptance/test_generate_orographic_smoothing_coefficients.py index 5dacf9a196..fcd8f84962 100644 --- a/improver_tests/acceptance/test_generate_orographic_smoothing_coefficients.py +++ b/improver_tests/acceptance/test_generate_orographic_smoothing_coefficients.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the generate-orographic-smoothing-coefficients CLI @@ -59,13 +59,7 @@ def test_altered_power(tmp_path): input_path = kgo_dir / "orography.nc" kgo_path = kgo_dir / "basic" / "kgo_different_power.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - "--power", - "0.5", - "--output", - output_path, - ] + args = [input_path, "--power", "0.5", "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_generate_percentiles.py b/improver_tests/acceptance/test_generate_percentiles.py index 6b253c26ea..48b9f95b36 100644 --- a/improver_tests/acceptance/test_generate_percentiles.py +++ b/improver_tests/acceptance/test_generate_percentiles.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the generate-percentiles CLI""" @@ -53,7 +53,7 @@ def test_probconvert(tmp_path, count): @pytest.mark.slow -def test_ignore_ecc_bounds(tmp_path,): +def test_ignore_ecc_bounds(tmp_path): """Test ECC bounds warning option""" kgo_dir = acc.kgo_root() / "generate-percentiles/ecc_bounds_warning" kgo_path = kgo_dir / "kgo.nc" @@ -150,11 +150,7 @@ def test_rebadging(tmp_path, identifier): kgo_path = kgo_dir / "rebadging" / f"{identifier}_kgo.nc" perc_input = kgo_dir / "input.nc" output_path = tmp_path / "output.nc" - args = [ - perc_input, - "--output", - output_path, - ] + args = [perc_input, "--output", output_path] if identifier == "optimal_crps_percentiles": args += ["--optimal-crps-percentiles"] diff --git a/improver_tests/acceptance/test_generate_realizations.py b/improver_tests/acceptance/test_generate_realizations.py index e72a2af756..c43d4e90d7 100644 --- a/improver_tests/acceptance/test_generate_realizations.py +++ b/improver_tests/acceptance/test_generate_realizations.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the generate-realizations CLI @@ -63,13 +63,7 @@ def test_skip_ecc_bounds_extreme_percentiles(tmp_path, bounds_option, kgo): kgo_path = kgo_dir / kgo percentiles_path = kgo_dir / "few_percentiles_wind_cube.nc" output_path = tmp_path / "output.nc" - args = [ - "--realizations-count", - "5", - percentiles_path, - "--output", - output_path, - ] + args = ["--realizations-count", "5", percentiles_path, "--output", output_path] if bounds_option: args += [bounds_option] run_cli(args) diff --git a/improver_tests/acceptance/test_generate_solar_time.py b/improver_tests/acceptance/test_generate_solar_time.py index 3ec06d4175..958ca0439a 100644 --- a/improver_tests/acceptance/test_generate_solar_time.py +++ b/improver_tests/acceptance/test_generate_solar_time.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the generate-solar-time CLI.""" @@ -19,13 +19,7 @@ def test_basic(tmp_path): kgo_path = kgo_dir / "basic" / "kgo.nc" input_path = kgo_dir / "surface_altitude.nc" # Use this as target_grid output_path = tmp_path / "output.nc" - args = [ - input_path, - "--time", - "20220607T0000Z", - "--output", - output_path, - ] + args = [input_path, "--time", "20220607T0000Z", "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_generate_topography_bands.py b/improver_tests/acceptance/test_generate_topography_bands.py index e4af1b163b..67a25439b5 100644 --- a/improver_tests/acceptance/test_generate_topography_bands.py +++ b/improver_tests/acceptance/test_generate_topography_bands.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the generate-topography-bands-mask and diff --git a/improver_tests/acceptance/test_gradient_between_vertical_levels.py b/improver_tests/acceptance/test_gradient_between_vertical_levels.py index e6e3977682..02422f29d4 100644 --- a/improver_tests/acceptance/test_gradient_between_vertical_levels.py +++ b/improver_tests/acceptance/test_gradient_between_vertical_levels.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the gradient-between-vertical-levels CLI""" diff --git a/improver_tests/acceptance/test_hail_fraction.py b/improver_tests/acceptance/test_hail_fraction.py index 3ce5dac0ad..923e382506 100644 --- a/improver_tests/acceptance/test_hail_fraction.py +++ b/improver_tests/acceptance/test_hail_fraction.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the hail fraction CLI""" diff --git a/improver_tests/acceptance/test_hail_size.py b/improver_tests/acceptance/test_hail_size.py index 20ae73649a..0ea32c819a 100644 --- a/improver_tests/acceptance/test_hail_size.py +++ b/improver_tests/acceptance/test_hail_size.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the hail_size CLI""" diff --git a/improver_tests/acceptance/test_height_of_max_vertical_velocity.py b/improver_tests/acceptance/test_height_of_max_vertical_velocity.py index 8ea42ec1f7..c037eacda9 100644 --- a/improver_tests/acceptance/test_height_of_max_vertical_velocity.py +++ b/improver_tests/acceptance/test_height_of_max_vertical_velocity.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests the height_of_max_vertical_velocity cli""" @@ -19,12 +19,7 @@ def test_basic(tmp_path): input_file1 = kgo_dir / "vertical_velocity_on_height_levels.nc" input_file2 = kgo_dir / "max_vertical_velocity.nc" output_path = tmp_path / "output.nc" - args = [ - input_file1, - input_file2, - "--output", - f"{output_path}", - ] + args = [input_file1, input_file2, "--output", f"{output_path}"] kgo_path = kgo_dir / "kgo.nc" run_cli(args) diff --git a/improver_tests/acceptance/test_integrate_time_bounds.py b/improver_tests/acceptance/test_integrate_time_bounds.py index a212dcc527..95fd8f48b7 100644 --- a/improver_tests/acceptance/test_integrate_time_bounds.py +++ b/improver_tests/acceptance/test_integrate_time_bounds.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the integrate_time_bounds CLI diff --git a/improver_tests/acceptance/test_interpolate_using_difference.py b/improver_tests/acceptance/test_interpolate_using_difference.py index b6b3d79610..d22e089a6a 100644 --- a/improver_tests/acceptance/test_interpolate_using_difference.py +++ b/improver_tests/acceptance/test_interpolate_using_difference.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the interpolate-using-difference CLI diff --git a/improver_tests/acceptance/test_interpret_metadata.py b/improver_tests/acceptance/test_interpret_metadata.py index bcb6264260..0606543759 100644 --- a/improver_tests/acceptance/test_interpret_metadata.py +++ b/improver_tests/acceptance/test_interpret_metadata.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the interpret-metadata CLI diff --git a/improver_tests/acceptance/test_lightning_from_cape_and_precip.py b/improver_tests/acceptance/test_lightning_from_cape_and_precip.py index e0a166e087..d13601c43a 100644 --- a/improver_tests/acceptance/test_lightning_from_cape_and_precip.py +++ b/improver_tests/acceptance/test_lightning_from_cape_and_precip.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the lightning_from_cape_and_precip CLI""" @@ -21,12 +21,7 @@ def test_basic(tmp_path, with_model_attr): cape_path = kgo_dir / "cape.nc" precipitation_path = kgo_dir / "precipitation_rate.nc" output_path = tmp_path / "output.nc" - args = [ - cape_path, - precipitation_path, - "--output", - f"{output_path}", - ] + args = [cape_path, precipitation_path, "--output", f"{output_path}"] if with_model_attr: args.append("--model-id-attr=mosg__model_configuration") kgo_path = kgo_dir / "kgo_with_model_config.nc" diff --git a/improver_tests/acceptance/test_lightning_multivariate_probability_usaf2024.py b/improver_tests/acceptance/test_lightning_multivariate_probability_usaf2024.py index a35b3195a1..f27f095fb8 100644 --- a/improver_tests/acceptance/test_lightning_multivariate_probability_usaf2024.py +++ b/improver_tests/acceptance/test_lightning_multivariate_probability_usaf2024.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the lightning_usaf""" diff --git a/improver_tests/acceptance/test_manipulate_reliability_table.py b/improver_tests/acceptance/test_manipulate_reliability_table.py index 611e04a581..5c392195b4 100644 --- a/improver_tests/acceptance/test_manipulate_reliability_table.py +++ b/improver_tests/acceptance/test_manipulate_reliability_table.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the manipulate-reliability-table CLI.""" diff --git a/improver_tests/acceptance/test_max_in_height.py b/improver_tests/acceptance/test_max_in_height.py index 6f482240ff..cf8d2f6665 100644 --- a/improver_tests/acceptance/test_max_in_height.py +++ b/improver_tests/acceptance/test_max_in_height.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests the max_in_height CLI""" diff --git a/improver_tests/acceptance/test_max_in_time_window.py b/improver_tests/acceptance/test_max_in_time_window.py index 4c6d3f14b1..77a11c0f9f 100644 --- a/improver_tests/acceptance/test_max_in_time_window.py +++ b/improver_tests/acceptance/test_max_in_time_window.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the max_in_time_window CLI""" diff --git a/improver_tests/acceptance/test_merge.py b/improver_tests/acceptance/test_merge.py index 1ee7842f35..c584675e6f 100644 --- a/improver_tests/acceptance/test_merge.py +++ b/improver_tests/acceptance/test_merge.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the merge CLI diff --git a/improver_tests/acceptance/test_nbhood.py b/improver_tests/acceptance/test_nbhood.py index c485651076..76ec3fc9ce 100644 --- a/improver_tests/acceptance/test_nbhood.py +++ b/improver_tests/acceptance/test_nbhood.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the nbhood CLI diff --git a/improver_tests/acceptance/test_nbhood_iterate_with_mask.py b/improver_tests/acceptance/test_nbhood_iterate_with_mask.py index 33c1e008b0..53ee1298ce 100644 --- a/improver_tests/acceptance/test_nbhood_iterate_with_mask.py +++ b/improver_tests/acceptance/test_nbhood_iterate_with_mask.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the nbhood-iterate-with-mask CLI diff --git a/improver_tests/acceptance/test_nbhood_land_and_sea.py b/improver_tests/acceptance/test_nbhood_land_and_sea.py index 724eec949d..04240147e6 100644 --- a/improver_tests/acceptance/test_nbhood_land_and_sea.py +++ b/improver_tests/acceptance/test_nbhood_land_and_sea.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the nbhood-land-and-sea CLI @@ -16,7 +16,7 @@ @pytest.mark.parametrize( - "kgo_name, shape", (("kgo.nc", "square"), ("kgo_circular.nc", "circular")), + "kgo_name, shape", (("kgo.nc", "square"), ("kgo_circular.nc", "circular")) ) def test_basic(tmp_path, kgo_name, shape): """Test basic land-sea without topographic bands""" diff --git a/improver_tests/acceptance/test_neighbour_finding.py b/improver_tests/acceptance/test_neighbour_finding.py index 368a75c3a0..b00bdc9a35 100644 --- a/improver_tests/acceptance/test_neighbour_finding.py +++ b/improver_tests/acceptance/test_neighbour_finding.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the neighbour-finding CLI diff --git a/improver_tests/acceptance/test_normalise_to_reference.py b/improver_tests/acceptance/test_normalise_to_reference.py index b18beb6c1d..2c86376b13 100644 --- a/improver_tests/acceptance/test_normalise_to_reference.py +++ b/improver_tests/acceptance/test_normalise_to_reference.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the normalise-to-reference CLI.""" @@ -17,9 +17,7 @@ "forecast_type,ignore_zero_total", (("probability", False), ("percentile", False), ("percentile", True)), ) -def test_normalise_to_reference( - tmp_path, forecast_type, ignore_zero_total, -): +def test_normalise_to_reference(tmp_path, forecast_type, ignore_zero_total): """ Test input cubes are updated correctly so that their total equals the reference cube """ diff --git a/improver_tests/acceptance/test_nowcast_accumulate.py b/improver_tests/acceptance/test_nowcast_accumulate.py index 67dbf231b2..7ef4026005 100644 --- a/improver_tests/acceptance/test_nowcast_accumulate.py +++ b/improver_tests/acceptance/test_nowcast_accumulate.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests the nowcast-accumulate CLI""" diff --git a/improver_tests/acceptance/test_nowcast_extrapolate.py b/improver_tests/acceptance/test_nowcast_extrapolate.py index 4072b1caee..53ee313999 100644 --- a/improver_tests/acceptance/test_nowcast_extrapolate.py +++ b/improver_tests/acceptance/test_nowcast_extrapolate.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the nowcast-extrapolate CLI diff --git a/improver_tests/acceptance/test_nowcast_optical_flow.py b/improver_tests/acceptance/test_nowcast_optical_flow.py index 687fd59792..5afd3d8df7 100644 --- a/improver_tests/acceptance/test_nowcast_optical_flow.py +++ b/improver_tests/acceptance/test_nowcast_optical_flow.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the nowcast-optical-flow CLI diff --git a/improver_tests/acceptance/test_nowcast_optical_flow_from_winds.py b/improver_tests/acceptance/test_nowcast_optical_flow_from_winds.py index 9879e72557..825ef9bfe4 100644 --- a/improver_tests/acceptance/test_nowcast_optical_flow_from_winds.py +++ b/improver_tests/acceptance/test_nowcast_optical_flow_from_winds.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the nowcast-optical-flow-from-winds CLI""" diff --git a/improver_tests/acceptance/test_orographic_enhancement.py b/improver_tests/acceptance/test_orographic_enhancement.py index 8d065800fe..79c7dff781 100644 --- a/improver_tests/acceptance/test_orographic_enhancement.py +++ b/improver_tests/acceptance/test_orographic_enhancement.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the orographic-enhancement CLI diff --git a/improver_tests/acceptance/test_phase_change_level.py b/improver_tests/acceptance/test_phase_change_level.py index 861f065402..9734c905fd 100644 --- a/improver_tests/acceptance/test_phase_change_level.py +++ b/improver_tests/acceptance/test_phase_change_level.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the phase-change-level CLI @@ -27,11 +27,11 @@ ) def test_phase_change(tmp_path, phase_type, kgo_name, horiz_interp, model_id_attr): """Testing: - snow/sleet level - sleet/rain level - hail/rain level - sleet/rain level leaving below orography points unfilled. - Tests are for with and without the provision of the model_id_attr attribute. + snow/sleet level + sleet/rain level + hail/rain level + sleet/rain level leaving below orography points unfilled. + Tests are for with and without the provision of the model_id_attr attribute. """ pytest.importorskip("stratify") test_dir = acc.kgo_root() / CLI diff --git a/improver_tests/acceptance/test_phase_mask.py b/improver_tests/acceptance/test_phase_mask.py index 57e1364ca2..58b8b2b47a 100644 --- a/improver_tests/acceptance/test_phase_mask.py +++ b/improver_tests/acceptance/test_phase_mask.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the snow-fraction CLI""" diff --git a/improver_tests/acceptance/test_phase_probability.py b/improver_tests/acceptance/test_phase_probability.py index 11d49a892d..1009910d19 100644 --- a/improver_tests/acceptance/test_phase_probability.py +++ b/improver_tests/acceptance/test_phase_probability.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the phase-probability CLI @@ -19,11 +19,7 @@ @pytest.mark.parametrize("ptype", ("deterministic", "percentiles")) @pytest.mark.parametrize( "kgo_name,input_file", - [ - ("snow_kgo", "snow_sleet"), - ("rain_kgo", "sleet_rain"), - ("hail_kgo", "hail_rain"), - ], + [("snow_kgo", "snow_sleet"), ("rain_kgo", "sleet_rain"), ("hail_kgo", "hail_rain")], ) def test_phase_probabilities(tmp_path, kgo_name, input_file, ptype, gtype): """Test phase probability calculations for snow->sleet, sleet->rain and hail->rain. @@ -37,10 +33,7 @@ def test_phase_probabilities(tmp_path, kgo_name, input_file, ptype, gtype): kgo_dir = acc.kgo_root() / f"{CLI}/{gtype}" kgo_path = kgo_dir / f"{kgo_name}_{ptype}.nc" output_path = tmp_path / "output.nc" - input_paths = [ - kgo_dir / "altitudes.nc", - kgo_dir / f"{input_file}_{ptype}.nc", - ] + input_paths = [kgo_dir / "altitudes.nc", kgo_dir / f"{input_file}_{ptype}.nc"] args = [*input_paths, "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_recursive_filter.py b/improver_tests/acceptance/test_recursive_filter.py index 618cee7607..4ffa019009 100644 --- a/improver_tests/acceptance/test_recursive_filter.py +++ b/improver_tests/acceptance/test_recursive_filter.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the recursive-filter CLI @@ -34,11 +34,6 @@ def test_internal_mask(tmp_path): input_path = kgo_dir / "input_masked.nc" smoothing_coefficients_path = kgo_dir / "smoothing_coefficients.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - smoothing_coefficients_path, - "--output", - output_path, - ] + args = [input_path, smoothing_coefficients_path, "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_regrid.py b/improver_tests/acceptance/test_regrid.py index c333f03602..7efe2e1c23 100644 --- a/improver_tests/acceptance/test_regrid.py +++ b/improver_tests/acceptance/test_regrid.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the regrid CLI diff --git a/improver_tests/acceptance/test_relabel_to_period.py b/improver_tests/acceptance/test_relabel_to_period.py index b02d315dd4..b7f8080554 100644 --- a/improver_tests/acceptance/test_relabel_to_period.py +++ b/improver_tests/acceptance/test_relabel_to_period.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the relabel_to_period CLI.""" diff --git a/improver_tests/acceptance/test_remake_as_shower_condition.py b/improver_tests/acceptance/test_remake_as_shower_condition.py index aed89b6cd1..0b319fde03 100644 --- a/improver_tests/acceptance/test_remake_as_shower_condition.py +++ b/improver_tests/acceptance/test_remake_as_shower_condition.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the remake-as-shower-condition CLI""" @@ -21,10 +21,6 @@ def test_basic(tmp_path): inputs = kgo_dir / "cloud_texture.nc" output_path = tmp_path / "output.nc" - args = [ - inputs, - "--output", - output_path, - ] + args = [inputs, "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_resolve_wind_components.py b/improver_tests/acceptance/test_resolve_wind_components.py index b42a726cec..b2db7713ae 100644 --- a/improver_tests/acceptance/test_resolve_wind_components.py +++ b/improver_tests/acceptance/test_resolve_wind_components.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the resolve-wind-components CLI diff --git a/improver_tests/acceptance/test_shower_condition_probability.py b/improver_tests/acceptance/test_shower_condition_probability.py index ab7bb3c85d..41886cca35 100644 --- a/improver_tests/acceptance/test_shower_condition_probability.py +++ b/improver_tests/acceptance/test_shower_condition_probability.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the shower-condition-probability CLI""" diff --git a/improver_tests/acceptance/test_sleet_probability.py b/improver_tests/acceptance/test_sleet_probability.py index e713fd6f4b..34f884b2c4 100644 --- a/improver_tests/acceptance/test_sleet_probability.py +++ b/improver_tests/acceptance/test_sleet_probability.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the sleet-probability CLI diff --git a/improver_tests/acceptance/test_snow_fraction.py b/improver_tests/acceptance/test_snow_fraction.py index dce174059b..af1d699bf9 100644 --- a/improver_tests/acceptance/test_snow_fraction.py +++ b/improver_tests/acceptance/test_snow_fraction.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the snow-fraction CLI""" diff --git a/improver_tests/acceptance/test_snow_splitter.py b/improver_tests/acceptance/test_snow_splitter.py index 761e5c9755..cc57ef5854 100644 --- a/improver_tests/acceptance/test_snow_splitter.py +++ b/improver_tests/acceptance/test_snow_splitter.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the snow-splitter CLI""" diff --git a/improver_tests/acceptance/test_spot_extract.py b/improver_tests/acceptance/test_spot_extract.py index 6016e5f422..90f0ac7c5e 100644 --- a/improver_tests/acceptance/test_spot_extract.py +++ b/improver_tests/acceptance/test_spot_extract.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the spot-extract CLI diff --git a/improver_tests/acceptance/test_standardise.py b/improver_tests/acceptance/test_standardise.py index 99441f47ab..5a47426b8a 100644 --- a/improver_tests/acceptance/test_standardise.py +++ b/improver_tests/acceptance/test_standardise.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the standardise CLI @@ -48,13 +48,7 @@ def test_fix_float64(tmp_path): kgo_path = kgo_dir / "kgo.nc" input_path = kgo_dir / "float64_data.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - "--attributes-config", - ATTRIBUTES_PATH, - "--output", - output_path, - ] + args = [input_path, "--attributes-config", ATTRIBUTES_PATH, "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_temp_lapse_rate.py b/improver_tests/acceptance/test_temp_lapse_rate.py index 5ec429b905..9b7c4010a4 100644 --- a/improver_tests/acceptance/test_temp_lapse_rate.py +++ b/improver_tests/acceptance/test_temp_lapse_rate.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the temp-lapse-rate CLI diff --git a/improver_tests/acceptance/test_temporal_interpolate.py b/improver_tests/acceptance/test_temporal_interpolate.py index c3dea620a1..e5bbb1d212 100644 --- a/improver_tests/acceptance/test_temporal_interpolate.py +++ b/improver_tests/acceptance/test_temporal_interpolate.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the temporal-interpolate CLI diff --git a/improver_tests/acceptance/test_threshold.py b/improver_tests/acceptance/test_threshold.py index a98cd5b129..186ffc779f 100644 --- a/improver_tests/acceptance/test_threshold.py +++ b/improver_tests/acceptance/test_threshold.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the threshold CLI diff --git a/improver_tests/acceptance/test_time_lagged_ensembles.py b/improver_tests/acceptance/test_time_lagged_ensembles.py index 70c562d30b..171ce27a19 100644 --- a/improver_tests/acceptance/test_time_lagged_ensembles.py +++ b/improver_tests/acceptance/test_time_lagged_ensembles.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the time-lagged-ensembles CLI diff --git a/improver_tests/acceptance/test_uv_index.py b/improver_tests/acceptance/test_uv_index.py index 688afae763..06fec3b804 100644 --- a/improver_tests/acceptance/test_uv_index.py +++ b/improver_tests/acceptance/test_uv_index.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the uv-index CLI diff --git a/improver_tests/acceptance/test_vertical_updraught.py b/improver_tests/acceptance/test_vertical_updraught.py index 2708103e10..41099f1f69 100644 --- a/improver_tests/acceptance/test_vertical_updraught.py +++ b/improver_tests/acceptance/test_vertical_updraught.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the vertical-updraught CLI""" diff --git a/improver_tests/acceptance/test_vicinity.py b/improver_tests/acceptance/test_vicinity.py index 8c1f63c4ab..2b985990ae 100644 --- a/improver_tests/acceptance/test_vicinity.py +++ b/improver_tests/acceptance/test_vicinity.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the vicinity CLI""" @@ -20,12 +20,7 @@ def test_basic(tmp_path, vicinity): kgo_path = kgo_dir / f"kgo_{vicinity}.nc" input_path = kgo_dir / "lightning.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - vicinity, - "--output", - f"{output_path}", - ] + args = [input_path, vicinity, "--output", f"{output_path}"] run_cli(args) acc.compare(output_path, kgo_path) @@ -37,12 +32,7 @@ def test_multiple_vicinities(tmp_path): kgo_path = kgo_dir / "kgo_multiple_radii.nc" input_path = kgo_dir / "lightning.nc" output_path = tmp_path / "output.nc" - args = [ - input_path, - "10000,20000", - "--output", - f"{output_path}", - ] + args = [input_path, "10000,20000", "--output", f"{output_path}"] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_visibility_combine_cloud_base.py b/improver_tests/acceptance/test_visibility_combine_cloud_base.py index d91a94c44e..c6a621d5c2 100644 --- a/improver_tests/acceptance/test_visibility_combine_cloud_base.py +++ b/improver_tests/acceptance/test_visibility_combine_cloud_base.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the VisibilityCombineCloudBase CLI""" diff --git a/improver_tests/acceptance/test_weighted_blending.py b/improver_tests/acceptance/test_weighted_blending.py index f067fcbe35..e5a0791248 100644 --- a/improver_tests/acceptance/test_weighted_blending.py +++ b/improver_tests/acceptance/test_weighted_blending.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the weighted-blending CLI diff --git a/improver_tests/acceptance/test_wet_bulb_freezing_level.py b/improver_tests/acceptance/test_wet_bulb_freezing_level.py index 1aaaf43b10..826b1c5c33 100644 --- a/improver_tests/acceptance/test_wet_bulb_freezing_level.py +++ b/improver_tests/acceptance/test_wet_bulb_freezing_level.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the wet-bulb-freezing-level CLI""" @@ -19,10 +19,6 @@ def test_basic(tmp_path): kgo_path = kgo_dir / "kgo.nc" output_path = tmp_path / "output.nc" - args = [ - kgo_dir / "wet_bulb_temperature.nc", - "--output", - output_path, - ] + args = [kgo_dir / "wet_bulb_temperature.nc", "--output", output_path] run_cli(args) acc.compare(output_path, kgo_path) diff --git a/improver_tests/acceptance/test_wet_bulb_temperature.py b/improver_tests/acceptance/test_wet_bulb_temperature.py index de5b9cec47..7d08a3aac4 100644 --- a/improver_tests/acceptance/test_wet_bulb_temperature.py +++ b/improver_tests/acceptance/test_wet_bulb_temperature.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the wet-bulb-temperature CLI""" diff --git a/improver_tests/acceptance/test_wet_bulb_temperature_integral.py b/improver_tests/acceptance/test_wet_bulb_temperature_integral.py index e1de8d417c..44ce9ee124 100644 --- a/improver_tests/acceptance/test_wet_bulb_temperature_integral.py +++ b/improver_tests/acceptance/test_wet_bulb_temperature_integral.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Tests for the wet-bulb-temperature-integral CLI diff --git a/improver_tests/acceptance/test_wind_direction.py b/improver_tests/acceptance/test_wind_direction.py index b668046dc1..0135380180 100644 --- a/improver_tests/acceptance/test_wind_direction.py +++ b/improver_tests/acceptance/test_wind_direction.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the wind-direction CLI""" diff --git a/improver_tests/acceptance/test_wind_downscaling.py b/improver_tests/acceptance/test_wind_downscaling.py index bb1107d516..beedbb94f9 100644 --- a/improver_tests/acceptance/test_wind_downscaling.py +++ b/improver_tests/acceptance/test_wind_downscaling.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the wind-downscaling CLI""" diff --git a/improver_tests/acceptance/test_wind_gust_diagnostic.py b/improver_tests/acceptance/test_wind_gust_diagnostic.py index c1cafcb165..669ef760d4 100644 --- a/improver_tests/acceptance/test_wind_gust_diagnostic.py +++ b/improver_tests/acceptance/test_wind_gust_diagnostic.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the wind-gust-diagnostic CLI""" diff --git a/improver_tests/between_thresholds/test_between_thresholds.py b/improver_tests/between_thresholds/test_between_thresholds.py index 35c03759f6..8629125f4b 100644 --- a/improver_tests/between_thresholds/test_between_thresholds.py +++ b/improver_tests/between_thresholds/test_between_thresholds.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the OccurrenceBetweenThresholds plugin""" diff --git a/improver_tests/blending/blend_across_adjacent_points/test_TriangularWeightedBlendAcrossAdjacentPoints.py b/improver_tests/blending/blend_across_adjacent_points/test_TriangularWeightedBlendAcrossAdjacentPoints.py index c98029feff..9d5e7724c1 100644 --- a/improver_tests/blending/blend_across_adjacent_points/test_TriangularWeightedBlendAcrossAdjacentPoints.py +++ b/improver_tests/blending/blend_across_adjacent_points/test_TriangularWeightedBlendAcrossAdjacentPoints.py @@ -1,9 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the - weighted_blend.TriangularWeightedBlendAcrossAdjacentPoints plugin.""" +weighted_blend.TriangularWeightedBlendAcrossAdjacentPoints plugin.""" import unittest from datetime import datetime as dt @@ -45,7 +45,6 @@ def set_up_cubes_for_process_tests(): class Test__repr__(IrisTest): - """Test the __repr__ method.""" def test_basic(self): @@ -66,7 +65,6 @@ def test_basic(self): class Test__init__(IrisTest): - """Test the __init__ method.""" def test_basic(self): @@ -108,7 +106,7 @@ def test_central_point_available(self): def test_central_point_not_available(self): """Test that the central point is not available within the - input cube.""" + input cube.""" forecast_period = 2 plugin = TriangularWeightedBlendAcrossAdjacentPoints( "forecast_period", forecast_period, "hours", self.width @@ -128,7 +126,7 @@ def setUp(self): def test_basic_triangle_width_1(self): """Test that the plugin produces sensible results when the width - of the triangle is 1. This is equivalent to no blending.""" + of the triangle is 1. This is equivalent to no blending.""" width = 1.0 plugin = TriangularWeightedBlendAcrossAdjacentPoints( "forecast_period", self.forecast_period, "hours", width @@ -142,7 +140,7 @@ def test_basic_triangle_width_1(self): def test_basic_triangle_width_2(self): """Test that the plugin produces sensible results when the width - of the triangle is 2 and there is some blending.""" + of the triangle is 2 and there is some blending.""" width = 2.0 plugin = TriangularWeightedBlendAcrossAdjacentPoints( "forecast_period", self.forecast_period, "hours", width @@ -157,7 +155,7 @@ def test_basic_triangle_width_2(self): def test_central_point_not_in_allowed_range(self): """Test that an exception is generated when the central cube is not - within the allowed range.""" + within the allowed range.""" width = 1.0 forecast_period = 2 plugin = TriangularWeightedBlendAcrossAdjacentPoints( @@ -169,7 +167,7 @@ def test_central_point_not_in_allowed_range(self): def test_alternative_parameter_units(self): """Test that the plugin produces sensible results when the width - of the triangle is 7200 seconds. """ + of the triangle is 7200 seconds.""" forecast_period = 0 width = 7200.0 plugin = TriangularWeightedBlendAcrossAdjacentPoints( @@ -201,7 +199,7 @@ def test_input_cube_no_change(self): def test_extra_dimension(self): """Test that the plugin retains the single height point from the input - cube.""" + cube.""" # Creates a cube containing the expected outputs. fill_value = 1 + 1 / 3.0 @@ -229,7 +227,7 @@ def test_extra_dimension(self): def test_works_two_thresh(self): """Test that the plugin works with a cube that contains multiple - thresholds.""" + thresholds.""" width = 2.0 thresh_cube = self.cube.copy() thresh_cubes = add_coordinate( diff --git a/improver_tests/blending/calculate_weights_and_blend/test_WeightAndBlend.py b/improver_tests/blending/calculate_weights_and_blend/test_WeightAndBlend.py index d321353e1b..195c31b30a 100644 --- a/improver_tests/blending/calculate_weights_and_blend/test_WeightAndBlend.py +++ b/improver_tests/blending/calculate_weights_and_blend/test_WeightAndBlend.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the WeightAndBlend plugin""" @@ -340,7 +340,7 @@ def setUp(self): def test_basic(self): """Test output is a cube""" result = self.plugin_cycle.process( - [self.ukv_cube, self.ukv_cube_latest], cycletime=self.cycletime, + [self.ukv_cube, self.ukv_cube_latest], cycletime=self.cycletime ) self.assertIsInstance(result, iris.cube.Cube) @@ -353,7 +353,7 @@ def test_masked_blending_warning(self): message = "Blending masked data without spatial weights" with pytest.warns(UserWarning, match=message): self.plugin_cycle.process( - [ukv_cube, self.ukv_cube_latest], cycletime=self.cycletime, + [ukv_cube, self.ukv_cube_latest], cycletime=self.cycletime ) def test_cycle_blend_linear(self): diff --git a/improver_tests/blending/spatial_weights/test_SpatiallyVaryingWeightsFromMask.py b/improver_tests/blending/spatial_weights/test_SpatiallyVaryingWeightsFromMask.py index fb50ce30a6..ae8ade72ec 100644 --- a/improver_tests/blending/spatial_weights/test_SpatiallyVaryingWeightsFromMask.py +++ b/improver_tests/blending/spatial_weights/test_SpatiallyVaryingWeightsFromMask.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the spatial_weights.SpatiallyVaryingWeightsFromMask - plugin.""" - +plugin.""" import unittest from datetime import datetime @@ -22,7 +21,6 @@ class Test__repr__(IrisTest): - """Test the repr method.""" def test_basic(self): @@ -117,7 +115,7 @@ def test_basic(self): def test_basic_no_change(self): """Test a correct template slice is returned for a case where - no slicing is needed""" + no slicing is needed""" input_cube = self.cube_to_collapse.copy()[:, 0, :, :] expected = input_cube.copy() result = self.plugin._create_template_slice(input_cube) @@ -126,7 +124,7 @@ def test_basic_no_change(self): def test_aux_blending_coord(self): """Test a correct template slice is returned when blending_coord is - an AuxCoord""" + an AuxCoord""" expected = self.cube_to_collapse.copy()[:, 0, :, :] plugin = SpatiallyVaryingWeightsFromMask("forecast_period") result = plugin._create_template_slice(self.cube_to_collapse) @@ -213,7 +211,7 @@ def test_none_masked(self): message = "Expected masked input" with pytest.warns(UserWarning, match=message): result = self.plugin.process( - self.cube_to_collapse, self.one_dimensional_weights_cube, + self.cube_to_collapse, self.one_dimensional_weights_cube ) self.assertArrayEqual(result.data, expected_data) self.assertEqual(result.dtype, np.float32) @@ -223,7 +221,7 @@ def test_all_masked(self): self.cube_to_collapse.data = np.ones(self.cube_to_collapse.data.shape) self.cube_to_collapse.data = np.ma.masked_equal(self.cube_to_collapse.data, 1) result = self.plugin.process( - self.cube_to_collapse, self.one_dimensional_weights_cube, + self.cube_to_collapse, self.one_dimensional_weights_cube ) expected_data = np.zeros((3, 2, 3)) self.assertArrayAlmostEqual(expected_data, result.data) @@ -242,7 +240,7 @@ def test_no_fuzziness_no_one_dimensional_weights(self): dtype=np.float32, ) result = self.plugin_no_fuzzy.process( - self.cube_to_collapse, self.one_dimensional_weights_cube, + self.cube_to_collapse, self.one_dimensional_weights_cube ) self.assertArrayAlmostEqual(result.data, expected_result) self.assertEqual(result.metadata, self.cube_to_collapse.metadata) @@ -262,7 +260,7 @@ def test_no_fuzziness_no_one_dimensional_weights_transpose(self): ) self.cube_to_collapse.transpose([2, 0, 1, 3]) result = self.plugin_no_fuzzy.process( - self.cube_to_collapse, self.one_dimensional_weights_cube, + self.cube_to_collapse, self.one_dimensional_weights_cube ) self.assertArrayAlmostEqual(result.data, expected_result) self.assertEqual(result.metadata, self.cube_to_collapse.metadata) @@ -279,7 +277,7 @@ def test_no_fuzziness_with_one_dimensional_weights(self): dtype=np.float32, ) result = self.plugin_no_fuzzy.process( - self.cube_to_collapse, self.one_dimensional_weights_cube, + self.cube_to_collapse, self.one_dimensional_weights_cube ) self.assertArrayAlmostEqual(result.data, expected_result) self.assertEqual(result.metadata, self.cube_to_collapse.metadata) @@ -297,7 +295,7 @@ def test_fuzziness_no_one_dimensional_weights(self): dtype=np.float32, ) result = self.plugin.process( - self.cube_to_collapse, self.one_dimensional_weights_cube, + self.cube_to_collapse, self.one_dimensional_weights_cube ) self.assertArrayAlmostEqual(result.data, expected_result) self.assertEqual(result.metadata, self.cube_to_collapse.metadata) @@ -314,7 +312,7 @@ def test_fuzziness_with_one_dimensional_weights(self): dtype=np.float32, ) result = self.plugin.process( - self.cube_to_collapse, self.one_dimensional_weights_cube, + self.cube_to_collapse, self.one_dimensional_weights_cube ) self.assertArrayAlmostEqual(result.data, expected_result) self.assertEqual(result.metadata, self.cube_to_collapse.metadata) @@ -337,7 +335,7 @@ def test_fuzziness_with_unequal_weightings(self): dtype=np.float32, ) result = self.plugin.process( - self.cube_to_collapse, self.one_dimensional_weights_cube, + self.cube_to_collapse, self.one_dimensional_weights_cube ) self.assertArrayAlmostEqual(result.data, expected_data) diff --git a/improver_tests/blending/test_utilities.py b/improver_tests/blending/test_utilities.py index 5043b935cf..5cc0d52de9 100644 --- a/improver_tests/blending/test_utilities.py +++ b/improver_tests/blending/test_utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Test utilities to support weighted blending""" @@ -428,7 +428,7 @@ def test_record_run_coord_to_attr_discard_weights_no_duplicates( [ [1 / 3, 1 / 3, 1 / 3], # Evenly weighted [0.25, 0.25, 0.5], # Unevenly weighted - [1, 1, 1] # Overweighted. This method does nothing to prevent this; relies on + [1, 1, 1], # Overweighted. This method does nothing to prevent this; relies on # sensible input weights. ], ) diff --git a/improver_tests/blending/weighted_blend/test_MergeCubesForWeightedBlending.py b/improver_tests/blending/weighted_blend/test_MergeCubesForWeightedBlending.py index 01d3cd5d44..269361af65 100644 --- a/improver_tests/blending/weighted_blend/test_MergeCubesForWeightedBlending.py +++ b/improver_tests/blending/weighted_blend/test_MergeCubesForWeightedBlending.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for MergeCubesForWeightedBlending""" @@ -361,9 +361,9 @@ def test_record_run_existing(self): model_id_attr="mosg__model_configuration", record_run_attr="mosg__model_run", ) - self.cube_ukv.attributes[ - "mosg__model_run" - ] = "uk_det:20151123T0200Z:0.500\nuk_det:20151123T0300Z:0.500" + self.cube_ukv.attributes["mosg__model_run"] = ( + "uk_det:20151123T0200Z:0.500\nuk_det:20151123T0300Z:0.500" + ) cube = plugin.process([self.cube_ukv, self.cube_enuk]) self.assertArrayEqual( cube.coord("blend_record").points, diff --git a/improver_tests/blending/weighted_blend/test_PercentileBlendingAggregator.py b/improver_tests/blending/weighted_blend/test_PercentileBlendingAggregator.py index 0a700a5dd0..673ef50094 100644 --- a/improver_tests/blending/weighted_blend/test_PercentileBlendingAggregator.py +++ b/improver_tests/blending/weighted_blend/test_PercentileBlendingAggregator.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the weighted_blend.PercentileBlendingAggregator class.""" - import unittest import numpy as np @@ -169,13 +168,11 @@ def test_blend_percentile_aggregate(self): result = PercentileBlendingAggregator.aggregate( PERCENTILE_DATA, 1, percentiles, weights ) - self.assertArrayAlmostEqual( - result, BLENDED_PERCENTILE_DATA, - ) + self.assertArrayAlmostEqual(result, BLENDED_PERCENTILE_DATA) def test_2D_simple_case(self): - """ Test that for a simple case with only one point in the resulting - array the function behaves as expected""" + """Test that for a simple case with only one point in the resulting + array the function behaves as expected""" weights = generate_matching_weights_array([0.8, 0.2], 1) percentiles = np.array([0, 50, 100]) perc_data = np.array([[1.0, 2.0], [5.0, 5.0], [10.0, 9.0]]) @@ -186,8 +183,8 @@ def test_2D_simple_case(self): self.assertArrayAlmostEqual(result, expected_result) def test_3D_simple_case(self): - """ Test that for a simple case with only one point and an extra - internal dimension behaves as expected""" + """Test that for a simple case with only one point and an extra + internal dimension behaves as expected""" weights = generate_matching_weights_array([0.5, 0.5], 1) percentiles = np.array([0, 50, 100]) perc_data = np.array([[[1.0], [2.0]], [[5.0], [6.0]], [[10.0], [9.0]]]) @@ -198,8 +195,8 @@ def test_3D_simple_case(self): self.assertArrayAlmostEqual(result, expected_result) def test_4D_simple_case(self): - """ Test that for a simple case with only one point and 4D input data - it behaves as expected""" + """Test that for a simple case with only one point and 4D input data + it behaves as expected""" weights = generate_matching_weights_array([0.5, 0.5], 1) percentiles = np.array([0, 50, 100]) perc_data = np.array([1.0, 3.0, 2.0, 4.0, 5.0, 6.0]) @@ -254,7 +251,7 @@ def test_blend_percentiles(self): def test_two_percentiles(self): """Test that when two percentiles are provided, the extreme values in - the set of thresholds we are blending are returned""" + the set of thresholds we are blending are returned""" weights = np.array([0.5, 0.5]) percentiles = np.array([30.0, 60.0]) percentile_values = np.array([[5.0, 8.0], [6.0, 7.0]]) @@ -266,7 +263,7 @@ def test_two_percentiles(self): def test_three_percentiles_symmetric_case(self): """Test that when three percentiles are provided the correct values - are returned, not a simple average""" + are returned, not a simple average""" weights = np.array([0.5, 0.5]) percentiles = np.array([20.0, 50.0, 80.0]) percentile_values = np.array([[5.0, 6.0, 7.0], [5.0, 6.5, 7.0]]) @@ -278,7 +275,7 @@ def test_three_percentiles_symmetric_case(self): def test_only_one_point_to_blend(self): """Test case where there is only one point in the coordinate we are - blending over.""" + blending over.""" weights = np.array([1.0]) percentiles = np.array([20.0, 50.0, 80.0]) percentile_values = np.array([[5.0, 6.0, 7.0]]) diff --git a/improver_tests/blending/weighted_blend/test_WeightedBlendAcrossWholeDimension.py b/improver_tests/blending/weighted_blend/test_WeightedBlendAcrossWholeDimension.py index 3a2f038f4a..0128c9fc12 100644 --- a/improver_tests/blending/weighted_blend/test_WeightedBlendAcrossWholeDimension.py +++ b/improver_tests/blending/weighted_blend/test_WeightedBlendAcrossWholeDimension.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the - weighted_blend.WeightedBlendAcrossWholeDimension plugin.""" - +weighted_blend.WeightedBlendAcrossWholeDimension plugin.""" import unittest from datetime import datetime @@ -55,7 +54,6 @@ def percentile_cube(frt_points, time, frt): class Test__init__(IrisTest): - """Test the __init__ method.""" def test_basic(self): @@ -72,7 +70,6 @@ def test_threshold_blending_unsupported(self): class Test__repr__(IrisTest): - """Test the repr method.""" def test_basic(self): @@ -83,7 +80,6 @@ def test_basic(self): class Test_weighted_blend(IrisTest): - """A shared setup for tests in the WeightedBlendAcrossWholeDimension plugin.""" @@ -170,7 +166,6 @@ def setUp(self): class Test_check_percentile_coord(Test_weighted_blend): - """Test the percentile coord checking function.""" def test_basic(self): @@ -200,7 +195,6 @@ def test_fails_only_one_percentile_value(self): class Test_check_compatible_time_points(Test_weighted_blend): - """Test the time point compatibility checking function.""" def test_basic(self): @@ -231,7 +225,6 @@ def test_unmatched_validity_time_exemption(self): class Test_shape_weights(Test_weighted_blend): - """Test the shape weights function is able to create a valid a set of weights, or raises an error.""" @@ -311,7 +304,6 @@ def test_incompatible_weights_and_data_cubes_shape(self): class Test_get_weights_array(Test_weighted_blend): - """Test the get_weights_array function.""" def test_no_weights_cube_provided(self): @@ -344,7 +336,6 @@ def test_3D_weights(self): class Test__normalise_weights(Test_weighted_blend): - """Test the _normalise_weights function.""" def test_noop(self): @@ -375,14 +366,13 @@ def test_normalisation(self): [[0.1, 0.5625], [0.2, 0.4]], [[0.1, 0.1875], [0.2, 0.4]], [[0.8, 0.25], [0.6, 0.2]], - ], + ] ) result = self.plugin._normalise_weights(weights) self.assertArrayAlmostEqual(result, expected_data) class Test_percentile_weighted_mean(Test_weighted_blend): - """Test the percentile_weighted_mean function.""" def test_with_weights(self): @@ -415,7 +405,6 @@ def test_without_weights(self): class Test_weighted_mean(Test_weighted_blend): - """Test the weighted_mean function.""" def test_with_weights(self): @@ -449,10 +438,7 @@ def test_without_weights(self): def test_wind_directions(self): """Test function when a wind direction data cube is provided, and the directions don't cross the 0/360° boundary.""" - frt_points = [ - datetime(2015, 11, 19, 0), - datetime(2015, 11, 19, 1), - ] + frt_points = [datetime(2015, 11, 19, 0), datetime(2015, 11, 19, 1)] cube = set_up_variable_cube( np.zeros((2, 2), dtype=np.float32), name="wind_from_direction", @@ -474,10 +460,7 @@ def test_wind_directions(self): def test_wind_directions_over_north(self): """Test function when a wind direction data cube is provided, and the directions cross the 0/360° boundary.""" - frt_points = [ - datetime(2015, 11, 19, 0), - datetime(2015, 11, 19, 1), - ] + frt_points = [datetime(2015, 11, 19, 0), datetime(2015, 11, 19, 1)] cube = set_up_variable_cube( np.zeros((2, 2), dtype=np.float32), name="wind_direction", @@ -510,7 +493,6 @@ def test_collapse_dims_with_weights(self): class Test_process(Test_weighted_blend): - """Test the process method.""" def test_basic(self): diff --git a/improver_tests/blending/weights/test_ChooseDefaultWeightsLinear.py b/improver_tests/blending/weights/test_ChooseDefaultWeightsLinear.py index 29da0bb739..b6a0e5e2d7 100644 --- a/improver_tests/blending/weights/test_ChooseDefaultWeightsLinear.py +++ b/improver_tests/blending/weights/test_ChooseDefaultWeightsLinear.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the weights.ChooseDefaultWeightsLinear plugin.""" - import unittest from datetime import datetime as dt @@ -30,14 +29,14 @@ def test_basic(self): self.assertEqual(plugin.ynval, 2.0) def test_fails_y0val_less_than_zero(self): - """Test it raises a Value Error if y0val less than zero. """ + """Test it raises a Value Error if y0val less than zero.""" msg = "y0val must be a float >= 0.0" with self.assertRaisesRegex(ValueError, msg): LinearWeights(y0val=-10.0, ynval=2.0) class Test_linear_weights(IrisTest): - """Test the linear weights function. """ + """Test the linear weights function.""" def test_basic(self): """Test that the function returns an array of weights""" @@ -72,7 +71,7 @@ def test_fails_if_total_weights_zero(self): class Test_process(IrisTest): - """Test the Default Linear Weights plugin. """ + """Test the Default Linear Weights plugin.""" def setUp(self): """Set up for testing process method""" @@ -92,19 +91,19 @@ def setUp(self): self.coord_name = "time" def test_basic(self): - """Test that the plugin returns a cube of weights. """ + """Test that the plugin returns a cube of weights.""" plugin = LinearWeights(y0val=20.0, ynval=2.0) result = plugin.process(self.cube, self.coord_name) self.assertIsInstance(result, iris.cube.Cube) def test_array_sum_equals_one(self): - """Test that the resulting weights add up to one. """ + """Test that the resulting weights add up to one.""" plugin = LinearWeights(y0val=20.0, ynval=2.0) result = plugin.process(self.cube, self.coord_name) self.assertAlmostEqual(result.data.sum(), 1.0) def test_fails_input_not_a_cube(self): - """Test it raises a Value Error if not supplied with a cube. """ + """Test it raises a Value Error if not supplied with a cube.""" plugin = LinearWeights(y0val=20.0, ynval=2.0) notacube = 0.0 msg = "The first argument must be an instance of iris.cube.Cube" @@ -112,7 +111,7 @@ def test_fails_input_not_a_cube(self): plugin.process(notacube, self.coord_name) def test_works_scalar_coord(self): - """Test it works if scalar coordinate. """ + """Test it works if scalar coordinate.""" self.cube.add_aux_coord(AuxCoord(1, long_name="scalar_coord", units="no_unit")) coord = self.cube.coord("scalar_coord") plugin = LinearWeights(y0val=20.0, ynval=2.0) @@ -120,21 +119,21 @@ def test_works_scalar_coord(self): self.assertArrayAlmostEqual(result.data, np.array([1.0])) def test_works_defaults_used(self): - """Test it works if defaults used. """ + """Test it works if defaults used.""" plugin = LinearWeights(y0val=20.0, ynval=2.0) result = plugin.process(self.cube, self.coord_name) expected_result = np.array([0.90909091, 0.09090909]) self.assertArrayAlmostEqual(result.data, expected_result) def test_works_y0val_and_ynval_set(self): - """Test it works if y0val and ynval set. """ + """Test it works if y0val and ynval set.""" plugin = LinearWeights(y0val=10.0, ynval=5.0) result = plugin.process(self.cube, self.coord_name) expected_result = np.array([0.66666667, 0.33333333]) self.assertArrayAlmostEqual(result.data, expected_result) def test_works_with_larger_num(self): - """Test it works with larger num_of_vals. """ + """Test it works with larger num_of_vals.""" plugin = LinearWeights(y0val=10.0, ynval=5.0) cubenew = add_coordinate(self.cube, np.arange(6), "realization", dtype=np.int32) coord = cubenew.coord("realization") diff --git a/improver_tests/blending/weights/test_ChooseDefaultWeightsNonLinear.py b/improver_tests/blending/weights/test_ChooseDefaultWeightsNonLinear.py index 58b96076ff..9a63dd4217 100644 --- a/improver_tests/blending/weights/test_ChooseDefaultWeightsNonLinear.py +++ b/improver_tests/blending/weights/test_ChooseDefaultWeightsNonLinear.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the weights.ChooseDefaultWeightsNonLinear plugin.""" - import unittest from datetime import datetime as dt @@ -44,10 +43,10 @@ def test_fails_cval_set_wrong(self): class Test_nonlinear_weights(IrisTest): - """Test the nonlinear weights function. """ + """Test the nonlinear weights function.""" def test_basic(self): - """Test that the function returns an array of weights. """ + """Test that the function returns an array of weights.""" result = NonLinearWeights(0.85).nonlinear_weights(3) self.assertIsInstance(result, np.ndarray) @@ -61,7 +60,7 @@ def test_values(self): class Test_process(IrisTest): - """Test the Default non-Linear Weights plugin. """ + """Test the Default non-Linear Weights plugin.""" def setUp(self): """Set up test cube and coordinate""" @@ -81,19 +80,19 @@ def setUp(self): self.coord_name = "time" def test_basic(self): - """Test that the plugin returns an array of weights. """ + """Test that the plugin returns an array of weights.""" plugin = NonLinearWeights(0.85) result = plugin.process(self.cube, self.coord_name) self.assertIsInstance(result, iris.cube.Cube) def test_array_sum_equals_one(self): - """Test that the resulting weights add up to one. """ + """Test that the resulting weights add up to one.""" plugin = NonLinearWeights(0.85) result = plugin.process(self.cube, self.coord_name) self.assertAlmostEqual(result.data.sum(), 1.0) def test_fails_input_not_a_cube(self): - """Test it raises a Value Error if not supplied with a cube. """ + """Test it raises a Value Error if not supplied with a cube.""" plugin = NonLinearWeights(0.85) notacube = 0.0 msg = "The first argument must be an instance of iris.cube.Cube" @@ -101,7 +100,7 @@ def test_fails_input_not_a_cube(self): plugin.process(notacube, self.coord_name) def test_scalar_coord(self): - """Test it works if blend coordinate is scalar. """ + """Test it works if blend coordinate is scalar.""" self.cube.add_aux_coord(AuxCoord(1, long_name="scalar_coord", units="no_unit")) coord = self.cube.coord("scalar_coord") plugin = NonLinearWeights(0.85) @@ -109,7 +108,7 @@ def test_scalar_coord(self): self.assertArrayAlmostEqual(result.data, np.array([1.0])) def test_values(self): - """Test weights values. """ + """Test weights values.""" plugin = NonLinearWeights(cval=0.85) result = plugin.process(self.cube, self.coord_name) expected_result = np.array([0.54054054, 0.45945946]) @@ -117,7 +116,7 @@ def test_values(self): def test_values_inverse_ordering(self): """Test inverting the order of the input cube produces inverted weights - order, with the cube and weights cube still matching in dimensions. """ + order, with the cube and weights cube still matching in dimensions.""" reference_cube = self.cube.copy() plugin = NonLinearWeights(cval=0.85) result = plugin.process(self.cube, self.coord_name, inverse_ordering=True) @@ -135,14 +134,14 @@ def test_values_inverse_ordering(self): ) def test_cval_equal_one(self): - """Test it works with cval = 1.0, i.e. equal weights. """ + """Test it works with cval = 1.0, i.e. equal weights.""" plugin = NonLinearWeights(cval=1.0) result = plugin.process(self.cube, self.coord_name) expected_result = np.array([0.5, 0.5]) self.assertArrayAlmostEqual(result.data, expected_result) def test_larger_num(self): - """Test it works with larger num_of_vals. """ + """Test it works with larger num_of_vals.""" plugin = NonLinearWeights(cval=0.5) cubenew = add_coordinate(self.cube, np.arange(6), "realization", dtype=np.int32) coord_name = "realization" diff --git a/improver_tests/blending/weights/test_ChooseDefaultWeightsTriangular.py b/improver_tests/blending/weights/test_ChooseDefaultWeightsTriangular.py index 28f0281eda..7e97ae3180 100644 --- a/improver_tests/blending/weights/test_ChooseDefaultWeightsTriangular.py +++ b/improver_tests/blending/weights/test_ChooseDefaultWeightsTriangular.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the weights.ChooseDefaultWeightsTriangular plugin.""" - import unittest from datetime import datetime as dt @@ -48,8 +47,8 @@ class Test_triangular_weights(IrisTest): def test_basic(self): """Test that the function returns a numpy array. - Also check that the length of the weights is correct and they add - up to 1.0""" + Also check that the length of the weights is correct and they add + up to 1.0""" width = 3 triangular_weights_instance = ChooseDefaultWeightsTriangular(width) coord_vals = np.arange(15) @@ -64,7 +63,7 @@ def test_basic(self): def test_basic_weights(self): """Test that the function returns the correct triangular weights in a - simple case""" + simple case""" width = 3 triangular_weights_instance = ChooseDefaultWeightsTriangular(width) coord_vals = np.arange(15) @@ -95,8 +94,8 @@ def test_basic_weights(self): def test_midpoint_at_edge(self): """Test that the correct triangular weights are returned for a case - where the midpoint is close to the end of the input coordinate. - In this case the triangle is cut off at the end of the coordinate""" + where the midpoint is close to the end of the input coordinate. + In this case the triangle is cut off at the end of the coordinate""" width = 3 triangular_weights_instance = ChooseDefaultWeightsTriangular(width) coord_vals = np.arange(15) @@ -127,9 +126,9 @@ def test_midpoint_at_edge(self): def test_large_width(self): """Test the case where the width of the triangle is larger than the - coordinate input. - In this case all the weights are non-zero but still form the - shape of a triangle.""" + coordinate input. + In this case all the weights are non-zero but still form the + shape of a triangle.""" width = 10 triangular_weights_instance = ChooseDefaultWeightsTriangular(width) coord_vals = np.arange(15) @@ -160,8 +159,8 @@ def test_large_width(self): def test_non_integer_midpoint(self): """Test the case where the midpoint of the triangle is not a point in - the input coordinate. - In this case we do not sample the peak of the triangle.""" + the input coordinate. + In this case we do not sample the peak of the triangle.""" width = 2 triangular_weights_instance = ChooseDefaultWeightsTriangular(width) coord_vals = np.arange(15) @@ -192,7 +191,7 @@ def test_non_integer_midpoint(self): def test_non_integer_width(self): """Test when the width of the triangle does not fall on a grid point. - This only affects the slope of the triangle slightly.""" + This only affects the slope of the triangle slightly.""" width = 3.5 triangular_weights_instance = ChooseDefaultWeightsTriangular(width) coord_vals = np.arange(15) @@ -223,9 +222,9 @@ def test_non_integer_width(self): def test_unevenly_spaced_coord(self): """Test the case where the input coordinate is not equally spaced. - This represents the case where the data changes to 3 hourly. In this - case the weights are assigned according to the value in the - coordinate.""" + This represents the case where the data changes to 3 hourly. In this + case the weights are assigned according to the value in the + coordinate.""" width = 5 triangular_weights_instance = ChooseDefaultWeightsTriangular(width) coord_vals = np.arange(10) @@ -271,7 +270,7 @@ def test_cf_unit_input(self): def test_string_input(self): """Test the case where a string is passed and gets converted to a - Unit instance""" + Unit instance""" units = "hour" width = 5 weights_instance = ChooseDefaultWeightsTriangular(width, units=units) @@ -308,7 +307,7 @@ def setUp(self): def test_same_units(self): """Test plugin produces the correct weights when the parameters for - the triangle are in the same units as the input cube's coordinate""" + the triangle are in the same units as the input cube's coordinate""" width = 7200 weights_instance = ChooseDefaultWeightsTriangular(width, units=self.units) midpoint = 3600 @@ -317,9 +316,9 @@ def test_same_units(self): self.assertArrayAlmostEqual(weights.data, expected_weights) def test_different_units(self): - """"Test plugin produces the correct weights when the parameters for - the triangle (width and midpoint are in different units to the - input cube's coordinate""" + """ "Test plugin produces the correct weights when the parameters for + the triangle (width and midpoint are in different units to the + input cube's coordinate""" width = 2 weights_instance = ChooseDefaultWeightsTriangular(width, units="hours") midpoint = 1 @@ -328,9 +327,9 @@ def test_different_units(self): self.assertArrayAlmostEqual(weights.data, expected_weights) def test_unconvertable_units(self): - """"Test plugin produces the correct weights when the parameters for - the triangle cannot be converted to the same units as the - coordinate""" + """ "Test plugin produces the correct weights when the parameters for + the triangle cannot be converted to the same units as the + coordinate""" width = 7200 weights_instance = ChooseDefaultWeightsTriangular(width, units="m") midpoint = 3600 diff --git a/improver_tests/blending/weights/test_ChooseWeightsLinear.py b/improver_tests/blending/weights/test_ChooseWeightsLinear.py index daeeaf9488..ecb9fd0a4d 100644 --- a/improver_tests/blending/weights/test_ChooseWeightsLinear.py +++ b/improver_tests/blending/weights/test_ChooseWeightsLinear.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the ChooseWeightsLinear plugin.""" @@ -213,12 +213,9 @@ def test_basic(self): plugin = ChooseWeightsLinear(self.weighting_coord_name, config_dict) - ( - source_points, - target_points, - source_weights, - fill_value, - ) = plugin._get_interpolation_inputs_from_dict(self.cube) + (source_points, target_points, source_weights, fill_value) = ( + plugin._get_interpolation_inputs_from_dict(self.cube) + ) self.assertArrayAlmostEqual(source_points, self.expected_source_points) self.assertArrayAlmostEqual(target_points, self.expected_target_points) @@ -240,12 +237,9 @@ def test_unit_conversion(self): plugin = ChooseWeightsLinear(self.weighting_coord_name, config_dict) - ( - source_points, - target_points, - source_weights, - fill_value, - ) = plugin._get_interpolation_inputs_from_dict(self.cube) + (source_points, target_points, source_weights, fill_value) = ( + plugin._get_interpolation_inputs_from_dict(self.cube) + ) self.assertArrayAlmostEqual(source_points, self.expected_source_points) self.assertArrayAlmostEqual(target_points, self.expected_target_points) @@ -393,7 +387,7 @@ def test_new_weights_with_dict_masked_input(single_thresh_input_cube, weights, p """Test a new weights cube is created as intended when we have a masked input gridded or spot forecast cube.""" single_thresh_input_cube.data = np.ma.masked_array( - single_thresh_input_cube.data, np.ones(single_thresh_input_cube.data.shape), + single_thresh_input_cube.data, np.ones(single_thresh_input_cube.data.shape) ) new_weights_cube = plugin._create_new_weights_cube( single_thresh_input_cube, weights @@ -488,9 +482,7 @@ def multi_model_inputs(request, output_type): return no_threshold_cube, reference_cubelist -@pytest.mark.parametrize( - "output_type", ["threshold", "single_threshold"], -) +@pytest.mark.parametrize("output_type", ["threshold", "single_threshold"]) def test__slice_input_slices(plugin, multi_model_inputs): """Test function slices out extra dimensions to leave only the spatial dimensions. Tested using a cube with and without a threshold coordinate.""" diff --git a/improver_tests/blending/weights/test_WeightsUtilities.py b/improver_tests/blending/weights/test_WeightsUtilities.py index 35add53c5a..4b743c0e49 100644 --- a/improver_tests/blending/weights/test_WeightsUtilities.py +++ b/improver_tests/blending/weights/test_WeightsUtilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the weights.ChooseDefaultWeightsLinear plugin.""" @@ -20,7 +20,6 @@ class Test__repr__(IrisTest): - """Test the repr method.""" def test_basic(self): @@ -31,36 +30,36 @@ def test_basic(self): class Test_normalise_weights(IrisTest): - """Test the normalise_weights function. """ + """Test the normalise_weights function.""" def test_basic(self): - """Test that the function returns an array of weights. """ + """Test that the function returns an array of weights.""" weights_in = np.array([1.0, 2.0, 3.0]) result = WeightsUtilities.normalise_weights(weights_in) self.assertIsInstance(result, np.ndarray) def test_array_sum_equals_one(self): - """Test that the resulting weights add up to one. """ + """Test that the resulting weights add up to one.""" weights_in = np.array([1.0, 2.0, 3.0]) result = WeightsUtilities.normalise_weights(weights_in) self.assertAlmostEqual(result.sum(), 1.0) def test_fails_weight_less_than_zero(self): - """Test it fails if weight less than zero. """ + """Test it fails if weight less than zero.""" weights_in = np.array([-1.0, 0.1]) msg = "Weights must be positive" with self.assertRaisesRegex(ValueError, msg): WeightsUtilities.normalise_weights(weights_in) def test_fails_sum_equals_zero(self): - """Test it fails if sum of input weights is zero. """ + """Test it fails if sum of input weights is zero.""" weights_in = np.array([0.0, 0.0, 0.0]) msg = "Sum of weights must be > 0.0" with self.assertRaisesRegex(ValueError, msg): WeightsUtilities.normalise_weights(weights_in) def test_returns_correct_values(self): - """Test it returns the correct values. """ + """Test it returns the correct values.""" weights_in = np.array([6.0, 3.0, 1.0]) result = WeightsUtilities.normalise_weights(weights_in) expected_result = np.array([0.6, 0.3, 0.1]) @@ -82,7 +81,7 @@ def test_returns_correct_values_2darray_axis1(self): def test_returns_correct_values_2darray_zero_weights(self): """Test normalizing along the columns of the array when there are - zeros in the input array.""" + zeros in the input array.""" weights_in = np.array([[6.0, 3.0, 0.0], [0.0, 1.0, 3.0]]) result = WeightsUtilities.normalise_weights(weights_in, axis=0) expected_result = np.array([[1.0, 0.75, 0.0], [0.0, 0.25, 1.0]]) @@ -90,7 +89,7 @@ def test_returns_correct_values_2darray_zero_weights(self): class Test_build_weights_cube(IrisTest): - """Test the build_weights_cube function. """ + """Test the build_weights_cube function.""" def setUp(self): """Setup for testing cube creation.""" diff --git a/improver_tests/calibration/dataframe_utilities/test_dataframe_utilities.py b/improver_tests/calibration/dataframe_utilities/test_dataframe_utilities.py index be04fed6d9..ad46fdba43 100644 --- a/improver_tests/calibration/dataframe_utilities/test_dataframe_utilities.py +++ b/improver_tests/calibration/dataframe_utilities/test_dataframe_utilities.py @@ -1,12 +1,13 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the utilities within the `calibration.dataframe_utilities` module. """ + import unittest import iris @@ -40,7 +41,6 @@ def _chunker(seq, size): class SetupSharedDataFrames(ImproverTest): - """A shared dataframe creation class.""" def setUp(self): @@ -136,7 +136,7 @@ def setUp(self): ) self.height_coord = iris.coords.AuxCoord( - np.array(self.height, dtype=np.float32), "height", units="m", + np.array(self.height, dtype=np.float32), "height", units="m" ) # Modify the forecast and truth DataFrames so that one of the sites is @@ -179,7 +179,6 @@ def setUp(self): class SetupConstructedForecastCubes(SetupSharedDataFrames): - """A constructed forecast cube class.""" def setUp(self): @@ -292,7 +291,6 @@ def setUp(self): class SetupConstructedTruthCubes(SetupSharedDataFrames): - """A constructed truth cube class.""" def setUp(self): @@ -361,7 +359,6 @@ def setUp(self): class Test_forecast_dataframe_to_cube(SetupConstructedForecastCubes): - """Test the forecast_dataframe_to_cube function.""" def setUp(self): @@ -413,7 +410,6 @@ def test_nonunique_values_in_column(self): class Test_truth_dataframe_to_cube(SetupConstructedTruthCubes): - """Test the truth_dataframe_to_cube function.""" def setUp(self): @@ -423,20 +419,20 @@ def setUp(self): def test_three_day_training_period_diag(self): """Test an input DataFrame is converted correctly into an Iris Cube for a three day training length for a period diagnostic.""" - result = truth_dataframe_to_cube(self.truth_df, self.date_range,) + result = truth_dataframe_to_cube(self.truth_df, self.date_range) self.assertCubeEqual(result, self.expected_period_truth) def test_three_day_training_instantaneous_diag(self): """Test an input DataFrame is converted correctly into an Iris Cube for a three day training length for an instantaneous diagnostic.""" self.truth_df["period"] = pd.Timedelta("NaT") - result = truth_dataframe_to_cube(self.truth_df, self.date_range,) + result = truth_dataframe_to_cube(self.truth_df, self.date_range) self.assertCubeEqual(result, self.expected_instantaneous_truth) def test_two_day_training(self): """Test an input DataFrame is converted correctly into an Iris Cube for a two day training length.""" - result = truth_dataframe_to_cube(self.truth_df, self.date_range_two_days,) + result = truth_dataframe_to_cube(self.truth_df, self.date_range_two_days) self.assertCubeEqual(result, self.expected_period_truth[1:, :]) def test_empty_dataframe(self): @@ -445,7 +441,7 @@ def test_empty_dataframe(self): date_range = pd.date_range( end=validity_time, periods=int(self.training_length), freq="D", tz="UTC" ) - result = truth_dataframe_to_cube(self.truth_df, date_range,) + result = truth_dataframe_to_cube(self.truth_df, date_range) self.assertIsNone(result) def test_nonunique_values_in_column(self): @@ -460,7 +456,6 @@ def test_nonunique_values_in_column(self): class Test_forecast_and_truth_dataframes_to_cubes( SetupConstructedForecastCubes, SetupConstructedTruthCubes ): - """Test the forecast_and_truth_dataframes_to_cubes function.""" def setUp(self): diff --git a/improver_tests/calibration/dz_rescaling/test_apply_dz_rescaling.py b/improver_tests/calibration/dz_rescaling/test_apply_dz_rescaling.py index 3c566ff5c3..9dd7f6d924 100644 --- a/improver_tests/calibration/dz_rescaling/test_apply_dz_rescaling.py +++ b/improver_tests/calibration/dz_rescaling/test_apply_dz_rescaling.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the ApplyDzRescaling plugin.""" + from datetime import datetime as dt from typing import List @@ -23,7 +24,7 @@ def _create_forecasts( - forecast_reference_time: str, validity_time: str, forecast_percs: List[float], + forecast_reference_time: str, validity_time: str, forecast_percs: List[float] ) -> Cube: """Create site forecast cube for testing. @@ -140,7 +141,7 @@ def test_apply_dz_rescaling( + pd.Timedelta(hours=forecast_period + forecast_period_offset) ).strftime(DT_FORMAT) - forecast = _create_forecasts(forecast_reference_time, validity_time, forecast,) + forecast = _create_forecasts(forecast_reference_time, validity_time, forecast) # Use min(fp, 24) here to ensure that the scaling cube contains # the scaling factor for the last forecast_period if the specified # forecast period is beyond the T+24 limit of the scaling cube. @@ -184,7 +185,7 @@ def test_use_correct_time(): pd.Timestamp(forecast_reference_time) + pd.Timedelta(hours=forecast_period) ).strftime(DT_FORMAT) - forecast = _create_forecasts(forecast_reference_time, validity_time, forecast,) + forecast = _create_forecasts(forecast_reference_time, validity_time, forecast) scaling_factor = _create_scaling_factor_cube(12, forecast_period, scaling_factor) scaling_factor.data[0, 0, 0] = scaling_factor.data[0, 0, 0].copy() + 0.01 diff --git a/improver_tests/calibration/dz_rescaling/test_estimate_dz_rescaling.py b/improver_tests/calibration/dz_rescaling/test_estimate_dz_rescaling.py index 0d4d8abab3..3d69f87c14 100644 --- a/improver_tests/calibration/dz_rescaling/test_estimate_dz_rescaling.py +++ b/improver_tests/calibration/dz_rescaling/test_estimate_dz_rescaling.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the EstimateDzRescaling plugin.""" @@ -25,7 +25,7 @@ def _create_forecasts( - forecast_reference_times: List[str], forecast_periods: List[float], + forecast_reference_times: List[str], forecast_periods: List[float] ) -> Cube: """Create site forecasts for testing. @@ -61,7 +61,7 @@ def _create_forecasts( def _create_truths( - forecast_reference_times: List[str], forecast_periods: List[float], + forecast_reference_times: List[str], forecast_periods: List[float] ) -> Cube: """Create site truths for testing. The truth data here shows an example where the wind speed is slightly greater at the sites with higher altitude_grid. @@ -164,8 +164,8 @@ def _create_neighbour_cube() -> Cube: ([6], -75, 75, -1, [1.0, 0.9747, 0.9083, 0.9083]), ([6], -200, 200, 1, [1.0, 1.0142, 1.0731, 1.0580]), ([6], -75, 75, 1, [1.0, 1.0247, 1.0958, 1.0958]), - ([6, 12], -200, 200, 0, [1.0, 1.0043, 1.0218, 1.0174],), - ([6, 12], -75, 75, 0, [1.0, 1.0, 1.0, 1.0],), + ([6, 12], -200, 200, 0, [1.0, 1.0043, 1.0218, 1.0174]), + ([6, 12], -75, 75, 0, [1.0, 1.0, 1.0, 1.0]), ], ) def test_estimate_dz_rescaling( diff --git a/improver_tests/calibration/ensemble_calibration/helper_functions.py b/improver_tests/calibration/ensemble_calibration/helper_functions.py index d8770c1756..06bb7e957e 100644 --- a/improver_tests/calibration/ensemble_calibration/helper_functions.py +++ b/improver_tests/calibration/ensemble_calibration/helper_functions.py @@ -1,10 +1,11 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Functions for use within unit tests for `ensemble_calibration` plugins. """ + import datetime import iris @@ -21,7 +22,6 @@ class EnsembleCalibrationAssertions(IrisTest): - """Additional assertions, specifically for usage in the ensemble calibration unit tests.""" @@ -38,7 +38,7 @@ def assertEMOSCoefficientsAlmostEqual(self, first, second): First array to compare. second (numpy.ndarray): Second array to compare. - """ + """ self.assertArrayAlmostEqual(first, second, decimal=4) def assertCalibratedVariablesAlmostEqual(self, first, second): @@ -54,12 +54,11 @@ def assertCalibratedVariablesAlmostEqual(self, first, second): First array to compare. second (numpy.ndarray): Second array to compare. - """ + """ self.assertArrayAlmostEqual(first, second, decimal=4) class SetupCubes(IrisTest): - """Set up cubes for testing.""" def setUp(self): diff --git a/improver_tests/calibration/ensemble_calibration/test_ApplyEMOS.py b/improver_tests/calibration/ensemble_calibration/test_ApplyEMOS.py index fbf6c4a5a3..dcb731ca05 100644 --- a/improver_tests/calibration/ensemble_calibration/test_ApplyEMOS.py +++ b/improver_tests/calibration/ensemble_calibration/test_ApplyEMOS.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the `ensemble_calibration.ApplyEMOS` class.""" diff --git a/improver_tests/calibration/ensemble_calibration/test_CalibratedForecastDistributionParameters.py b/improver_tests/calibration/ensemble_calibration/test_CalibratedForecastDistributionParameters.py index 779dd3f074..91d8bb953c 100644 --- a/improver_tests/calibration/ensemble_calibration/test_CalibratedForecastDistributionParameters.py +++ b/improver_tests/calibration/ensemble_calibration/test_CalibratedForecastDistributionParameters.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the @@ -8,6 +8,7 @@ class. """ + import unittest import numpy as np @@ -29,7 +30,6 @@ class SetupCoefficientsCubes(SetupCubes, SetupExpectedCoefficients): - """Set up coefficients cubes for testing.""" def setUp(self): @@ -150,7 +150,7 @@ def setUp(self): dtype=np.float32, ) self.expected_loc_param_realizations_sites = np.array( - [277.7531, 277.4529, 277.553, 277.2528], dtype=np.float32, + [277.7531, 277.4529, 277.553, 277.2528], dtype=np.float32 ) self.expected_scale_param_realizations_sites = np.array( @@ -191,7 +191,6 @@ def setUp(self): class Test__init__(IrisTest): - """Test the __init__ method.""" def test_basic(self): @@ -206,7 +205,6 @@ def test_with_predictor(self): class Test__repr__(IrisTest): - """Test the __repr__ method.""" def test_basic(self): @@ -223,8 +221,7 @@ def test_with_predictor(self): class Test__spatial_domain_match(SetupCoefficientsCubes): - - """ Test the _spatial_domain_match method.""" + """Test the _spatial_domain_match method.""" def setUp(self): super().setUp() @@ -281,7 +278,6 @@ def test_skipping_spot_forecast(self): class Test__calculate_location_parameter_from_mean( SetupCoefficientsCubes, EnsembleCalibrationAssertions ): - """Test the __calculate_location_parameter_from_mean method.""" def setUp(self): @@ -302,7 +298,7 @@ def test_basic(self): location_parameter, self.expected_loc_param_mean ) assert_array_almost_equal( - location_parameter, self.expected_loc_param_realizations, decimal=0, + location_parameter, self.expected_loc_param_realizations, decimal=0 ) def test_missing_additional_predictor(self): @@ -317,7 +313,6 @@ def test_missing_additional_predictor(self): class Test__calculate_location_parameter_from_realizations( SetupCoefficientsCubes, EnsembleCalibrationAssertions ): - """Test the _calculate_location_parameter_from_realizations method.""" def setUp(self): @@ -347,7 +342,6 @@ def test_basic(self): class Test__calculate_scale_parameter( SetupCoefficientsCubes, EnsembleCalibrationAssertions ): - """Test the _calculate_scale_parameter method.""" def setUp(self): @@ -366,7 +360,6 @@ def test_basic(self): class Test__create_output_cubes(SetupCoefficientsCubes, EnsembleCalibrationAssertions): - """Test the _create_output_cubes method.""" def setUp(self): @@ -378,18 +371,16 @@ def setUp(self): def test_basic(self): """Test that the cubes created containing the location and scale parameter are formatted as expected.""" - ( - location_parameter_cube, - scale_parameter_cube, - ) = self.plugin._create_output_cubes( - self.expected_loc_param_mean, self.expected_scale_param_mean + (location_parameter_cube, scale_parameter_cube) = ( + self.plugin._create_output_cubes( + self.expected_loc_param_mean, self.expected_scale_param_mean + ) ) self.assertEqual(location_parameter_cube, self.expected_loc_param_mean_cube) self.assertEqual(scale_parameter_cube, self.expected_scale_param_mean_cube) class Test_process(SetupCoefficientsCubes, EnsembleCalibrationAssertions): - """Test the process plugin.""" def setUp(self): diff --git a/improver_tests/calibration/ensemble_calibration/test_ContinuousRankedProbabilityScoreMinimisers.py b/improver_tests/calibration/ensemble_calibration/test_ContinuousRankedProbabilityScoreMinimisers.py index 4a602f5e89..3e277865a2 100644 --- a/improver_tests/calibration/ensemble_calibration/test_ContinuousRankedProbabilityScoreMinimisers.py +++ b/improver_tests/calibration/ensemble_calibration/test_ContinuousRankedProbabilityScoreMinimisers.py @@ -1,12 +1,13 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the `ensemble_calibration.ContinuousRankedProbabilityScoreMinimisers` class. """ + import unittest import iris @@ -24,7 +25,6 @@ class SetupInputs(IrisTest): - """Set up inputs for testing.""" def setUp(self): @@ -47,7 +47,6 @@ def setUp(self): class SetupNormalInputs(SetupInputs, SetupCubes): - """Create a class for setting up cubes for testing.""" def setUp(self): @@ -100,20 +99,19 @@ def setUp(self): spatial_product = np.prod(self.truth.shape[-2:]) self.initial_guess_spot_mean = np.broadcast_to( self.initial_guess_for_mean, - (spatial_product, len(self.initial_guess_for_mean),), + (spatial_product, len(self.initial_guess_for_mean)), ) self.initial_guess_spot_realizations = np.broadcast_to( self.initial_guess_for_realization, - (spatial_product, len(self.initial_guess_for_realization),), + (spatial_product, len(self.initial_guess_for_realization)), ) self.ig_spot_mean_additional_predictor = np.broadcast_to( self.initial_guess_mean_additional_predictor, - (spatial_product, len(self.initial_guess_mean_additional_predictor),), + (spatial_product, len(self.initial_guess_mean_additional_predictor)), ) class Test_calculate_normal_crps(SetupNormalInputs): - """ Test minimising the CRPS for a normal distribution. Either the ensemble mean or the individual ensemble realizations are @@ -184,7 +182,6 @@ def test_basic_mean_predictor_bad_value(self): class Test_process_normal_distribution( SetupNormalInputs, EnsembleCalibrationAssertions ): - """ Test minimising the CRPS for a normal distribution. Either the ensemble mean or the individual ensemble realizations are used @@ -529,9 +526,9 @@ def test_point_by_point_with_nans(self): self.forecast_variance, distribution, ) - self.expected_mean_coefficients_point_by_point[ - :, 0, 0 - ] = self.initial_guess_for_mean + self.expected_mean_coefficients_point_by_point[:, 0, 0] = ( + self.initial_guess_for_mean + ) self.assertEMOSCoefficientsAlmostEqual( result, self.expected_mean_coefficients_point_by_point ) @@ -578,7 +575,6 @@ def test_mean_predictor_point_by_point_sites_additional_predictor(self): class SetupTruncatedNormalInputs(SetupInputs, SetupCubes): - """Create a class for setting up cubes for testing.""" def setUp(self): @@ -638,7 +634,6 @@ def setUp(self): class Test_calculate_truncated_normal_crps(SetupTruncatedNormalInputs): - """ Test minimising the crps for a truncated normal distribution. Either the ensemble mean or the individual ensemble realizations are used @@ -709,7 +704,6 @@ def test_basic_mean_predictor_bad_value(self): class Test_process_truncated_normal_distribution( SetupTruncatedNormalInputs, EnsembleCalibrationAssertions ): - """ Test minimising the CRPS for a truncated normal distribution. Either the ensemble mean or the individual ensemble realizations are used diff --git a/improver_tests/calibration/ensemble_calibration/test_EstimateCoefficientsForEnsembleCalibration.py b/improver_tests/calibration/ensemble_calibration/test_EstimateCoefficientsForEnsembleCalibration.py index c704276f9f..60b9fb5561 100644 --- a/improver_tests/calibration/ensemble_calibration/test_EstimateCoefficientsForEnsembleCalibration.py +++ b/improver_tests/calibration/ensemble_calibration/test_EstimateCoefficientsForEnsembleCalibration.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the @@ -8,6 +8,7 @@ class. """ + import datetime import unittest from functools import partial @@ -30,7 +31,6 @@ class SetupExpectedCoefficients(IrisTest): - """Expected coefficients generated by EMOS using the test data.""" def setUp(self): @@ -67,11 +67,7 @@ def setUp(self): ] ), "emos_coefficient_beta": np.array( - [ - [0.9999, 1.0001, 1.0006], - [1.0008, 1.0003, 1.0], - [1.0001, 1.0006, 1.0], - ] + [[0.9999, 1.0001, 1.0006], [1.0008, 1.0003, 1.0], [1.0001, 1.0006, 1.0]] ), "emos_coefficient_gamma": np.array( [ @@ -143,11 +139,7 @@ def setUp(self): ] ), "emos_coefficient_delta": np.array( - [ - [-0.0, 0.0, -0.0005], - [0.0009, 0.0, 0.0003], - [0.0001, -0.0008, 0.0001], - ], + [[-0.0, 0.0, -0.0005], [0.0009, 0.0, 0.0003], [0.0001, -0.0008, 0.0001]] ), } self.expected_mean_pred_each_site = { @@ -192,7 +184,6 @@ def setUp(self): class Test__init__(SetupCubes): - """Test the initialisation of the class.""" def setUp(self): @@ -204,7 +195,7 @@ def test_coeff_names(self): """Test that the plugin instance defines the expected coefficient names.""" expected = ["alpha", "beta", "gamma", "delta"] - plugin = Plugin(self.distribution,) + plugin = Plugin(self.distribution) self.assertEqual(plugin.coeff_names, expected) def test_invalid_distribution(self): @@ -216,7 +207,6 @@ def test_invalid_distribution(self): class Test_create_coefficients_cubelist(SetupCubes, SetupExpectedCoefficients): - """Test the create_coefficients_cubelist method.""" def setUp(self): @@ -274,11 +264,9 @@ def test_coefficients_from_mean(self): self.assertEqual(len(result), 4) for cube in result: self.assertEqual( - cube.coord("forecast_reference_time").cell(0).point, self.expected_frt, - ) - self.assertEqual( - cube.coord("forecast_period"), self.expected_fp, + cube.coord("forecast_reference_time").cell(0).point, self.expected_frt ) + self.assertEqual(cube.coord("forecast_period"), self.expected_fp) self.assertArrayAlmostEqual( cube.coord(axis="x").points, self.expected_x_coord_points ) @@ -310,11 +298,9 @@ def test_coordinates_from_mean_period_diagnostic(self): self.assertEqual(len(result), 4) for cube in result: self.assertEqual( - cube.coord("forecast_reference_time").cell(0).point, self.expected_frt, - ) - self.assertEqual( - cube.coord("forecast_period"), self.expected_fp, + cube.coord("forecast_reference_time").cell(0).point, self.expected_frt ) + self.assertEqual(cube.coord("forecast_period"), self.expected_fp) def test_exception_for_multi_valued_forecast_period(self): """Test that an exception is raised if the forecast_period is multi- @@ -389,11 +375,9 @@ def test_coefficients_point_by_point_sites(self): self.assertEqual(len(result), 4) for cube in result: self.assertEqual( - cube.coord("forecast_reference_time").cell(0).point, self.expected_frt, - ) - self.assertEqual( - cube.coord("forecast_period"), self.expected_fp, + cube.coord("forecast_reference_time").cell(0).point, self.expected_frt ) + self.assertEqual(cube.coord("forecast_period"), self.expected_fp) self.assertAlmostEqual( cube.coord("latitude"), self.historic_forecast_spot_cube.coord("latitude"), @@ -457,7 +441,7 @@ def test_too_few_coefficients(self): predictor = "mean" optimised_coeffs = [1, 2, 3] plugin = Plugin( - distribution=distribution, desired_units=desired_units, predictor=predictor, + distribution=distribution, desired_units=desired_units, predictor=predictor ) msg = "The number of coefficients in" with self.assertRaisesRegex(ValueError, msg): @@ -492,7 +476,6 @@ def _create_multi_date_cube(data): class Test_compute_initial_guess(IrisTest): - """Test the compute_initial_guess method.""" def setUp(self): @@ -572,8 +555,8 @@ def setUp(self): self.hist_fcast_pred_mean_mhalo = cube.collapsed( "realization", iris.analysis.MEAN ) - self.hist_fcast_pred_mean_mhalo.data = self.hist_fcast_pred_mean_mhalo.data.astype( - np.float32 + self.hist_fcast_pred_mean_mhalo.data = ( + self.hist_fcast_pred_mean_mhalo.data.astype(np.float32) ) self.hist_fcast_pred_mean_mhalo_data = np.expand_dims( self.hist_fcast_pred_mean_mhalo.data, axis=0 @@ -628,7 +611,7 @@ def test_basic_mean_predictor(self): ) result = plugin.compute_initial_guess( - self.truth.data, self.hist_fcast_pred_mean_data, self.predictor, None, + self.truth.data, self.hist_fcast_pred_mean_data, self.predictor, None ) self.assertIsInstance(result, np.ndarray) self.assertArrayAlmostEqual( @@ -677,7 +660,7 @@ def test_mean_predictor_estimate_coefficients(self): desired_units=self.desired_units, ) result = plugin.compute_initial_guess( - self.truth.data, self.hist_fcast_pred_mean_data, self.predictor, None, + self.truth.data, self.hist_fcast_pred_mean_data, self.predictor, None ) self.assertArrayAlmostEqual( @@ -703,10 +686,7 @@ def test_realizations_predictor_estimate_coefficients(self): desired_units=self.desired_units, ) result = plugin.compute_initial_guess( - self.truth.data, - forecast_predictor.data, - predictor, - self.no_of_realizations, + self.truth.data, forecast_predictor.data, predictor, self.no_of_realizations ) self.assertArrayAlmostEqual( self.expected_realizations_pred_compute_initial_guess, result @@ -781,7 +761,7 @@ def test_mean_predictor_multiple_forecast_predictors_default(self): desired_units=self.desired_units, ) result = plugin.compute_initial_guess( - self.truth.data, self.additional_predictors, self.predictor, None, + self.truth.data, self.additional_predictors, self.predictor, None ) self.assertIsInstance(result, np.ndarray) self.assertArrayAlmostEqual(result, self.expected_multiple_predictors_default) @@ -799,7 +779,7 @@ def test_mean_predictor_multiple_forecast_predictors_nondefault(self): desired_units=self.desired_units, ) result = plugin.compute_initial_guess( - self.truth.data, self.additional_predictors, self.predictor, None, + self.truth.data, self.additional_predictors, self.predictor, None ) self.assertIsInstance(result, np.ndarray) self.assertArrayAlmostEqual( @@ -881,7 +861,6 @@ def test_fail_transposed_input(self): class Test_process( SetupCubes, EnsembleCalibrationAssertions, SetupExpectedCoefficients ): - """Test the process method""" def setUp(self): @@ -927,7 +906,7 @@ def test_coefficient_values_for_norm_distribution(self): ) self.assertEMOSCoefficientsAlmostEqual( - np.array([cube.data for cube in result]), self.expected_mean_pred_norm, + np.array([cube.data for cube in result]), self.expected_mean_pred_norm ) self.assertArrayEqual( [cube.name() for cube in result], self.expected_coeff_names @@ -949,7 +928,7 @@ def test_coefficient_values_for_norm_distribution_landsea_mask(self): ) self.assertEMOSCoefficientsAlmostEqual( - np.array([cube.data for cube in result]), self.expected_mean_pred_norm, + np.array([cube.data for cube in result]), self.expected_mean_pred_norm ) self.assertArrayEqual( [cube.name() for cube in result], self.expected_coeff_names @@ -1035,7 +1014,7 @@ def test_coefficient_values_for_norm_distribution_max_iterations(self): ) self.assertEMOSCoefficientsAlmostEqual( - np.array([cube.data for cube in result]), self.expected_mean_pred_norm, + np.array([cube.data for cube in result]), self.expected_mean_pred_norm ) self.assertArrayEqual( [cube.name() for cube in result], self.expected_coeff_names @@ -1055,7 +1034,7 @@ def test_coefficient_values_for_truncnorm_distribution(self): ) self.assertEMOSCoefficientsAlmostEqual( - np.array([cube.data for cube in result]), self.expected_mean_pred_truncnorm, + np.array([cube.data for cube in result]), self.expected_mean_pred_truncnorm ) self.assertArrayEqual( [cube.name() for cube in result], self.expected_coeff_names @@ -1084,7 +1063,7 @@ def test_coefficient_values_for_truncnorm_distribution_mask(self): ) self.assertEMOSCoefficientsAlmostEqual( - np.array([cube.data for cube in result]), self.expected_mean_pred_truncnorm, + np.array([cube.data for cube in result]), self.expected_mean_pred_truncnorm ) self.assertArrayEqual( [cube.name() for cube in result], self.expected_coeff_names @@ -1165,11 +1144,11 @@ def test_point_by_point(self): ) for cube in result: self.assertEMOSCoefficientsAlmostEqual( - cube.data, self.expected_mean_pred_each_grid_point[cube.name()], + cube.data, self.expected_mean_pred_each_grid_point[cube.name()] ) self.assertIn(cube.name(), self.expected_coeff_names) self.assertEqual( - [c.name() for c in cube.coords(dim_coords=True)], expected_dim_coord, + [c.name() for c in cube.coords(dim_coords=True)], expected_dim_coord ) beta_cube = result.extract_cube("emos_coefficient_beta") self.assertArrayEqual( @@ -1196,11 +1175,11 @@ def test_point_by_point_with_nans(self): ) for cube in result: self.assertEMOSCoefficientsAlmostEqual( - cube.data, self.expected_mean_pred_each_grid_point[cube.name()], + cube.data, self.expected_mean_pred_each_grid_point[cube.name()] ) self.assertIn(cube.name(), self.expected_coeff_names) self.assertEqual( - [c.name() for c in cube.coords(dim_coords=True)], expected_dim_coords, + [c.name() for c in cube.coords(dim_coords=True)], expected_dim_coords ) def test_point_by_point_sites(self): @@ -1212,11 +1191,11 @@ def test_point_by_point_sites(self): result = plugin.process(self.historic_forecast_spot_cube, self.truth_spot_cube) for cube in result: self.assertEMOSCoefficientsAlmostEqual( - cube.data, self.expected_mean_pred_each_site[cube.name()], + cube.data, self.expected_mean_pred_each_site[cube.name()] ) self.assertIn(cube.name(), self.expected_coeff_names) self.assertEqual( - [c.name() for c in cube.coords(dim_coords=True)], expected_dim_coords, + [c.name() for c in cube.coords(dim_coords=True)], expected_dim_coords ) def test_point_by_point_sites_realizations(self): @@ -1236,7 +1215,7 @@ def test_point_by_point_sites_realizations(self): result = plugin.process(self.historic_forecast_spot_cube, self.truth_spot_cube) for cube in result: self.assertEMOSCoefficientsAlmostEqual( - cube.data, self.expected_realizations_each_site[cube.name()], + cube.data, self.expected_realizations_each_site[cube.name()] ) self.assertIn(cube.name(), self.expected_coeff_names) self.assertEqual( @@ -1258,7 +1237,8 @@ def test_point_by_point_landsea_mask(self): def test_point_by_point_default_initial_guess(self): """Test computing coefficients independently for each grid point - (minimisation only) returns the expected coefficients and associated metadata.""" + (minimisation only) returns the expected coefficients and associated metadata. + """ expected_dim_coords = ["latitude", "longitude"] plugin = self.plugin( @@ -1269,12 +1249,11 @@ def test_point_by_point_default_initial_guess(self): ) for cube in result: self.assertEMOSCoefficientsAlmostEqual( - cube.data, - self.expected_mean_pred_minimise_each_grid_point[cube.name()], + cube.data, self.expected_mean_pred_minimise_each_grid_point[cube.name()] ) self.assertIn(cube.name(), self.expected_coeff_names) self.assertEqual( - [c.name() for c in cube.coords(dim_coords=True)], expected_dim_coords, + [c.name() for c in cube.coords(dim_coords=True)], expected_dim_coords ) def test_point_by_point_default_initial_guess_realizations(self): @@ -1317,7 +1296,7 @@ def test_sites_additional_static_predictor(self): CubeList([self.spot_altitude_cube]), ) self.assertEMOSCoefficientsAlmostEqual( - np.hstack([cube.data for cube in result]), self.expected_mean_pred_norm_alt, + np.hstack([cube.data for cube in result]), self.expected_mean_pred_norm_alt ) self.assertArrayEqual( [cube.name() for cube in result], self.expected_coeff_names @@ -1348,7 +1327,7 @@ def test_sites_point_by_point_with_additional_static_predictor(self): for cube in result: self.assertEMOSCoefficientsAlmostEqual( - cube.data, self.expected_mean_pred_each_site_alt[cube.name()], + cube.data, self.expected_mean_pred_each_site_alt[cube.name()] ) self.assertIn(cube.name(), self.expected_coeff_names) self.assertEqual( @@ -1398,7 +1377,7 @@ def test_truth_unit_conversion(self): ) self.assertEMOSCoefficientsAlmostEqual( - np.array([cube.data for cube in result]), self.expected_mean_pred_norm, + np.array([cube.data for cube in result]), self.expected_mean_pred_norm ) def test_historic_forecast_unit_conversion(self): @@ -1413,7 +1392,7 @@ def test_historic_forecast_unit_conversion(self): ) self.assertEMOSCoefficientsAlmostEqual( - np.array([cube.data for cube in result]), self.expected_mean_pred_norm, + np.array([cube.data for cube in result]), self.expected_mean_pred_norm ) def test_non_matching_units(self): diff --git a/improver_tests/calibration/rainforests_calibration/conftest.py b/improver_tests/calibration/rainforests_calibration/conftest.py index 7145d52e5b..879bf66baa 100644 --- a/improver_tests/calibration/rainforests_calibration/conftest.py +++ b/improver_tests/calibration/rainforests_calibration/conftest.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Fixtures for rainforests calibration.""" + import os from datetime import datetime diff --git a/improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibration.py b/improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibration.py index e2c55eab3b..782db728ca 100644 --- a/improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibration.py +++ b/improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibration.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the ApplyRainForestsCalibration class.""" + import sys import numpy as np @@ -44,7 +45,7 @@ def __init__(self, libpath, nthread, **kwargs): @pytest.mark.parametrize("treelite_model", (TREELITE_ENABLED, False)) @pytest.mark.parametrize("treelite_file", (True, False)) def test__new__( - lightgbm_keys, treelite_model, treelite_file, monkeypatch, model_config, + lightgbm_keys, treelite_model, treelite_file, monkeypatch, model_config ): """Test treelite models are loaded if model_config correctly defines them. If all thresholds contain treelite model AND the treelite module is available, treelite Predictor is returned, diff --git a/improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibrationLightGBM.py b/improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibrationLightGBM.py index 9c69112370..557b887fa7 100644 --- a/improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibrationLightGBM.py +++ b/improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibrationLightGBM.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the ApplyRainForestsCalibrationLightGBM class.""" + import numpy as np import pytest from iris import Constraint @@ -106,7 +107,7 @@ def test__align_feature_variables_ensemble(ensemble_features, ensemble_forecast) derived_field_cube.remove_coord("realization") ensemble_features.append(derived_field_cube) - (aligned_features, aligned_forecast,) = ApplyRainForestsCalibrationLightGBM( + (aligned_features, aligned_forecast) = ApplyRainForestsCalibrationLightGBM( model_config_dict={} )._align_feature_variables(ensemble_features, ensemble_forecast) @@ -128,7 +129,7 @@ def test__align_feature_variables_deterministic( deterministic_forecast = deterministic_forecast.extract(Constraint(realization=0)) deterministic_forecast.remove_coord("realization") - (aligned_features, aligned_forecast,) = ApplyRainForestsCalibrationLightGBM( + (aligned_features, aligned_forecast) = ApplyRainForestsCalibrationLightGBM( model_config_dict={} )._align_feature_variables(deterministic_features, deterministic_forecast) @@ -207,12 +208,10 @@ def test__evaluate_probabilities( probability data.""" plugin_cls, dummy_models = plugin_and_dummy_models plugin = plugin_cls(model_config_dict={}) - plugin.tree_models, plugin.lead_times, plugin.model_thresholds, = dummy_models + plugin.tree_models, plugin.lead_times, plugin.model_thresholds = dummy_models input_dataset = plugin._prepare_features_array(ensemble_features) data_before = threshold_cube.data.copy() - plugin._evaluate_probabilities( - input_dataset, 24, threshold_cube.data, - ) + plugin._evaluate_probabilities(input_dataset, 24, threshold_cube.data) diff = threshold_cube.data - data_before # check each threshold has been populated assert np.all(np.any(diff != 0, axis=0)) @@ -343,13 +342,13 @@ def test_lead_time_without_matching_model( output_thresholds = [0.0, 0.0005, 0.001] result_24_hour = plugin.process( - ensemble_forecast, ensemble_features, output_thresholds, + ensemble_forecast, ensemble_features, output_thresholds ) ensemble_forecast.coord("forecast_period").points = [27 * SECONDS_IN_HOUR] for cube in ensemble_features: cube.coord("forecast_period").points = [27 * SECONDS_IN_HOUR] result_27_hour = plugin.process( - ensemble_forecast, ensemble_features, output_thresholds, + ensemble_forecast, ensemble_features, output_thresholds ) np.testing.assert_almost_equal(result_24_hour.data, result_27_hour.data) @@ -364,7 +363,7 @@ def test_process_ensemble_specifying_thresholds( plugin.tree_models, plugin.lead_times, plugin.model_thresholds = dummy_models output_thresholds = [0.0, 0.0005, 0.001] - result = plugin.process(ensemble_forecast, ensemble_features, output_thresholds,) + result = plugin.process(ensemble_forecast, ensemble_features, output_thresholds) forecast_variable = ensemble_forecast.name() assert result.long_name == f"probability_of_{forecast_variable}_above_threshold" @@ -414,7 +413,7 @@ def test_process_with_bin_data( plugin.tree_models, plugin.lead_times, plugin.model_thresholds = dummy_models output_thresholds = [0.0, 0.0005, 0.001] - result = plugin.process(ensemble_forecast, ensemble_features, output_thresholds,) + result = plugin.process(ensemble_forecast, ensemble_features, output_thresholds) # check that there are duplicated rows in result (so that binning will actually # have an effect) @@ -423,9 +422,7 @@ def test_process_with_bin_data( plugin = plugin_cls(model_config_dict={}, bin_data=True) plugin.tree_models, plugin.lead_times, plugin.model_thresholds = dummy_models plugin.combined_feature_splits = plugin._get_feature_splits(model_config) - result_bin = plugin.process( - ensemble_forecast, ensemble_features, output_thresholds, - ) + result_bin = plugin.process(ensemble_forecast, ensemble_features, output_thresholds) np.testing.assert_equal(result.data, result_bin.data) @@ -440,7 +437,7 @@ def test_process_deterministic( plugin.tree_models, plugin.lead_times, plugin.model_thresholds = dummy_models output_thresholds = [0.0, 0.0005, 0.001] result = plugin.process( - deterministic_forecast, deterministic_features, output_thresholds, + deterministic_forecast, deterministic_features, output_thresholds ) forecast_variable = deterministic_forecast.name() diff --git a/improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibrationTreelite.py b/improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibrationTreelite.py index 6b486e9852..89dbf97889 100644 --- a/improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibrationTreelite.py +++ b/improver_tests/calibration/rainforests_calibration/test_ApplyRainForestsCalibrationTreelite.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the ApplyRainForestsCalibrationTreelite class.""" + import sys import numpy as np diff --git a/improver_tests/calibration/reliability_calibration/conftest.py b/improver_tests/calibration/reliability_calibration/conftest.py index ecd0144b5c..9008baf1b5 100644 --- a/improver_tests/calibration/reliability_calibration/conftest.py +++ b/improver_tests/calibration/reliability_calibration/conftest.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Fixtures for reliability calibration tests.""" @@ -96,7 +96,7 @@ def forecast_spot(forecast_grid): forecasts_spot_list = CubeList() for day in range(5, 7): time_coords = construct_scalar_time_coords( - datetime(2017, 11, day, 4, 0), None, datetime(2017, 11, day, 0, 0), + datetime(2017, 11, day, 4, 0), None, datetime(2017, 11, day, 0, 0) ) time_coords = [t[0] for t in time_coords] forecasts_spot_list.append( @@ -122,7 +122,7 @@ def truth_spot(truth_grid): truths_spot_list = CubeList() for day in range(5, 7): time_coords = construct_scalar_time_coords( - datetime(2017, 11, day, 4, 0), None, datetime(2017, 11, day, 4, 0), + datetime(2017, 11, day, 4, 0), None, datetime(2017, 11, day, 4, 0) ) time_coords = [t[0] for t in time_coords] truths_spot_list.append( @@ -369,7 +369,7 @@ def reliability_table_point_grid(forecast_grid, truth_grid, reliability_data): @pytest.fixture(params=["point_spot", "point_grid"]) def create_rel_tables_point( - request, reliability_table_point_spot, reliability_table_point_grid, + request, reliability_table_point_spot, reliability_table_point_grid ): if request.param == "point_spot": return RelTables( diff --git a/improver_tests/calibration/reliability_calibration/test_AggregateReliabilityCalibrationTables.py b/improver_tests/calibration/reliability_calibration/test_AggregateReliabilityCalibrationTables.py index f9612159d6..dd0edd8377 100644 --- a/improver_tests/calibration/reliability_calibration/test_AggregateReliabilityCalibrationTables.py +++ b/improver_tests/calibration/reliability_calibration/test_AggregateReliabilityCalibrationTables.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the AggregateReliabilityCalibrationTables plugin.""" @@ -112,7 +112,7 @@ def test_process_aggregating_over_cubes_and_coordinates( plugin = Plugin() result = plugin.process( - [reliability_cube, different_frt], coordinates=["latitude", "longitude"], + [reliability_cube, different_frt], coordinates=["latitude", "longitude"] ) assert_array_equal(result.data, lat_lon_collapse * 2) assert_array_equal(result.coord(frt).points, expected_points) diff --git a/improver_tests/calibration/reliability_calibration/test_ApplyReliabilityCalibration.py b/improver_tests/calibration/reliability_calibration/test_ApplyReliabilityCalibration.py index 3752a3ffb9..c116a85464 100644 --- a/improver_tests/calibration/reliability_calibration/test_ApplyReliabilityCalibration.py +++ b/improver_tests/calibration/reliability_calibration/test_ApplyReliabilityCalibration.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the ApplyReliabilityCalibration plugin.""" @@ -64,7 +64,6 @@ def create_point_by_point_reliability_table( class Test_ReliabilityCalibrate(unittest.TestCase): - """Test class for the Test_ApplyReliabilityCalibration tests, setting up cubes to use as inputs.""" @@ -161,7 +160,6 @@ def setUp(self): class Test__init__(unittest.TestCase): - """Test the __init__ method.""" def test_using_defaults(self): @@ -172,7 +170,6 @@ def test_using_defaults(self): class Test__extract_matching_reliability_table(Test_ReliabilityCalibrate): - """Test the _extract_matching_reliability_table method.""" def test_matching_coords(self): @@ -206,7 +203,6 @@ def test_unmatching_coords(self): class Test__ensure_monotonicity_across_thresholds(Test_ReliabilityCalibrate): - """Test the _ensure_monotonicity_across_thresholds method.""" def test_monotonic_case(self): @@ -243,9 +239,9 @@ def test_monotonic_in_wrong_direction(self): the relative_to_threshold attribute.""" expected = self.forecast.copy(data=self.forecast.data[::-1]) - self.forecast.coord(self.threshold).attributes[ - "spp__relative_to_threshold" - ] = "below" + self.forecast.coord(self.threshold).attributes["spp__relative_to_threshold"] = ( + "below" + ) warning_msg = "Below threshold probabilities are not increasing" with pytest.warns(UserWarning, match=warning_msg): @@ -267,7 +263,6 @@ def test_exception_without_relative_to_threshold(self): class Test__calculate_reliability_probabilities(Test_ReliabilityCalibrate): - """Test the _calculate_reliability_probabilities method.""" def test_values(self): @@ -322,11 +317,9 @@ def test_fewer_than_two_bins(self): class Test__interpolate(unittest.TestCase): - """Test the _interpolate method.""" def setUp(self): - """Set up data for testing the interpolate method.""" self.reliability_probabilities = np.array([0.0, 0.4, 0.8]) @@ -398,7 +391,6 @@ def test_reshaping(self): class Test_process(Test_ReliabilityCalibrate): - """Test the process method.""" def test_calibrating_forecast_with_reliability_table_cube(self): diff --git a/improver_tests/calibration/reliability_calibration/test_ConstructReliabilityCalibrationTables.py b/improver_tests/calibration/reliability_calibration/test_ConstructReliabilityCalibrationTables.py index 9d4ec79fa0..0b32e543f9 100644 --- a/improver_tests/calibration/reliability_calibration/test_ConstructReliabilityCalibrationTables.py +++ b/improver_tests/calibration/reliability_calibration/test_ConstructReliabilityCalibrationTables.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the ConstructReliabilityCalibrationTables plugin.""" @@ -152,7 +152,7 @@ def test_cpb_coordinate_no_single_value_bins(): type with no single value lower and upper bins.""" expected_bounds = np.array([[0, 0.5], [0.5, 1]]) expected_points = np.mean(expected_bounds, axis=1) - plugin = Plugin(n_probability_bins=2,) + plugin = Plugin(n_probability_bins=2) result = plugin._create_probability_bins_coord() assert isinstance(result, iris.coords.DimCoord) diff --git a/improver_tests/calibration/reliability_calibration/test_ManipulateReliabilityTable.py b/improver_tests/calibration/reliability_calibration/test_ManipulateReliabilityTable.py index 528730069e..32adadca29 100644 --- a/improver_tests/calibration/reliability_calibration/test_ManipulateReliabilityTable.py +++ b/improver_tests/calibration/reliability_calibration/test_ManipulateReliabilityTable.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the ManipulateReliabilityTable plugin.""" @@ -41,7 +41,7 @@ def test_cub_monotonic_no_undersampled_bins( obs_count = forecast_probability_sum = default_obs_counts result = Plugin()._combine_undersampled_bins( - obs_count, forecast_probability_sum, default_fcst_counts, probability_bin_coord, + obs_count, forecast_probability_sum, default_fcst_counts, probability_bin_coord ) assert_array_equal( @@ -64,12 +64,12 @@ def test_cub_poorly_sampled_bins(probability_bin_coord): ) result = Plugin()._combine_undersampled_bins( - obs_count, forecast_probability_sum, forecast_count, probability_bin_coord, + obs_count, forecast_probability_sum, forecast_count, probability_bin_coord ) assert_array_equal(result[:3], expected) expected_bin_coord_points = np.array([0.5], dtype=np.float32) - expected_bin_coord_bounds = np.array([[0.0, 1.0]], dtype=np.float32,) + expected_bin_coord_bounds = np.array([[0.0, 1.0]], dtype=np.float32) assert_allclose(expected_bin_coord_points, result[3].points) assert_allclose(expected_bin_coord_bounds, result[3].bounds) @@ -89,13 +89,13 @@ def test_cub_one_undersampled_bin_at_top(probability_bin_coord): ) result = Plugin()._combine_undersampled_bins( - obs_count, forecast_probability_sum, forecast_count, probability_bin_coord, + obs_count, forecast_probability_sum, forecast_count, probability_bin_coord ) assert_array_equal(result[:3], expected) expected_bin_coord_points = np.array([0.1, 0.3, 0.5, 0.8], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.2], [0.2, 0.4], [0.4, 0.6], [0.6, 1.0]], dtype=np.float32, + [[0.0, 0.2], [0.2, 0.4], [0.4, 0.6], [0.6, 1.0]], dtype=np.float32 ) assert_allclose(expected_bin_coord_points, result[3].points) assert_allclose(expected_bin_coord_bounds, result[3].bounds) @@ -114,13 +114,13 @@ def test_cub_one_undersampled_bin_at_bottom(default_obs_counts, probability_bin_ ] ) result = Plugin()._combine_undersampled_bins( - obs_count, forecast_probability_sum, forecast_count, probability_bin_coord, + obs_count, forecast_probability_sum, forecast_count, probability_bin_coord ) assert_array_equal(result[:3], expected) expected_bin_coord_points = np.array([0.2, 0.5, 0.7, 0.9], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.4], [0.4, 0.6], [0.6, 0.8], [0.8, 1.0]], dtype=np.float32, + [[0.0, 0.4], [0.4, 0.6], [0.6, 0.8], [0.8, 1.0]], dtype=np.float32 ) assert_allclose(expected_bin_coord_points, result[3].points) assert_allclose(expected_bin_coord_bounds, result[3].bounds) @@ -141,13 +141,13 @@ def test_cub_one_undersampled_bin_lower_neighbour(probability_bin_coord): ] ) result = Plugin()._combine_undersampled_bins( - obs_count, forecast_probability_sum, forecast_count, probability_bin_coord, + obs_count, forecast_probability_sum, forecast_count, probability_bin_coord ) assert_array_equal(result[:3], expected) expected_bin_coord_points = np.array([0.1, 0.4, 0.7, 0.9], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.2], [0.2, 0.6], [0.6, 0.8], [0.8, 1.0]], dtype=np.float32, + [[0.0, 0.2], [0.2, 0.6], [0.6, 0.8], [0.8, 1.0]], dtype=np.float32 ) assert_allclose(expected_bin_coord_points, result[3].points) assert_allclose(expected_bin_coord_bounds, result[3].bounds) @@ -168,13 +168,13 @@ def test_cub_one_undersampled_bin_upper_neighbour(probability_bin_coord): ] ) result = Plugin()._combine_undersampled_bins( - obs_count, forecast_probability_sum, forecast_count, probability_bin_coord, + obs_count, forecast_probability_sum, forecast_count, probability_bin_coord ) assert_array_equal(result[:3], expected) expected_bin_coord_points = np.array([0.1, 0.3, 0.6, 0.9], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.2], [0.2, 0.4], [0.4, 0.8], [0.8, 1.0]], dtype=np.float32, + [[0.0, 0.2], [0.2, 0.4], [0.4, 0.8], [0.8, 1.0]], dtype=np.float32 ) assert_allclose(expected_bin_coord_points, result[3].points) assert_allclose(expected_bin_coord_bounds, result[3].bounds) @@ -194,13 +194,13 @@ def test_cub_two_undersampled_bins(probability_bin_coord): ] ) result = Plugin()._combine_undersampled_bins( - obs_count, forecast_probability_sum, forecast_count, probability_bin_coord, + obs_count, forecast_probability_sum, forecast_count, probability_bin_coord ) assert_array_equal(result[:3], expected) expected_bin_coord_points = np.array([0.1, 0.4, 0.8], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.2], [0.2, 0.6], [0.6, 1.0]], dtype=np.float32, + [[0.0, 0.2], [0.2, 0.6], [0.6, 1.0]], dtype=np.float32 ) assert_allclose(expected_bin_coord_points, result[3].points) assert_allclose(expected_bin_coord_bounds, result[3].bounds) @@ -222,13 +222,13 @@ def test_cub_two_equal_undersampled_bins(probability_bin_coord): ) result = Plugin()._combine_undersampled_bins( - obs_count, forecast_probability_sum, forecast_count, probability_bin_coord, + obs_count, forecast_probability_sum, forecast_count, probability_bin_coord ) assert_array_equal(result[:3], expected) expected_bin_coord_points = np.array([0.1, 0.4, 0.8], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.2], [0.2, 0.6], [0.6, 1.0]], dtype=np.float32, + [[0.0, 0.2], [0.2, 0.6], [0.6, 1.0]], dtype=np.float32 ) assert_allclose(expected_bin_coord_points, result[3].points) assert_allclose(expected_bin_coord_bounds, result[3].bounds) @@ -249,13 +249,13 @@ def test_cub_three_equal_undersampled_bin_neighbours(probability_bin_coord): ) result = Plugin()._combine_undersampled_bins( - obs_count, forecast_probability_sum, forecast_count, probability_bin_coord, + obs_count, forecast_probability_sum, forecast_count, probability_bin_coord ) assert_array_equal(result[:3], expected) expected_bin_coord_points = np.array([0.1, 0.5, 0.9], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.2], [0.2, 0.8], [0.8, 1.0]], dtype=np.float32, + [[0.0, 0.2], [0.2, 0.8], [0.8, 1.0]], dtype=np.float32 ) assert_allclose(expected_bin_coord_points, result[3].points) assert_allclose(expected_bin_coord_bounds, result[3].bounds) @@ -271,12 +271,12 @@ def test_cbp_one_non_monotonic_bin_pair( obs_count = np.array([0, 250, 500, 1000, 750], dtype=np.float32) forecast_probability_sum = default_obs_counts result = Plugin()._combine_bin_pair( - obs_count, forecast_probability_sum, default_fcst_counts, probability_bin_coord, + obs_count, forecast_probability_sum, default_fcst_counts, probability_bin_coord ) assert_array_equal(result[:3], expected_enforced_monotonic) expected_bin_coord_points = np.array([0.1, 0.3, 0.5, 0.8], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.2], [0.2, 0.4], [0.4, 0.6], [0.6, 1.0]], dtype=np.float32, + [[0.0, 0.2], [0.2, 0.4], [0.4, 0.6], [0.6, 1.0]], dtype=np.float32 ) assert_allclose(expected_bin_coord_points, result[3].points) assert_allclose(expected_bin_coord_bounds, result[3].bounds) @@ -295,12 +295,12 @@ def test_cbp_two_non_monotonic_bin_pairs( forecast_probability_sum = default_obs_counts expected_enforced_monotonic[0][1] = 750 # Amend observation count result = Plugin()._combine_bin_pair( - obs_count, forecast_probability_sum, default_fcst_counts, probability_bin_coord, + obs_count, forecast_probability_sum, default_fcst_counts, probability_bin_coord ) assert_array_equal(result[:3], expected_enforced_monotonic) expected_bin_coord_points = np.array([0.1, 0.3, 0.5, 0.8], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.2], [0.2, 0.4], [0.4, 0.6], [0.6, 1.0]], dtype=np.float32, + [[0.0, 0.2], [0.2, 0.4], [0.4, 0.6], [0.6, 1.0]], dtype=np.float32 ) assert_allclose(expected_bin_coord_points, result[3].points) assert_allclose(expected_bin_coord_bounds, result[3].bounds) @@ -310,7 +310,7 @@ def test_acof_monotonic(default_fcst_counts): """Test no change to observation frequency, if already monotonic.""" obs_count = np.array([0, 0, 250, 500, 750], dtype=np.float32) result = Plugin()._assume_constant_observation_frequency( - obs_count, default_fcst_counts, + obs_count, default_fcst_counts ) assert_array_equal(result.data, obs_count) @@ -320,7 +320,7 @@ def test_acof_non_monotonic_equal_forecast_count(default_fcst_counts): obs_count = np.array([0, 750, 500, 1000, 750], dtype=np.float32) expected_result = np.array([0, 750, 750, 1000, 1000], dtype=np.float32) result = Plugin()._assume_constant_observation_frequency( - obs_count, default_fcst_counts, + obs_count, default_fcst_counts ) assert_array_equal(result.data, expected_result) @@ -352,7 +352,7 @@ def test_emcam_combine_undersampled_bins_monotonic(reliability_table_slice): ) expected_bin_coord_points = np.array([0.1, 0.3, 0.6, 0.9], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.2], [0.2, 0.4], [0.4, 0.8], [0.8, 1.0]], dtype=np.float32, + [[0.0, 0.2], [0.2, 0.4], [0.4, 0.8], [0.8, 1.0]], dtype=np.float32 ) reliability_table_slice.data = np.array( [ @@ -375,7 +375,7 @@ def test_emcam_combine_undersampled_bins_non_monotonic(reliability_table_slice): expected_data = np.array([[1000, 425, 1000], [1000, 425, 1000], [2000, 600, 1000]]) expected_bin_coord_points = np.array([0.2, 0.6, 0.9], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.4], [0.4, 0.8], [0.8, 1.0]], dtype=np.float32, + [[0.0, 0.4], [0.4, 0.8], [0.8, 1.0]], dtype=np.float32 ) reliability_table_slice.data = np.array( [ @@ -401,7 +401,7 @@ def test_emcam_highest_bin_non_monotonic(reliability_table_slice): ) expected_bin_coord_points = np.array([0.1, 0.3, 0.5, 0.8], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.2], [0.2, 0.4], [0.4, 0.6], [0.6, 1.0]], dtype=np.float32, + [[0.0, 0.2], [0.2, 0.4], [0.4, 0.6], [0.6, 1.0]], dtype=np.float32 ) reliability_table_slice.data = np.array( [ @@ -425,7 +425,7 @@ def test_emcam_central_bin_non_monotonic(reliability_table_slice): ) expected_bin_coord_points = np.array([0.1, 0.4, 0.7, 0.9], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.2], [0.2, 0.6], [0.6, 0.8], [0.8, 1.0]], dtype=np.float32, + [[0.0, 0.2], [0.2, 0.6], [0.6, 0.8], [0.8, 1.0]], dtype=np.float32 ) reliability_table_slice.data = np.array( [ @@ -449,7 +449,7 @@ def test_emcam_upper_bins_non_monotonic(reliability_table_slice): ) expected_bin_coord_points = np.array([0.1, 0.3, 0.5, 0.8], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.2], [0.2, 0.4], [0.4, 0.6], [0.6, 1.0]], dtype=np.float32, + [[0.0, 0.2], [0.2, 0.4], [0.4, 0.6], [0.6, 1.0]], dtype=np.float32 ) reliability_table_slice.data = np.array( [ @@ -475,7 +475,7 @@ def test_emcam_lowest_bin_non_monotonic(reliability_table_slice): expected_bin_coord_points = np.array([0.2, 0.5, 0.7, 0.9], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.4], [0.4, 0.6], [0.6, 0.8], [0.8, 1.0]], dtype=np.float32, + [[0.0, 0.4], [0.4, 0.6], [0.6, 0.8], [0.8, 1.0]], dtype=np.float32 ) reliability_table_slice.data = np.array( @@ -527,7 +527,7 @@ def test_process_undersampled_non_monotonic_point(create_rel_tables_point): expected_data = np.array([[1000, 425, 1000], [1000, 425, 1000], [2000, 600, 1000]]) expected_bin_coord_points = np.array([0.2, 0.6, 0.9], dtype=np.float32) expected_bin_coord_bounds = np.array( - [[0.0, 0.4], [0.4, 0.8], [0.8, 1.0]], dtype=np.float32, + [[0.0, 0.4], [0.4, 0.8], [0.8, 1.0]], dtype=np.float32 ) rel_table = create_rel_tables_point.table rel_table.data[create_rel_tables_point.indices0] = np.array( diff --git a/improver_tests/calibration/simple_bias_correction/test_ApplyBiasCorrection.py b/improver_tests/calibration/simple_bias_correction/test_ApplyBiasCorrection.py index b807dcfdc2..654e24a7cf 100644 --- a/improver_tests/calibration/simple_bias_correction/test_ApplyBiasCorrection.py +++ b/improver_tests/calibration/simple_bias_correction/test_ApplyBiasCorrection.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. from datetime import datetime, timedelta @@ -208,9 +208,7 @@ def test_inconsistent_bias_forecast_inputs(forecast_cube, num_bias_inputs): single_frt_with_bounds=True, ) with pytest.raises(ValueError, match="valid-hour differ"): - ApplyBiasCorrection()._check_forecast_bias_consistent( - forecast_cube, bias_cubes, - ) + ApplyBiasCorrection()._check_forecast_bias_consistent(forecast_cube, bias_cubes) # Case 2: The bias data defined with a mix of forecast_reference_time valid-hours bias_cubes = generate_bias_cubelist( num_bias_inputs, last_valid_time=VALID_TIME, single_frt_with_bounds=False @@ -223,9 +221,7 @@ def test_inconsistent_bias_forecast_inputs(forecast_cube, num_bias_inputs): ) ) with pytest.raises(ValueError, match="Multiple forecast_reference_time valid-hour"): - ApplyBiasCorrection()._check_forecast_bias_consistent( - forecast_cube, bias_cubes, - ) + ApplyBiasCorrection()._check_forecast_bias_consistent(forecast_cube, bias_cubes) # Case 3: The bias data defined for different forecast_period relative to forecast bias_cubes = generate_bias_cubelist( num_bias_inputs, last_valid_time=VALID_TIME, single_frt_with_bounds=True @@ -235,9 +231,7 @@ def test_inconsistent_bias_forecast_inputs(forecast_cube, num_bias_inputs): "forecast_period" ).points + (3 * 3600) with pytest.raises(ValueError, match="Forecast period differ"): - ApplyBiasCorrection()._check_forecast_bias_consistent( - forecast_cube, bias_cubes, - ) + ApplyBiasCorrection()._check_forecast_bias_consistent(forecast_cube, bias_cubes) # Case 4: The bias data defined with a mix of forecast-period values bias_cubes = generate_bias_cubelist( num_bias_inputs, last_valid_time=VALID_TIME, single_frt_with_bounds=False @@ -245,14 +239,12 @@ def test_inconsistent_bias_forecast_inputs(forecast_cube, num_bias_inputs): bias_cube_w_different_fp = generate_bias_cubelist( 1, last_valid_time=VALID_TIME - timedelta(days=6), single_frt_with_bounds=False )[0] - bias_cube_w_different_fp.coord( - "forecast_period" - ).points = bias_cube_w_different_fp.coord("forecast_period").points + (3 * 3600) + bias_cube_w_different_fp.coord("forecast_period").points = ( + bias_cube_w_different_fp.coord("forecast_period").points + (3 * 3600) + ) bias_cubes.append(bias_cube_w_different_fp) with pytest.raises(ValueError, match="Multiple forecast period"): - ApplyBiasCorrection()._check_forecast_bias_consistent( - forecast_cube, bias_cubes, - ) + ApplyBiasCorrection()._check_forecast_bias_consistent(forecast_cube, bias_cubes) @pytest.mark.parametrize("num_bias_inputs", (1, 30)) @@ -352,9 +344,7 @@ def test_missing_fcst_file(): a ValueError. """ bias_cubes = generate_bias_cubelist( - 3, - last_valid_time=VALID_TIME + timedelta(hours=3), - single_frt_with_bounds=False, + 3, last_valid_time=VALID_TIME + timedelta(hours=3), single_frt_with_bounds=False ) with pytest.raises(ValueError, match="No forecast"): @@ -367,9 +357,7 @@ def test_multiple_fcst_files(forecast_cube): ValueError. """ bias_cubes = generate_bias_cubelist( - 3, - last_valid_time=VALID_TIME + timedelta(hours=3), - single_frt_with_bounds=False, + 3, last_valid_time=VALID_TIME + timedelta(hours=3), single_frt_with_bounds=False ) with pytest.raises(ValueError, match="Multiple forecast"): diff --git a/improver_tests/calibration/simple_bias_correction/test_CalculateForecastBias.py b/improver_tests/calibration/simple_bias_correction/test_CalculateForecastBias.py index cce13a7112..cf081ab67a 100644 --- a/improver_tests/calibration/simple_bias_correction/test_CalculateForecastBias.py +++ b/improver_tests/calibration/simple_bias_correction/test_CalculateForecastBias.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. from datetime import datetime, timedelta diff --git a/improver_tests/calibration/test_init.py b/improver_tests/calibration/test_init.py index 0b306b229e..82747bdbde 100644 --- a/improver_tests/calibration/test_init.py +++ b/improver_tests/calibration/test_init.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for calibration.__init__""" @@ -28,7 +28,6 @@ class Test_split_forecasts_and_truth(unittest.TestCase): - """Test the split_forecasts_and_truth method.""" def setUp(self): @@ -213,7 +212,6 @@ def test_exception_for_missing_forecast_inputs(self): class Test_split_forecasts_and_coeffs(ImproverTest): - """Test the split_forecasts_and_coeffs function.""" def setUp(self): @@ -298,15 +296,11 @@ def setUp(self): def test_realization_forecast_and_coefficients(self): """Test a realization forecast input.""" - ( - forecast, - coeffs, - additional_predictors, - land_sea_mask, - template, - ) = split_forecasts_and_coeffs( - CubeList([self.realization_forecast, self.coefficient_cubelist]), - self.land_sea_mask_name, + (forecast, coeffs, additional_predictors, land_sea_mask, template) = ( + split_forecasts_and_coeffs( + CubeList([self.realization_forecast, self.coefficient_cubelist]), + self.land_sea_mask_name, + ) ) self.assertCubeEqual(forecast, self.realization_forecast[0]) @@ -317,15 +311,11 @@ def test_realization_forecast_and_coefficients(self): def test_percentile_forecast_and_coefficients(self): """Test a percentile forecast input.""" - ( - forecast, - coeffs, - additional_predictors, - land_sea_mask, - template, - ) = split_forecasts_and_coeffs( - CubeList([self.percentile_forecast, self.coefficient_cubelist]), - self.land_sea_mask_name, + (forecast, coeffs, additional_predictors, land_sea_mask, template) = ( + split_forecasts_and_coeffs( + CubeList([self.percentile_forecast, self.coefficient_cubelist]), + self.land_sea_mask_name, + ) ) self.assertCubeEqual(forecast, self.percentile_forecast[0]) self.assertCubeListEqual(coeffs, self.coefficient_cubelist) @@ -335,15 +325,11 @@ def test_percentile_forecast_and_coefficients(self): def test_probability_forecast_and_coefficients(self): """Test a probability forecast input.""" - ( - forecast, - coeffs, - additional_predictors, - land_sea_mask, - template, - ) = split_forecasts_and_coeffs( - CubeList([self.probability_forecast, self.coefficient_cubelist]), - self.land_sea_mask_name, + (forecast, coeffs, additional_predictors, land_sea_mask, template) = ( + split_forecasts_and_coeffs( + CubeList([self.probability_forecast, self.coefficient_cubelist]), + self.land_sea_mask_name, + ) ) self.assertCubeEqual(forecast, self.probability_forecast[0]) self.assertCubeListEqual(coeffs, self.coefficient_cubelist) @@ -353,21 +339,17 @@ def test_probability_forecast_and_coefficients(self): def test_forecast_coefficients_additional_predictor(self): """Test the addition of a static additional predictor.""" - ( - forecast, - coeffs, - additional_predictors, - land_sea_mask, - template, - ) = split_forecasts_and_coeffs( - CubeList( - [ - self.realization_forecast, - self.coefficient_cubelist, - self.additional_predictors, - ] - ), - self.land_sea_mask_name, + (forecast, coeffs, additional_predictors, land_sea_mask, template) = ( + split_forecasts_and_coeffs( + CubeList( + [ + self.realization_forecast, + self.coefficient_cubelist, + self.additional_predictors, + ] + ), + self.land_sea_mask_name, + ) ) self.assertCubeEqual(forecast, self.realization_forecast[0]) self.assertCubeListEqual(coeffs, self.coefficient_cubelist) @@ -377,21 +359,17 @@ def test_forecast_coefficients_additional_predictor(self): def test_forecast_coefficients_and_land_sea_mask(self): """Test the addition of a land-sea mask.""" - ( - forecast, - coeffs, - additional_predictors, - land_sea_mask, - template, - ) = split_forecasts_and_coeffs( - CubeList( - [ - self.realization_forecast, - self.coefficient_cubelist, - self.land_sea_mask, - ] - ), - self.land_sea_mask_name, + (forecast, coeffs, additional_predictors, land_sea_mask, template) = ( + split_forecasts_and_coeffs( + CubeList( + [ + self.realization_forecast, + self.coefficient_cubelist, + self.land_sea_mask, + ] + ), + self.land_sea_mask_name, + ) ) self.assertCubeEqual(forecast, self.realization_forecast[0]) @@ -402,14 +380,10 @@ def test_forecast_coefficients_and_land_sea_mask(self): def test_no_land_sea_mask_name(self): """Test when not providing the land_sea_mask_name option.""" - ( - forecast, - coeffs, - additional_predictors, - land_sea_mask, - template, - ) = split_forecasts_and_coeffs( - CubeList([self.realization_forecast, self.coefficient_cubelist]), + (forecast, coeffs, additional_predictors, land_sea_mask, template) = ( + split_forecasts_and_coeffs( + CubeList([self.realization_forecast, self.coefficient_cubelist]) + ) ) self.assertCubeEqual(forecast, self.realization_forecast[0]) @@ -420,21 +394,17 @@ def test_no_land_sea_mask_name(self): def test_forecast_coefficients_prob_template(self): """Test the addition of a probability template cube.""" - ( - forecast, - coeffs, - additional_predictors, - land_sea_mask, - template, - ) = split_forecasts_and_coeffs( - CubeList( - [ - self.realization_forecast, - self.coefficient_cubelist, - self.probability_forecast, - ] - ), - self.land_sea_mask_name, + (forecast, coeffs, additional_predictors, land_sea_mask, template) = ( + split_forecasts_and_coeffs( + CubeList( + [ + self.realization_forecast, + self.coefficient_cubelist, + self.probability_forecast, + ] + ), + self.land_sea_mask_name, + ) ) self.assertCubeEqual(forecast, self.realization_forecast[0]) self.assertCubeListEqual(coeffs, self.coefficient_cubelist) @@ -445,23 +415,19 @@ def test_forecast_coefficients_prob_template(self): def test_all_options(self): """Test providing a forecast, coefficients, additional predictor, land-sea mask and a probability template.""" - ( - forecast, - coeffs, - additional_predictors, - land_sea_mask, - template, - ) = split_forecasts_and_coeffs( - CubeList( - [ - self.realization_forecast, - self.coefficient_cubelist, - self.additional_predictors, - self.land_sea_mask, - self.probability_forecast, - ] - ), - self.land_sea_mask_name, + (forecast, coeffs, additional_predictors, land_sea_mask, template) = ( + split_forecasts_and_coeffs( + CubeList( + [ + self.realization_forecast, + self.coefficient_cubelist, + self.additional_predictors, + self.land_sea_mask, + self.probability_forecast, + ] + ), + self.land_sea_mask_name, + ) ) self.assertCubeEqual(forecast, self.realization_forecast[0]) self.assertCubeListEqual(coeffs, self.coefficient_cubelist) @@ -610,9 +576,7 @@ def test_matching_validity_times(time, validity_times, expected): assert result is expected -@pytest.mark.parametrize( - "comment", [(None), ("Example comment")], -) +@pytest.mark.parametrize("comment", [(None), ("Example comment")]) def test_add_warning_to_comment(comment): """Test the addition of a warning comment if calibration has been attempted but not applied successfully.""" diff --git a/improver_tests/calibration/utilities/conftest.py b/improver_tests/calibration/utilities/conftest.py index 36c0a99a98..fc25b95b81 100644 --- a/improver_tests/calibration/utilities/conftest.py +++ b/improver_tests/calibration/utilities/conftest.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Fixtures for calibration utilities tests.""" diff --git a/improver_tests/calibration/utilities/test_utilities.py b/improver_tests/calibration/utilities/test_utilities.py index deeb981c8b..8b3f42f11c 100644 --- a/improver_tests/calibration/utilities/test_utilities.py +++ b/improver_tests/calibration/utilities/test_utilities.py @@ -1,12 +1,13 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the utilities within the `calibration.utilities` module. """ + import datetime import unittest @@ -43,7 +44,6 @@ class Test_convert_cube_data_to_2d(IrisTest): - """Test the convert_cube_data_to_2d utility.""" def setUp(self): @@ -120,7 +120,6 @@ def test_5d_cube(self): class Test_flatten_ignoring_masked_data(IrisTest): - """Test the flatten_ignoring_masked_data utility.""" def setUp(self): @@ -204,7 +203,7 @@ def test_1D_input(self): def test_4D_input_not_masked_preserve_leading_dim(self): """Test input array is unchanged when input in 4D. - This should give the same answer as the corresponding 3D array.""" + This should give the same answer as the corresponding 3D array.""" data_array = self.data_array.reshape((3, 2, 2, 2)) result = flatten_ignoring_masked_data( data_array, preserve_leading_dimension=True @@ -230,7 +229,6 @@ def test_inconsistent_mask_along_leading_dim(self): class Test_check_predictor(unittest.TestCase): - """ Test to check the predictor. """ @@ -399,7 +397,7 @@ def test_duplicate_truths(self): # Add multi-dimensional time coordinate. time_coord = AuxCoord( - np.array(np.reshape(time_points, (2, 2)), dtype=TIME_COORDS["time"].dtype,), + np.array(np.reshape(time_points, (2, 2)), dtype=TIME_COORDS["time"].dtype), "time", units=TIME_COORDS["time"].units, ) @@ -504,7 +502,6 @@ def test_create_unified_frt_input_with_bounds(reliability_cube, different_frt): class Test_merge_land_and_sea(IrisTest): - """Test merge_land_and_sea""" def setUp(self): @@ -589,9 +586,8 @@ def test_input_not_masked(self): class Test_forecast_coords_match(IrisTest): - """Test for function that tests if forecast period and the hour of the - forecast_reference_time coordinate match between two cubes.""" + forecast_reference_time coordinate match between two cubes.""" def setUp(self): """Set-up testing.""" @@ -653,7 +649,6 @@ def test_frt_hour_mismatch(self): class Test_get_frt_hours(IrisTest): - """Test the get_frt_hours function.""" def test_single_value(self): @@ -682,7 +677,6 @@ def test_multiple_values(self): class Test_check_forecast_consistency(IrisTest): - """Test the check_forecast_consistency function.""" def setUp(self): @@ -742,7 +736,6 @@ def test_mismatching_forecast_periods(self): class Test_broadcast_data_to_time_coord(IrisTest): - """Test the broadcast_data_to_time_coord function.""" def setUp(self): diff --git a/improver_tests/categorical/decision_tree/__init__.py b/improver_tests/categorical/decision_tree/__init__.py index 2e51ae9013..008df493a1 100644 --- a/improver_tests/categorical/decision_tree/__init__.py +++ b/improver_tests/categorical/decision_tree/__init__.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Utilities for Unit tests for ApplyDecisionTree""" diff --git a/improver_tests/categorical/decision_tree/test_ApplyDecisionTree.py b/improver_tests/categorical/decision_tree/test_ApplyDecisionTree.py index fd401468b2..99bff79ed4 100644 --- a/improver_tests/categorical/decision_tree/test_ApplyDecisionTree.py +++ b/improver_tests/categorical/decision_tree/test_ApplyDecisionTree.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for ApplyDecisionTree class.""" @@ -163,7 +163,6 @@ def test_deterministic_complex_diagnostic_fields(precip_cube, hail_cube): class Test_WXCode(IrisTest): - """Test class for the WX code tests, setting up inputs.""" def setUp(self): @@ -336,7 +335,7 @@ def setUp(self): thresholds = np.array([1.0], dtype=np.float32) data_shower_condition = np.array( - [[[0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0]]], dtype=np.float32, + [[[0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0]]], dtype=np.float32 ) blend_time = next(blend_times) shower_condition = set_up_probability_cube( @@ -406,7 +405,6 @@ def assertArrayAndMaskEqual(self, array_a, array_b, **kwargs): class Test__repr__(IrisTest): - """Test the repr method.""" def test_basic(self): @@ -417,7 +415,6 @@ def test_basic(self): class Test_prepare_input_cubes(Test_WXCode): - """Test the prepare_input_cubes method.""" def test_basic(self): @@ -495,7 +492,6 @@ def test_returns_used_cubes(self): class Test_invert_condition(IrisTest): - """Test the invert condition method.""" def test_basic(self): @@ -546,7 +542,7 @@ class Test_create_condition_chain(Test_WXCode): """Test the create_condition_chain method.""" def setUp(self): - """ Set up queries for testing""" + """Set up queries for testing""" super().setUp() self.dummy_queries = { "significant_precipitation": { @@ -670,9 +666,7 @@ def test_old_naming_convention(self): def test_complex_condition(self): """Test with a condition that uses an operator""" - query = { - "rain_or_snow": self.dummy_queries["significant_precipitation"], - } + query = {"rain_or_snow": self.dummy_queries["significant_precipitation"]} query["rain_or_snow"]["diagnostic_fields"] = [ [ "probability_of_lwe_sleetfall_rate_above_threshold", @@ -775,7 +769,6 @@ def test_complex_condition(self): class Test_construct_extract_constraint(Test_WXCode): - """Test the construct_extract_constraint method .""" def test_basic(self): @@ -842,7 +835,7 @@ def test_basic(self): iris.Constraint( name="probability_of_lwe_sleetfall_rate_above_threshold", lwe_sleetfall_rate=lambda cell: np.isclose( - cell.point, t.points[0], rtol=self.plugin.float_tolerance, atol=0, + cell.point, t.points[0], rtol=self.plugin.float_tolerance, atol=0 ), ), "-", @@ -851,7 +844,7 @@ def test_basic(self): iris.Constraint( name="probability_of_rainfall_rate_above_threshold", rainfall_rate=lambda cell: np.isclose( - cell.point, t.points[0], rtol=self.plugin.float_tolerance, atol=0, + cell.point, t.points[0], rtol=self.plugin.float_tolerance, atol=0 ), ), ] @@ -872,7 +865,7 @@ def test_sub_expresssions(self): iris.Constraint( name="probability_of_lwe_sleetfall_rate_above_threshold", lwe_sleetfall_rate=lambda cell: np.isclose( - cell.point, t.points[0], rtol=self.plugin.float_tolerance, atol=0, + cell.point, t.points[0], rtol=self.plugin.float_tolerance, atol=0 ), ), "+", @@ -1160,7 +1153,6 @@ def test_blank_condition(self): class Test_remove_optional_missing(IrisTest): - """Test the rewriting of the decision tree on-the-fly to take into account allowed missing diagnostics.""" @@ -1251,11 +1243,10 @@ def test_nonsequential_missing_nodes(self): class Test_find_all_routes(IrisTest): - """Test the find_all_routes method .""" def setUp(self): - """ Setup testing graph """ + """Setup testing graph""" self.test_graph = { "start_node": ["success_1", "fail_0"], "success_1": ["success_1_1", "fail_1_0"], @@ -1398,7 +1389,6 @@ def test_no_period_diagnostics(self): class Test_create_categorical_cube(IrisTest): - """Test the create_categorical_cube method .""" def setUp(self): @@ -1418,9 +1408,9 @@ def setUp(self): blend_time=dt(2017, 11, 9, 1, 0), ) cube.attributes["mosg__model_configuration"] = "uk_det uk_ens" - cube.attributes[ - "mosg__model_run" - ] = "uk_det:20171109T2300Z:0.500\nuk_ens:20171109T2100Z:0.500" + cube.attributes["mosg__model_run"] = ( + "uk_det:20171109T2300Z:0.500\nuk_ens:20171109T2100Z:0.500" + ) self.cube = cube self.plugin = ApplyDecisionTree(decision_tree=wxcode_decision_tree()) @@ -1502,9 +1492,9 @@ def test_bounds_preserved_if_present(self): self.cube.coord("forecast_period").points[0], ] - self.cube.coord("time").bounds = np.array(expected_time, dtype=np.int64,) + self.cube.coord("time").bounds = np.array(expected_time, dtype=np.int64) self.cube.coord("forecast_period").bounds = np.array( - expected_fp, dtype=np.int32, + expected_fp, dtype=np.int32 ) self.plugin.template_cube = self.cube result = self.plugin.create_categorical_cube([self.cube]) @@ -1547,12 +1537,10 @@ def test_reference_time_multiple_inputs(self): for coord_name in ["blend_time", "forecast_reference_time"]: self.assertEqual( - result.coord(coord_name).cell(0).point, dt(2017, 11, 9, 2, 0), + result.coord(coord_name).cell(0).point, dt(2017, 11, 9, 2, 0) ) self.assertEqual(len(result.coord(coord_name).points), 1) - self.assertEqual( - result.coord("forecast_period").points[0], 26 * 3600, - ) + self.assertEqual(result.coord("forecast_period").points[0], 26 * 3600) self.assertEqual(len(result.coord("forecast_period").points), 1) def test_error_blend_and_frt_inputs(self): @@ -1598,11 +1586,10 @@ def test_error_on_unexpected_comparison(self): class Test_process(Test_WXCode): - """Test the find_all_routes method .""" def setUp(self): - """ Set up wxcubes for testing. """ + """Set up wxcubes for testing.""" super().setUp() self.expected_wxcode = np.array([[1, 29, 5], [6, 7, 8], [10, 11, 12]]) self.expected_wxcode_night = np.array([[0, 28, 5], [6, 7, 8], [9, 11, 12]]) @@ -1614,8 +1601,7 @@ def setUp(self): ) def test_basic(self): - """Test process returns a weather code cube with right values and type. - """ + """Test process returns a weather code cube with right values and type.""" result = self.plugin.process(self.cubes) self.assertIsInstance(result, iris.cube.Cube) self.assertArrayAndMaskEqual(result.data, self.expected_wxcode) @@ -1646,7 +1632,7 @@ def test_no_lightning(self): self.assertArrayAndMaskEqual(result.data, self.expected_wxcode_no_lightning) def test_lightning(self): - """Test process returns right values if all lightning. """ + """Test process returns right values if all lightning.""" data_lightning = np.ones((3, 3)) cubes = self.cubes cubes[9].data = data_lightning @@ -1724,7 +1710,7 @@ def test_weather_data(self): dtype=np.float32, ) data_shower_condition = np.array( - [[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]], dtype=np.float32, + [[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]], dtype=np.float32 ) data_cld_low = np.zeros((3, 3)) diff --git a/improver_tests/categorical/modal_code/test_ModalCategory.py b/improver_tests/categorical/modal_code/test_ModalCategory.py index 8a83c259ed..7839346513 100644 --- a/improver_tests/categorical/modal_code/test_ModalCategory.py +++ b/improver_tests/categorical/modal_code/test_ModalCategory.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for ModalCategory class.""" @@ -187,13 +187,9 @@ def test_metadata(wxcode_series): def as_utc_timestamp(time): return timegm(time.utctimetuple()) - ( - interval, - model_id_attr, - record_run_attr, - offset_reference_times, - wxcode_cubes, - ) = wxcode_series + (interval, model_id_attr, record_run_attr, offset_reference_times, wxcode_cubes) = ( + wxcode_series + ) kwargs = {} if model_id_attr: diff --git a/improver_tests/categorical/test_utilities.py b/improver_tests/categorical/test_utilities.py index ed13efb6d3..48094fc708 100644 --- a/improver_tests/categorical/test_utilities.py +++ b/improver_tests/categorical/test_utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for weather code utilities.""" @@ -79,20 +79,20 @@ def test_update_tree_thresholds_exception(): class Test_categorical_attributes(IrisTest): - """ Test categorical_attributes is working correctly """ + """Test categorical_attributes is working correctly""" def setUp(self): - """Set up cube """ + """Set up cube""" data = np.array( [0, 1, 5, 11, 20, 5, 9, 10, 4, 2, 0, 1, 29, 30, 1, 5, 6, 6], dtype=np.int32 ).reshape((2, 3, 3)) - cube = set_up_variable_cube(data, name="weather_code", units="1",) + cube = set_up_variable_cube(data, name="weather_code", units="1") date_times = [ datetime.datetime(2017, 11, 19, 0, 30), datetime.datetime(2017, 11, 19, 1, 30), ] self.cube = add_coordinate( - cube, date_times, "time", is_datetime=True, order=[1, 0, 2, 3], + cube, date_times, "time", is_datetime=True, order=[1, 0, 2, 3] ) self.decision_tree = wxcode_decision_tree() wxmeanings = [ @@ -161,10 +161,10 @@ def test_metadata_saves(self): class Test_expand_nested_lists(IrisTest): - """ Test expand_nested_lists is working correctly """ + """Test expand_nested_lists is working correctly""" def setUp(self): - """ Set up dictionary for testing """ + """Set up dictionary for testing""" self.dictionary = { "list": ["a", "a"], "list_of_lists": [["a", "a"], ["a", "a"]], @@ -272,7 +272,7 @@ def test_wxcode_updated(self): self.assertEqual(result.shape, (16, 16)) def test_wxcode_time_different_seconds(self): - """ Test code works if time coordinate has a difference in the number + """Test code works if time coordinate has a difference in the number of seconds, which should round to the same time in hours and minutes. This was raised by changes to cftime which altered its precision.""" cube = set_up_wxcube(time=datetime.datetime(2018, 9, 12, 5, 42, 59)) @@ -303,7 +303,7 @@ def test_wxcode_time_different_seconds(self): self.assertEqual(result.data.shape, (16, 16)) def test_wxcode_time_as_array(self): - """ Test code works if time is an array of dimension > 1 """ + """Test code works if time is an array of dimension > 1""" time_points = [ datetime.datetime(2018, 9, 12, 5), datetime.datetime(2018, 9, 12, 6), @@ -360,18 +360,18 @@ def test_wxcode_updated_on_latlon(self): def test_interrogate_decision_tree(): """Test that the function returns the right strings.""" expected = ( - "\u26C5 probability_of_low_and_medium_type_cloud_area_fraction_above_threshold (1): 0.1875, 0.8125\n" # noqa: E501 - "\u26C5 probability_of_low_type_cloud_area_fraction_above_threshold (1): 0.85\n" - "\u26C5 probability_of_lwe_graupel_and_hail_fall_rate_in_vicinity_above_threshold (mm hr-1): 0.0\n" # noqa: E501 - "\u26C5 probability_of_lwe_precipitation_rate_above_threshold (mm hr-1): 0.03, 1.0\n" # noqa: E501 - "\u26C5 probability_of_lwe_precipitation_rate_in_vicinity_above_threshold (mm hr-1): 0.1, 1.0\n" # noqa: E501 - "\u26C5 probability_of_lwe_precipitation_rate_max_above_threshold (mm hr-1): 1.0\n" # noqa: E501 - "\u26C5 probability_of_lwe_sleetfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" - "\u26C5 probability_of_lwe_snowfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" - "\u26C5 probability_of_number_of_lightning_flashes_per_unit_area_in_vicinity_above_threshold (m-2): 0.0\n" # noqa: E501 - "\u26C5 probability_of_rainfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" - "\u26C5 probability_of_shower_condition_above_threshold (1): 1.0\n" - "\u26C5 probability_of_visibility_in_air_below_threshold (m): 1000.0, 5000.0\n" + "\u26c5 probability_of_low_and_medium_type_cloud_area_fraction_above_threshold (1): 0.1875, 0.8125\n" # noqa: E501 + "\u26c5 probability_of_low_type_cloud_area_fraction_above_threshold (1): 0.85\n" + "\u26c5 probability_of_lwe_graupel_and_hail_fall_rate_in_vicinity_above_threshold (mm hr-1): 0.0\n" # noqa: E501 + "\u26c5 probability_of_lwe_precipitation_rate_above_threshold (mm hr-1): 0.03, 1.0\n" # noqa: E501 + "\u26c5 probability_of_lwe_precipitation_rate_in_vicinity_above_threshold (mm hr-1): 0.1, 1.0\n" # noqa: E501 + "\u26c5 probability_of_lwe_precipitation_rate_max_above_threshold (mm hr-1): 1.0\n" # noqa: E501 + "\u26c5 probability_of_lwe_sleetfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" + "\u26c5 probability_of_lwe_snowfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" + "\u26c5 probability_of_number_of_lightning_flashes_per_unit_area_in_vicinity_above_threshold (m-2): 0.0\n" # noqa: E501 + "\u26c5 probability_of_rainfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" + "\u26c5 probability_of_shower_condition_above_threshold (1): 1.0\n" + "\u26c5 probability_of_visibility_in_air_below_threshold (m): 1000.0, 5000.0\n" ) tree = update_tree_thresholds(wxcode_decision_tree(), None) result = interrogate_decision_tree(tree) @@ -381,19 +381,19 @@ def test_interrogate_decision_tree(): def test_interrogate_decision_tree_accumulation_1h(): """Test that the function returns the right strings.""" expected = ( - "\u26C5 probability_of_low_and_medium_type_cloud_area_fraction_above_threshold (1): 0.1875, 0.8125\n" # noqa: E501 - "\u26C5 probability_of_low_type_cloud_area_fraction_above_threshold (1): 0.85\n" - "\u26C5 probability_of_lwe_graupel_and_hail_fall_rate_in_vicinity_above_threshold (mm hr-1): 0.0\n" # noqa: E501 - "\u26C5 probability_of_lwe_precipitation_rate_above_threshold (mm hr-1): 0.03\n" # noqa: E501 - "\u26C5 probability_of_lwe_precipitation_rate_in_vicinity_above_threshold (mm hr-1): 0.1, 1.0\n" # noqa: E501 - "\u26C5 probability_of_lwe_precipitation_rate_max_above_threshold (mm hr-1): 1.0\n" # noqa: E501 - "\u26C5 probability_of_lwe_sleetfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" - "\u26C5 probability_of_lwe_snowfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" - "\u26C5 probability_of_lwe_thickness_of_precipitation_amount_above_threshold (mm): 1.0\n" # noqa: E501 - "\u26C5 probability_of_number_of_lightning_flashes_per_unit_area_in_vicinity_above_threshold (m-2): 0.0\n" # noqa: E501 - "\u26C5 probability_of_rainfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" - "\u26C5 probability_of_shower_condition_above_threshold (1): 1.0\n" - "\u26C5 probability_of_visibility_in_air_below_threshold (m): 1000.0, 5000.0\n" + "\u26c5 probability_of_low_and_medium_type_cloud_area_fraction_above_threshold (1): 0.1875, 0.8125\n" # noqa: E501 + "\u26c5 probability_of_low_type_cloud_area_fraction_above_threshold (1): 0.85\n" + "\u26c5 probability_of_lwe_graupel_and_hail_fall_rate_in_vicinity_above_threshold (mm hr-1): 0.0\n" # noqa: E501 + "\u26c5 probability_of_lwe_precipitation_rate_above_threshold (mm hr-1): 0.03\n" # noqa: E501 + "\u26c5 probability_of_lwe_precipitation_rate_in_vicinity_above_threshold (mm hr-1): 0.1, 1.0\n" # noqa: E501 + "\u26c5 probability_of_lwe_precipitation_rate_max_above_threshold (mm hr-1): 1.0\n" # noqa: E501 + "\u26c5 probability_of_lwe_sleetfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" + "\u26c5 probability_of_lwe_snowfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" + "\u26c5 probability_of_lwe_thickness_of_precipitation_amount_above_threshold (mm): 1.0\n" # noqa: E501 + "\u26c5 probability_of_number_of_lightning_flashes_per_unit_area_in_vicinity_above_threshold (m-2): 0.0\n" # noqa: E501 + "\u26c5 probability_of_rainfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" + "\u26c5 probability_of_shower_condition_above_threshold (1): 1.0\n" + "\u26c5 probability_of_visibility_in_air_below_threshold (m): 1000.0, 5000.0\n" ) tree = update_tree_thresholds(wxcode_decision_tree(accumulation=True), 3600) result = interrogate_decision_tree(tree) @@ -403,19 +403,19 @@ def test_interrogate_decision_tree_accumulation_1h(): def test_interrogate_decision_tree_accumulation_3h(): """Test that the function returns the right strings.""" expected = ( - "\u26C5 probability_of_low_and_medium_type_cloud_area_fraction_above_threshold (1): 0.1875, 0.8125\n" # noqa: E501 - "\u26C5 probability_of_low_type_cloud_area_fraction_above_threshold (1): 0.85\n" - "\u26C5 probability_of_lwe_graupel_and_hail_fall_rate_in_vicinity_above_threshold (mm hr-1): 0.0\n" # noqa: E501 - "\u26C5 probability_of_lwe_precipitation_rate_above_threshold (mm hr-1): 0.03\n" # noqa: E501 - "\u26C5 probability_of_lwe_precipitation_rate_in_vicinity_above_threshold (mm hr-1): 0.1, 1.0\n" # noqa: E501 - "\u26C5 probability_of_lwe_precipitation_rate_max_above_threshold (mm hr-1): 1.0\n" # noqa: E501 - "\u26C5 probability_of_lwe_sleetfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" - "\u26C5 probability_of_lwe_snowfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" - "\u26C5 probability_of_lwe_thickness_of_precipitation_amount_above_threshold (mm): 3.0\n" # noqa: E501 - "\u26C5 probability_of_number_of_lightning_flashes_per_unit_area_in_vicinity_above_threshold (m-2): 0.0\n" # noqa: E501 - "\u26C5 probability_of_rainfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" - "\u26C5 probability_of_shower_condition_above_threshold (1): 1.0\n" - "\u26C5 probability_of_visibility_in_air_below_threshold (m): 1000.0, 5000.0\n" + "\u26c5 probability_of_low_and_medium_type_cloud_area_fraction_above_threshold (1): 0.1875, 0.8125\n" # noqa: E501 + "\u26c5 probability_of_low_type_cloud_area_fraction_above_threshold (1): 0.85\n" + "\u26c5 probability_of_lwe_graupel_and_hail_fall_rate_in_vicinity_above_threshold (mm hr-1): 0.0\n" # noqa: E501 + "\u26c5 probability_of_lwe_precipitation_rate_above_threshold (mm hr-1): 0.03\n" # noqa: E501 + "\u26c5 probability_of_lwe_precipitation_rate_in_vicinity_above_threshold (mm hr-1): 0.1, 1.0\n" # noqa: E501 + "\u26c5 probability_of_lwe_precipitation_rate_max_above_threshold (mm hr-1): 1.0\n" # noqa: E501 + "\u26c5 probability_of_lwe_sleetfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" + "\u26c5 probability_of_lwe_snowfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" + "\u26c5 probability_of_lwe_thickness_of_precipitation_amount_above_threshold (mm): 3.0\n" # noqa: E501 + "\u26c5 probability_of_number_of_lightning_flashes_per_unit_area_in_vicinity_above_threshold (m-2): 0.0\n" # noqa: E501 + "\u26c5 probability_of_rainfall_rate_above_threshold (mm hr-1): 0.03, 1.0\n" + "\u26c5 probability_of_shower_condition_above_threshold (1): 1.0\n" + "\u26c5 probability_of_visibility_in_air_below_threshold (m): 1000.0, 5000.0\n" ) tree = update_tree_thresholds(wxcode_decision_tree(accumulation=True), 10800) result = interrogate_decision_tree(tree) @@ -425,8 +425,8 @@ def test_interrogate_decision_tree_accumulation_3h(): def test_interrogate_decision_tree_deterministic(): """Test that the function returns the right strings.""" expected = ( - "\u26C5 hail_rate (deterministic)\n" - "\u26C5 precipitation_rate (deterministic)\n" + "\u26c5 hail_rate (deterministic)\n" + "\u26c5 precipitation_rate (deterministic)\n" ) tree = deterministic_diagnostic_tree() result = interrogate_decision_tree(tree) @@ -473,9 +473,9 @@ def modify_tree_fixture(node, key, value): @pytest.mark.parametrize( "node, key, value, expected", ( - ("meta", None, None, "Decision tree does not contain a mandatory meta key",), - ("meta", "name", None, "Meta node does not contain mandatory keys {'name'}",), - ("meta", "pets", "kittens", "Meta node contains unexpected keys {'pets'}",), + ("meta", None, None, "Decision tree does not contain a mandatory meta key"), + ("meta", "name", None, "Meta node does not contain mandatory keys {'name'}"), + ("meta", "pets", "kittens", "Meta node contains unexpected keys {'pets'}"), ( "lightning", "if_diagnostic_missing", @@ -518,7 +518,7 @@ def modify_tree_fixture(node, key, value): "should be 'above' or 'below'" ), ), - ("Thunder", "leaf", 10.2, "Leaf 'Thunder' has non-int target: 10.2",), + ("Thunder", "leaf", 10.2, "Leaf 'Thunder' has non-int target: 10.2"), ( "Clear_Night", "pets", @@ -537,7 +537,7 @@ def modify_tree_fixture(node, key, value): None, "Unreachable leaf 'Dust'. Add 'is_unreachable': True to suppress this issue.", ), - ("Mist", "group", None, "Leaf 'Fog' is in a group of 1 (visibility).",), + ("Mist", "group", None, "Leaf 'Fog' is in a group of 1 (visibility)."), ( "sleet_in_vicinity_cloud", "if_false", @@ -609,7 +609,7 @@ def modify_tree_fixture(node, key, value): "no_precipitation_cloud", "Unreachable node 'fog_conditions'", ), - ("lightning", "kittens", 0, "Node lightning contains unknown key 'kittens'",), + ("lightning", "kittens", 0, "Node lightning contains unknown key 'kittens'"), ( "sleet_in_vicinity_cloud", "if_false", @@ -631,7 +631,7 @@ def test_check_tree(modify_tree, expected): @pytest.mark.parametrize( "value, expected", ( - ("kittens", "Leaf 'Sunny_Day' does not point to a valid target (kittens).",), + ("kittens", "Leaf 'Sunny_Day' does not point to a valid target (kittens)."), ( "Partly_Cloudy_Day", "Night target 'Partly_Cloudy_Day' of leaf 'Sunny_Day' also has a night target.", @@ -653,7 +653,7 @@ def test_check_tree_if_night(modify_tree, expected): @pytest.mark.parametrize( "nodes, expected", ( - ({"Thunder": 28}, "These leaf categories are used more than once: [28]",), + ({"Thunder": 28}, "These leaf categories are used more than once: [28]"), ( {"Thunder": 28, "Thunder_Shower_Day": 28}, "These leaf categories are used more than once: [28]", diff --git a/improver_tests/cli/nowcast_accumulate/test_name_constraint.py b/improver_tests/cli/nowcast_accumulate/test_name_constraint.py index 09309e3bfd..5c83bee12a 100644 --- a/improver_tests/cli/nowcast_accumulate/test_name_constraint.py +++ b/improver_tests/cli/nowcast_accumulate/test_name_constraint.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Test nowcast_accumulate name_constraint function""" diff --git a/improver_tests/cli/test_init.py b/improver_tests/cli/test_init.py index cad7d9677d..33183e5475 100644 --- a/improver_tests/cli/test_init.py +++ b/improver_tests/cli/test_init.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for cli.__init__""" @@ -57,7 +57,6 @@ def wrapped_with_output(first): class Test_docutilize(unittest.TestCase): - """Test the docutilize function.""" def setUp(self): @@ -218,7 +217,7 @@ def test_with_output_no_compression(self, m): @patch("improver.utilities.save.save_netcdf") def test_with_output_with_least_significant_figure(self, m): - """Tests save_netcdf, compression-level=0 and least-significant-digit=2 """ + """Tests save_netcdf, compression-level=0 and least-significant-digit=2""" # pylint disable is needed as it can't see the wrappers output kwarg. result = wrapped_with_output.cli( "argv[0]", @@ -321,7 +320,7 @@ def test_list_two_diff_shapes(self): def test_list_no_match(self): """Tests that providing no valid constraints raises a ConstraintMismatchError.""" func = create_constrained_inputcubelist_converter( - "airspeed_velocity_of_unladen_swallow", + "airspeed_velocity_of_unladen_swallow" ) with self.assertRaisesRegex(ConstraintMismatchError, "^Got 0 cubes"): func(self.wind_cubes) @@ -329,7 +328,7 @@ def test_list_no_match(self): def test_two_valid_cubes(self): """Tests that providing 2 valid constraints raises a ConstraintMismatchError.""" func = create_constrained_inputcubelist_converter( - lambda cube: cube.name() in ["wind_speed", "wind_from_direction"], + lambda cube: cube.name() in ["wind_speed", "wind_from_direction"] ) with self.assertRaisesRegex(ConstraintMismatchError, "^Got 2 cubes"): func(self.wind_cubes) diff --git a/improver_tests/conftest.py b/improver_tests/conftest.py index 69f71cf763..4a58154e0a 100644 --- a/improver_tests/conftest.py +++ b/improver_tests/conftest.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Test wide setup and configuration""" diff --git a/improver_tests/cube_combiner/test_Combine.py b/improver_tests/cube_combiner/test_Combine.py index 6d390e1688..10b3c5738c 100644 --- a/improver_tests/cube_combiner/test_Combine.py +++ b/improver_tests/cube_combiner/test_Combine.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the cube_combiner.Combine plugin.""" + from datetime import datetime from unittest.mock import patch, sentinel @@ -89,9 +90,7 @@ def test_filtering_realizations(realization_cubes, short_realizations): @pytest.mark.parametrize("coordinate_name", ("realization", "percentile")) -def test_cubes_different_size( - realization_cubes, coordinate_name, -): +def test_cubes_different_size(realization_cubes, coordinate_name): """Checks Combine works with different broadcast coordinates.""" cubes = realization_cubes.merge_cube() cubes.data = np.full_like(cubes.data, 1) diff --git a/improver_tests/cube_combiner/test_CubeCombiner.py b/improver_tests/cube_combiner/test_CubeCombiner.py index baee8076f9..595dc65972 100644 --- a/improver_tests/cube_combiner/test_CubeCombiner.py +++ b/improver_tests/cube_combiner/test_CubeCombiner.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the cube_combiner.CubeCombiner plugin.""" + import unittest from copy import deepcopy from datetime import datetime @@ -25,7 +26,6 @@ class Test__init__(IrisTest): - """Test the __init__ method.""" def test_basic(self): @@ -44,7 +44,7 @@ class CombinerTest(ImproverTest): """Set up a common set of test cubes for subsequent test classes.""" def setUp(self): - """ Set up cubes for testing. """ + """Set up cubes for testing.""" data = np.full((1, 2, 2), 0.5, dtype=np.float32) self.cube1 = set_up_probability_cube( data, @@ -94,7 +94,7 @@ def setUp(self): "sum", coords="time", comments="of lwe_thickness_of_precipitation_amount", - ), + ) ] self.cube5.cell_methods = cell_methods @@ -144,7 +144,6 @@ def test_unmatched_coords_ignored(self): class Test_process(CombinerTest): - """Test the plugin combines the cubelist into a cube.""" def test_basic(self): @@ -172,7 +171,7 @@ def test_basic_with_Combine(self): self.assertCubeListEqual(input_copy, cubelist) def test_mean(self): - """Test that the plugin calculates the mean correctly. """ + """Test that the plugin calculates the mean correctly.""" plugin = CubeCombiner("mean") cubelist = iris.cube.CubeList([self.cube1, self.cube2]) result = plugin.process(cubelist, "new_cube_name") @@ -340,7 +339,7 @@ def test_broadcast_non_threshold_coord(self): frt=forecast_reference_time, ) orography = set_up_variable_cube( - np.full((3, 4), 80, dtype=np.float32), name="orography", units="m", + np.full((3, 4), 80, dtype=np.float32), name="orography", units="m" ) new_name = ( "cloud_base_height_assuming_only_consider_cloud_area_fraction_greater_" @@ -412,8 +411,8 @@ def test_multiply_preserves_bounds(self): time=validity_time, frt=forecast_reference_time, ) - result = CubeCombiner(operation="*",)( - [precip_accum, snow_prob], "lwe_thickness_of_snowfall_amount", + result = CubeCombiner(operation="*")( + [precip_accum, snow_prob], "lwe_thickness_of_snowfall_amount" ) self.assertArrayAlmostEqual(result.data, np.full((2, 3, 3), 0.3)) self.assertArrayEqual(result.coord("time"), precip_accum.coord("time")) @@ -448,7 +447,7 @@ def test_update_cell_methods_non_probabilistic(self): new_cube_name = "new_cube_name" expected = CellMethod("sum", coords="time", comments=f"of {new_cube_name}") - result = CubeCombiner(operation="*",)(cubelist, new_cube_name) + result = CubeCombiner(operation="*")(cubelist, new_cube_name) self.assertEqual(result.cell_methods[0], expected) def test_unmodified_cell_methods(self): @@ -481,7 +480,7 @@ def test_exception_mismatched_dimensions(self): """Test an error is raised if dimension coordinates do not match""" self.multiplier.coord("latitude").rename("projection_y_coordinate") new_cube_name = "new_cube_name" - plugin = CubeCombiner(operation="*",) + plugin = CubeCombiner(operation="*") msg = "Cannot combine cubes with different dimensions" with self.assertRaisesRegex(ValueError, msg): plugin.process([self.cube5.copy(), self.multiplier], new_cube_name) diff --git a/improver_tests/cube_combiner/test_MaxInTimeWindow.py b/improver_tests/cube_combiner/test_MaxInTimeWindow.py index 095eae7740..13561ed2d5 100644 --- a/improver_tests/cube_combiner/test_MaxInTimeWindow.py +++ b/improver_tests/cube_combiner/test_MaxInTimeWindow.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the cube_combiner.MaxInTimeWindow plugin.""" + from datetime import datetime, timedelta import numpy as np @@ -59,11 +60,9 @@ def setup_probability_cubes(period=3) -> CubeList: return cubes +@pytest.mark.parametrize("period", [(3), (1)]) @pytest.mark.parametrize( - "period", [(3), (1)], -) -@pytest.mark.parametrize( - "forecast_cubes", [(setup_realization_cubes), (setup_probability_cubes)], + "forecast_cubes", [(setup_realization_cubes), (setup_probability_cubes)] ) def test_basic(forecast_cubes, period): """Test for max in a time window.""" @@ -143,9 +142,7 @@ def test_bound_mismatch(): MaxInTimeWindow()(cubes) -@pytest.mark.parametrize( - "minimum_realizations", [(4), (5)], -) +@pytest.mark.parametrize("minimum_realizations", [(4), (5)]) def test_minimum_realizations(minimum_realizations): """Test the behaviour if the number of realizations is less than the minimum allowed.""" diff --git a/improver_tests/developer_tools/conftest.py b/improver_tests/developer_tools/conftest.py index 537691907b..f3435372a4 100644 --- a/improver_tests/developer_tools/conftest.py +++ b/improver_tests/developer_tools/conftest.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Set up fixtures for metadata interpreter tests""" @@ -165,7 +165,7 @@ def probability_over_time_in_vicinity_above_fixture(): ) cube.add_cell_method( iris.coords.CellMethod( - method="sum", coords="time", comments=(f"of {diagnostic_name}",), + method="sum", coords="time", comments=(f"of {diagnostic_name}",) ) ) for coord in ["time", "forecast_period"]: diff --git a/improver_tests/developer_tools/test_MOMetadataInterpreter.py b/improver_tests/developer_tools/test_MOMetadataInterpreter.py index bdf4764b80..b7e1b1cc51 100644 --- a/improver_tests/developer_tools/test_MOMetadataInterpreter.py +++ b/improver_tests/developer_tools/test_MOMetadataInterpreter.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the MOMetadataInterpreter plugin""" @@ -95,9 +95,9 @@ def test_probabilities_above(probability_above_cube, interpreter): def test_handles_duplicate_model_string(probability_above_cube, interpreter): """Test the interpreter can distinguish between the Global Model and the Global Grid in cube titles""" - probability_above_cube.attributes[ - "title" - ] = "UKV Model Forecast on Global 10 km Standard Grid" + probability_above_cube.attributes["title"] = ( + "UKV Model Forecast on Global 10 km Standard Grid" + ) interpreter.run(probability_above_cube) assert interpreter.model == "UKV" @@ -500,9 +500,9 @@ def test_error_missing_model_run_information( def test_error_unrecognised_model_in_blend(blended_probability_below_cube, interpreter): """Test error when a blended model ID attribute has an unknown value""" - blended_probability_below_cube.attributes[ - "mosg__model_configuration" - ] = "nc_ens uk_det" + blended_probability_below_cube.attributes["mosg__model_configuration"] = ( + "nc_ens uk_det" + ) with pytest.raises(ValueError, match="unrecognised model code"): interpreter.run(blended_probability_below_cube) @@ -510,9 +510,9 @@ def test_error_unrecognised_model_in_blend(blended_probability_below_cube, inter def test_error_blend_missing_from_title(blended_probability_below_cube, interpreter): """Test error raised if a blended cube title doesn't indicate a blend, but the model ID attribute contains multiple models""" - blended_probability_below_cube.attributes[ - "title" - ] = "IMPROVER Forecast on UK 2 km Standard Grid" + blended_probability_below_cube.attributes["title"] = ( + "IMPROVER Forecast on UK 2 km Standard Grid" + ) with pytest.raises(ValueError, match="is not a valid single model"): interpreter.run(blended_probability_below_cube) @@ -553,9 +553,9 @@ def test_error_inconsistent_spot_coords( def test_error_inconsistent_spot_title(blended_spot_median_cube, interpreter): """Test error raised if a spot cube has a non-spot title""" - blended_spot_median_cube.attributes[ - "title" - ] = "IMPROVER Post-Processed Multi-Model Blend on UK 2 km Standard Grid" + blended_spot_median_cube.attributes["title"] = ( + "IMPROVER Post-Processed Multi-Model Blend on UK 2 km Standard Grid" + ) with pytest.raises(ValueError, match="not consistent with spot data"): interpreter.run(blended_spot_median_cube) diff --git a/improver_tests/developer_tools/test_display_interpretation.py b/improver_tests/developer_tools/test_display_interpretation.py index d90efa92c1..9456a76535 100644 --- a/improver_tests/developer_tools/test_display_interpretation.py +++ b/improver_tests/developer_tools/test_display_interpretation.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the display_interpretation function""" diff --git a/improver_tests/ensemble_copula_coupling/ecc_test_data.py b/improver_tests/ensemble_copula_coupling/ecc_test_data.py index 286e5cd1bb..854e7da81d 100644 --- a/improver_tests/ensemble_copula_coupling/ecc_test_data.py +++ b/improver_tests/ensemble_copula_coupling/ecc_test_data.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module defining input data for ECC tests""" diff --git a/improver_tests/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py b/improver_tests/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py index 3e4c4b4372..62442e658b 100644 --- a/improver_tests/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py +++ b/improver_tests/ensemble_copula_coupling/test_ConvertLocationAndScaleParameters.py @@ -1,10 +1,11 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for ConvertLocationAndScaleParameters """ + import unittest import numpy as np @@ -18,7 +19,6 @@ class Test__init__(IrisTest): - """Test the __init__ method.""" def test_valid_distribution(self): @@ -47,7 +47,6 @@ def test_invalid_distribution(self): class Test__repr__(IrisTest): - """Test string representation of plugin.""" def test_basic(self): @@ -61,7 +60,6 @@ def test_basic(self): class Test__rescale_shape_parameters(IrisTest): - """Test the _rescale_shape_parameters""" def setUp(self): diff --git a/improver_tests/ensemble_copula_coupling/test_ConvertLocationAndScaleParametersToPercentiles.py b/improver_tests/ensemble_copula_coupling/test_ConvertLocationAndScaleParametersToPercentiles.py index 2f2b266a02..1c14cf584f 100644 --- a/improver_tests/ensemble_copula_coupling/test_ConvertLocationAndScaleParametersToPercentiles.py +++ b/improver_tests/ensemble_copula_coupling/test_ConvertLocationAndScaleParametersToPercentiles.py @@ -1,11 +1,12 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the `ensemble_copula_coupling.ConvertLocationAndScaleParametersToPercentiles` """ + import unittest import iris @@ -22,7 +23,6 @@ class Test__repr__(IrisTest): - """Test string representation of plugin.""" def test_basic(self): @@ -36,7 +36,6 @@ def test_basic(self): class Test__location_and_scale_parameters_to_percentiles(IrisTest): - """Test the _location_and_scale_parameters_to_percentiles plugin.""" def setUp(self): @@ -69,7 +68,7 @@ def setUp(self): "realization", iris.analysis.MEAN ) self.scale_parameter = self.temperature_cube.collapsed( - "realization", iris.analysis.STD_DEV, + "realization", iris.analysis.STD_DEV ) self.percentiles = [10, 50, 90] @@ -198,7 +197,7 @@ def test_simple_data_truncnorm_distribution(self): # Use an adjusted version of the ensemble standard deviation as a proxy for the # scale parameter for the truncated normal distribution. current_forecast_stddev = self.temperature_cube.collapsed( - "realization", iris.analysis.STD_DEV, + "realization", iris.analysis.STD_DEV ) current_forecast_stddev.data = current_forecast_stddev.data + 1 plugin = Plugin( @@ -376,7 +375,7 @@ def test_spot_forecasts_check_data(self): current_forecast_predictor = cube.collapsed("realization", iris.analysis.MEAN) current_forecast_stddev = cube.collapsed("realization", iris.analysis.STD_DEV) result = Plugin()._location_and_scale_parameters_to_percentiles( - current_forecast_predictor, current_forecast_stddev, cube, self.percentiles, + current_forecast_predictor, current_forecast_stddev, cube, self.percentiles ) self.assertIsInstance(result, Cube) np.testing.assert_allclose(result.data, data, rtol=1.0e-4) @@ -397,7 +396,6 @@ def test_scalar_realisation_percentile(self): class Test_process(IrisTest): - """Test the process plugin.""" def setUp(self): diff --git a/improver_tests/ensemble_copula_coupling/test_ConvertLocationAndScaleParametersToProbabilities.py b/improver_tests/ensemble_copula_coupling/test_ConvertLocationAndScaleParametersToProbabilities.py index 20e167572e..cffae3a622 100644 --- a/improver_tests/ensemble_copula_coupling/test_ConvertLocationAndScaleParametersToProbabilities.py +++ b/improver_tests/ensemble_copula_coupling/test_ConvertLocationAndScaleParametersToProbabilities.py @@ -1,10 +1,11 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for ConvertLocationAndScaleParametersToProbabilities """ + import unittest import iris @@ -21,7 +22,6 @@ class Test__repr__(IrisTest): - """Test string representation of plugin.""" def test_basic(self): @@ -35,7 +35,6 @@ def test_basic(self): class Test__check_template_cube(IrisTest): - """Test the _check_template_cube function.""" def setUp(self): @@ -80,7 +79,6 @@ def test_fail_with_missing_spatial_coordinate(self): class Test__check_unit_compatibility(IrisTest): - """Test the _check_unit_compatibility function.""" def setUp(self): @@ -125,7 +123,6 @@ def test_incompatible_units(self): class Test__location_and_scale_parameters_to_probabilities(IrisTest): - """Test the _location_and_scale_parameters_to_probabilities function.""" def setUp(self): @@ -243,7 +240,6 @@ def test_threshold_below_cube(self): class Test_process(IrisTest): - """Test the process function.""" def setUp(self): diff --git a/improver_tests/ensemble_copula_coupling/test_ConvertProbabilitiesToPercentiles.py b/improver_tests/ensemble_copula_coupling/test_ConvertProbabilitiesToPercentiles.py index 4a4377ddae..6225a72a16 100644 --- a/improver_tests/ensemble_copula_coupling/test_ConvertProbabilitiesToPercentiles.py +++ b/improver_tests/ensemble_copula_coupling/test_ConvertProbabilitiesToPercentiles.py @@ -1,11 +1,12 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the `ensemble_copula_coupling.ConvertProbabilitiesToPercentiles` class. """ + import unittest from datetime import datetime @@ -34,7 +35,6 @@ class Test__add_bounds_to_thresholds_and_probabilities(IrisTest): - """ Test the _add_bounds_to_thresholds_and_probabilities method of the ConvertProbabilitiesToPercentiles. @@ -137,7 +137,6 @@ def test_new_endpoints_generation(self): class Test__probabilities_to_percentiles(IrisTest): - """Test the _probabilities_to_percentiles method of the ConvertProbabilitiesToPercentiles plugin.""" @@ -488,7 +487,6 @@ def test_masked_data_above(self): class Test_process(IrisTest): - """ Test the process method of the ConvertProbabilitiesToPercentiles plugin. """ diff --git a/improver_tests/ensemble_copula_coupling/test_EnsembleReordering.py b/improver_tests/ensemble_copula_coupling/test_EnsembleReordering.py index 07967a813b..e9ef16daf2 100644 --- a/improver_tests/ensemble_copula_coupling/test_EnsembleReordering.py +++ b/improver_tests/ensemble_copula_coupling/test_EnsembleReordering.py @@ -1,12 +1,13 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the `ensemble_copula_coupling.EnsembleReordering` plugin. """ + import itertools import unittest @@ -26,7 +27,6 @@ class Test__recycle_raw_ensemble_realizations(IrisTest): - """ Test the _recycle_raw_ensemble_realizations method in the EnsembleReordering plugin. @@ -67,7 +67,7 @@ def test_realization_for_equal(self): ) result = Plugin()._recycle_raw_ensemble_realizations( - self.percentile_cube, self.realization_cube, self.perc_coord, + self.percentile_cube, self.realization_cube, self.perc_coord ) self.assertIsInstance(result, Cube) self.assertArrayEqual(result.coord("realization").points, [0, 1, 2]) @@ -88,7 +88,7 @@ def test_realization_for_greater_than(self): raw_forecast_realizations = self.realization_cube[:2, :, :] raw_forecast_realizations.coord("realization").points = [12, 13] result = Plugin()._recycle_raw_ensemble_realizations( - self.percentile_cube, raw_forecast_realizations, self.perc_coord, + self.percentile_cube, raw_forecast_realizations, self.perc_coord ) self.assertIsInstance(result, Cube) self.assertArrayEqual(result.coord("realization").points, [12, 13, 14]) @@ -108,7 +108,7 @@ def test_realization_for_less_than(self): post_processed_forecast_percentiles = self.percentile_cube[:2, :, :] result = Plugin()._recycle_raw_ensemble_realizations( - post_processed_forecast_percentiles, self.realization_cube, self.perc_coord, + post_processed_forecast_percentiles, self.realization_cube, self.perc_coord ) self.assertIsInstance(result, Cube) self.assertArrayEqual(result.coord("realization").points, [0, 1]) @@ -116,7 +116,6 @@ def test_realization_for_less_than(self): class Test_rank_ecc(IrisTest): - """Test the rank_ecc method in the EnsembleReordering plugin.""" def setUp(self): @@ -355,7 +354,6 @@ def test_1d_cube_random_ordering(self): class Test__check_input_cube_masks(IrisTest): - """Test the _check_input_cube_masks method in the EnsembleReordering plugin.""" def setUp(self): @@ -455,7 +453,6 @@ def test_consistent_masks(self): class Test_process(IrisTest): - """Test the EnsembleReordering plugin.""" def setUp(self): diff --git a/improver_tests/ensemble_copula_coupling/test_RebadgePercentilesAsRealizations.py b/improver_tests/ensemble_copula_coupling/test_RebadgePercentilesAsRealizations.py index 5e26ca482e..6f63f49559 100644 --- a/improver_tests/ensemble_copula_coupling/test_RebadgePercentilesAsRealizations.py +++ b/improver_tests/ensemble_copula_coupling/test_RebadgePercentilesAsRealizations.py @@ -1,12 +1,13 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the `ensemble_copula_coupling.RebadgePercentilesAsRealizations` class. """ + import unittest import numpy as np @@ -24,7 +25,6 @@ class Test_process(IrisTest): - """Test the process method of the RebadgePercentilesAsRealizations plugin.""" diff --git a/improver_tests/ensemble_copula_coupling/test_RebadgeRealizationsAsPercentiles.py b/improver_tests/ensemble_copula_coupling/test_RebadgeRealizationsAsPercentiles.py index ea1e840cac..72df1e3686 100644 --- a/improver_tests/ensemble_copula_coupling/test_RebadgeRealizationsAsPercentiles.py +++ b/improver_tests/ensemble_copula_coupling/test_RebadgeRealizationsAsPercentiles.py @@ -1,11 +1,12 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the `ensemble_copula_coupling.RebadgeRealizationsAsPercentiles` class. """ + import numpy as np import pytest from iris.coords import DimCoord @@ -23,8 +24,8 @@ from .ecc_test_data import ECC_TEMPERATURE_REALIZATIONS -@pytest.mark.parametrize("scalar_realization", (True, False,)) -@pytest.mark.parametrize("optimal_crps_percentiles", (True, False,)) +@pytest.mark.parametrize("scalar_realization", (True, False)) +@pytest.mark.parametrize("optimal_crps_percentiles", (True, False)) @pytest.mark.parametrize( "data", (ECC_TEMPERATURE_REALIZATIONS, ECC_TEMPERATURE_REALIZATIONS[::-1]) ) diff --git a/improver_tests/ensemble_copula_coupling/test_ResamplePercentiles.py b/improver_tests/ensemble_copula_coupling/test_ResamplePercentiles.py index a4ce88ca5f..9ca68d2160 100644 --- a/improver_tests/ensemble_copula_coupling/test_ResamplePercentiles.py +++ b/improver_tests/ensemble_copula_coupling/test_ResamplePercentiles.py @@ -1,10 +1,11 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the `ensemble_copula_coupling.ResamplePercentiles` class. """ + import unittest from datetime import datetime @@ -25,7 +26,6 @@ class Test__add_bounds_to_percentiles_and_forecast_values(IrisTest): - """ Test the _add_bounds_to_percentiles_and_forecast_values method of the ResamplePercentiles plugin. @@ -165,7 +165,6 @@ def test_percentiles_not_ascending(self): class Test__interpolate_percentiles(IrisTest): - """ Test the _interpolate_percentiles method of the ResamplePercentiles plugin. """ @@ -424,7 +423,6 @@ def test_check_data_spot_forecasts(self): class Test_process(IrisTest): - """Test the process plugin of the Resample Percentiles plugin.""" def setUp(self): diff --git a/improver_tests/ensemble_copula_coupling/test__scipy_continuous_distns.py b/improver_tests/ensemble_copula_coupling/test__scipy_continuous_distns.py index 77db865481..9c759184d0 100644 --- a/improver_tests/ensemble_copula_coupling/test__scipy_continuous_distns.py +++ b/improver_tests/ensemble_copula_coupling/test__scipy_continuous_distns.py @@ -1,12 +1,13 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the `ensemble_copula_coupling._scipy_continuous_distns` scipy truncnorm workaround. """ + import unittest import numpy as np diff --git a/improver_tests/ensemble_copula_coupling/test_utilities.py b/improver_tests/ensemble_copula_coupling/test_utilities.py index 2438a88aba..26d62612ee 100644 --- a/improver_tests/ensemble_copula_coupling/test_utilities.py +++ b/improver_tests/ensemble_copula_coupling/test_utilities.py @@ -1,11 +1,12 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the `ensemble_copula_coupling.EnsembleCopulaCouplingUtilities` class. """ + import importlib import unittest import unittest.mock as mock @@ -41,7 +42,6 @@ class Test_concatenate_2d_array_with_2d_array_endpoints(IrisTest): - """Test the concatenate_2d_array_with_2d_array_endpoints.""" def test_basic(self): @@ -68,7 +68,6 @@ def test_3d_input(self): class Test_choose_set_of_percentiles(IrisTest): - """Test the choose_set_of_percentiles plugin.""" def test_basic(self): @@ -113,7 +112,6 @@ def test_unknown_sampling_option(self): class Test_create_cube_with_percentiles(IrisTest): - """Test the _create_cube_with_percentiles plugin.""" def setUp(self): @@ -139,8 +137,7 @@ def test_changed_cube_units(self): self.assertEqual(result.units, Unit("1")) def test_many_percentiles(self): - """Test that the plugin returns an Iris.cube.Cube with many percentiles. - """ + """Test that the plugin returns an Iris.cube.Cube with many percentiles.""" percentiles = np.linspace(0, 100, 100) cube_data = np.zeros( [ @@ -247,7 +244,6 @@ def test_coordinate_copy(self): class Test_get_bounds_of_distribution(IrisTest): - """Test the get_bounds_of_distribution plugin.""" def test_basic(self): @@ -291,7 +287,6 @@ def test_check_exception_is_raised(self): class Test_insert_lower_and_upper_endpoint_to_1d_array(IrisTest): - """Test the insert_lower_and_upper_endpoint_to_1d_array.""" def test_basic(self): @@ -311,7 +306,6 @@ def test_2d_example(self): class Test_restore_non_percentile_dimensions(IrisTest): - """Test the restore_non_percentile_dimensions.""" def setUp(self): @@ -392,7 +386,6 @@ def test_multiple_timesteps(self): class Test_interpolate_multiple_rows_same_y(IrisTest): - """Test interpolate_multiple_rows_same_y""" def setUp(self): @@ -480,7 +473,6 @@ def test_slow_vs_multi(self): class TestInterpolateMultipleRowsSameX(IrisTest): - """Test interpolate_multiple_rows""" def setUp(self): diff --git a/improver_tests/expected_value/test_expected_value.py b/improver_tests/expected_value/test_expected_value.py index 7853efa51c..7426fb119a 100644 --- a/improver_tests/expected_value/test_expected_value.py +++ b/improver_tests/expected_value/test_expected_value.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the ExpectedValue plugin.""" + import numpy as np import pytest from iris.coords import CellMethod @@ -64,7 +65,7 @@ def single_bounded_threshold_cube(): [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.1, 0.0, 0.0, 0.0, 0.0, 0.0], [0.8, 0.7, 0.2, 0.1, 0.05, 0.02], - ], + ] ).transpose(1, 0) data = np.broadcast_to(probs[:, np.newaxis, :], [6, 2, 3]) return set_up_probability_cube( @@ -84,7 +85,7 @@ def double_bounded_threshold_cube(): [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.25, 0.2, 0.1, 0.05, 0.02, 0.01, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], - ], + ] ).transpose(1, 0) data = np.broadcast_to(probs[:, np.newaxis, :], [10, 2, 3]) return set_up_probability_cube( @@ -154,9 +155,7 @@ def test_process_threshold_doublebounded(double_bounded_threshold_cube): def test_process_threshold_bounded(single_bounded_threshold_cube): """Check expected value of a below bounded distribution eg. precipitation.""" expval = ExpectedValue().process(single_bounded_threshold_cube) - np.testing.assert_allclose( - expval.data[0], [0.0, 0.01, 3.985], rtol=0, atol=1e-6, - ) + np.testing.assert_allclose(expval.data[0], [0.0, 0.01, 3.985], rtol=0, atol=1e-6) def test_process_threshold_abovebelow(threshold_cube): @@ -166,7 +165,7 @@ def test_process_threshold_abovebelow(threshold_cube): threshold_cube_airtemp = threshold_cube.coord("air_temperature") threshold_below_cube_airtemp = threshold_below_cube.coord("air_temperature") np.testing.assert_array_equal( - threshold_cube_airtemp.points, threshold_below_cube_airtemp.points, + threshold_cube_airtemp.points, threshold_below_cube_airtemp.points ) assert ( threshold_cube_airtemp.attributes["spp__relative_to_threshold"] diff --git a/improver_tests/feels_like_temperature/test_feels_like_temperature.py b/improver_tests/feels_like_temperature/test_feels_like_temperature.py index a08f9035c7..c5d7a224bb 100644 --- a/improver_tests/feels_like_temperature/test_feels_like_temperature.py +++ b/improver_tests/feels_like_temperature/test_feels_like_temperature.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the feels_like_temperature module""" diff --git a/improver_tests/generate_ancillaries/test_CorrectLandSeaMask.py b/improver_tests/generate_ancillaries/test_CorrectLandSeaMask.py index acf0200d5e..dac213ab64 100644 --- a/improver_tests/generate_ancillaries/test_CorrectLandSeaMask.py +++ b/improver_tests/generate_ancillaries/test_CorrectLandSeaMask.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the generate_ancillary.CorrectLandSeaMask plugin.""" - import unittest import numpy as np diff --git a/improver_tests/generate_ancillaries/test_GenerateClearskySolarRadiation.py b/improver_tests/generate_ancillaries/test_GenerateClearskySolarRadiation.py index 7f52e7d90b..6fa5eee1ad 100644 --- a/improver_tests/generate_ancillaries/test_GenerateClearskySolarRadiation.py +++ b/improver_tests/generate_ancillaries/test_GenerateClearskySolarRadiation.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the GenerateClearskySolarRadiation plugin.""" @@ -279,7 +279,6 @@ def test__calc_clearsky_solar_radiation_data( @pytest.mark.parametrize("at_mean_sea_level", (True, False)) @pytest.mark.parametrize("new_title", (None, "IMPROVER ancillary on sample grid")) def test__create_solar_radiation_cube(target_grid, at_mean_sea_level, new_title): - solar_radiation_data = np.zeros_like(target_grid.data) time = datetime(2022, 1, 1, 0, 0) accumulation_period = 24 @@ -327,7 +326,7 @@ def test_process_lat_lon(target_grid, surface_altitude): accumulation_period = 24 # Check that default behaviour results in cube with altitude for z-coord. - result = GenerateClearskySolarRadiation()(target_grid, time, accumulation_period,) + result = GenerateClearskySolarRadiation()(target_grid, time, accumulation_period) assert np.isclose(result.coord("altitude").points[0], 0.0) # Check cube has same spatial coords as target_grid @@ -355,7 +354,7 @@ def test_process_equal_area(target_grid_equal_area): # Check that default behaviour results in cube with altitude for z-coord. result = GenerateClearskySolarRadiation()( - target_grid_equal_area, time, accumulation_period, + target_grid_equal_area, time, accumulation_period ) # Check cube has same spatial coords as target_grid assert result.coords(dim_coords=True) == target_grid_equal_area.coords( diff --git a/improver_tests/generate_ancillaries/test_GenerateOrographyBandAncils.py b/improver_tests/generate_ancillaries/test_GenerateOrographyBandAncils.py index 99e85f5c4c..e3566cebe9 100644 --- a/improver_tests/generate_ancillaries/test_GenerateOrographyBandAncils.py +++ b/improver_tests/generate_ancillaries/test_GenerateOrographyBandAncils.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the generate_ancillary.GenerateOrogBandAncils plugin.""" @@ -188,7 +188,7 @@ def test_high_landband_data(self): def test_all_land_points(self): """Test that a correct mask is produced when the landsea mask only has - land points in it.""" + land points in it.""" land_mask_cube = self.landmask.copy() land_mask_cube.data = np.ones((3, 3)) result = GenOrogMasks().gen_orography_masks( @@ -199,7 +199,7 @@ def test_all_land_points(self): def test_any_surface_type_mask(self): """Test that the correct mask is produced when no landsea mask is - provided. This is equivalent to the all_land_points test above.""" + provided. This is equivalent to the all_land_points test above.""" result = GenOrogMasks().gen_orography_masks( self.orography, None, self.valley_threshold ) diff --git a/improver_tests/generate_ancillaries/test_GenerateSolarTime.py b/improver_tests/generate_ancillaries/test_GenerateSolarTime.py index fce97cd41c..4618677074 100644 --- a/improver_tests/generate_ancillaries/test_GenerateSolarTime.py +++ b/improver_tests/generate_ancillaries/test_GenerateSolarTime.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the GenerateSolarTime plugin.""" @@ -26,7 +26,7 @@ @pytest.fixture def target_grid() -> Cube: return set_up_variable_cube( - data=np.ones((10, 8), dtype=np.float32), name="template", attributes=ATTRIBUTES, + data=np.ones((10, 8), dtype=np.float32), name="template", attributes=ATTRIBUTES ) @@ -42,7 +42,6 @@ def target_grid_equal_area() -> Cube: @pytest.mark.parametrize("new_title", (None, "IMPROVER ancillary on sample grid")) def test__create_solar_time_cube(target_grid, new_title): - solar_time_data = np.zeros_like(target_grid.data) time = datetime(2022, 1, 1, 0, 0) diff --git a/improver_tests/generate_ancillaries/test_GenerateTopographicZoneWeights.py b/improver_tests/generate_ancillaries/test_GenerateTopographicZoneWeights.py index 4a5a67f232..783fb54cbb 100644 --- a/improver_tests/generate_ancillaries/test_GenerateTopographicZoneWeights.py +++ b/improver_tests/generate_ancillaries/test_GenerateTopographicZoneWeights.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the GenerateTopographicZoneWeights plugin.""" @@ -323,7 +323,7 @@ def test_data_no_mask(self): def test_data_no_mask_input(self): """Test that the result data is as expected, when no landsea - mask is input.""" + mask is input.""" expected_weights_data = np.array( [[[1.0, 1.0], [0.33, 0.17]], [[0.0, 0.0], [0.67, 0.83]]], dtype=np.float32 ) @@ -333,7 +333,7 @@ def test_data_no_mask_input(self): def test_data_no_mask_input_metatdata(self): """Test that the result metadata is as expected, when no landsea - mask is input.""" + mask is input.""" result = self.plugin.process(self.orography, self.thresholds_dict) self.assertIsInstance(result, iris.cube.Cube) self.assertEqual( diff --git a/improver_tests/generate_ancillaries/test_OrographicSmoothingCoefficients.py b/improver_tests/generate_ancillaries/test_OrographicSmoothingCoefficients.py index 7e8e0510be..11b3987724 100644 --- a/improver_tests/generate_ancillaries/test_OrographicSmoothingCoefficients.py +++ b/improver_tests/generate_ancillaries/test_OrographicSmoothingCoefficients.py @@ -1,11 +1,12 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the OrographicSmoothingCoefficients utility. """ + import numpy as np import pytest from iris.cube import Cube, CubeList @@ -23,7 +24,7 @@ def orography_fixture() -> Cube: """Orography cube with three gradients in each dimension.""" - data = np.array([[0, 0, 0], [1, 3, 5], [2, 6, 10]], dtype=np.float32,) + data = np.array([[0, 0, 0], [1, 3, 5], [2, 6, 10]], dtype=np.float32) cube = set_up_variable_cube( data, name="surface_altitude", diff --git a/improver_tests/generate_ancillaries/test_SaturatedVapourPressureTable.py b/improver_tests/generate_ancillaries/test_SaturatedVapourPressureTable.py index eb2d3ab3de..20156eb286 100644 --- a/improver_tests/generate_ancillaries/test_SaturatedVapourPressureTable.py +++ b/improver_tests/generate_ancillaries/test_SaturatedVapourPressureTable.py @@ -1,11 +1,12 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the SaturatedVapourPressureTable utility. """ + import unittest import numpy as np @@ -18,7 +19,6 @@ class Test__repr__(IrisTest): - """Test the repr method.""" def test_basic(self): @@ -32,7 +32,6 @@ def test_basic(self): class Test_saturation_vapour_pressure_goff_gratch(IrisTest): - """Test calculations of the saturated vapour pressure using the Goff-Gratch method.""" @@ -46,7 +45,6 @@ def test_basic(self): class Test_process(IrisTest): - """Test that the plugin functions as expected.""" def test_cube_attributes(self): diff --git a/improver_tests/generate_ancillaries/test_generate_ancillary.py b/improver_tests/generate_ancillaries/test_generate_ancillary.py index 7abcea8417..64507a4307 100644 --- a/improver_tests/generate_ancillaries/test_generate_ancillary.py +++ b/improver_tests/generate_ancillaries/test_generate_ancillary.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the the stand alone functions in generate_ancillary.py""" @@ -87,7 +87,7 @@ def test_cube_attribute_no_seapoints(self): def test_cube_attribute_include_seapoints(self): """Test the new attribute is added to the cube when seapoints - included.""" + included.""" result = _make_mask_cube( self.mask, self.coords, diff --git a/improver_tests/lapse_rate/test_ApplyGriddedLapseRate.py b/improver_tests/lapse_rate/test_ApplyGriddedLapseRate.py index f353bcde3f..ec63a7d4ca 100644 --- a/improver_tests/lapse_rate/test_ApplyGriddedLapseRate.py +++ b/improver_tests/lapse_rate/test_ApplyGriddedLapseRate.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the ApplyGriddedLapseRate plugin.""" diff --git a/improver_tests/lapse_rate/test_LapseRate.py b/improver_tests/lapse_rate/test_LapseRate.py index 76d2e9c58b..42039e13f1 100644 --- a/improver_tests/lapse_rate/test_LapseRate.py +++ b/improver_tests/lapse_rate/test_LapseRate.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the LapseRate plugin.""" @@ -54,7 +54,7 @@ def setUp(self): self.land_sea_mask = ~np.zeros_like(self.temperature, dtype=bool) def test_returns_expected_values(self): - """Test that the function returns expected lapse rate. """ + """Test that the function returns expected lapse rate.""" expected_out = -0.00765005774676 result = LapseRate(nbhood_radius=1)._generate_lapse_rate_array( @@ -64,7 +64,7 @@ def test_returns_expected_values(self): def test_handles_nan(self): """Test that the function returns DALR value when central point - is NaN.""" + is NaN.""" self.temperature[..., 1, 1] = np.nan expected_out = DALR @@ -124,7 +124,7 @@ def setUp(self): self.land_sea_mask.units = cf_units.Unit("1") def test_basic(self): - """Test that the plugin returns expected data type. """ + """Test that the plugin returns expected data type.""" result = LapseRate(nbhood_radius=1).process( self.temperature, self.orography, self.land_sea_mask ) @@ -176,7 +176,7 @@ def test_model_id_attr(self): def test_fails_if_temperature_is_not_cube(self): """Test code raises a Type Error if input temperature cube is - not a cube.""" + not a cube.""" incorrect_input = 50.0 msg = "Temperature input is not a cube, but {0}".format(type(incorrect_input)) with self.assertRaisesRegexp(TypeError, msg): @@ -186,7 +186,7 @@ def test_fails_if_temperature_is_not_cube(self): def test_fails_if_orography_is_not_cube(self): """Test code raises a Type Error if input orography cube is - not a cube.""" + not a cube.""" incorrect_input = 50.0 msg = "Orography input is not a cube, but {0}".format(type(incorrect_input)) with self.assertRaisesRegexp(TypeError, msg): @@ -196,7 +196,7 @@ def test_fails_if_orography_is_not_cube(self): def test_fails_if_land_sea_mask_is_not_cube(self): """Test code raises a Type Error if input land/sea mask cube is - not a cube.""" + not a cube.""" incorrect_input = 50.0 msg = "Land/Sea mask input is not a cube, but {0}".format(type(incorrect_input)) with self.assertRaisesRegexp(TypeError, msg): @@ -206,7 +206,7 @@ def test_fails_if_land_sea_mask_is_not_cube(self): def test_fails_if_temperature_wrong_units(self): """Test code raises a Value Error if the temperature cube is the - wrong unit.""" + wrong unit.""" # Swap cubes around so have wrong units. msg = r"Unable to convert from 'Unit\('m'\)' to 'Unit\('K'\)'." with self.assertRaisesRegexp(ValueError, msg): @@ -216,7 +216,7 @@ def test_fails_if_temperature_wrong_units(self): def test_fails_if_orography_wrong_units(self): """Test code raises a Value Error if the orography cube is the - wrong unit.""" + wrong unit.""" msg = r"Unable to convert from 'Unit\('K'\)' to 'Unit\('metres'\)'." with self.assertRaisesRegexp(ValueError, msg): LapseRate(nbhood_radius=1).process( @@ -250,7 +250,7 @@ def test_return_single_precision(self): def test_constant_orog(self): """Test that the function returns expected DALR values where the - orography fields are constant values. + orography fields are constant values. """ expected_out = np.full((1, 5, 5), DALR) @@ -295,7 +295,7 @@ def test_fails_if_max_height_diff_less_than_zero(self): def test_lapse_rate_limits(self): """Test that the function limits the lapse rate to +DALR and -3*DALR. - Where DALR = Dry Adiabatic Lapse Rate. + Where DALR = Dry Adiabatic Lapse Rate. """ expected_out = np.array( [ @@ -417,7 +417,7 @@ def test_specified_max_and_min_lapse_rate(self): def test_handles_nan_value(self): """Test that the function handles a NaN temperature value by replacing - it with DALR. + it with DALR. """ expected_out = np.array( [ @@ -450,7 +450,7 @@ def test_handles_nan_value(self): def test_landsea_mask(self): """Test that the function returns DALR values wherever a land/sea - mask is true. Mask is True for land-points and False for Sea. + mask is true. Mask is True for land-points and False for Sea. """ expected_out = np.array( [ @@ -512,7 +512,7 @@ def test_mask_max_height_diff(self): self.assertArrayAlmostEqual(result.data, expected_out) def test_mask_max_height_diff_arg(self): - """ Test that the function removes or leaves neighbours where their + """Test that the function removes or leaves neighbours where their height difference from the centre point is greater than a specified, non-default max_height_diff.""" expected_out = np.array( @@ -543,8 +543,8 @@ def test_mask_max_height_diff_arg(self): self.assertArrayAlmostEqual(result.data, expected_out) def test_decr_temp_incr_orog(self): - """ Test code where temperature is decreasing with height. This is the - expected scenario for lapse rate. + """Test code where temperature is decreasing with height. This is the + expected scenario for lapse rate. """ expected_out = np.array( [ @@ -573,7 +573,7 @@ def test_decr_temp_incr_orog(self): self.assertArrayAlmostEqual(result.data, expected_out) def test_decr_temp_decr_orog(self): - """ Test code where the temperature increases with height.""" + """Test code where the temperature increases with height.""" expected_out = np.array( [ [ diff --git a/improver_tests/lapse_rate/test_compute_lapse_rate_adjustment.py b/improver_tests/lapse_rate/test_compute_lapse_rate_adjustment.py index 89dd3d8483..0f81d9aef9 100644 --- a/improver_tests/lapse_rate/test_compute_lapse_rate_adjustment.py +++ b/improver_tests/lapse_rate/test_compute_lapse_rate_adjustment.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the compute_lapse_rate_adjustment function.""" @@ -24,12 +24,7 @@ def set_up_cubes(lapse_rate): Cube of the orographic difference and a cube of the lapse rate. """ orog_diff = np.array( - [ - [10, 20, -10, -20], - [200.0, -200, 10, 0], - [30, 40, 50, -50], - [5, 0.5, 40, 60], - ], + [[10, 20, -10, -20], [200.0, -200, 10, 0], [30, 40, 50, -50], [5, 0.5, 40, 60]], dtype=np.float32, ) orog_diff_cube = set_up_variable_cube( @@ -47,7 +42,7 @@ def set_up_cubes(lapse_rate): return orog_diff_cube, lapse_rate_cube -@pytest.mark.parametrize("max_orog_diff_limit", (50, 70,)) +@pytest.mark.parametrize("max_orog_diff_limit", (50, 70)) @pytest.mark.parametrize("lapse_rate", (-ELR, 0, ELR)) def test_compute_lapse_rate_adjustment(lapse_rate, max_orog_diff_limit): """Test the computation of the lapse rate adjustment.""" diff --git a/improver_tests/lightning/test_LightningFromCapePrecip.py b/improver_tests/lightning/test_LightningFromCapePrecip.py index b42a31f155..77513804d6 100644 --- a/improver_tests/lightning/test_LightningFromCapePrecip.py +++ b/improver_tests/lightning/test_LightningFromCapePrecip.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Test methods in lightning.LightningFromCapePrecip""" + from datetime import datetime from unittest.mock import patch, sentinel diff --git a/improver_tests/lightning/test_LightningMultivariateProbability_USAF2024.py b/improver_tests/lightning/test_LightningMultivariateProbability_USAF2024.py index 3463fcaec5..3434c6fbfc 100644 --- a/improver_tests/lightning/test_LightningMultivariateProbability_USAF2024.py +++ b/improver_tests/lightning/test_LightningMultivariateProbability_USAF2024.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Test methods in lightning.LightningMultivariateProbability_USAF2024""" diff --git a/improver_tests/metadata/test_amend.py b/improver_tests/metadata/test_amend.py index ddb285a866..30158dbe0f 100644 --- a/improver_tests/metadata/test_amend.py +++ b/improver_tests/metadata/test_amend.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the improver.metadata.amend module""" + import re import unittest from datetime import datetime as dt @@ -133,7 +134,6 @@ def test_history_append_no_existing(self): class Test_update_model_id_attr_attribute(IrisTest): - """Test the update_model_id_attr_attribute function.""" def setUp(self): diff --git a/improver_tests/metadata/test_check_datatypes.py b/improver_tests/metadata/test_check_datatypes.py index 9cdbb55d3d..73c2c9e82c 100644 --- a/improver_tests/metadata/test_check_datatypes.py +++ b/improver_tests/metadata/test_check_datatypes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the improver.metadata.check_datatypes module.""" @@ -24,7 +24,6 @@ class Test_check_mandatory_standards(IrisTest): - """Test whether a cube conforms to mandatory dtype and units standards.""" def setUp(self): @@ -156,7 +155,6 @@ def test_multiple_errors(self): class Test_enforce_dtypes(IrisTest): - """Test whether a cube conforms to mandatory dtype and units standards.""" def setUp(self): diff --git a/improver_tests/metadata/test_forecast_times.py b/improver_tests/metadata/test_forecast_times.py index 07b63639d2..a12ce33ee9 100644 --- a/improver_tests/metadata/test_forecast_times.py +++ b/improver_tests/metadata/test_forecast_times.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for forecast time coordinate utilities""" @@ -255,7 +255,6 @@ def test_single_cube_with_cycletime(self): class Test_unify_cycletime(IrisTest): - """Test the unify_cycletime function.""" def setUp(self): @@ -350,12 +349,11 @@ def test_input_no_forecast_period_coordinate(self): class Test__find_latest_cycletime(IrisTest): - """Test the _find_latest_cycletime function.""" def setUp(self): """Set up a template cubes with scalar time, forecast_reference_time - and forecast_period coordinates""" + and forecast_period coordinates""" self.input_cube = set_up_variable_cube( np.full((7, 7), 273.15, dtype=np.float32), time=datetime(2015, 11, 23, 6), @@ -385,7 +383,7 @@ def test_returns_latest(self): def test_two_cubes_same_reference_time(self): """Test the a cycletime is still found when two cubes have the same - cycletime.""" + cycletime.""" input_cubelist = iris.cube.CubeList([self.input_cube, self.input_cube.copy()]) cycletime = _find_latest_cycletime(input_cubelist) expected_datetime = datetime(2015, 11, 23, 3) diff --git a/improver_tests/metadata/test_probabilistic.py b/improver_tests/metadata/test_probabilistic.py index 7e1924eaf5..2abae0f83c 100644 --- a/improver_tests/metadata/test_probabilistic.py +++ b/improver_tests/metadata/test_probabilistic.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the improver.metadata.probabilistic module""" @@ -42,7 +42,7 @@ def setUp(self): self.threshold_points = np.array([276, 277, 278], dtype=np.float32) def test_above(self): - """ Tests the case where spp__relative_threshold is above""" + """Tests the case where spp__relative_threshold is above""" cube = set_up_probability_cube( self.data, self.threshold_points, spp__relative_to_threshold="above" ) @@ -50,7 +50,7 @@ def test_above(self): self.assertEqual(result, "above") def test_below(self): - """ Tests the case where spp__relative_threshold is below""" + """Tests the case where spp__relative_threshold is below""" cube = set_up_probability_cube( self.data, self.threshold_points, spp__relative_to_threshold="below" ) @@ -58,7 +58,7 @@ def test_below(self): self.assertEqual(result, "below") def test_greater_than(self): - """ Tests the case where spp__relative_threshold is greater_than""" + """Tests the case where spp__relative_threshold is greater_than""" cube = set_up_probability_cube( self.data, self.threshold_points, spp__relative_to_threshold="greater_than" ) @@ -66,7 +66,7 @@ def test_greater_than(self): self.assertEqual(result, "above") def test_greater_than_or_equal_to(self): - """ Tests the case where spp__relative_threshold is + """Tests the case where spp__relative_threshold is greater_than_or_equal_to""" cube = set_up_probability_cube( self.data, @@ -77,7 +77,7 @@ def test_greater_than_or_equal_to(self): self.assertEqual(result, "above") def test_less_than(self): - """ Tests the case where spp__relative_threshold is less_than""" + """Tests the case where spp__relative_threshold is less_than""" cube = set_up_probability_cube( self.data, self.threshold_points, spp__relative_to_threshold="less_than" ) @@ -85,7 +85,7 @@ def test_less_than(self): self.assertEqual(result, "below") def test_less_than_or_equal_to(self): - """ Tests the case where spp__relative_threshold is + """Tests the case where spp__relative_threshold is less_than_or_equal_to""" cube = set_up_probability_cube( self.data, @@ -98,7 +98,7 @@ def test_less_than_or_equal_to(self): def test_no_spp__relative_to_threshold(self): """Tests it returns None if there is no spp__relative_to_threshold attribute.""" - cube = set_up_probability_cube(self.data, self.threshold_points,) + cube = set_up_probability_cube(self.data, self.threshold_points) cube.coord("air_temperature").attributes = { "relative_to_threshold": "greater_than" } @@ -108,7 +108,7 @@ def test_no_spp__relative_to_threshold(self): def test_incorrect_attribute(self): """Tests it returns None if the spp__relative_to_threshold attribute has an invalid value.""" - cube = set_up_probability_cube(self.data, self.threshold_points,) + cube = set_up_probability_cube(self.data, self.threshold_points) cube.coord("air_temperature").attributes = { "spp__relative_to_threshold": "higher" } @@ -179,8 +179,7 @@ def test_below_threshold(self): self.assertEqual(result, "air_temperature") def test_between_thresholds(self): - """Test correct name is returned from a probability between thresholds - """ + """Test correct name is returned from a probability between thresholds""" result = get_threshold_coord_name_from_probability_name( "probability_of_visibility_in_air_between_thresholds" ) @@ -278,8 +277,7 @@ def test_basic(self): self.assertIsInstance(threshold_coord, iris.coords.Coord) def test_old_convention(self): - """Test function recognises threshold coordinate with name "threshold" - """ + """Test function recognises threshold coordinate with name "threshold" """ threshold_coord = find_threshold_coordinate(self.cube_old) self.assertEqual(threshold_coord.name(), "threshold") self.assertArrayAlmostEqual(threshold_coord.points, self.threshold_points) @@ -307,7 +305,6 @@ def test_fails_if_no_threshold_coord(self): class Test_find_percentile_coordinate(IrisTest): - """Test whether the cube has a percentile coordinate.""" def setUp(self): diff --git a/improver_tests/metadata/test_utilities.py b/improver_tests/metadata/test_utilities.py index 282a52ec71..a3a2d918eb 100644 --- a/improver_tests/metadata/test_utilities.py +++ b/improver_tests/metadata/test_utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the improver.metadata.utilities module""" @@ -318,7 +318,6 @@ def test_variation(self): class Test_check_grid_match(unittest.TestCase): - """Test the check_grid_match function.""" def setUp(self): @@ -462,8 +461,7 @@ def attribute_not_unique(cubes: List[Cube]): ), ) def test_errors_get_model_id_attr(cubes: List[Cube], method: Callable, message): - """Checks that get_model_id_attr raises useful errors when the required conditions are not met. - """ + """Checks that get_model_id_attr raises useful errors when the required conditions are not met.""" model_id_attr = "test_attribute" model_id_value = "test_value" for cube in cubes: diff --git a/improver_tests/nbhood/nbhood/test_BaseNeighbourhoodProcessing.py b/improver_tests/nbhood/nbhood/test_BaseNeighbourhoodProcessing.py index ebc25c137b..06fc322651 100644 --- a/improver_tests/nbhood/nbhood/test_BaseNeighbourhoodProcessing.py +++ b/improver_tests/nbhood/nbhood/test_BaseNeighbourhoodProcessing.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the nbhood.BaseNeighbourhoodProcessing plugin.""" - import unittest import numpy as np @@ -15,7 +14,6 @@ class Test__init__(IrisTest): - """Test the __init__ method of NeighbourhoodProcessing""" def test_radii_varying_with_lead_time_mismatch(self): @@ -31,7 +29,6 @@ def test_radii_varying_with_lead_time_mismatch(self): class Test__find_radii(IrisTest): - """Test the internal _find_radii function is working correctly.""" def test_basic_array_cube_lead_times_an_array(self): @@ -57,7 +54,6 @@ def test_interpolation(self): class Test_process(IrisTest): - """Tests for the process method of NeighbourhoodProcessing.""" RADIUS = 6300 # Gives 3 grid cells worth. @@ -66,7 +62,7 @@ def setUp(self): """Set up cube.""" data = np.ones((16, 16), dtype=np.float32) data[7, 7] = 0 - self.cube = set_up_variable_cube(data, spatial_grid="equalarea",) + self.cube = set_up_variable_cube(data, spatial_grid="equalarea") def test_single_point_nan(self): """Test behaviour for a single NaN grid cell.""" @@ -77,7 +73,7 @@ def test_single_point_nan(self): def test_correct_radii_set(self): """Test that the correct neighbourhood radius is set when interpolation - is required""" + is required""" radii = [5600, 9500] lead_times = [3, 5] diff --git a/improver_tests/nbhood/nbhood/test_GeneratePercentilesFromANeighbourhood.py b/improver_tests/nbhood/nbhood/test_GeneratePercentilesFromANeighbourhood.py index 0a19a01556..cf23427ad9 100644 --- a/improver_tests/nbhood/nbhood/test_GeneratePercentilesFromANeighbourhood.py +++ b/improver_tests/nbhood/nbhood/test_GeneratePercentilesFromANeighbourhood.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the nbhood.nbhood.GeneratePercentilesFromANeighbourhood plugin.""" - import unittest import iris @@ -21,16 +20,15 @@ class Test_make_percentile_cube(IrisTest): - """Test the make_percentile_cube method from - GeneratePercentilesFromANeighbourhood.""" + GeneratePercentilesFromANeighbourhood.""" def setUp(self): """Set up a 2D cube.""" data = np.ones((5, 5), dtype=np.float32) data[2, 2] = 0 - self.cube = set_up_variable_cube(data, spatial_grid="equalarea",) + self.cube = set_up_variable_cube(data, spatial_grid="equalarea") def test_basic(self): """Test that the plugin returns an iris.cube.Cube.""" @@ -73,14 +71,13 @@ def test_coord_is_dim_scalar(self): class Test_pad_and_unpad_cube(IrisTest): - """Test the padding and unpadding of the data within a cube.""" def setUp(self): """Set up a 2D cube.""" data = np.ones((5, 5), dtype=np.float32) - self.cube = set_up_variable_cube(data, spatial_grid="equalarea",) + self.cube = set_up_variable_cube(data, spatial_grid="equalarea") def test_2d_slice(self): """Test a 2D slice.""" @@ -108,7 +105,7 @@ def test_2d_slice(self): [1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0], ], - ], + ] ) kernel = np.array([[0.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, 1.0, 0.0]]) self.cube.data[2, 2] = 0 @@ -143,7 +140,7 @@ def test_irregular_kernel(self): [1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0], ], - ], + ] ) kernel = np.array([[0.0, 1.0, 0.0], [1.0, 0.0, 1.0], [0.0, 0.0, 1.0]]) self.cube.data[2, 2] = 0 @@ -159,7 +156,7 @@ def test_single_point_almost_edge(self): data = np.ones((3, 3), dtype=np.float32) data[1, 1] = 0 - cube = set_up_variable_cube(data, spatial_grid="equalarea",) + cube = set_up_variable_cube(data, spatial_grid="equalarea") # Just within range of the edge. @@ -303,7 +300,6 @@ def test_single_point_on_corner(self): class Test_process(IrisTest): - """Test the process method within the plugin to calculate percentile values from a neighbourhood.""" @@ -311,7 +307,7 @@ def setUp(self): """Set up a 2D cube.""" data = np.ones((5, 5), dtype=np.float32) - self.cube = set_up_variable_cube(data, spatial_grid="equalarea",) + self.cube = set_up_variable_cube(data, spatial_grid="equalarea") def test_basic(self): """Test that the plugin returns an iris.cube.Cube.""" @@ -352,7 +348,7 @@ def test_single_point(self): data = np.ones((5, 5), dtype=np.float32) data[2, 2] = 0 - cube = set_up_variable_cube(data, spatial_grid="equalarea",) + cube = set_up_variable_cube(data, spatial_grid="equalarea") percentiles = np.array([10, 50, 90]) radius = 2000.0 result = GeneratePercentilesFromANeighbourhood( @@ -375,7 +371,7 @@ def test_single_point_single_percentile(self): data = np.ones((5, 5), dtype=np.float32) data[2, 2] = 0 - cube = set_up_variable_cube(data, spatial_grid="equalarea",) + cube = set_up_variable_cube(data, spatial_grid="equalarea") percentiles = np.array([50]) radius = 2000.0 result = GeneratePercentilesFromANeighbourhood( @@ -387,7 +383,7 @@ def test_multi_point_multireals(self): """Test behaviour for points over multiple realizations.""" data = np.ones((5, 5), dtype=np.float32) - cube = set_up_variable_cube(data, spatial_grid="equalarea",) + cube = set_up_variable_cube(data, spatial_grid="equalarea") reals_points = np.array([0, 1], dtype=np.int32) cube = add_coordinate(cube, coord_points=reals_points, coord_name="realization") cube.data[0, 2, 2] = 0 @@ -454,7 +450,7 @@ def test_multi_point_single_real(self): """Test behaviour for points over a single realization.""" data = np.ones((5, 5), dtype=np.float32) - cube = set_up_variable_cube(data, spatial_grid="equalarea",) + cube = set_up_variable_cube(data, spatial_grid="equalarea") reals_points = np.array([0], dtype=np.int32) cube = add_coordinate(cube, coord_points=reals_points, coord_name="realization") cube.data[2, 2] = 0 @@ -497,7 +493,7 @@ def test_single_point_lat_long(self): data = np.ones((16, 16), dtype=np.float32) data[7, 7] = 0 - cube = set_up_variable_cube(data, spatial_grid="latlon",) + cube = set_up_variable_cube(data, spatial_grid="latlon") msg = "Unable to convert from" radius = 6000.0 @@ -654,7 +650,7 @@ def test_number_of_percentiles_equals_number_of_points(self): data = np.ones((7, 7), dtype=np.float32) data[3, 3] = 0 - cube = set_up_variable_cube(data, spatial_grid="equalarea",) + cube = set_up_variable_cube(data, spatial_grid="equalarea") percentiles = np.array([5, 10, 15, 20, 25]) radius = 2000.0 result = GeneratePercentilesFromANeighbourhood( @@ -762,7 +758,7 @@ def test_number_of_points_half_of_number_of_percentiles(self): data = np.ones((7, 7), dtype=np.float32) data[3, 3] = 0 - cube = set_up_variable_cube(data, spatial_grid="equalarea",) + cube = set_up_variable_cube(data, spatial_grid="equalarea") percentiles = np.array([2.5, 5, 7.5, 10, 12.5, 15, 17.5, 20, 22.5, 25]) radius = 2000.0 diff --git a/improver_tests/nbhood/nbhood/test_MetaNeighbourhood.py b/improver_tests/nbhood/nbhood/test_MetaNeighbourhood.py index b957a06796..835b958559 100644 --- a/improver_tests/nbhood/nbhood/test_MetaNeighbourhood.py +++ b/improver_tests/nbhood/nbhood/test_MetaNeighbourhood.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. from unittest.mock import patch, sentinel @@ -61,7 +61,7 @@ def test___init___exceptions( degrees_as_complex, exception_msg, ): - """Exception when passing """ + """Exception when passing""" args = [neighbourhood_output] kwargs = { "weighted_mode": weighted_mode, diff --git a/improver_tests/nbhood/nbhood/test_NeighbourhoodProcessing.py b/improver_tests/nbhood/nbhood/test_NeighbourhoodProcessing.py index a598bdf8b7..48a9a3bc38 100644 --- a/improver_tests/nbhood/nbhood/test_NeighbourhoodProcessing.py +++ b/improver_tests/nbhood/nbhood/test_NeighbourhoodProcessing.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the nbhood.NeighbourhoodProcessing plugin.""" - import unittest import numpy as np @@ -17,7 +16,6 @@ class Test__init__(IrisTest): - """Test the __init__ method of NeighbourhoodProcessing.""" def test_neighbourhood_method_does_not_exist(self): @@ -39,7 +37,6 @@ def test_square_nbhood_with_weighted_mode(self): class Test__calculate_neighbourhood(IrisTest): - """Test the _calculate_neighbourhood method.""" RADIUS = 2500 @@ -374,7 +371,6 @@ def test_external_mask_with_masked_data_square(self): class Test_process(IrisTest): - """Test the process method.""" def setUp(self): diff --git a/improver_tests/nbhood/nbhood/test_check_radius_against_distance.py b/improver_tests/nbhood/nbhood/test_check_radius_against_distance.py index fc8f415bb8..3b7700a531 100644 --- a/improver_tests/nbhood/nbhood/test_check_radius_against_distance.py +++ b/improver_tests/nbhood/nbhood/test_check_radius_against_distance.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for nbhood.nbhood.check_radius_against_distance.""" @@ -14,7 +14,6 @@ class Test_check_radius_against_distance(IrisTest): - """Test check_radius_against_distance function.""" def setUp(self): diff --git a/improver_tests/nbhood/nbhood/test_circular_kernel.py b/improver_tests/nbhood/nbhood/test_circular_kernel.py index 71c1627407..d17d89c334 100644 --- a/improver_tests/nbhood/nbhood/test_circular_kernel.py +++ b/improver_tests/nbhood/nbhood/test_circular_kernel.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the nbhood.nbhood.circular_kernel function.""" @@ -13,7 +13,6 @@ class Test_circular_kernel(IrisTest): - """Test neighbourhood processing plugin.""" def test_basic(self): diff --git a/improver_tests/nbhood/recursive_filter/test_RecursiveFilter.py b/improver_tests/nbhood/recursive_filter/test_RecursiveFilter.py index a9faf28a77..39828e4a3e 100644 --- a/improver_tests/nbhood/recursive_filter/test_RecursiveFilter.py +++ b/improver_tests/nbhood/recursive_filter/test_RecursiveFilter.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the nbhood.RecursiveFilter plugin.""" @@ -27,7 +27,6 @@ def _mean_points(points): class Test_RecursiveFilter(IrisTest): - """Test class for the RecursiveFilter tests, setting up cubes.""" def setUp(self): @@ -124,7 +123,6 @@ def setUp(self): class Test__init__(Test_RecursiveFilter): - """Test plugin initialisation.""" def test_basic(self): @@ -138,13 +136,10 @@ def test_iterations(self): iterations = 0 msg = "Invalid number of iterations: must be >= 1: 0" with self.assertRaisesRegex(ValueError, msg): - RecursiveFilter( - iterations=iterations, edge_width=1, - ) + RecursiveFilter(iterations=iterations, edge_width=1) class Test__validate_coefficients(Test_RecursiveFilter): - """Test the _validate_coefficients method""" def test_return_order(self): @@ -275,12 +270,11 @@ def test_padding_non_constant_values(self): class Test__recurse_forward(Test_RecursiveFilter): - """Test the _recurse_forward method""" def test_first_axis(self): """Test that the returned _recurse_forward array has the expected - type and result.""" + type and result.""" expected_result = np.array( [ [0.0000, 0.00000, 0.100000, 0.00000, 0.0000], @@ -298,7 +292,7 @@ def test_first_axis(self): def test_second_axis(self): """Test that the returned _recurse_forward array has the expected - type and result.""" + type and result.""" expected_result = np.array( [ [0.0, 0.000, 0.0500, 0.02500, 0.012500], @@ -316,12 +310,11 @@ def test_second_axis(self): class Test__recurse_backward(Test_RecursiveFilter): - """Test the _recurse_backward method""" def test_first_axis(self): """Test that the returned _recurse_backward array has the expected - type and result.""" + type and result.""" expected_result = np.array( [ [0.0125, 0.03125, 0.196875, 0.03125, 0.0125], @@ -339,7 +332,7 @@ def test_first_axis(self): def test_second_axis(self): """Test that the returned _recurse_backward array has the expected - type and result.""" + type and result.""" expected_result = np.array( [ [0.012500, 0.02500, 0.0500, 0.000, 0.0], @@ -357,7 +350,6 @@ def test_second_axis(self): class Test__run_recursion(Test_RecursiveFilter): - """Test the _run_recursion method""" def test_return_type(self): @@ -404,7 +396,7 @@ def test_result_multiple_iterations(self): padded_cube = pad_cube_with_halo(cube, 2 * edge_width, 2 * edge_width) result = RecursiveFilter(edge_width=edge_width)._run_recursion( - padded_cube, smoothing_coefficients_x, smoothing_coefficients_y, 3, + padded_cube, smoothing_coefficients_x, smoothing_coefficients_y, 3 ) expected_result = 0.034629755 self.assertAlmostEqual(result.data[4][4], expected_result) @@ -438,8 +430,7 @@ def test_different_smoothing_coefficients(self): class Test_process(Test_RecursiveFilter): - - """Test the process method. """ + """Test the process method.""" # Test output from plugin returns expected values def test_return_type_and_shape(self): @@ -447,16 +438,16 @@ def test_return_type_and_shape(self): the expected shape.""" # Output data array should have same dimensions as input data array expected_shape = (1, 5, 5) - plugin = RecursiveFilter(iterations=self.iterations,) - result = plugin(self.cube, smoothing_coefficients=self.smoothing_coefficients,) + plugin = RecursiveFilter(iterations=self.iterations) + result = plugin(self.cube, smoothing_coefficients=self.smoothing_coefficients) self.assertIsInstance(result, Cube) self.assertEqual(result.shape, expected_shape) self.assertEqual(result.shape, expected_shape) def test_smoothing_coefficient_cubes(self): """Test that the RecursiveFilter plugin returns the correct data.""" - plugin = RecursiveFilter(iterations=self.iterations,) - result = plugin(self.cube, smoothing_coefficients=self.smoothing_coefficients,) + plugin = RecursiveFilter(iterations=self.iterations) + result = plugin(self.cube, smoothing_coefficients=self.smoothing_coefficients) expected = 0.14994797 self.assertAlmostEqual(result.data[0][2][2], expected) @@ -464,7 +455,7 @@ def test_smoothing_coefficient_cubes_masked_data(self): """Test that the RecursiveFilter plugin returns the correct data when a masked data cube. """ - plugin = RecursiveFilter(iterations=self.iterations,) + plugin = RecursiveFilter(iterations=self.iterations) mask = np.zeros(self.cube.data.shape) mask[0][3][2] = 1 self.cube.data = np.ma.MaskedArray(self.cube.data, mask=mask) @@ -478,7 +469,7 @@ def test_coordinate_reordering_with_different_smoothing_coefficients(self): coordinate when the input cube spatial dimensions are (x, y) not (y, x)""" enforce_coordinate_ordering(self.cube, ["realization", "longitude", "latitude"]) - plugin = RecursiveFilter(iterations=self.iterations,) + plugin = RecursiveFilter(iterations=self.iterations) result = plugin( self.cube, smoothing_coefficients=self.smoothing_coefficients_alternative ) @@ -510,7 +501,7 @@ def test_error_multiple_times_masked(self): mask[0, 0, 2, 2] = 1 mask[1, 0, 2, 3] = 1 cube.data = np.ma.MaskedArray(cube.data, mask=mask) - plugin = RecursiveFilter(iterations=self.iterations,) + plugin = RecursiveFilter(iterations=self.iterations) msg = "multiple time points is unsupported" with self.assertRaisesRegex(ValueError, msg): plugin(cube, smoothing_coefficients=self.smoothing_coefficients) diff --git a/improver_tests/nbhood/test_init.py b/improver_tests/nbhood/test_init.py index d6beaee8cc..4dc453c8ad 100644 --- a/improver_tests/nbhood/test_init.py +++ b/improver_tests/nbhood/test_init.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for nbhood.__init__""" @@ -10,7 +10,6 @@ class Test_radius_by_lead_time(unittest.TestCase): - """Test the radius_by_lead_time method.""" def test_single_radius(self): diff --git a/improver_tests/nbhood/use_nbhood/test_ApplyNeighbourhoodProcessingWithAMask.py b/improver_tests/nbhood/use_nbhood/test_ApplyNeighbourhoodProcessingWithAMask.py index 4b8342c710..fb31632c40 100644 --- a/improver_tests/nbhood/use_nbhood/test_ApplyNeighbourhoodProcessingWithAMask.py +++ b/improver_tests/nbhood/use_nbhood/test_ApplyNeighbourhoodProcessingWithAMask.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for nbhood.ApplyNeighbourhoodProcessingWithAMask.""" @@ -40,7 +40,7 @@ def setUp(self): dtype=np.float32, ) cube = set_up_probability_cube( - np.ones((1, 3, 3), dtype=np.float32), [278.15], spatial_grid="equalarea", + np.ones((1, 3, 3), dtype=np.float32), [278.15], spatial_grid="equalarea" ) self.cube = add_coordinate(cube, [50, 100, 150], "topographic_zone", "m") self.cube = iris.util.squeeze(self.cube) @@ -150,7 +150,6 @@ def test_masked_weights_and_missing(self): class Test_process(unittest.TestCase): - """Test the process method of ApplyNeighbourhoodProcessingWithAMask.""" def setUp(self): @@ -161,8 +160,8 @@ def setUp(self): Set up expected results. """ # Set up cube to process. - data = np.array([[[1, 1, 1], [1, 1, 0], [0, 0, 0]]], dtype=np.float32,) - self.cube = set_up_probability_cube(data, [278.15], spatial_grid="equalarea",) + data = np.array([[[1, 1, 1], [1, 1, 0], [0, 0, 0]]], dtype=np.float32) + self.cube = set_up_probability_cube(data, [278.15], spatial_grid="equalarea") # Set up mask cube. Currently mask cubes have sea points set to zero, # not masked out. mask_data = np.array( @@ -227,10 +226,10 @@ def setUp(self): ) # Set up expected collapsed result expected_result = np.array( - [[np.nan, 1.0, 0.5], [1.0, 0.625, 0.25], [0.0, 0.0, 0.0]], dtype=np.float32, + [[np.nan, 1.0, 0.5], [1.0, 0.625, 0.25], [0.0, 0.0, 0.0]], dtype=np.float32 ) expected_mask = np.array( - [[True, False, False], [False, False, False], [False, False, False]], + [[True, False, False], [False, False, False], [False, False, False]] ) self.expected_collapsed_result = np.ma.MaskedArray( expected_result, expected_mask @@ -272,9 +271,9 @@ def test_sparse_no_collapse_square(self): """ data = np.zeros((1, 9, 9), dtype=np.float32) data[..., 3:6, 3:6] = np.array( - [[[1, 1, 1], [1, 1, 0], [0, 0, 0]]], dtype=np.float32, + [[[1, 1, 1], [1, 1, 0], [0, 0, 0]]], dtype=np.float32 ) - cube = set_up_probability_cube(data, [278.15], spatial_grid="equalarea",) + cube = set_up_probability_cube(data, [278.15], spatial_grid="equalarea") # Set up mask cube. Currently mask cubes have sea points set to zero, # not masked out. mask_data = np.zeros((3, 9, 9), dtype=np.float32) diff --git a/improver_tests/nowcasting/accumulation/test_Accumulation.py b/improver_tests/nowcasting/accumulation/test_Accumulation.py index 9fff0a123b..168d60a968 100644 --- a/improver_tests/nowcasting/accumulation/test_Accumulation.py +++ b/improver_tests/nowcasting/accumulation/test_Accumulation.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Unit tests for the nowcasting.Accumulation plugin """ +"""Unit tests for the nowcasting.Accumulation plugin""" import datetime import unittest @@ -172,7 +172,6 @@ def test_times(self): class Test__check_inputs(rate_cube_set_up): - """Test the _check_inputs method.""" def test_basic(self): @@ -278,7 +277,6 @@ def test_raises_exception_for_impossible_aggregation(self): class Test__get_cube_subsets(rate_cube_set_up): - """Test the _get_cube_subsets method.""" def test_basic(self): @@ -295,7 +293,6 @@ def test_basic(self): class Test__calculate_accumulation(rate_cube_set_up): - """Test the _calculate_accumulation method.""" def test_basic(self): @@ -330,7 +327,6 @@ def test_basic(self): class Test__set_metadata(rate_cube_set_up): - """Test the _set_metadata method.""" def test_basic(self): diff --git a/improver_tests/nowcasting/forecasting/test_AdvectField.py b/improver_tests/nowcasting/forecasting/test_AdvectField.py index feb60e6b73..db64a022ac 100644 --- a/improver_tests/nowcasting/forecasting/test_AdvectField.py +++ b/improver_tests/nowcasting/forecasting/test_AdvectField.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Unit tests for the nowcasting.AdvectField plugin """ +"""Unit tests for the nowcasting.AdvectField plugin""" import datetime import unittest diff --git a/improver_tests/nowcasting/forecasting/test_CreateExtrapolationForecast.py b/improver_tests/nowcasting/forecasting/test_CreateExtrapolationForecast.py index 0b37e16af7..9b6ec0266c 100644 --- a/improver_tests/nowcasting/forecasting/test_CreateExtrapolationForecast.py +++ b/improver_tests/nowcasting/forecasting/test_CreateExtrapolationForecast.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Unit tests for the nowcasting.CreateExtrapolationForecast plugin """ +"""Unit tests for the nowcasting.CreateExtrapolationForecast plugin""" import unittest @@ -41,7 +41,7 @@ class SetUpCubes(IrisTest): """ def setUp(self): - """Set up cubes needed for the __init__ method """ + """Set up cubes needed for the __init__ method""" self.precip_cube = setup_precipitation_cube() self.oe_cube = setup_orographic_enhancement_cube() self.vel_x = set_up_xy_velocity_cube("advection_velocity_x") @@ -67,7 +67,7 @@ def test_basic(self): def test_basic_with_metadata_dict(self): """Test for simple case where __init__ does not change the input and - we amend the attributes.""" + we amend the attributes.""" # Change the input cube so no orographic enhancement is expected. input_cube = self.precip_cube.copy() input_cube.rename("air_temperature") @@ -92,7 +92,7 @@ def test_no_orographic_enhancement(self): def test_no_orographic_enhancement_rainfall_rate(self): """Test what happens if no orographic enhancement cube is provided. - for rainfall_rate""" + for rainfall_rate""" message = ( "For precipitation or rainfall fields, orographic " "enhancement cube must be supplied." diff --git a/improver_tests/nowcasting/lightning/test_NowcastLightning.py b/improver_tests/nowcasting/lightning/test_NowcastLightning.py index 1326234f7d..6fcf51f9a5 100644 --- a/improver_tests/nowcasting/lightning/test_NowcastLightning.py +++ b/improver_tests/nowcasting/lightning/test_NowcastLightning.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the nowcast.lightning.NowcastLightning plugin.""" - import unittest from datetime import datetime as dt @@ -132,7 +131,6 @@ def set_up_lightning_test_cubes( class Test__init__(IrisTest): - """Test the __init__ method accepts keyword arguments.""" def test_with_radius(self): @@ -145,7 +143,6 @@ def test_with_radius(self): class Test__repr__(IrisTest): - """Test the repr method.""" def test_basic(self): @@ -167,7 +164,6 @@ def test_basic(self): class Test__update_metadata(IrisTest): - """Test the _update_metadata method.""" def setUp(self): @@ -230,7 +226,6 @@ def test_missing_threshold_coord(self): class Test__modify_first_guess(IrisTest): - """Test the _modify_first_guess method.""" def setUp(self): @@ -258,13 +253,9 @@ def setUp(self): Has extra coordinate of length(3) "threshold" containing points [0.5, 1., 2.] kg m-2. """ - ( - self.cube, - self.fg_cube, - self.ltng_cube, - self.precip_cube, - self.vii_cube, - ) = set_up_lightning_test_cubes() + (self.cube, self.fg_cube, self.ltng_cube, self.precip_cube, self.vii_cube) = ( + set_up_lightning_test_cubes() + ) self.plugin = Plugin() def test_basic(self): @@ -438,7 +429,6 @@ def test_lrate_small(self): class Test_apply_precip(IrisTest): - """Test the apply_precip method.""" def setUp(self): @@ -586,7 +576,6 @@ def test_precip_intense_null(self): class Test_apply_ice(IrisTest): - """Test the apply_ice method.""" def setUp(self): @@ -712,7 +701,6 @@ def test_ice_large_with_fc(self): class Test_process(IrisTest): - """Test the nowcast lightning plugin.""" def setUp(self): @@ -738,13 +726,9 @@ def setUp(self): Has extra coordinate of length(3) "threshold" containing points [0.5, 1., 2.] kg m-2. """ - ( - _, - self.fg_cube, - self.ltng_cube, - self.precip_cube, - self.vii_cube, - ) = set_up_lightning_test_cubes(grid_points=16) + (_, self.fg_cube, self.ltng_cube, self.precip_cube, self.vii_cube) = ( + set_up_lightning_test_cubes(grid_points=16) + ) # reset some data and give precip cube a 4 hour forecast period self.precip_cube.data[0, ...] = 1.0 self.precip_cube.coord("forecast_period").points = [4 * 3600.0] diff --git a/improver_tests/nowcasting/optical_flow/__init__.py b/improver_tests/nowcasting/optical_flow/__init__.py index 5e0c7fdc5d..956fa933d9 100644 --- a/improver_tests/nowcasting/optical_flow/__init__.py +++ b/improver_tests/nowcasting/optical_flow/__init__.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Set up function for dummy cube with correct metadata""" diff --git a/improver_tests/nowcasting/optical_flow/test_OpticalFlow.py b/improver_tests/nowcasting/optical_flow/test_OpticalFlow.py index a9d8ca632e..e1c341bf14 100644 --- a/improver_tests/nowcasting/optical_flow/test_OpticalFlow.py +++ b/improver_tests/nowcasting/optical_flow/test_OpticalFlow.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Unit tests for the nowcasting.OpticalFlow plugin """ +"""Unit tests for the nowcasting.OpticalFlow plugin""" import unittest import warnings diff --git a/improver_tests/nowcasting/optical_flow/test_generate_advection_velocities_from_winds.py b/improver_tests/nowcasting/optical_flow/test_generate_advection_velocities_from_winds.py index 00fd924984..186c070ca4 100644 --- a/improver_tests/nowcasting/optical_flow/test_generate_advection_velocities_from_winds.py +++ b/improver_tests/nowcasting/optical_flow/test_generate_advection_velocities_from_winds.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for generation of optical flow components from a background flow""" diff --git a/improver_tests/nowcasting/optical_flow/test_generate_optical_flow_components.py b/improver_tests/nowcasting/optical_flow/test_generate_optical_flow_components.py index 86df8c9cab..0599de7b69 100644 --- a/improver_tests/nowcasting/optical_flow/test_generate_optical_flow_components.py +++ b/improver_tests/nowcasting/optical_flow/test_generate_optical_flow_components.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for generation of optical flow components""" diff --git a/improver_tests/nowcasting/optical_flow/test_utilities.py b/improver_tests/nowcasting/optical_flow/test_utilities.py index 23e92eec59..611beb80df 100644 --- a/improver_tests/nowcasting/optical_flow/test_utilities.py +++ b/improver_tests/nowcasting/optical_flow/test_utilities.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Unit tests for optical flow utilities """ +"""Unit tests for optical flow utilities""" import unittest diff --git a/improver_tests/nowcasting/pysteps_advection/test_PystepsExtrapolate.py b/improver_tests/nowcasting/pysteps_advection/test_PystepsExtrapolate.py index f3fbf419b1..da56504c05 100644 --- a/improver_tests/nowcasting/pysteps_advection/test_PystepsExtrapolate.py +++ b/improver_tests/nowcasting/pysteps_advection/test_PystepsExtrapolate.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for PystepsExtrapolate plugin""" diff --git a/improver_tests/nowcasting/utilities/test_ApplyOrographicEnhancement.py b/improver_tests/nowcasting/utilities/test_ApplyOrographicEnhancement.py index 3bfc5a35c3..a009cd2819 100644 --- a/improver_tests/nowcasting/utilities/test_ApplyOrographicEnhancement.py +++ b/improver_tests/nowcasting/utilities/test_ApplyOrographicEnhancement.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module with tests for the ApplyOrographicEnhancement plugin.""" @@ -80,7 +80,6 @@ def set_up_orographic_enhancement_cube(): class Test__init__(IrisTest): - """Test the __init__ method.""" def test_basic(self): @@ -90,7 +89,6 @@ def test_basic(self): class Test__repr__(IrisTest): - """Test the __repr__ method.""" def test_basic(self): @@ -101,7 +99,6 @@ def test_basic(self): class Test__select_orographic_enhancement_cube(IrisTest): - """Test the _select_orographic_enhancement method.""" def setUp(self): @@ -171,7 +168,6 @@ def test_alternative_time_quarter_to(self): class Test__apply_orographic_enhancement(IrisTest): - """Test the _apply_orographic_enhancement method.""" def setUp(self): @@ -232,7 +228,6 @@ def test_check_unchanged_oe_cube_for_subtract(self): class Test__apply_minimum_precip_rate(IrisTest): - """Test the _apply_minimum_precip_rate method.""" def setUp(self): @@ -406,7 +401,6 @@ def test_NaN_values(self): class Test_process(IrisTest): - """Test the apply_orographic_enhancement method.""" def setUp(self): diff --git a/improver_tests/nowcasting/utilities/test_ExtendRadarMask.py b/improver_tests/nowcasting/utilities/test_ExtendRadarMask.py index a7906d9f90..6e8b58cbda 100644 --- a/improver_tests/nowcasting/utilities/test_ExtendRadarMask.py +++ b/improver_tests/nowcasting/utilities/test_ExtendRadarMask.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Module with tests for the ExtendRadarMask plugin.""" diff --git a/improver_tests/nowcasting/utilities/test_FillRadarHoles.py b/improver_tests/nowcasting/utilities/test_FillRadarHoles.py index e5cf7d4036..cfa0e26635 100644 --- a/improver_tests/nowcasting/utilities/test_FillRadarHoles.py +++ b/improver_tests/nowcasting/utilities/test_FillRadarHoles.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the FillRadarHoles plugin""" diff --git a/improver_tests/orographic_enhancement/test_OrographicEnhancement.py b/improver_tests/orographic_enhancement/test_OrographicEnhancement.py index 41e7e58eab..075b1db802 100644 --- a/improver_tests/orographic_enhancement/test_OrographicEnhancement.py +++ b/improver_tests/orographic_enhancement/test_OrographicEnhancement.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the OrographicEnhancement plugin.""" diff --git a/improver_tests/percentile/test_PercentileConverter.py b/improver_tests/percentile/test_PercentileConverter.py index aa4d5d0248..298156ab63 100644 --- a/improver_tests/percentile/test_PercentileConverter.py +++ b/improver_tests/percentile/test_PercentileConverter.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the percentile.PercentileConverter plugin.""" @@ -18,7 +18,6 @@ class Test_process(IrisTest): - """Test the creation of percentiles by the plugin.""" def setUp(self): diff --git a/improver_tests/precipitation_type/calculate_sleet_prob/test_calculate_sleet_probability.py b/improver_tests/precipitation_type/calculate_sleet_prob/test_calculate_sleet_probability.py index 11de0f744b..1a5ed7d242 100644 --- a/improver_tests/precipitation_type/calculate_sleet_prob/test_calculate_sleet_probability.py +++ b/improver_tests/precipitation_type/calculate_sleet_prob/test_calculate_sleet_probability.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the calculate_sleet_probability plugin.""" @@ -14,7 +14,7 @@ class Test_calculate_sleet_probability(IrisTest): - """ Tests the calculate sleet probability function.""" + """Tests the calculate sleet probability function.""" def setUp(self): """Create cubes to input into the function.""" diff --git a/improver_tests/precipitation_type/convection/test_ConvectionRatioFromComponents.py b/improver_tests/precipitation_type/convection/test_ConvectionRatioFromComponents.py index 1bbf1ae347..ef20af076d 100644 --- a/improver_tests/precipitation_type/convection/test_ConvectionRatioFromComponents.py +++ b/improver_tests/precipitation_type/convection/test_ConvectionRatioFromComponents.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the ConvectionRatioFromComponents plugin.""" diff --git a/improver_tests/precipitation_type/freezing_rain/conftest.py b/improver_tests/precipitation_type/freezing_rain/conftest.py index 5e57ec7a25..1125783dec 100644 --- a/improver_tests/precipitation_type/freezing_rain/conftest.py +++ b/improver_tests/precipitation_type/freezing_rain/conftest.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Fixtures for freezing rain tests""" diff --git a/improver_tests/precipitation_type/freezing_rain/test_FreezingRain.py b/improver_tests/precipitation_type/freezing_rain/test_FreezingRain.py index ddd8f19cac..218cb9d4ec 100644 --- a/improver_tests/precipitation_type/freezing_rain/test_FreezingRain.py +++ b/improver_tests/precipitation_type/freezing_rain/test_FreezingRain.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Tests of FreezingRain plugin""" +"""Tests of FreezingRain plugin""" import itertools from unittest.mock import patch, sentinel @@ -232,7 +232,7 @@ def test_realization_matching( @pytest.mark.parametrize("period", TIME_WINDOW_TYPE) def test_no_realization_matching( - precipitation_multi_realization, temperature_multi_realization, + precipitation_multi_realization, temperature_multi_realization ): """Test that an error is raised if the inputs have no common realizations.""" cubes = iris.cube.CubeList( diff --git a/improver_tests/precipitation_type/hail_fraction/test_HailFraction.py b/improver_tests/precipitation_type/hail_fraction/test_HailFraction.py index 4e513adb4a..88612fe139 100644 --- a/improver_tests/precipitation_type/hail_fraction/test_HailFraction.py +++ b/improver_tests/precipitation_type/hail_fraction/test_HailFraction.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the HailFraction plugin.""" + from unittest.mock import patch, sentinel import iris @@ -165,10 +166,10 @@ def test_basic( ) hail_size.data = np.full_like(hail_size.data, hail_size_value) cloud_condensation_level.data = np.full_like( - cloud_condensation_level.data, cloud_condensation_level_value, + cloud_condensation_level.data, cloud_condensation_level_value ) convective_cloud_top.data = np.full_like( - convective_cloud_top.data, convective_cloud_top_value, + convective_cloud_top.data, convective_cloud_top_value ) hail_melting_level.data = np.full_like( hail_melting_level.data, hail_melting_level_value diff --git a/improver_tests/precipitation_type/shower_condition_probability/test_ShowerConditionProbability.py b/improver_tests/precipitation_type/shower_condition_probability/test_ShowerConditionProbability.py index 80bbc23381..8e0aa232bf 100644 --- a/improver_tests/precipitation_type/shower_condition_probability/test_ShowerConditionProbability.py +++ b/improver_tests/precipitation_type/shower_condition_probability/test_ShowerConditionProbability.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for ShowerConditionProbability plugin""" diff --git a/improver_tests/precipitation_type/snow_fraction/test_SnowFraction.py b/improver_tests/precipitation_type/snow_fraction/test_SnowFraction.py index 73b7af2e0a..8c7bd83056 100644 --- a/improver_tests/precipitation_type/snow_fraction/test_SnowFraction.py +++ b/improver_tests/precipitation_type/snow_fraction/test_SnowFraction.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Tests of SnowFraction plugin""" +"""Tests of SnowFraction plugin""" from datetime import datetime diff --git a/improver_tests/precipitation_type/snow_splitter/test_snow_splitter.py b/improver_tests/precipitation_type/snow_splitter/test_snow_splitter.py index 98f801598a..9a1443cb8b 100644 --- a/improver_tests/precipitation_type/snow_splitter/test_snow_splitter.py +++ b/improver_tests/precipitation_type/snow_splitter/test_snow_splitter.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the SnowSplitter plugin""" + from datetime import datetime from unittest.mock import patch, sentinel diff --git a/improver_tests/precipitation_type/test_utilities.py b/improver_tests/precipitation_type/test_utilities.py index b4997e270b..629f718a56 100644 --- a/improver_tests/precipitation_type/test_utilities.py +++ b/improver_tests/precipitation_type/test_utilities.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Tests of precipitation_type utilities""" +"""Tests of precipitation_type utilities""" import numpy as np import pytest diff --git a/improver_tests/psychrometric_calculations/cloud_condensation_level/test_CloudCondensationLevel.py b/improver_tests/psychrometric_calculations/cloud_condensation_level/test_CloudCondensationLevel.py index 7adcd6fa96..06dc705476 100644 --- a/improver_tests/psychrometric_calculations/cloud_condensation_level/test_CloudCondensationLevel.py +++ b/improver_tests/psychrometric_calculations/cloud_condensation_level/test_CloudCondensationLevel.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the CloudCondensationLevel plugin""" + from typing import Tuple import numpy as np @@ -28,7 +29,7 @@ def temperature_cube_fixture() -> Cube: """Set up a r, y, x cube of temperature data""" data = np.full((2, 2, 2), fill_value=300, dtype=np.float32) temperature_cube = set_up_variable_cube( - data, name="air_temperature", units="K", attributes=LOCAL_MANDATORY_ATTRIBUTES, + data, name="air_temperature", units="K", attributes=LOCAL_MANDATORY_ATTRIBUTES ) return temperature_cube diff --git a/improver_tests/psychrometric_calculations/cloud_condensation_level/test_MetaCloudCondensationLevel.py b/improver_tests/psychrometric_calculations/cloud_condensation_level/test_MetaCloudCondensationLevel.py index 8357686769..499ace7fb0 100644 --- a/improver_tests/psychrometric_calculations/cloud_condensation_level/test_MetaCloudCondensationLevel.py +++ b/improver_tests/psychrometric_calculations/cloud_condensation_level/test_MetaCloudCondensationLevel.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the MetaCloudCondensationLevel plugin.""" + from unittest.mock import patch, sentinel from improver.psychrometric_calculations.cloud_condensation_level import ( diff --git a/improver_tests/psychrometric_calculations/cloud_top_temperature/test_CloudTopTemperature.py b/improver_tests/psychrometric_calculations/cloud_top_temperature/test_CloudTopTemperature.py index e9750586d5..78385be88b 100644 --- a/improver_tests/psychrometric_calculations/cloud_top_temperature/test_CloudTopTemperature.py +++ b/improver_tests/psychrometric_calculations/cloud_top_temperature/test_CloudTopTemperature.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the CloudTopTemperature plugin""" + import copy from unittest.mock import patch, sentinel @@ -23,9 +24,9 @@ "institution": "somewhere", } POST_PROCESSED_MANDATORY_ATTRIBUTES = copy.deepcopy(LOCAL_MANDATORY_ATTRIBUTES) -POST_PROCESSED_MANDATORY_ATTRIBUTES[ - "title" -] = f"Post-Processed {POST_PROCESSED_MANDATORY_ATTRIBUTES['title']}" +POST_PROCESSED_MANDATORY_ATTRIBUTES["title"] = ( + f"Post-Processed {POST_PROCESSED_MANDATORY_ATTRIBUTES['title']}" +) class HaltExecution(Exception): diff --git a/improver_tests/psychrometric_calculations/hail_size/test_HailSize.py b/improver_tests/psychrometric_calculations/hail_size/test_HailSize.py index 5b90de48cf..26f14bc9c5 100644 --- a/improver_tests/psychrometric_calculations/hail_size/test_HailSize.py +++ b/improver_tests/psychrometric_calculations/hail_size/test_HailSize.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the HailSize plugin""" + from unittest.mock import patch, sentinel import numpy as np @@ -81,7 +82,7 @@ def orography() -> Cube: """Set up a r, y, x cube of orography data""" data = np.full((3, 2), fill_value=0, dtype=np.float32) orography_cube = set_up_variable_cube( - data, name="surface_altitude", units="m", attributes=LOCAL_MANDATORY_ATTRIBUTES, + data, name="surface_altitude", units="m", attributes=LOCAL_MANDATORY_ATTRIBUTES ) return orography_cube @@ -151,10 +152,10 @@ def cube_shape_check(hail_cube): @pytest.mark.parametrize( "ccl_p,ccl_t,wbz,orog,expected", ( - (75000, 290, 2200, 0, 0.035,), # values approx from tephigram in literature - (75000, 290, 5000, 0, 0,), # wet bulb zero (wbz) height greater than 4400m + (75000, 290, 2200, 0, 0.035), # values approx from tephigram in literature + (75000, 290, 5000, 0, 0), # wet bulb zero (wbz) height greater than 4400m (75000, 290, 5000, 2800, 0.035), # orography reduces wbz height to 2200m - (75000, 290, 3400, 0, 0.025,), # wbz height above 3350m but less than 4400m + (75000, 290, 3400, 0, 0.025), # wbz height above 3350m but less than 4400m (94000, 273, 2200, 0, 0), # vertical value negative (1000, 270, 2200, 0, 0), # horizontal value negative (95000, 330, 2200, 0, 0.08), # vertical greater than length of table @@ -209,10 +210,7 @@ def test_temperature_too_high( data = temperature_on_pressure_levels.data.copy() data[:, :, 1] = 300 temperature_on_pressure_levels.data = data - expected = [ - [[0.1, 0.1], [0, 0], [0.1, 0.1]], - [[0.1, 0.1], [0, 0], [0.1, 0.1]], - ] + expected = [[[0.1, 0.1], [0, 0], [0.1, 0.1]], [[0.1, 0.1], [0, 0], [0.1, 0.1]]] result = HailSize()( ccl_temperature, @@ -305,7 +303,6 @@ def test_re_ordered_cubes( wet_bulb_freezing, orography, ): - """Tests the plugin if the input cubes have coordinates that need to be rearranged. Checks that the outputted cube has coordinates in the same order as the inputs""" diff --git a/improver_tests/psychrometric_calculations/precip_phase_probability/test_PrecipPhaseProbability.py b/improver_tests/psychrometric_calculations/precip_phase_probability/test_PrecipPhaseProbability.py index 087c831b28..0d7661c7f4 100644 --- a/improver_tests/psychrometric_calculations/precip_phase_probability/test_PrecipPhaseProbability.py +++ b/improver_tests/psychrometric_calculations/precip_phase_probability/test_PrecipPhaseProbability.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for psychrometric_calculations PrecipPhaseProbability plugin.""" + import operator from unittest.mock import patch, sentinel diff --git a/improver_tests/psychrometric_calculations/test_HumidityMixingRatio.py b/improver_tests/psychrometric_calculations/test_HumidityMixingRatio.py index 460df26371..7c818e7801 100644 --- a/improver_tests/psychrometric_calculations/test_HumidityMixingRatio.py +++ b/improver_tests/psychrometric_calculations/test_HumidityMixingRatio.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the HumidityMixingRatio plugin""" + from unittest.mock import patch, sentinel import numpy as np @@ -49,7 +50,7 @@ def temperature_cube_fixture() -> Cube: """Set up a r, y, x cube of temperature data""" data = np.full((2, 2, 2), fill_value=300, dtype=np.float32) temperature_cube = set_up_variable_cube( - data, name="air_temperature", units="K", attributes=LOCAL_MANDATORY_ATTRIBUTES, + data, name="air_temperature", units="K", attributes=LOCAL_MANDATORY_ATTRIBUTES ) return temperature_cube @@ -72,10 +73,7 @@ def humidity_cube_fixture() -> Cube: """Set up a r, y, x cube of relative humidity data""" data = np.full((2, 2, 2), fill_value=1e-1, dtype=np.float32) humidity_cube = set_up_variable_cube( - data, - name="relative_humidity", - units="1", - attributes=LOCAL_MANDATORY_ATTRIBUTES, + data, name="relative_humidity", units="1", attributes=LOCAL_MANDATORY_ATTRIBUTES ) return humidity_cube diff --git a/improver_tests/psychrometric_calculations/test_PhaseChangeLevel.py b/improver_tests/psychrometric_calculations/test_PhaseChangeLevel.py index 82304de348..6f471aae63 100644 --- a/improver_tests/psychrometric_calculations/test_PhaseChangeLevel.py +++ b/improver_tests/psychrometric_calculations/test_PhaseChangeLevel.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for psychrometric_calculations PhaseChangeLevel.""" @@ -24,7 +24,6 @@ class Test__init__(IrisTest): - """Test the init method.""" def test_snow_sleet(self): @@ -75,7 +74,6 @@ def test_unknown_phase_change(self): class Test_find_falling_level(IrisTest): - """Test the find_falling_level method.""" def setUp(self): @@ -114,7 +112,6 @@ def test_outside_range(self): class Test_fill_in_high_phase_change_falling_levels(IrisTest): - """Test the fill_in_high_phase_change_falling_levels method.""" def setUp(self): @@ -157,7 +154,6 @@ def test_no_fill_if_conditions_not_met(self): class Test_linear_wet_bulb_fit(IrisTest): - """Test the linear_wet_bulb_fit method.""" def setUp(self): @@ -207,7 +203,6 @@ def test_land_points(self): class Test_find_extrapolated_falling_level(IrisTest): - """Test the find_extrapolated_falling_level method.""" def setUp(self): @@ -271,7 +266,6 @@ def test_gradients_zero(self): class Test_fill_sea_points(IrisTest): - """Test the fill_in_sea_points method.""" def setUp(self): @@ -365,7 +359,6 @@ def test_non_zero_orography(self): class Test_find_max_in_nbhood_orography(IrisTest): - """Test the find_max_in_nbhood_orography method""" def setUp(self): @@ -427,7 +420,6 @@ def test_null_lat_lon(self): class Test_horizontally_interpolate_phase(IrisTest): - """Test the PhaseChangeLevel horizontal interpolation.""" def setUp(self): @@ -599,7 +591,6 @@ def test_interpolate_edge_case_2d_crater_grid_point_radius_2(self): class Test_process(IrisTest): - """Test the PhaseChangeLevel processing works""" def setUp(self): @@ -719,9 +710,9 @@ def test_model_id_attr(self): values when the model_id_attr is provided. In this instance the phase change is from snow to sleet. The returned level has three values, all above orography.""" - self.wet_bulb_temperature_cube.attributes[ - "mosg__model_configuration" - ] = "uk_ens" + self.wet_bulb_temperature_cube.attributes["mosg__model_configuration"] = ( + "uk_ens" + ) self.wet_bulb_integral_cube.attributes["mosg__model_configuration"] = "uk_ens" result = PhaseChangeLevel( phase_change="snow-sleet", model_id_attr="mosg__model_configuration" @@ -745,9 +736,9 @@ def test_model_id_attr(self): def test_model_id_attr_exception(self): """Test that non-matching model_id_attr values result in an exception.""" - self.wet_bulb_temperature_cube.attributes[ - "mosg__model_configuration" - ] = "uk_ens" + self.wet_bulb_temperature_cube.attributes["mosg__model_configuration"] = ( + "uk_ens" + ) self.wet_bulb_integral_cube.attributes["mosg__model_configuration"] = "uk_det" msg = "Attribute mosg__model_configuration" with self.assertRaisesRegex(ValueError, msg): diff --git a/improver_tests/psychrometric_calculations/test_calculate_svp_in_air.py b/improver_tests/psychrometric_calculations/test_calculate_svp_in_air.py index 110ba740ad..91a6cd41af 100644 --- a/improver_tests/psychrometric_calculations/test_calculate_svp_in_air.py +++ b/improver_tests/psychrometric_calculations/test_calculate_svp_in_air.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for psychrometric_calculations calculate_svp_in_air""" diff --git a/improver_tests/psychrometric_calculations/test_psychrometric_calculations.py b/improver_tests/psychrometric_calculations/test_psychrometric_calculations.py index fe4c6688bb..ab96ee8f9c 100644 --- a/improver_tests/psychrometric_calculations/test_psychrometric_calculations.py +++ b/improver_tests/psychrometric_calculations/test_psychrometric_calculations.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the dry_adiabatic_temperature and dry_adiabatic_pressure methods.""" + import numpy as np import pytest @@ -42,7 +43,8 @@ def test_dry_adiabatic_methods(shape, method, t1, p1, n2, expected): """Test that we can move between pairs of points in both directions with both methods. Point pairs are t_1,p_1 and t_2,p_2. t1,p1 is the starting point for a test and - n2 is the target point, either temperature or pressure depending on the method being tested.""" + n2 is the target point, either temperature or pressure depending on the method being tested. + """ result = method( np.full(shape, t1, dtype=np.float32), np.full(shape, p1, dtype=np.float32), diff --git a/improver_tests/psychrometric_calculations/test_significant_phase_mask/test_SignificantPhaseMask.py b/improver_tests/psychrometric_calculations/test_significant_phase_mask/test_SignificantPhaseMask.py index 695e0e44a7..a229d3b626 100644 --- a/improver_tests/psychrometric_calculations/test_significant_phase_mask/test_SignificantPhaseMask.py +++ b/improver_tests/psychrometric_calculations/test_significant_phase_mask/test_SignificantPhaseMask.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for psychrometric_calculations SignificantPhaseMask plugin.""" @@ -83,7 +83,7 @@ def test_masked_values(): data = np.zeros((2, 2), dtype=np.float32) data = np.ma.masked_array(data, [[True, False], [False, False]]) input_cube = set_up_variable_cube( - data, name="snow_fraction", units="1", standard_grid_metadata="uk_ens", + data, name="snow_fraction", units="1", standard_grid_metadata="uk_ens" ) with pytest.raises( NotImplementedError, match="SignificantPhaseMask cannot handle masked data" @@ -139,8 +139,10 @@ def test_data_error(snow_fraction): units="1", standard_grid_metadata="uk_ens", ) - msg = "Expected cube data to be in range 0 <= x <= 1. Found max={0}; min={0}".format( - snow_fraction + msg = ( + "Expected cube data to be in range 0 <= x <= 1. Found max={0}; min={0}".format( + snow_fraction + ) ) with pytest.raises(ValueError, match=msg): SignificantPhaseMask()(input_cube, "snow") diff --git a/improver_tests/psychrometric_calculations/wet_bulb_temperature/test_MetaWetBulbFreezingLevel.py b/improver_tests/psychrometric_calculations/wet_bulb_temperature/test_MetaWetBulbFreezingLevel.py index 80d1d65bd7..665ddd5c9b 100644 --- a/improver_tests/psychrometric_calculations/wet_bulb_temperature/test_MetaWetBulbFreezingLevel.py +++ b/improver_tests/psychrometric_calculations/wet_bulb_temperature/test_MetaWetBulbFreezingLevel.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. from unittest.mock import patch, sentinel diff --git a/improver_tests/psychrometric_calculations/wet_bulb_temperature/test_WetBulbTemperature.py b/improver_tests/psychrometric_calculations/wet_bulb_temperature/test_WetBulbTemperature.py index de9e7232a0..606e9e74fa 100644 --- a/improver_tests/psychrometric_calculations/wet_bulb_temperature/test_WetBulbTemperature.py +++ b/improver_tests/psychrometric_calculations/wet_bulb_temperature/test_WetBulbTemperature.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for psychrometric_calculations WetBulbTemperature""" + import unittest from unittest.mock import patch, sentinel diff --git a/improver_tests/psychrometric_calculations/wet_bulb_temperature/test_WetBulbTemperatureIntegral.py b/improver_tests/psychrometric_calculations/wet_bulb_temperature/test_WetBulbTemperatureIntegral.py index 6c533fa785..22f771327e 100644 --- a/improver_tests/psychrometric_calculations/wet_bulb_temperature/test_WetBulbTemperatureIntegral.py +++ b/improver_tests/psychrometric_calculations/wet_bulb_temperature/test_WetBulbTemperatureIntegral.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for psychrometric_calculations WetBulbTemperatureIntegral.""" @@ -20,7 +20,6 @@ class Test_process(IrisTest): - """Test the calculation of the wet bulb temperature integral from temperature, pressure, and relative humidity information using the process function. Integration is calculated in the vertical. diff --git a/improver_tests/regrid/test_AdjustLandSeaPoints.py b/improver_tests/regrid/test_AdjustLandSeaPoints.py index 223b596f92..ca1bef5980 100644 --- a/improver_tests/regrid/test_AdjustLandSeaPoints.py +++ b/improver_tests/regrid/test_AdjustLandSeaPoints.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the AdjustLandSeaPoints class""" @@ -89,10 +89,7 @@ def setUp(self): data = np.ones((3, 3), dtype=np.float32) data[1, 1] = 0.0 cube = set_up_variable_cube( - data, - name="precipitation_amount", - units="kg m^-2", - spatial_grid="equalarea", + data, name="precipitation_amount", units="kg m^-2", spatial_grid="equalarea" ) self.plugin.input_land = cube.copy() self.plugin.output_land = cube.copy() @@ -168,10 +165,7 @@ def test_not_in_vicinity(self): data = np.ones((5, 5), dtype=np.float32) data[1, 1] = 0.0 cube = set_up_variable_cube( - data, - name="precipitation_amount", - units="kg m^-2", - spatial_grid="equalarea", + data, name="precipitation_amount", units="kg m^-2", spatial_grid="equalarea" ) self.plugin.output_land = cube.copy() self.plugin.nearest_cube = cube.copy() diff --git a/improver_tests/regrid/test_RegridLandSea.py b/improver_tests/regrid/test_RegridLandSea.py index 70369cca3c..2d089e2f68 100644 --- a/improver_tests/regrid/test_RegridLandSea.py +++ b/improver_tests/regrid/test_RegridLandSea.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the standardise.RegridLandSea plugin.""" diff --git a/improver_tests/regrid/test_RegridWithLandSeaMask.py b/improver_tests/regrid/test_RegridWithLandSeaMask.py index 6895dac8db..2c737ed509 100644 --- a/improver_tests/regrid/test_RegridWithLandSeaMask.py +++ b/improver_tests/regrid/test_RegridWithLandSeaMask.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the RegridWithLandSeaMask class""" # set up a special data set and corresponding land-sea mask info @@ -31,7 +31,7 @@ def modify_cube_coordinate_value(cube, coord_x, coord_y): def define_source_target_grid_data(): - """ define cube_in, cube_in_mask,cube_out_mask using assumed data """ + """define cube_in, cube_in_mask,cube_out_mask using assumed data""" # source (input) grid in_lats = np.linspace(0, 15, 4, dtype=np.float32) in_lons = np.linspace(0, 40, 5, dtype=np.float32) @@ -75,7 +75,7 @@ def define_source_target_grid_data(): def define_source_target_grid_data_same_domain(): - """ define cube_in, cube_in_mask,cube_out_mask, assume the same domain """ + """define cube_in, cube_in_mask,cube_out_mask, assume the same domain""" # source (input) grid in_lats = np.linspace(0, 15, 4, dtype=np.float32) in_lons = np.linspace(0, 40, 5, dtype=np.float32) @@ -117,7 +117,7 @@ def define_source_target_grid_data_same_domain(): def test_basic_indexes(): - """Test basic_indexes for identical source and target domain case """ + """Test basic_indexes for identical source and target domain case""" cube_in, cube_out_mask, _ = define_source_target_grid_data_same_domain() in_latlons = latlon_from_cube(cube_in) out_latlons = latlon_from_cube(cube_out_mask) @@ -143,7 +143,7 @@ def test_regrid_nearest_2(): """Test nearest neighbour regridding option 'nearest-2'""" cube_in, cube_out_mask, _ = define_source_target_grid_data() - regrid_nearest = RegridLandSea(regrid_mode="nearest-2",)(cube_in, cube_out_mask) + regrid_nearest = RegridLandSea(regrid_mode="nearest-2")(cube_in, cube_out_mask) expected_results = np.array( [ [0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3], @@ -163,7 +163,7 @@ def test_regrid_bilinear_2(): """Test bilinear regridding option 'bilinear-2'""" cube_in, cube_out_mask, _ = define_source_target_grid_data() - regrid_bilinear = RegridLandSea(regrid_mode="bilinear-2",)(cube_in, cube_out_mask) + regrid_bilinear = RegridLandSea(regrid_mode="bilinear-2")(cube_in, cube_out_mask) expected_results = np.array( [ @@ -223,7 +223,7 @@ def test_regrid_nearest_with_mask_2(): def test_regrid_bilinear_with_mask_2(): - """Test bilinear-with-mask-2 regridding """ + """Test bilinear-with-mask-2 regridding""" cube_in, cube_out_mask, cube_in_mask = define_source_target_grid_data() regrid_bilinear_with_mask = RegridLandSea( @@ -303,14 +303,14 @@ def test_target_domain_bigger_than_source_domain(regridder, landmask, maskedinpu # run the regridding regridderLandSea = RegridLandSea( - regrid_mode=regrid_mode, landmask=cube_in_mask, landmask_vicinity=250000000, + regrid_mode=regrid_mode, landmask=cube_in_mask, landmask_vicinity=250000000 ) regrid_out = regridderLandSea(cube_in, cube_out_mask) regrid_out_pad = regridderLandSea(cube_in, cube_out_mask_pad) # check that results inside the padding matches the same regridding without padding np.testing.assert_allclose( - regrid_out.data, regrid_out_pad.data[width_y:-width_y, width_x:-width_x], + regrid_out.data, regrid_out_pad.data[width_y:-width_y, width_x:-width_x] ) # check results in the padded area diff --git a/improver_tests/regrid/test_grid.py b/improver_tests/regrid/test_grid.py index ac00026288..95530b27d9 100644 --- a/improver_tests/regrid/test_grid.py +++ b/improver_tests/regrid/test_grid.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the functions from grid.py.""" @@ -109,7 +109,7 @@ def test_latlon_from_cube(request, fixture_name, expected): @pytest.mark.parametrize( - "fixture_name", ["latlon_single", "equal_single", "latlon_ens", "equal_ens"], + "fixture_name", ["latlon_single", "equal_single", "latlon_ens", "equal_ens"] ) def test_flatten_spatial_dimensions(request, fixture_name): """Test the flatten_spatial_dimensions function""" diff --git a/improver_tests/regrid/test_grid_contains_cutout.py b/improver_tests/regrid/test_grid_contains_cutout.py index 862b6aea7a..f44dc07b85 100644 --- a/improver_tests/regrid/test_grid_contains_cutout.py +++ b/improver_tests/regrid/test_grid_contains_cutout.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for grid_contains_cutout""" diff --git a/improver_tests/spotdata/test_HeightAdjustment.py b/improver_tests/spotdata/test_HeightAdjustment.py index 38f3bd9b11..aa9e8f8635 100644 --- a/improver_tests/spotdata/test_HeightAdjustment.py +++ b/improver_tests/spotdata/test_HeightAdjustment.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for SpotHeightAdjustment plugin""" @@ -26,7 +26,7 @@ def prob_cube() -> Cube: longitude = np.linspace(-0.25, 0.5, 4) wmo_id = ["03854", "03962", "03142", "03331"] threshold_coord = DimCoord( - points=[50, 100, 1000], var_name="threshold", long_name=name, units="m", + points=[50, 100, 1000], var_name="threshold", long_name=name, units="m" ) data = np.asarray([[0.1, 0, 0.2, 0.1], [0.7, 0, 0.3, 0.2], [1, 0.4, 0.4, 0.9]]) diff --git a/improver_tests/spotdata/test_NeighbourSelection.py b/improver_tests/spotdata/test_NeighbourSelection.py index 8b6c080897..4915df4daa 100755 --- a/improver_tests/spotdata/test_NeighbourSelection.py +++ b/improver_tests/spotdata/test_NeighbourSelection.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for NeighbourSelection class""" @@ -18,7 +18,6 @@ class Test_NeighbourSelection(IrisTest): - """Test class for the NeighbourSelection tests, setting up inputs.""" def setUp(self): @@ -118,7 +117,6 @@ def setUp(self): class Test__repr__(IrisTest): - """Tests the class __repr__ function.""" def test_basic(self): @@ -155,7 +153,6 @@ def test_non_default(self): class Test__transform_sites_coordinate_system(Test_NeighbourSelection): - """Test the function for converting arrays of site coordinates into the correct coordinate system for the model/grid cube.""" @@ -221,7 +218,6 @@ def test_region_to_region(self): class Test_check_sites_are_within_domain(Test_NeighbourSelection): - """Test the function that removes sites falling outside the model domain from the site list.""" @@ -260,13 +256,10 @@ def test_some_invalid(self): msg = "1 spot sites fall outside the grid" with pytest.warns(UserWarning, match=msg): - ( - sites_out, - site_coords_out, - out_x, - out_y, - ) = plugin.check_sites_are_within_domain( - sites, site_coords, x_points, y_points, self.region_orography + (sites_out, site_coords_out, out_x, out_y) = ( + plugin.check_sites_are_within_domain( + sites, site_coords, x_points, y_points, self.region_orography + ) ) self.assertArrayEqual(sites_out, sites[0:2]) @@ -291,13 +284,10 @@ def test_global_invalid(self): plugin.global_coordinate_system = True with pytest.warns(UserWarning, match=msg): - ( - sites_out, - site_coords_out, - out_x, - out_y, - ) = plugin.check_sites_are_within_domain( - sites, site_coords, x_points, y_points, self.global_orography + (sites_out, site_coords_out, out_x, out_y) = ( + plugin.check_sites_are_within_domain( + sites, site_coords, x_points, y_points, self.global_orography + ) ) self.assertArrayEqual(sites_out, sites[0:2]) @@ -333,7 +323,6 @@ def test_global_circular_valid(self): class Test_get_nearest_indices(Test_NeighbourSelection): - """Test function wrapping iris functionality to get nearest grid point indices to arbitrary coordinates.""" @@ -356,7 +345,6 @@ def test_basic(self): class Test_geocentric_cartesian(Test_NeighbourSelection): - """Test conversion of global coordinates to geocentric cartesians. In this coordinate system, x and y are in the equitorial plane, and z is towards the poles.""" @@ -456,7 +444,6 @@ def test_negative_45_degrees_latitude_and_longitude(self): class Test_build_KDTree(Test_NeighbourSelection): - """Test construction of a KDTree with scipy.""" def test_basic(self): @@ -487,7 +474,6 @@ def test_only_land(self): class Test_select_minimum_dz(Test_NeighbourSelection): - """Test extraction of the minimum height difference points from a provided array of neighbours. Note that the region orography has a series of islands at a y index of 4, changing elevation with x. As such the nodes are chosen @@ -560,7 +546,6 @@ def test_incomplete_search(self): class Test_process(Test_NeighbourSelection): - """Test the process method of the NeighbourSelection class.""" def test_non_metre_spatial_dimensions(self): diff --git a/improver_tests/spotdata/test_SpotExtraction.py b/improver_tests/spotdata/test_SpotExtraction.py index e636be9a4b..cf97fca35d 100755 --- a/improver_tests/spotdata/test_SpotExtraction.py +++ b/improver_tests/spotdata/test_SpotExtraction.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for SpotExtraction class""" @@ -22,7 +22,6 @@ class Test_SpotExtraction(IrisTest): - """Test class for the SpotExtraction tests, setting up inputs.""" def setUp(self): @@ -159,7 +158,6 @@ def setUp(self): class Test__repr__(IrisTest): - """Tests the class __repr__ function.""" def test_basic(self): @@ -179,7 +177,6 @@ def test_non_default(self): class Test_extract_coordinates(Test_SpotExtraction): - """Test the extraction of x and y coordinate indices from a neighbour cube for a given neighbour_selection_method.""" @@ -207,7 +204,6 @@ def test_invalid_method(self): class Test_check_for_unique_id(Test_SpotExtraction): - """Test identification of unique site ID coordinates from coordinate attributes.""" @@ -229,7 +225,6 @@ def test_unique_is_not_present(self): class Test_get_aux_coords(Test_SpotExtraction): - """Test the extraction of scalar and non-scalar auxiliary coordinates from a cube.""" @@ -289,7 +284,6 @@ def test_multiple_nonscalar_coords(self): class Test_get_coordinate_data(Test_SpotExtraction): - """Test the extraction of data from the provided coordinates.""" def test_coordinate_with_bounds_extraction(self): @@ -324,7 +318,6 @@ def test_coordinate_without_bounds_extraction(self): class Test_build_diagnostic_cube(Test_SpotExtraction): - """Test the building of a spot data cube with given inputs.""" def test_building_cube(self): @@ -353,7 +346,6 @@ def test_building_cube(self): class Test_process(Test_SpotExtraction): - """Test the process method which extracts data and builds cubes with metadata added.""" diff --git a/improver_tests/spotdata/test_SpotLapseRateAdjust.py b/improver_tests/spotdata/test_SpotLapseRateAdjust.py index 5d54f20f7f..ef9fd7f75e 100755 --- a/improver_tests/spotdata/test_SpotLapseRateAdjust.py +++ b/improver_tests/spotdata/test_SpotLapseRateAdjust.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for SpotLapseRateAdjust class""" @@ -27,7 +27,6 @@ class Test_SpotLapseRateAdjust(IrisTest): - """Test class for the SpotLapseRateAdjust tests, setting up inputs.""" def setUp(self): @@ -136,9 +135,9 @@ def setUp(self): coord_name="height", ) - self.spot_temperature_nearest.attributes[ - "model_grid_hash" - ] = diagnostic_cube_hash + self.spot_temperature_nearest.attributes["model_grid_hash"] = ( + diagnostic_cube_hash + ) # This temperature cube is set up with the spot sites having obtained # their temperature values from the nearest minimum vertical @@ -162,7 +161,6 @@ def setUp(self): class Test_process(Test_SpotLapseRateAdjust): - """Tests the class process method.""" def test_basic(self): @@ -249,7 +247,7 @@ def test_xy_ordered_lapse_rate_cube(self): def test_probability_cube(self): """Ensure that the plugin exits with value error if the spot data cube - is in probability space. """ + is in probability space.""" diagnostic_cube_hash = create_coordinate_hash(self.lapse_rate_cube) data = np.ones((3, 3, 3), dtype=np.float32) diff --git a/improver_tests/spotdata/test_SpotManipulation.py b/improver_tests/spotdata/test_SpotManipulation.py index 2509af3aea..dd694c4367 100755 --- a/improver_tests/spotdata/test_SpotManipulation.py +++ b/improver_tests/spotdata/test_SpotManipulation.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for SpotManipulation class""" @@ -34,7 +34,7 @@ def gridded_variable(forecast_data): np.array([1.5], dtype=np.float32), standard_name="height", units="m" ) return set_up_variable_cube( - forecast_data, include_scalar_coords=[height_crd], attributes=ATTRIBUTES, + forecast_data, include_scalar_coords=[height_crd], attributes=ATTRIBUTES ) @@ -44,7 +44,7 @@ def spot_variable(forecast_data): np.array([1.5], dtype=np.float32), standard_name="height", units="m" ) return set_up_spot_variable_cube( - forecast_data, include_scalar_coords=[height_crd], attributes=ATTRIBUTES, + forecast_data, include_scalar_coords=[height_crd], attributes=ATTRIBUTES ) @@ -67,7 +67,7 @@ def gridded_percentiles(forecast_data): """Create a gridded percentile cube from which to extract spot forecasts.""" n_percentiles = forecast_data.shape[0] percentiles = np.linspace(20, 80, n_percentiles) - return set_up_percentile_cube(forecast_data, percentiles, attributes=ATTRIBUTES,) + return set_up_percentile_cube(forecast_data, percentiles, attributes=ATTRIBUTES) def spot_percentiles(forecast_data): @@ -75,7 +75,7 @@ def spot_percentiles(forecast_data): n_percentiles = forecast_data.shape[0] percentiles = np.linspace(20, 80, n_percentiles) return set_up_spot_percentile_cube( - forecast_data, percentiles, attributes=ATTRIBUTES, + forecast_data, percentiles, attributes=ATTRIBUTES ) @@ -83,7 +83,7 @@ def gridded_probabilities(forecast_data): """Create a gridded probability cube from which to extract spot forecasts.""" n_thresholds = forecast_data.shape[0] thresholds = np.linspace(273, 283, n_thresholds) - return set_up_probability_cube(forecast_data, thresholds, attributes=ATTRIBUTES,) + return set_up_probability_cube(forecast_data, thresholds, attributes=ATTRIBUTES) def spot_probabilities(forecast_data): @@ -91,7 +91,7 @@ def spot_probabilities(forecast_data): n_thresholds = forecast_data.shape[0] thresholds = np.linspace(273, 283, n_thresholds) return set_up_spot_probability_cube( - forecast_data, thresholds, attributes=ATTRIBUTES, + forecast_data, thresholds, attributes=ATTRIBUTES ) @@ -454,7 +454,7 @@ def test_neighbour_selection_method_setting(kwargs, expected): @pytest.mark.parametrize( - "neighbour_data", [np.array([[[1, 2, 3], [0, 0, 0], [5, 10, 15]]])], + "neighbour_data", [np.array([[[1, 2, 3], [0, 0, 0], [5, 10, 15]]])] ) def test_spot_subset_incomplete(neighbour_cube): """Test spot subsetting where the neighbour cube includes sites that are @@ -475,7 +475,7 @@ def test_spot_subset_incomplete(neighbour_cube): @pytest.mark.parametrize( - "neighbour_data", [np.array([[[1, 2, 3], [0, 0, 0], [5, 10, 15]]])], + "neighbour_data", [np.array([[[1, 2, 3], [0, 0, 0], [5, 10, 15]]])] ) def test_spot_unset_ids(neighbour_cube): """Test spot subsetting where the neighbour cube and forecast cube include @@ -500,7 +500,7 @@ def test_spot_unset_ids(neighbour_cube): @pytest.mark.parametrize( - "neighbour_data", [np.array([[[1, 2, 3], [0, 0, 0], [5, 10, 15]]])], + "neighbour_data", [np.array([[[1, 2, 3], [0, 0, 0], [5, 10, 15]]])] ) def test_spot_subset_coord_not_found(neighbour_cube): """Test exception raised for unknown subsetting coordinate.""" @@ -511,7 +511,7 @@ def test_spot_subset_coord_not_found(neighbour_cube): @pytest.mark.parametrize( - "neighbour_data", [np.array([[[1, 2, 3], [0, 0, 0], [5, 10, 15]]])], + "neighbour_data", [np.array([[[1, 2, 3], [0, 0, 0], [5, 10, 15]]])] ) def test_no_spots_returned(neighbour_cube): """Test exception raised if subsetting a spot forecast results in no @@ -533,7 +533,7 @@ def test_no_spots_returned(neighbour_cube): @pytest.mark.parametrize( - "neighbour_data", [np.array([[[1, 2, 3], [0, 0, 0], [5, 10, 15]]])], + "neighbour_data", [np.array([[[1, 2, 3], [0, 0, 0], [5, 10, 15]]])] ) def test_spot_subset_lapse_rate_exception(neighbour_cube): """Test exception raised if attempting to apply a lapse rate to an existing diff --git a/improver_tests/spotdata/test_build_spotdata_cube.py b/improver_tests/spotdata/test_build_spotdata_cube.py index 45770f1953..9d87bfbb28 100755 --- a/improver_tests/spotdata/test_build_spotdata_cube.py +++ b/improver_tests/spotdata/test_build_spotdata_cube.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the build_spotdata_cube function""" @@ -100,9 +100,7 @@ def test_site_list_with_unique_id_coordinate_missing_name(self): data = np.array([1.6, 1.3, 1.4, 1.1]) msg = "A unique_site_id_key must be provided" with self.assertRaisesRegex(ValueError, msg): - build_spotdata_cube( - data, *self.args, unique_site_id=self.unique_site_id, - ) + build_spotdata_cube(data, *self.args, unique_site_id=self.unique_site_id) def test_neighbour_method(self): """Test output where neighbour_methods is populated""" @@ -129,7 +127,7 @@ def test_grid_attributes(self): ) result = build_spotdata_cube( - data, *self.args, grid_attributes=self.grid_attributes, + data, *self.args, grid_attributes=self.grid_attributes ) self.assertArrayAlmostEqual(result.data, data) diff --git a/improver_tests/spotdata/test_utilities.py b/improver_tests/spotdata/test_utilities.py index ead5ed7cb1..9bdd3c27f6 100644 --- a/improver_tests/spotdata/test_utilities.py +++ b/improver_tests/spotdata/test_utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for spot data utilities""" diff --git a/improver_tests/standardise/test_StandardiseMetadata.py b/improver_tests/standardise/test_StandardiseMetadata.py index 47e880071d..a54f45113b 100644 --- a/improver_tests/standardise/test_StandardiseMetadata.py +++ b/improver_tests/standardise/test_StandardiseMetadata.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the standardise.StandardiseMetadata plugin.""" diff --git a/improver_tests/synthetic_data/test_generate_metadata.py b/improver_tests/synthetic_data/test_generate_metadata.py index 06ad9bdbec..ba8c0e7d17 100644 --- a/improver_tests/synthetic_data/test_generate_metadata.py +++ b/improver_tests/synthetic_data/test_generate_metadata.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for metadata cube generation.""" @@ -37,7 +37,7 @@ "grid_spacing": 0.02, "units": "degrees", "coord_system": GLOBAL_GRID_CCRS, - }, + } }, "equalarea": { **{ @@ -46,21 +46,21 @@ "grid_spacing": 2000, "units": "metres", "coord_system": STANDARD_GRID_CCRS, - }, + } }, } def _check_cube_shape_different(cube): - """ Asserts that cube shape has been changed from default but name, units and - attributes are unchanged """ + """Asserts that cube shape has been changed from default but name, units and + attributes are unchanged""" default_cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS) assert cube.shape != default_cube.shape assert iris.util.describe_diff(cube, default_cube) is None def test_default(): - """ Tests default metadata cube generated """ + """Tests default metadata cube generated""" cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS) assert cube.name() == NAME_DEFAULT @@ -95,8 +95,8 @@ def test_default(): def test_set_name_no_units(): - """ Tests cube generated with specified name, automatically setting units, and the - rest of the values set as default values """ + """Tests cube generated with specified name, automatically setting units, and the + rest of the values set as default values""" name = "air_pressure" cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, name=name) @@ -114,7 +114,7 @@ def test_set_name_no_units(): def test_set_name_units(): - """ Tests cube generated with specified name and units, and the rest of the values + """Tests cube generated with specified name and units, and the rest of the values set as default values""" name = "air_pressure" units = "pascal" @@ -134,8 +134,8 @@ def test_set_name_units(): def test_name_unknown_no_units(): - """ Tests error raised if output variable name not in iris.std_names.STD_NAMES and - no unit provided """ + """Tests error raised if output variable name not in iris.std_names.STD_NAMES and + no unit provided""" name = "temperature" with pytest.raises(ValueError, match=name): @@ -143,11 +143,11 @@ def test_name_unknown_no_units(): def test_name_unknown_with_units(): - """ Tests cube generated with specified name which isn't a CF standard name, + """Tests cube generated with specified name which isn't a CF standard name, specified units, and the rest of the values set as default values""" name = "lapse_rate" units = "K m-1" - cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, name=name, units=units,) + cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, name=name, units=units) # "lapse_rate" not CF standard so standard_name expected None assert cube.name() == name @@ -166,8 +166,8 @@ def test_name_unknown_with_units(): @pytest.mark.parametrize("spatial_grid", ["latlon", "equalarea"]) def test_set_spatial_grid(spatial_grid): - """ Tests different spatial grids generates cubes with default values for that - spatial grid """ + """Tests different spatial grids generates cubes with default values for that + spatial grid""" cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, spatial_grid=spatial_grid) expected_spatial_grid_attributes = SPATIAL_GRID_ATTRIBUTE_DEFAULTS[spatial_grid] @@ -211,7 +211,7 @@ def test_set_spatial_grid(spatial_grid): def test_spatial_grid_not_supported(): - """ Tests error raised if spatial grid not supported """ + """Tests error raised if spatial grid not supported""" spatial_grid = "other" with pytest.raises(ValueError, match=spatial_grid): @@ -219,8 +219,8 @@ def test_spatial_grid_not_supported(): def test_set_time(): - """ Tests cube generated with specified time and the rest of the values set as - default values """ + """Tests cube generated with specified time and the rest of the values set as + default values""" time = datetime(2020, 1, 1, 0, 0) cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, time=time) @@ -237,10 +237,10 @@ def test_set_time(): def test_set_time_period(): - """ Tests cube generated with time bounds calculated using specified time_period - and the rest of the values set as default values """ + """Tests cube generated with time bounds calculated using specified time_period + and the rest of the values set as default values""" time_period = 150 - cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, time_period=time_period,) + cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, time_period=time_period) assert iris_time_to_datetime(cube.coord("time"))[0] == TIME_DEFAULT assert cube.coord("forecast_period").points == FORECAST_PERIOD_DEFAULT @@ -259,10 +259,10 @@ def test_set_time_period(): def test_set_frt(): - """ Tests cube generated with specified forecast reference time and the rest of the - values set as default values """ + """Tests cube generated with specified forecast reference time and the rest of the + values set as default values""" frt = datetime(2017, 1, 1, 0, 0) - cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, frt=frt,) + cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, frt=frt) assert iris_time_to_datetime(cube.coord("forecast_reference_time"))[0] == frt assert cube.coord("forecast_period").points > 0 @@ -280,10 +280,10 @@ def test_set_frt(): def test_set_ensemble_members(): - """ Tests cube generated with specified number of ensemble members """ + """Tests cube generated with specified number of ensemble members""" ensemble_members = 4 cube = generate_metadata( - MANDATORY_ATTRIBUTE_DEFAULTS, ensemble_members=ensemble_members, + MANDATORY_ATTRIBUTE_DEFAULTS, ensemble_members=ensemble_members ) assert cube.ndim == 3 @@ -296,9 +296,9 @@ def test_set_ensemble_members(): @pytest.mark.parametrize("ensemble_members", (0, 1)) def test_disable_ensemble(ensemble_members): - """ Tests cube generated without realizations dimension """ + """Tests cube generated without realizations dimension""" cube = generate_metadata( - MANDATORY_ATTRIBUTE_DEFAULTS, ensemble_members=ensemble_members, + MANDATORY_ATTRIBUTE_DEFAULTS, ensemble_members=ensemble_members ) assert cube.ndim == 2 @@ -316,11 +316,11 @@ def test_disable_ensemble(ensemble_members): "cube_type", ("variable", "percentile", "probability", "other") ) @pytest.mark.parametrize( - "spp__relative_to_threshold", ("greater_than", "less_than", None), + "spp__relative_to_threshold", ("greater_than", "less_than", None) ) def test_leading_dimension(cube_type, spp__relative_to_threshold): - """ Tests cube generated with leading dimension specified using percentile and - probability flags, and different values for spp__relative_to_threshold """ + """Tests cube generated with leading dimension specified using percentile and + probability flags, and different values for spp__relative_to_threshold""" if cube_type == "other": # Tests that error is raised when cube type isn't supported msg = ( @@ -389,8 +389,8 @@ def test_leading_dimension(cube_type, spp__relative_to_threshold): def test_set_attributes(): - """ Tests cube generated with specified attributes and the rest of the values set - as default values """ + """Tests cube generated with specified attributes and the rest of the values set + as default values""" attributes = {"test_attribute": "kittens"} cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, attributes=attributes) expected_attributes = MANDATORY_ATTRIBUTE_DEFAULTS.copy() @@ -420,8 +420,8 @@ def test_missing_mandatory_attributes(use_attributes): def test_set_grid_spacing(): - """ Tests cube generated with specified grid_spacing and the rest of the values set - as default values """ + """Tests cube generated with specified grid_spacing and the rest of the values set + as default values""" grid_spacing = 5 cube = generate_metadata( MANDATORY_ATTRIBUTE_DEFAULTS, @@ -443,10 +443,10 @@ def test_set_grid_spacing(): def test_set_domain_corner(): - """ Tests cube generated with specified domain corner and the rest of the values - set as default values """ + """Tests cube generated with specified domain corner and the rest of the values + set as default values""" domain_corner = (0, 0) - cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, domain_corner=domain_corner,) + cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, domain_corner=domain_corner) assert cube.coord(axis="y").points[0] == domain_corner[0] assert cube.coord(axis="x").points[0] == domain_corner[1] @@ -470,7 +470,7 @@ def test_domain_corner_incorrect_length(domain_corner): def test_set_npoints(): - """ Tests cube generated with specified npoints """ + """Tests cube generated with specified npoints""" npoints = 500 cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, npoints=npoints) @@ -481,7 +481,7 @@ def test_set_npoints(): def test_set_height_levels(): - """ Tests cube generated with specified height levels as an additional dimension """ + """Tests cube generated with specified height levels as an additional dimension""" height_levels = [1.5, 3.0, 4.5] cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, height_levels=height_levels) @@ -508,13 +508,13 @@ def test_set_height_levels(): def test_set_height_levels_single_value(): - """ Tests cube generated with single height level is demoted from dimension to - scalar coordinate """ + """Tests cube generated with single height level is demoted from dimension to + scalar coordinate""" height_levels = [1.5] cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS, height_levels=height_levels) assert cube.ndim == 3 - assert cube.shape == (ENSEMBLE_MEMBERS_DEFAULT, NPOINTS_DEFAULT, NPOINTS_DEFAULT,) + assert cube.shape == (ENSEMBLE_MEMBERS_DEFAULT, NPOINTS_DEFAULT, NPOINTS_DEFAULT) expected_spatial_grid_attributes = SPATIAL_GRID_ATTRIBUTE_DEFAULTS[ SPATIAL_GRID_DEFAULT @@ -533,7 +533,7 @@ def test_set_height_levels_single_value(): def test_disable_ensemble_set_height_levels(): - """ Tests cube generated without realizations dimension but with height dimension """ + """Tests cube generated without realizations dimension but with height dimension""" ensemble_members = 1 height_levels = [1.5, 3.0, 4.5] cube = generate_metadata( @@ -543,7 +543,7 @@ def test_disable_ensemble_set_height_levels(): ) assert cube.ndim == 3 - assert cube.shape == (len(height_levels), NPOINTS_DEFAULT, NPOINTS_DEFAULT,) + assert cube.shape == (len(height_levels), NPOINTS_DEFAULT, NPOINTS_DEFAULT) expected_spatial_grid_attributes = SPATIAL_GRID_ATTRIBUTE_DEFAULTS[ SPATIAL_GRID_DEFAULT diff --git a/improver_tests/synthetic_data/test_set_up_test_cubes.py b/improver_tests/synthetic_data/test_set_up_test_cubes.py index d6cf759035..9f6bbfd92b 100644 --- a/improver_tests/synthetic_data/test_set_up_test_cubes.py +++ b/improver_tests/synthetic_data/test_set_up_test_cubes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for cube setup functions @@ -226,8 +226,7 @@ def test_error_negative_fp(self): ) def test_error_no_reference_time(self): - """Test an error is raised if neither a forecast reference time nor blend time are supplied - """ + """Test an error is raised if neither a forecast reference time nor blend time are supplied""" msg = ( "Cannot create forecast_period without either a forecast reference time " "or a blend time." @@ -443,7 +442,7 @@ def test_error_unmatched_height_levels(self): ) def test_realizations_from_data_height_levels(self): - """ Tests realizations from data and height coordinates added """ + """Tests realizations from data and height coordinates added""" height_levels = [1.5, 3.0, 4.5] data_4d = np.array([self.data_3d, self.data_3d]) result = set_up_variable_cube(data_4d, height_levels=height_levels) @@ -456,7 +455,7 @@ def test_realizations_from_data_height_levels(self): self.assertEqual(result.coord_dims("longitude"), (3,)) def test_realizations_height_levels(self): - """ Tests realizations and height coordinates added """ + """Tests realizations and height coordinates added""" realizations = [0, 3] height_levels = [1.5, 3.0, 4.5] data_4d = np.array([self.data_3d, self.data_3d]) @@ -474,7 +473,7 @@ def test_realizations_height_levels(self): self.assertEqual(result.coord_dims("longitude"), (3,)) def test_error_no_height_levels_4d_data(self): - """ Tests error is raised if 4d data provided but not height_levels """ + """Tests error is raised if 4d data provided but not height_levels""" data_4d = np.array([self.data_3d, self.data_3d]) msg = "Height levels must be provided if data has > 3 dimensions." with self.assertRaisesRegex(ValueError, msg): @@ -791,7 +790,7 @@ def test_error_unmatched_height_levels(self): ) def test_realizations_from_data_height_levels(self): - """ Tests realizations from data and height coordinates added """ + """Tests realizations from data and height coordinates added""" height_levels = [1.5, 3.0, 4.5] data_3d = np.array([self.data_2d, self.data_2d]) expected_site_dim = 2 @@ -805,7 +804,7 @@ def test_realizations_from_data_height_levels(self): self.assertEqual(result.coord_dims(crd)[0], expected_site_dim) def test_realizations_height_levels(self): - """ Tests realizations and height coordinates added """ + """Tests realizations and height coordinates added""" realizations = [0, 3] height_levels = [1.5, 3.0, 4.5] data_3d = np.array([self.data_2d, self.data_2d]) @@ -824,7 +823,7 @@ def test_realizations_height_levels(self): self.assertEqual(result.coord_dims(crd)[0], expected_site_dim) def test_error_no_height_levels_3d_data(self): - """ Tests error is raised if 3d data provided but not height_levels """ + """Tests error is raised if 3d data provided but not height_levels""" data_3d = np.array([self.data_2d, self.data_2d]) msg = "Height levels must be provided if data has > 2 dimensions." with self.assertRaisesRegex(ValueError, msg): @@ -908,7 +907,7 @@ def test_no_unique_id_key_exception(self): msg = "A unique_site_id_key must be provided if a unique_site_id" with self.assertRaisesRegex(ValueError, msg): set_up_spot_variable_cube( - self.data, wmo_ids=wmo_ids, unique_site_id=unique_ids, + self.data, wmo_ids=wmo_ids, unique_site_id=unique_ids ) @@ -1018,7 +1017,7 @@ def test_defaults(self): self.assertEqual(thresh_coord.units, "K") self.assertEqual(len(thresh_coord.attributes), 1) self.assertEqual( - thresh_coord.attributes["spp__relative_to_threshold"], "greater_than", + thresh_coord.attributes["spp__relative_to_threshold"], "greater_than" ) check_mandatory_standards(result) @@ -1063,7 +1062,7 @@ def test_single_threshold(self): def test_vicinity_cube(self): """Test an in-vicinity cube gets the correct name and threshold coordinate""" result = set_up_probability_cube( - self.data, self.thresholds, variable_name="air_temperature_in_vicinity", + self.data, self.thresholds, variable_name="air_temperature_in_vicinity" ) thresh_coord = find_threshold_coordinate(result) self.assertEqual( @@ -1100,7 +1099,7 @@ def test_defaults(self): self.assertEqual(thresh_coord.units, "K") self.assertEqual(len(thresh_coord.attributes), 1) self.assertEqual( - thresh_coord.attributes["spp__relative_to_threshold"], "greater_than", + thresh_coord.attributes["spp__relative_to_threshold"], "greater_than" ) check_mandatory_standards(result) diff --git a/improver_tests/synthetic_data/test_utilities.py b/improver_tests/synthetic_data/test_utilities.py index 759bfc7474..fe9f9db68e 100644 --- a/improver_tests/synthetic_data/test_utilities.py +++ b/improver_tests/synthetic_data/test_utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for synthetic data utilities. @@ -22,8 +22,8 @@ ], ) def test_get_leading_dimension(coord_data, expected_cube_type): - """ Tests leading dimension data extracted from dictionary and the correct cube - type is assigned, or if more than one leading dimension present raises an error """ + """Tests leading dimension data extracted from dictionary and the correct cube + type is assigned, or if more than one leading dimension present raises an error""" if expected_cube_type is None: msg = "Only one" with pytest.raises(ValueError, match=msg): @@ -47,7 +47,7 @@ def test_get_leading_dimension(coord_data, expected_cube_type): ], ) def test_get_height_levels(coord_data, expected_pressure): - """ Tests height level data extracted successfully and pressure flag set correctly """ + """Tests height level data extracted successfully and pressure flag set correctly""" dimension_key = list(coord_data)[0] if dimension_key == "realizations": diff --git a/improver_tests/test_PostProcessingPlugin.py b/improver_tests/test_PostProcessingPlugin.py index e7c4c7b962..b46a62fcc3 100644 --- a/improver_tests/test_PostProcessingPlugin.py +++ b/improver_tests/test_PostProcessingPlugin.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the improver.PostProcessingPlugin abstract base class""" diff --git a/improver_tests/test_api.py b/improver_tests/test_api.py index acdc5d3cfc..d97d0cf868 100644 --- a/improver_tests/test_api.py +++ b/improver_tests/test_api.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. import pytest diff --git a/improver_tests/test_source_code.py b/improver_tests/test_source_code.py deleted file mode 100644 index 562071db93..0000000000 --- a/improver_tests/test_source_code.py +++ /dev/null @@ -1,56 +0,0 @@ -# (C) Crown copyright, Met Office. All rights reserved. -# -# This file is part of IMPROVER and is released under a BSD 3-Clause license. -# See LICENSE in the root of the repository for full licensing details. -"""Checks on source code files.""" - -from pathlib import Path - -TOP_LEVEL_DIR = (Path(__file__).parent / "..").resolve() -DIRECTORIES_COVERED = [TOP_LEVEL_DIR / "improver", TOP_LEVEL_DIR / "improver_tests"] - - -def self_licence(): - """Collect licence text from this file""" - self_lines = Path(__file__).read_text().splitlines() - licence_lines = list() - for line in self_lines: - if not line.startswith("#"): - break - licence_lines.append(line) - licence = "\n".join(licence_lines) - return licence - - -def test_py_licence(): - """ - Check that non-empty python files contain 3-clause BSD licence text - """ - failed_files = [] - licence_text = self_licence() - for directory in DIRECTORIES_COVERED: - for file in directory.glob("**/*.py"): - contents = file.read_text() - # skip zero-byte empty files such as __init__.py - if len(contents) > 0 and licence_text not in contents: - failed_files.append(str(file)) - assert len(failed_files) == 0, "\n".join(failed_files) - - -def test_init_files_exist(): - """Check for missing __init__.py files.""" - failed_directories = [] - for directory in DIRECTORIES_COVERED: - for path in directory.glob("**"): - if not path.is_dir(): - continue - # ignore hidden directories and their sub-directories - if any([part.startswith(".") for part in path.parts]): - continue - # in-place running will produce pycache directories, these should be ignored - if path.name == "__pycache__": - continue - expected_init = path / "__init__.py" - if not expected_init.exists(): - failed_directories.append(str(path)) - assert len(failed_directories) == 0, "\n".join(failed_directories) diff --git a/improver_tests/threshold/conftest.py b/improver_tests/threshold/conftest.py index 4fec72d644..40ccb360bd 100644 --- a/improver_tests/threshold/conftest.py +++ b/improver_tests/threshold/conftest.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Fixtures for threshold tests""" @@ -262,8 +262,5 @@ def landmask(mask: np.ndarray) -> Cube: A land mask cube. """ return set_up_variable_cube( - mask.astype(np.int8), - name="land_binary_mask", - units=1, - spatial_grid="equalarea", + mask.astype(np.int8), name="land_binary_mask", units=1, spatial_grid="equalarea" ) diff --git a/improver_tests/threshold/test_LatitudeDependentThreshold.py b/improver_tests/threshold/test_LatitudeDependentThreshold.py index 3248606764..318c5a2c79 100644 --- a/improver_tests/threshold/test_LatitudeDependentThreshold.py +++ b/improver_tests/threshold/test_LatitudeDependentThreshold.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the threshold.LatitudeThreshold plugin.""" - import unittest import numpy as np @@ -76,7 +75,6 @@ def test_value_error(self): class Test_process(IrisTest): - """Test the thresholding plugin.""" def setUp(self): diff --git a/improver_tests/threshold/test_Threshold.py b/improver_tests/threshold/test_Threshold.py index ba6bbf0b15..5fbeb56d93 100644 --- a/improver_tests/threshold/test_Threshold.py +++ b/improver_tests/threshold/test_Threshold.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the threshold.Threshold plugin.""" - import numpy as np import pytest from iris.coords import CellMethod, DimCoord @@ -82,7 +81,7 @@ "threshold_config and threshold_values are mutually exclusive arguments", ), # at least one set means of defining the thresholds must be used. - ({}, "One of threshold_config or threshold_values must be provided.",), + ({}, "One of threshold_config or threshold_values must be provided."), ], ) def test_init(kwargs, exception): @@ -175,7 +174,7 @@ def test_threshold_metadata( threshold_values, threshold_units, ): - """"Test that the metadata relating to the thresholding options, on both + """ "Test that the metadata relating to the thresholding options, on both the cube and threshold coordinate is as expected. Many combinations of options are tested, including: diff --git a/improver_tests/utilities/common_input_handle/test_as_cube.py b/improver_tests/utilities/common_input_handle/test_as_cube.py index 9a8959f01e..a6c09f98fa 100644 --- a/improver_tests/utilities/common_input_handle/test_as_cube.py +++ b/improver_tests/utilities/common_input_handle/test_as_cube.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the as_cube function.""" + from unittest.mock import patch, sentinel import pytest diff --git a/improver_tests/utilities/common_input_handle/test_as_cubelist.py b/improver_tests/utilities/common_input_handle/test_as_cubelist.py index 218dfe626c..ad3a42720d 100644 --- a/improver_tests/utilities/common_input_handle/test_as_cubelist.py +++ b/improver_tests/utilities/common_input_handle/test_as_cubelist.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the as_cubelist function.""" + from itertools import permutations import pytest diff --git a/improver_tests/utilities/complex_conversion/__init__.py b/improver_tests/utilities/complex_conversion/__init__.py index b0565c9d7a..c82335cc4b 100644 --- a/improver_tests/utilities/complex_conversion/__init__.py +++ b/improver_tests/utilities/complex_conversion/__init__.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. import numpy as np diff --git a/improver_tests/utilities/complex_conversion/test_complex_to_deg.py b/improver_tests/utilities/complex_conversion/test_complex_to_deg.py index f335f4652f..ff07d80954 100644 --- a/improver_tests/utilities/complex_conversion/test_complex_to_deg.py +++ b/improver_tests/utilities/complex_conversion/test_complex_to_deg.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. import numpy as np import pytest diff --git a/improver_tests/utilities/complex_conversion/test_deg_to_complex.py b/improver_tests/utilities/complex_conversion/test_deg_to_complex.py index bc0b04bf8b..ea5681bd3b 100644 --- a/improver_tests/utilities/complex_conversion/test_deg_to_complex.py +++ b/improver_tests/utilities/complex_conversion/test_deg_to_complex.py @@ -1,9 +1,9 @@ import numpy as np from numpy.testing import assert_array_almost_equal -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. from improver.utilities.complex_conversion import deg_to_complex diff --git a/improver_tests/utilities/complex_conversion/test_integration.py b/improver_tests/utilities/complex_conversion/test_integration.py index 86b6da5202..14889f20b5 100644 --- a/improver_tests/utilities/complex_conversion/test_integration.py +++ b/improver_tests/utilities/complex_conversion/test_integration.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. import numpy as np from numpy.testing import assert_array_almost_equal diff --git a/improver_tests/utilities/copy_attributes/test_CopyAttributes.py b/improver_tests/utilities/copy_attributes/test_CopyAttributes.py index bccaf9bf54..5b3065ea2f 100644 --- a/improver_tests/utilities/copy_attributes/test_CopyAttributes.py +++ b/improver_tests/utilities/copy_attributes/test_CopyAttributes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. from unittest.mock import patch, sentinel diff --git a/improver_tests/utilities/cube_extraction/test_ExtractLevel.py b/improver_tests/utilities/cube_extraction/test_ExtractLevel.py index a8dac2f92d..3f078caabc 100644 --- a/improver_tests/utilities/cube_extraction/test_ExtractLevel.py +++ b/improver_tests/utilities/cube_extraction/test_ExtractLevel.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the ExtractLevel plugin""" + from collections.abc import Iterable import numpy as np @@ -184,9 +185,9 @@ def test_basic( expected_data = expected_data[0] if least_significant_digit: - temperature_on_levels.attributes[ - "least_significant_digit" - ] = least_significant_digit + temperature_on_levels.attributes["least_significant_digit"] = ( + least_significant_digit + ) result = ExtractLevel( value_of_level=temperature, positive_correlation=positive_correlation @@ -214,9 +215,7 @@ def test_basic( ), ) @pytest.mark.parametrize("special_value", (np.nan, True, np.inf)) -def test_only_one_point( - temperature_on_pressure_levels, index, expected, special_value, -): +def test_only_one_point(temperature_on_pressure_levels, index, expected, special_value): """Tests the ExtractLevel plugin with the unusual case that only one layer has a valid value. """ diff --git a/improver_tests/utilities/cube_extraction/test_ExtractSubCube.py b/improver_tests/utilities/cube_extraction/test_ExtractSubCube.py index e61b07f83f..d9c29a8010 100644 --- a/improver_tests/utilities/cube_extraction/test_ExtractSubCube.py +++ b/improver_tests/utilities/cube_extraction/test_ExtractSubCube.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. from unittest.mock import patch, sentinel diff --git a/improver_tests/utilities/cube_extraction/test_cube_extraction.py b/improver_tests/utilities/cube_extraction/test_cube_extraction.py index 5bc382a180..75ed1f2dd2 100644 --- a/improver_tests/utilities/cube_extraction/test_cube_extraction.py +++ b/improver_tests/utilities/cube_extraction/test_cube_extraction.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Unit tests for cube extraction utilities """ +"""Unit tests for cube extraction utilities""" import collections import unittest @@ -168,10 +168,10 @@ def test_with_float_type_multiple_values(self): class Test_parse_constraint_list(IrisTest): - """ Test function to parse constraints and units into dictionaries """ + """Test function to parse constraints and units into dictionaries""" def setUp(self): - """ Set up some constraints to parse """ + """Set up some constraints to parse""" self.constraints = ["percentile=10", "threshold=0.1"] self.units = ["none", "mm h-1"] self.p_crd = iris.coords.AuxCoord( @@ -182,7 +182,7 @@ def setUp(self): ) def test_basic_no_units(self): - """ Test simple key-value splitting with no units """ + """Test simple key-value splitting with no units""" result, udict, _, _ = parse_constraint_list(self.constraints) self.assertIsInstance(result, iris.Constraint) self.assertCountEqual( @@ -198,7 +198,7 @@ def test_basic_no_units(self): self.assertFalse(udict) def test_whitespace(self): - """ Test constraint parsing with padding whitespace """ + """Test constraint parsing with padding whitespace""" constraints = ["percentile = 10", "threshold = 0.1"] result, _, _, _ = parse_constraint_list(constraints) cdict = result._coord_values @@ -208,7 +208,7 @@ def test_whitespace(self): self.assertTrue(cdict["threshold"](self.t_crd.cell(0))) def test_string_constraint(self): - """ Test that a string constraint results in a simple iris constraint, + """Test that a string constraint results in a simple iris constraint, not a lambda function. This is created via the literal_eval ValueError. """ constraints = ["percentile=kittens"] @@ -219,27 +219,27 @@ def test_string_constraint(self): self.assertIsInstance(cdict, dict) def test_some_units(self): - """ Test units list containing "None" elements is correctly parsed """ + """Test units list containing "None" elements is correctly parsed""" _, udict, _, _ = parse_constraint_list(self.constraints, units=self.units) self.assertEqual(udict["threshold"], "mm h-1") self.assertNotIn("percentile", udict.keys()) def test_unmatched_units(self): - """ Test for ValueError if units list does not match constraints """ + """Test for ValueError if units list does not match constraints""" units = ["mm h-1"] msg = "units list must match constraints" with self.assertRaisesRegex(ValueError, msg): parse_constraint_list(self.constraints, units=units) def test_list_constraint(self): - """ Test that a list of constraints is parsed correctly """ + """Test that a list of constraints is parsed correctly""" constraints = ["threshold=[0.1,1.0]"] result, _, _, _ = parse_constraint_list(constraints) cdict = result._coord_values self.assertTrue(islambda(cdict["threshold"])) def test_range_constraint(self): - """ Test that a constraint passed in as a range is parsed correctly """ + """Test that a constraint passed in as a range is parsed correctly""" # create input cube precip_cube = set_up_precip_probability_cube() threshold_coord = find_threshold_coordinate(precip_cube).name() @@ -257,14 +257,14 @@ def test_range_constraint(self): ) def test_longitude_constraint(self): - """ Test that the longitude constraint is parsed correctly """ + """Test that the longitude constraint is parsed correctly""" constraint = ["longitude=[0:20:2]"] _, _, longitude_constraint, thinning_dict = parse_constraint_list(constraint) self.assertEqual(longitude_constraint, [0, 20]) self.assertEqual(thinning_dict, {"longitude": 2}) def test_longitude_constraint_whitespace(self): - """ Test that the longitude constraint is parsed correctly with whitespace """ + """Test that the longitude constraint is parsed correctly with whitespace""" constraint = ["longitude = [ 0 : 20 : 2 ]"] _, _, longitude_constraint, thinning_dict = parse_constraint_list(constraint) self.assertEqual(longitude_constraint, [0, 20]) @@ -272,10 +272,10 @@ def test_longitude_constraint_whitespace(self): class Test_apply_extraction(IrisTest): - """ Test function to extract subcube according to constraints """ + """Test function to extract subcube according to constraints""" def setUp(self): - """ Set up temporary input cube """ + """Set up temporary input cube""" self.precip_cube = set_up_precip_probability_cube() self.threshold_coord = find_threshold_coordinate(self.precip_cube).name() self.uk_gridded_cube = set_up_uk_gridded_cube() @@ -283,7 +283,7 @@ def setUp(self): self.units_dict = {self.threshold_coord: "mm h-1"} def test_basic_no_units(self): - """ Test cube extraction for single constraint without units """ + """Test cube extraction for single constraint without units""" constraint_dict = {"name": "probability_of_precipitation_rate_above_threshold"} constr = iris.Constraint(**constraint_dict) cube = apply_extraction(self.precip_cube, constr) @@ -292,7 +292,7 @@ def test_basic_no_units(self): self.assertArrayEqual(cube.data, reference_data) def test_basic_with_units(self): - """ Test cube extraction for single constraint with units """ + """Test cube extraction for single constraint with units""" constraint_dict = { self.threshold_coord: lambda cell: any(np.isclose(cell.point, [0.1])) } @@ -304,8 +304,8 @@ def test_basic_with_units(self): self.assertArrayEqual(cube.data, reference_data) def test_basic_without_reconverting_units(self): - """ Test cube extraction for single constraint with units, - where the coordinates are not reconverted into the original units.""" + """Test cube extraction for single constraint with units, + where the coordinates are not reconverted into the original units.""" constraint_dict = { self.threshold_coord: lambda cell: any(np.isclose(cell.point, [0.1])) } @@ -319,7 +319,7 @@ def test_basic_without_reconverting_units(self): self.assertArrayEqual(cube.data, reference_data) def test_multiple_constraints_with_units(self): - """ Test behaviour with a list of constraints and units """ + """Test behaviour with a list of constraints and units""" constraint_dict = { "name": "probability_of_precipitation_rate_above_threshold", self.threshold_coord: lambda cell: any(np.isclose(cell.point, [0.03])), @@ -331,17 +331,17 @@ def test_multiple_constraints_with_units(self): self.assertArrayEqual(cube.data, reference_data) def test_error_non_coord_units(self): - """ Test error raised if units are provided for a non-coordinate - constraint """ + """Test error raised if units are provided for a non-coordinate + constraint""" constraint_dict = {"name": "probability_of_precipitation_rate_above_threshold"} units_dict = {"name": "1"} with self.assertRaises(CoordinateNotFoundError): apply_extraction(self.precip_cube, constraint_dict, units_dict) def test_allow_none(self): - """ Test function returns None rather than raising an error where + """Test function returns None rather than raising an error where no subcubes match the required constraints, when unit conversion is - required """ + required""" constraint_dict = { "name": "probability_of_precipitation_rate_above_threshold", self.threshold_coord: 5, @@ -351,7 +351,7 @@ def test_allow_none(self): self.assertFalse(cube) def test_list_constraints(self): - """ Test that a list of constraints behaves correctly """ + """Test that a list of constraints behaves correctly""" constraint_dict = { self.threshold_coord: lambda cell: any(np.isclose(cell.point, [0.1, 1.0])) } @@ -361,7 +361,7 @@ def test_list_constraints(self): self.assertArrayEqual(cube.data, reference_data) def test_range_constraints(self): - """ Test that a list of constraints behaves correctly. This includes + """Test that a list of constraints behaves correctly. This includes converting the units to the units that the constraints is defined in.""" lower_bound = 0.03 - 1.0e-7 @@ -375,7 +375,7 @@ def test_range_constraints(self): self.assertArrayEqual(cube.data, reference_data) def test_subset_uk_grid(self): - """ Test subsetting a gridded cube. """ + """Test subsetting a gridded cube.""" expected_data = np.array( [ [27.0, 28.0, 29.0, 30.0], @@ -403,7 +403,7 @@ def test_subset_uk_grid(self): self.assertArrayAlmostEqual(result.coord(coord).points, expected_points) def test_subset_global_grid(self): - """ Extract subset of global lat-lon grid """ + """Extract subset of global lat-lon grid""" lower_bound = 42 - 1.0e-7 upper_bound = 52 + 1.0e-7 constraint_dict = { @@ -464,7 +464,7 @@ class Test_extract_subcube(IrisTest): applied.""" def setUp(self): - """ Set up temporary input cube """ + """Set up temporary input cube""" self.precip_cube = set_up_precip_probability_cube() self.global_gridded_cube = set_up_global_gridded_cube() @@ -541,7 +541,7 @@ def test_single_threshold_use_original_units(self): ) def test_thin_global_gridded_cube(self): - """ Subsets a grid from a global grid and thins the data""" + """Subsets a grid from a global grid and thins the data""" expected_result = np.array([[1.0, 4.0], [17.0, 20.0]]) result = extract_subcube( self.global_gridded_cube, ["latitude=[42:52:2]", "longitude=[0:7:3]"] @@ -555,7 +555,7 @@ def test_thin_global_gridded_cube(self): ) def test_thin_longitude_global_gridded_cube(self): - """ Subsets a grid from a global grid and thins the data""" + """Subsets a grid from a global grid and thins the data""" expected_result = np.array( [ [1.0, 4.0], @@ -565,7 +565,7 @@ def test_thin_longitude_global_gridded_cube(self): [33.0, 36.0], [41.0, 44.0], [49.0, 52.0], - ], + ] ) result = extract_subcube(self.global_gridded_cube, ["longitude=[0:7:3]"]) self.assertArrayAlmostEqual(result.data, expected_result) diff --git a/improver_tests/utilities/cube_manipulation/test_MergeCubes.py b/improver_tests/utilities/cube_manipulation/test_MergeCubes.py index 8585e92231..0052513834 100644 --- a/improver_tests/utilities/cube_manipulation/test_MergeCubes.py +++ b/improver_tests/utilities/cube_manipulation/test_MergeCubes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the "cube_manipulation.MergeCubes" plugin. diff --git a/improver_tests/utilities/cube_manipulation/test_add_coordinate_to_cube.py b/improver_tests/utilities/cube_manipulation/test_add_coordinate_to_cube.py index 940e69de86..2e6b6cc811 100644 --- a/improver_tests/utilities/cube_manipulation/test_add_coordinate_to_cube.py +++ b/improver_tests/utilities/cube_manipulation/test_add_coordinate_to_cube.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the function "cube_manipulation.add_coordinate_to_cube".""" @@ -14,10 +14,7 @@ from improver.synthetic_data.set_up_test_cubes import set_up_variable_cube from improver.utilities.cube_manipulation import add_coordinate_to_cube -ATTRIBUTES = { - "title": "Test forecast", - "source": "IMPROVER", -} +ATTRIBUTES = {"title": "Test forecast", "source": "IMPROVER"} @pytest.fixture diff --git a/improver_tests/utilities/cube_manipulation/test_clip_cube_data.py b/improver_tests/utilities/cube_manipulation/test_clip_cube_data.py index 2b28c61cb6..9430083a80 100644 --- a/improver_tests/utilities/cube_manipulation/test_clip_cube_data.py +++ b/improver_tests/utilities/cube_manipulation/test_clip_cube_data.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the function "cube_manipulation.clip_cube_data". diff --git a/improver_tests/utilities/cube_manipulation/test_collapse_realizations.py b/improver_tests/utilities/cube_manipulation/test_collapse_realizations.py index 95d9fd2829..d611920670 100644 --- a/improver_tests/utilities/cube_manipulation/test_collapse_realizations.py +++ b/improver_tests/utilities/cube_manipulation/test_collapse_realizations.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the function collapse_realizations. diff --git a/improver_tests/utilities/cube_manipulation/test_collapsed.py b/improver_tests/utilities/cube_manipulation/test_collapsed.py index c1e312dd64..ba09b17dab 100644 --- a/improver_tests/utilities/cube_manipulation/test_collapsed.py +++ b/improver_tests/utilities/cube_manipulation/test_collapsed.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the function collapsed. @@ -16,7 +16,6 @@ class Test_collapsed(unittest.TestCase): - """Test the collapsed utility.""" def setUp(self): diff --git a/improver_tests/utilities/cube_manipulation/test_compare_attributes.py b/improver_tests/utilities/cube_manipulation/test_compare_attributes.py index 87188fd0e2..dc4a09e4b3 100644 --- a/improver_tests/utilities/cube_manipulation/test_compare_attributes.py +++ b/improver_tests/utilities/cube_manipulation/test_compare_attributes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the function "cube_manipulation.compare_attributes". diff --git a/improver_tests/utilities/cube_manipulation/test_compare_coords.py b/improver_tests/utilities/cube_manipulation/test_compare_coords.py index e23b4845bb..beac1c6215 100644 --- a/improver_tests/utilities/cube_manipulation/test_compare_coords.py +++ b/improver_tests/utilities/cube_manipulation/test_compare_coords.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the function "cube_manipulation.compare_coords". diff --git a/improver_tests/utilities/cube_manipulation/test_enforce_coordinate_ordering.py b/improver_tests/utilities/cube_manipulation/test_enforce_coordinate_ordering.py index 358103aa8e..2675129ab3 100644 --- a/improver_tests/utilities/cube_manipulation/test_enforce_coordinate_ordering.py +++ b/improver_tests/utilities/cube_manipulation/test_enforce_coordinate_ordering.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the function "cube_manipulation.enforce_coordinate_ordering". @@ -21,7 +21,6 @@ class Test_enforce_coordinate_ordering(IrisTest): - """Test the enforce_coordinate_ordering utility.""" def setUp(self): diff --git a/improver_tests/utilities/cube_manipulation/test_expand_bounds.py b/improver_tests/utilities/cube_manipulation/test_expand_bounds.py index 8718917472..da5f55472a 100644 --- a/improver_tests/utilities/cube_manipulation/test_expand_bounds.py +++ b/improver_tests/utilities/cube_manipulation/test_expand_bounds.py @@ -1,10 +1,11 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the function "cube_manipulation.expand_bounds". """ + import unittest from datetime import datetime as dt @@ -21,7 +22,6 @@ class Test_expand_bounds(IrisTest): - """Test expand_bounds function""" def setUp(self): diff --git a/improver_tests/utilities/cube_manipulation/test_filter_realizations.py b/improver_tests/utilities/cube_manipulation/test_filter_realizations.py index 3639378d28..484d4dea1f 100644 --- a/improver_tests/utilities/cube_manipulation/test_filter_realizations.py +++ b/improver_tests/utilities/cube_manipulation/test_filter_realizations.py @@ -1,10 +1,11 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the "utilities.filter_realizations" function. """ + from datetime import datetime import numpy as np diff --git a/improver_tests/utilities/cube_manipulation/test_get_filtered_attributes.py b/improver_tests/utilities/cube_manipulation/test_get_filtered_attributes.py index 8b0cfd05f6..d7341ebf9e 100644 --- a/improver_tests/utilities/cube_manipulation/test_get_filtered_attributes.py +++ b/improver_tests/utilities/cube_manipulation/test_get_filtered_attributes.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the function "cube_manipulation.get_filtered_attributes". @@ -16,7 +16,6 @@ class Test_get_filtered_attributes(IrisTest): - """Test the get_filtered_attributes function.""" def setUp(self): diff --git a/improver_tests/utilities/cube_manipulation/test_height_of_maximum.py b/improver_tests/utilities/cube_manipulation/test_height_of_maximum.py index dc8c3b9850..833aff4c17 100644 --- a/improver_tests/utilities/cube_manipulation/test_height_of_maximum.py +++ b/improver_tests/utilities/cube_manipulation/test_height_of_maximum.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the function "cube_manipulation.height_of_maximum". diff --git a/improver_tests/utilities/cube_manipulation/test_maximum_in_height.py b/improver_tests/utilities/cube_manipulation/test_maximum_in_height.py index 972ed7d62f..c5d4ebc4ac 100644 --- a/improver_tests/utilities/cube_manipulation/test_maximum_in_height.py +++ b/improver_tests/utilities/cube_manipulation/test_maximum_in_height.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the function "cube_manipulation.maximum_in_height". diff --git a/improver_tests/utilities/cube_manipulation/test_sort_coord_in_cube.py b/improver_tests/utilities/cube_manipulation/test_sort_coord_in_cube.py index eb6a9bdbd3..0e0f483d89 100644 --- a/improver_tests/utilities/cube_manipulation/test_sort_coord_in_cube.py +++ b/improver_tests/utilities/cube_manipulation/test_sort_coord_in_cube.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the function "cube_manipulation.sort_coord_in_cube". diff --git a/improver_tests/utilities/cube_manipulation/test_strip_var_names.py b/improver_tests/utilities/cube_manipulation/test_strip_var_names.py index 3691a667c5..7922605549 100644 --- a/improver_tests/utilities/cube_manipulation/test_strip_var_names.py +++ b/improver_tests/utilities/cube_manipulation/test_strip_var_names.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the function "cube_manipulation.strip_var_names". @@ -16,7 +16,6 @@ class Test_strip_var_names(unittest.TestCase): - """Test the _slice_var_names utility.""" def setUp(self): diff --git a/improver_tests/utilities/solar/test_DayNightMask.py b/improver_tests/utilities/solar/test_DayNightMask.py index 30b2219038..f585850336 100644 --- a/improver_tests/utilities/solar/test_DayNightMask.py +++ b/improver_tests/utilities/solar/test_DayNightMask.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Unit tests for DayNightMask class """ +"""Unit tests for DayNightMask class""" import unittest from datetime import datetime, timedelta @@ -41,17 +41,17 @@ def create_spot_cube(xrange=175, yrange=85): time_coords = [item[0] for item in time_coords] spot_cube = build_spotdata_cube( - data, "generic_spot_cube", "1", *args, scalar_coords=time_coords, + data, "generic_spot_cube", "1", *args, scalar_coords=time_coords ) spot_cube.attributes = ATTRIBUTES return spot_cube class Test__init__(IrisTest): - """ Test initialisation of the DayNightMask class """ + """Test initialisation of the DayNightMask class""" def test_basic_init(self): - """ Test Initiation of DayNightMask Object""" + """Test Initiation of DayNightMask Object""" plugin = DayNightMask() self.assertEqual(plugin.day, 1) self.assertEqual(plugin.night, 0) @@ -59,17 +59,17 @@ def test_basic_init(self): class Test__repr__(IrisTest): - """ Test string representation """ + """Test string representation""" def test_basic_repr(self): - """ Test Representation string of DayNightMask Object""" + """Test Representation string of DayNightMask Object""" expected = "" result = str(DayNightMask()) self.assertEqual(result, expected) class Test__create_daynight_mask(IrisTest): - """ Test string representation """ + """Test string representation""" def setUp(self): """Set up the cube for testing.""" @@ -86,7 +86,7 @@ def setUp(self): self.spot_cube = create_spot_cube() def test_basic_daynight_mask(self): - """ Test this creates a blank mask cube for gridded data""" + """Test this creates a blank mask cube for gridded data""" plugin = DayNightMask() result = plugin._create_daynight_mask(self.cube) self.assertIsInstance(result, iris.cube.Cube) @@ -101,7 +101,7 @@ def test_basic_daynight_mask(self): self.assertEqual(plugin.irregular, False) def test_basic_daynight_mask_spot(self): - """ Test this creates a blank mask cube for spot data""" + """Test this creates a blank mask cube for spot data""" plugin = DayNightMask() result = plugin._create_daynight_mask(self.spot_cube) self.assertIsInstance(result, iris.cube.Cube) @@ -117,7 +117,7 @@ def test_basic_daynight_mask_spot(self): class Test__daynight_lat_lon_cube(IrisTest): - """ Test string representation """ + """Test string representation""" def setUp(self): """Set up the cube for testing.""" @@ -141,7 +141,7 @@ def setUp(self): self.spot_cube = create_spot_cube(xrange=10, yrange=10) def test_basic_lat_lon_cube_gridded(self): - """ Test this create a blank gridded mask cube""" + """Test this create a blank gridded mask cube""" day_of_year = 10 utc_hour = 12.0 expected_result = np.ones((16, 16)) @@ -153,7 +153,7 @@ def test_basic_lat_lon_cube_gridded(self): self.assertArrayEqual(result.data, expected_result) def test_basic_lat_lon_cube_360(self): - """ Test this still works with 360 data""" + """Test this still works with 360 data""" day_of_year = 10 utc_hour = 0.0 expected_result = np.zeros((16, 16)) @@ -165,7 +165,7 @@ def test_basic_lat_lon_cube_360(self): self.assertArrayEqual(result.data, expected_result) def test_basic_lat_lon_cube_spot(self): - """ Test this create a blank spot mask cube""" + """Test this create a blank spot mask cube""" day_of_year = 10 utc_hour = 12.0 expected_result = np.ones((99)) @@ -178,7 +178,6 @@ def test_basic_lat_lon_cube_spot(self): class Test_process(IrisTest): - """Test DayNight Mask.""" def setUp(self): diff --git a/improver_tests/utilities/solar/test_solar.py b/improver_tests/utilities/solar/test_solar.py index 5aa401d155..7ebde55d13 100644 --- a/improver_tests/utilities/solar/test_solar.py +++ b/improver_tests/utilities/solar/test_solar.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -"""Unit tests for the solar calculations in solar.py """ +"""Unit tests for the solar calculations in solar.py""" import unittest from datetime import datetime, timezone @@ -262,7 +262,6 @@ def test_sine_solar_elevation(self): class Test_daynight_terminator(IrisTest): - """Test DayNight terminator.""" def setUp(self): diff --git a/improver_tests/utilities/spatial/test_DifferenceBetweenAdjacentGridSquares.py b/improver_tests/utilities/spatial/test_DifferenceBetweenAdjacentGridSquares.py index 6db261d072..5d9efa41bd 100644 --- a/improver_tests/utilities/spatial/test_DifferenceBetweenAdjacentGridSquares.py +++ b/improver_tests/utilities/spatial/test_DifferenceBetweenAdjacentGridSquares.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Tests of DifferenceBetweenAdjacentGridSquares plugin.""" +"""Tests of DifferenceBetweenAdjacentGridSquares plugin.""" import unittest @@ -19,7 +19,6 @@ class Test_create_difference_cube(IrisTest): - """Test the create_difference_cube method.""" def setUp(self): @@ -27,7 +26,7 @@ def setUp(self): data = np.array([[1, 2, 3], [2, 4, 6], [5, 10, 15]]) self.diff_in_y_array = np.array([[1, 2, 3], [3, 6, 9]]) self.cube = set_up_variable_cube( - data, name="wind_speed", units="m s-1", spatial_grid="equalarea", + data, name="wind_speed", units="m s-1", spatial_grid="equalarea" ) self.plugin = DifferenceBetweenAdjacentGridSquares() @@ -133,7 +132,7 @@ def setUp(self): """Set up cube.""" data = np.array([[1, 2, 3, 4], [2, 4, 6, 8], [5, 10, 15, 20]]) self.cube = set_up_variable_cube( - data, "equalarea", name="wind_speed", units="m s-1", + data, "equalarea", name="wind_speed", units="m s-1" ) self.plugin = DifferenceBetweenAdjacentGridSquares() diff --git a/improver_tests/utilities/spatial/test_DistanceBetweenGridSquares.py b/improver_tests/utilities/spatial/test_DistanceBetweenGridSquares.py index 7bf4f77ccd..b0008f73cb 100644 --- a/improver_tests/utilities/spatial/test_DistanceBetweenGridSquares.py +++ b/improver_tests/utilities/spatial/test_DistanceBetweenGridSquares.py @@ -1,9 +1,10 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Tests of DifferenceBetweenAdjacentGridSquares plugin, which encompasses all paths through +"""Tests of DifferenceBetweenAdjacentGridSquares plugin, which encompasses all paths through LatLonCubeDistanceCalculator, ProjectionCubeDistanceCalculator and BaseDistanceCalculator.""" + from typing import Tuple import numpy as np @@ -131,10 +132,9 @@ def test_latlon_cube(longitudes, is_circular): expected_x_distances = ( np.diff(expected_longitudes) * ONE_DEGREE_DISTANCE_AT_TEST_LATITUDES ) - ( - calculated_x_distances_cube, - calculated_y_distances_cube, - ) = DistanceBetweenGridSquares()(input_cube) + (calculated_x_distances_cube, calculated_y_distances_cube) = ( + DistanceBetweenGridSquares()(input_cube) + ) for result, expected in zip( (calculated_x_distances_cube, calculated_y_distances_cube), (expected_x_distances, expected_y_distances), @@ -153,10 +153,9 @@ def test_equalarea_cube(): expected_x_distances = np.full(expected_x_distances_cube_shape, spacing) expected_y_distances = np.full((2, 3), spacing) - ( - calculated_x_distances_cube, - calculated_y_distances_cube, - ) = DistanceBetweenGridSquares()(input_cube) + (calculated_x_distances_cube, calculated_y_distances_cube) = ( + DistanceBetweenGridSquares()(input_cube) + ) for result, expected in zip( (calculated_x_distances_cube, calculated_y_distances_cube), (expected_x_distances, expected_y_distances), @@ -183,10 +182,9 @@ def test_equalarea_cube_nonstandard_units(): input_cube = make_equalarea_test_cube((3, 3), grid_spacing=10, units="km") expected_x_distances = np.full((3, 2), 10) expected_y_distances = np.full((2, 3), 10) - ( - calculated_x_distances_cube, - calculated_y_distances_cube, - ) = DistanceBetweenGridSquares()(input_cube) + (calculated_x_distances_cube, calculated_y_distances_cube) = ( + DistanceBetweenGridSquares()(input_cube) + ) for result, expected in zip( (calculated_x_distances_cube, calculated_y_distances_cube), (expected_x_distances, expected_y_distances), @@ -206,10 +204,9 @@ def test_transverse_mercator_cube(): ] ) expected_y_distances = np.full((2, 2), TRANSVERSE_MERCATOR_GRID_SPACING) - ( - calculated_x_distances_cube, - calculated_y_distances_cube, - ) = DistanceBetweenGridSquares()(input_cube) + (calculated_x_distances_cube, calculated_y_distances_cube) = ( + DistanceBetweenGridSquares()(input_cube) + ) for result, expected in zip( (calculated_x_distances_cube, calculated_y_distances_cube), (expected_x_distances, expected_y_distances), @@ -236,10 +233,9 @@ def test_distance_cube_with_no_coordinate_system(): ) expected_x_distances = np.full((3, 2), 1000) expected_y_distances = np.full((2, 3), 1000) - ( - calculated_x_distances_cube, - calculated_y_distances_cube, - ) = DistanceBetweenGridSquares()(input_cube) + (calculated_x_distances_cube, calculated_y_distances_cube) = ( + DistanceBetweenGridSquares()(input_cube) + ) for result, expected in zip( (calculated_x_distances_cube, calculated_y_distances_cube), (expected_x_distances, expected_y_distances), diff --git a/improver_tests/utilities/spatial/test_GradientBetweenAdjacentGridSquares.py b/improver_tests/utilities/spatial/test_GradientBetweenAdjacentGridSquares.py index 1378f9073c..aac8498efa 100644 --- a/improver_tests/utilities/spatial/test_GradientBetweenAdjacentGridSquares.py +++ b/improver_tests/utilities/spatial/test_GradientBetweenAdjacentGridSquares.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Tests of GradientBetweenAdjacentGridSquares plugin.""" +"""Tests of GradientBetweenAdjacentGridSquares plugin.""" import numpy as np import pytest diff --git a/improver_tests/utilities/spatial/test_spatial.py b/improver_tests/utilities/spatial/test_spatial.py index 1f050f9609..f32d6a0066 100644 --- a/improver_tests/utilities/spatial/test_spatial.py +++ b/improver_tests/utilities/spatial/test_spatial.py @@ -1,9 +1,10 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the distance_to_number_of_grid_cells function from - spatial.py.""" +spatial.py.""" + from copy import copy from datetime import datetime as dt @@ -39,7 +40,6 @@ class Test_common_functions(IrisTest): - """A class originally written for testing spot-data functionality that no longer exists. It was also used in this set of tests, so upon deletion of the old spot-data code, the class was moved here.""" @@ -269,7 +269,6 @@ def test_lat_lon_equal_spacing_recurring_decimal_spacing_passes(self): class Test_convert_distance_into_number_of_grid_cells(IrisTest): - """Test conversion of distance in metres into number of grid cells.""" def setUp(self): @@ -278,10 +277,7 @@ def setUp(self): data = np.ones((1, 16, 16), dtype=np.float32) data[:, 7, 7] = 0.0 self.cube = set_up_variable_cube( - data, - name="precipitation_amount", - units="kg m^-2", - spatial_grid="equalarea", + data, name="precipitation_amount", units="kg m^-2", spatial_grid="equalarea" ) def test_basic_distance_to_grid_cells(self): @@ -343,13 +339,12 @@ def test_single_point_range_0(self): class Test_number_of_grid_cells_to_distance(IrisTest): - """Test the number_of_grid_cells_to_distance method""" def setUp(self): """Set up a cube with x and y coordinates""" data = np.ones((3, 4)) - self.cube = Cube(data, standard_name="air_temperature",) + self.cube = Cube(data, standard_name="air_temperature") self.cube.add_dim_coord( DimCoord( np.linspace(2000.0, 6000.0, 3), "projection_x_coordinate", units="m" @@ -391,7 +386,6 @@ def test_check_different_input_radius(self): class Test_check_if_grid_is_equal_area(IrisTest): - """Test that the grid is an equal area grid.""" def setUp(self): @@ -497,7 +491,7 @@ def setUp(self): """Set up the cube.""" data = np.ones((1, 2, 4), dtype=np.float32) self.latlon_cube = set_up_variable_cube( - data, name="precipitation_amount", units="kg m^-2", + data, name="precipitation_amount", units="kg m^-2" ) self.expected_lons = np.array([-15, -5, 5, 15, -15, -5, 5, 15]).reshape(2, 4) self.expected_lats = np.array([-5, -5, -5, -5, 5, 5, 5, 5]).reshape(2, 4) @@ -684,7 +678,7 @@ def test_rename_vicinity_cube(test_cube): [ # Vicinity processing, with one non-zero central value resulting # in the whole domain returning values of 1 - (np.array([[0, 0, 0], [0, 1.0, 0], [0, 0, 0]]), 1, None, np.ones((3, 3)),), + (np.array([[0, 0, 0], [0, 1.0, 0], [0, 0, 0]]), 1, None, np.ones((3, 3))), # Vicinity processing, with one non-zero corner value resulting # in neighbouring cells values of 1 within the limit of the # defined vicinity radius diff --git a/improver_tests/utilities/temporal/test_temporal.py b/improver_tests/utilities/temporal/test_temporal.py index de3e56cb00..842e139e77 100644 --- a/improver_tests/utilities/temporal/test_temporal.py +++ b/improver_tests/utilities/temporal/test_temporal.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for temporal utilities.""" @@ -37,7 +37,6 @@ class Test_cycletime_to_datetime(IrisTest): - """Test that a cycletime of a format such as YYYYMMDDTHHMMZ is converted into a datetime object.""" @@ -58,7 +57,6 @@ def test_define_cycletime_format(self): class Test_datetime_to_cycletime(IrisTest): - """Test that a datetime object can be converted into a cycletime of a format such as YYYYMMDDTHHMMZ.""" @@ -86,7 +84,6 @@ def test_define_cycletime_format_with_seconds(self): class Test_cycletime_to_number(IrisTest): - """Test that a cycletime of a format such as YYYYMMDDTHHMMZ is converted into a numeric time value.""" @@ -174,7 +171,6 @@ def test_input_cube_unmodified(self): class Test_datetime_to_iris_time(IrisTest): - """Test the datetime_to_iris_time function.""" def setUp(self): @@ -314,7 +310,6 @@ def test_invalid_time(self): class Test_extract_nearest_time_point(IrisTest): - """Test the extract_nearest_time_point function.""" def setUp(self): @@ -406,7 +401,6 @@ def test_time_name_exception(self): class Test_relabel_to_period(unittest.TestCase): - """Test relabel_to_period function.""" def setUp(self): @@ -436,7 +430,7 @@ def test_basic(self): ) expected_fp = self.cube.coord("forecast_period").copy() expected_fp.bounds = np.array( - [2 * 3600, 3 * 3600], TIME_COORDS["forecast_period"].dtype, + [2 * 3600, 3 * 3600], TIME_COORDS["forecast_period"].dtype ) result = relabel_to_period(self.cube, 1) self.assertIsInstance(result, Cube) @@ -456,7 +450,7 @@ def test_input_period_diagnostic(self): ) expected_fp = self.cube.coord("forecast_period").copy() expected_fp.bounds = np.array( - [0, 3 * 3600], dtype=TIME_COORDS["forecast_period"].dtype, + [0, 3 * 3600], dtype=TIME_COORDS["forecast_period"].dtype ) result = relabel_to_period(self.cube_with_bounds, 3) self.assertEqual(result.coord("time"), expected_time) @@ -526,7 +520,7 @@ def period_cube(data, period_lengths): [ # Array with a rate of 1 per second, with a period of 3-hours. # The resulting data are a count of 10800 (3-hours in seconds * rate) - ({}, np.ones((5, 5)), [10800], np.full((5, 5), 10800),), + ({}, np.ones((5, 5)), [10800], np.full((5, 5), 10800)), # Array with two rates, 1/200 per second and 3/400 per second. Two # periods of 3 and 2 hours leading to counts of 54 in each period; # (10800 * 0.005) and (7200 * 0.0075). diff --git a/improver_tests/utilities/test_ExtractValueFromTable.py b/improver_tests/utilities/test_ExtractValueFromTable.py index 962bc0a194..d613d166dc 100644 --- a/improver_tests/utilities/test_ExtractValueFromTable.py +++ b/improver_tests/utilities/test_ExtractValueFromTable.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests of read_from_table utilities""" diff --git a/improver_tests/utilities/test_FieldTexture.py b/improver_tests/utilities/test_FieldTexture.py index e28cd5167a..01463961bd 100644 --- a/improver_tests/utilities/test_FieldTexture.py +++ b/improver_tests/utilities/test_FieldTexture.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -""" Tests of FieldTexture plugin""" +"""Tests of FieldTexture plugin""" import iris import numpy as np @@ -21,10 +21,7 @@ DIAG_THRESH = THRESHOLDS[2] CAF = "cloud_area_fraction" REALIZATION = "realization" -COMMON_ATTRS = { - "source": "Unified Model", - "institution": "Met Office", -} +COMMON_ATTRS = {"source": "Unified Model", "institution": "Met Office"} UK_ENS_ATTRS = { **COMMON_ATTRS, "title": "MOGREPS-UK Forecast on 2 km Standard Grid", @@ -86,7 +83,7 @@ def ftex_plugin( ): """Create an instance of the FieldTexture plugin with standard arguments""" fieldtexture_instance = FieldTexture( - nbhood_radius, textural_threshold, diagnostic_threshold, + nbhood_radius, textural_threshold, diagnostic_threshold ) return fieldtexture_instance @@ -112,7 +109,7 @@ def test__calculate_ratio(thresholded_cloud_cube): def test__calculate_transitions(thresholded_cloud_cube): """Test the _calculate_transitions function with a numpy array simulating - the input cube""" + the input cube""" expected_data = np.zeros((10, 10), dtype=np.float32) expected_data[1:4, 1:4] = np.array( [[2.0, 1.0, 2.0], [1.0, 0.0, 1.0], [2.0, 1.0, 2.0]] @@ -123,7 +120,7 @@ def test__calculate_transitions(thresholded_cloud_cube): def test_process_single_threshold(multi_cloud_cube): """Test the process function with single threshold version of the multi - realization input cube""" + realization input cube""" single_thresh_cloud_cube = multi_cloud_cube.extract( iris.Constraint(cloud_area_fraction=DIAG_THRESH) ) @@ -134,7 +131,7 @@ def test_process_single_threshold(multi_cloud_cube): def test_process_no_realization(no_realization_cloud_cube): """Test the process function when the input cube does not contain a - realization coordinate""" + realization coordinate""" cube = no_realization_cloud_cube.extract( iris.Constraint(cloud_area_fraction=DIAG_THRESH) ) @@ -154,7 +151,7 @@ def test_process_error(multi_cloud_cube): @pytest.mark.parametrize("cloud_frac, expected", ((0.0, 1.0), (1.0, 0.0))) def test_process_constant_cloud(multi_cloud_cube, cloud_frac, expected): """Test the FieldTexture plugin with multi realization input cube that has - no or all cloud present in the field""" + no or all cloud present in the field""" multi_cloud_cube.data[:] = cloud_frac result = ftex_plugin().process(multi_cloud_cube) np.testing.assert_allclose(result.data, expected) @@ -169,8 +166,8 @@ def test_no_threshold_cube(multi_cloud_cube): def test_wrong_threshold(multi_cloud_cube): """Test the process function with multi_cloud_cube where user defined - diagnostic_threshold variable does not match threshold available in - the cube""" + diagnostic_threshold variable does not match threshold available in + the cube""" wrong_threshold = 0.235 plugin = FieldTexture( nbhood_radius=NB_RADIUS, @@ -183,7 +180,7 @@ def test_wrong_threshold(multi_cloud_cube): def test_metadata_name(multi_cloud_cube): """Test that the metadata of the output cube follows expected conventions - after the plugin is complete and all old coordinates have been removed""" + after the plugin is complete and all old coordinates have been removed""" result = ftex_plugin().process(multi_cloud_cube) assert result.name() == f"probability_of_texture_of_{CAF}_above_threshold" assert result.units == "1" @@ -191,7 +188,7 @@ def test_metadata_name(multi_cloud_cube): def test_metadata_coords(multi_cloud_cube): """Test that the coordinate metadata in the output cube follows expected - conventions after that plugin has completed""" + conventions after that plugin has completed""" result = ftex_plugin().process(multi_cloud_cube) expected_scalar_coord = f"texture_of_{CAF}" @@ -211,7 +208,7 @@ def test_metadata_coords(multi_cloud_cube): @pytest.mark.parametrize("model_config", (True, False)) def test_metadata_attributes(multi_cloud_cube, model_config): """Test that the metadata attributes in the output cube follows expected - conventions after that plugin has completed""" + conventions after that plugin has completed""" expected_attributes = UK_ENS_ATTRS.copy() if model_config: fieldtexture_args = {"model_id_attr": "mosg__model_configuration"} diff --git a/improver_tests/utilities/test_GenerateTimeLaggedEnsemble.py b/improver_tests/utilities/test_GenerateTimeLaggedEnsemble.py index 69dd0feb70..eda696ff86 100644 --- a/improver_tests/utilities/test_GenerateTimeLaggedEnsemble.py +++ b/improver_tests/utilities/test_GenerateTimeLaggedEnsemble.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for GenerateTimeLaggedEnsemble plugin.""" @@ -16,7 +16,6 @@ class Test_process(IrisTest): - """Test interpolation of cubes to intermediate times using the plugin.""" def setUp(self): @@ -67,7 +66,7 @@ def test_basic(self): def test_realizations(self): """Test that the expected metadata is correct with a different - realizations""" + realizations""" self.input_cube2.coord("realization").points = np.array( [6, 7, 8], dtype=np.int32 ) @@ -86,8 +85,8 @@ def test_realizations(self): def test_duplicate_realizations(self): """Test that the expected metadata is correct with different - realizations and that realizations are renumbered if a - duplicate is found""" + realizations and that realizations are renumbered if a + duplicate is found""" self.input_cube2.coord("realization").points = np.array([0, 7, 8]) result = GenerateTimeLaggedEnsemble().process(self.input_cubelist) expected_realizations = [0, 1, 2, 3, 4, 5] @@ -104,8 +103,8 @@ def test_duplicate_realizations(self): def test_duplicate_realizations_more_input_cubes(self): """Test that the expected metadata is correct with different - realizations and that realizations are renumbered if a - duplicate is found, with 3 input cubes.""" + realizations and that realizations are renumbered if a + duplicate is found, with 3 input cubes.""" self.input_cube2.coord("realization").points = np.array([6, 7, 8]) input_cube3 = self.input_cube2.copy() input_cube3.coord("forecast_reference_time").points = np.array( diff --git a/improver_tests/utilities/test_GradientBetweenVerticalLevels.py b/improver_tests/utilities/test_GradientBetweenVerticalLevels.py index 4d11152696..ba3f2f42a8 100644 --- a/improver_tests/utilities/test_GradientBetweenVerticalLevels.py +++ b/improver_tests/utilities/test_GradientBetweenVerticalLevels.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the GradientBetweenVerticalLevels plugin.""" - import iris import numpy as np import pytest @@ -139,9 +138,7 @@ def test_height_and_no_orography( """Test an error is raised if a height coordinate is present but no orography cube is present.""" - with pytest.raises( - ValueError, match="No orography cube provided", - ): + with pytest.raises(ValueError, match="No orography cube provided"): GradientBetweenVerticalLevels()( iris.cube.CubeList( [ @@ -159,9 +156,7 @@ def test_pressure_coord_and_no_pressure_levels( """Test an error is raised if a pressure coordinate is present but no geopotential_height cube is present.""" - with pytest.raises( - ValueError, match="No geopotential height", - ): + with pytest.raises(ValueError, match="No geopotential height"): GradientBetweenVerticalLevels()( iris.cube.CubeList( [temperature_at_screen_level, temperature_at_850hPa, orography] diff --git a/improver_tests/utilities/test_InterpolateUsingDifference.py b/improver_tests/utilities/test_InterpolateUsingDifference.py index e83c1dba98..cfee5806a3 100644 --- a/improver_tests/utilities/test_InterpolateUsingDifference.py +++ b/improver_tests/utilities/test_InterpolateUsingDifference.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the InterpolateUsingDifference plugin.""" + import unittest from unittest.mock import patch, sentinel @@ -36,11 +37,10 @@ def test_as_cube_called(mock_as_cube): class Test_Setup(unittest.TestCase): - """Set up for InterpolateUsingDifference tests.""" def setUp(self): - """ Set up arrays for testing.""" + """Set up arrays for testing.""" snow_sleet = np.array( [[5.0, 5.0, 5.0], [10.0, 10.0, 10.0], [5.0, 5.0, 5.0]], dtype=np.float32 ) @@ -71,7 +71,6 @@ def setUp(self): class Test_repr(unittest.TestCase): - """Test the InterpolateUsingDifference __repr__ method.""" def test_basic(self): @@ -82,7 +81,6 @@ def test_basic(self): class Test_process_check_inputs(Test_Setup): - """Tests for input check behaviour of process method.""" def test_incomplete_reference_data(self): @@ -110,7 +108,7 @@ def test_incompatible_limit_units(self): msg = "Reference cube and/or limit do not have units compatible" with self.assertRaisesRegex(ValueError, msg): InterpolateUsingDifference().process( - self.sleet_rain, self.snow_sleet, limit=self.limit, + self.sleet_rain, self.snow_sleet, limit=self.limit ) def test_convert_units(self): @@ -126,7 +124,6 @@ def test_convert_units(self): class Test_process(Test_Setup): - """Test the InterpolateUsingDifference process method.""" def test_unlimited(self): @@ -153,7 +150,7 @@ def test_maximum_limited(self): ) result = InterpolateUsingDifference(limit_as_maximum=True).process( - self.sleet_rain, self.snow_sleet, limit=self.limit, + self.sleet_rain, self.snow_sleet, limit=self.limit ) assert_array_equal(result.data, expected) @@ -170,7 +167,7 @@ def test_minimum_limited(self): ) result = InterpolateUsingDifference(limit_as_maximum=False).process( - self.sleet_rain, self.snow_sleet, limit=self.limit, + self.sleet_rain, self.snow_sleet, limit=self.limit ) assert_array_equal(result.data, expected) @@ -191,7 +188,7 @@ def test_multi_realization_limited(self): ) result = InterpolateUsingDifference(limit_as_maximum=False).process( - sleet_rain, snow_sleet, limit=self.limit, + sleet_rain, snow_sleet, limit=self.limit ) assert_array_equal(result[0].data, expected) @@ -233,7 +230,7 @@ def test_crossing_values(self): ) result_limited = InterpolateUsingDifference(limit_as_maximum=False).process( - self.sleet_rain, self.snow_sleet, limit=self.snow_sleet, + self.sleet_rain, self.snow_sleet, limit=self.snow_sleet ) assert_array_equal(result_unlimited.data, expected_unlimited) @@ -290,7 +287,7 @@ def test_convert_units(self): self.limit.convert_units("cm") result = InterpolateUsingDifference().process( - self.sleet_rain, self.snow_sleet, limit=self.limit, + self.sleet_rain, self.snow_sleet, limit=self.limit ) assert_array_equal(result.data, expected) diff --git a/improver_tests/utilities/test_OccurrenceWithinVicinity.py b/improver_tests/utilities/test_OccurrenceWithinVicinity.py index fc2afb373b..c6e5190b01 100644 --- a/improver_tests/utilities/test_OccurrenceWithinVicinity.py +++ b/improver_tests/utilities/test_OccurrenceWithinVicinity.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the utilities.OccurrenceWithinVicinity plugin.""" @@ -91,7 +91,7 @@ def latlon_cube() -> Cube: @pytest.fixture def radius_coord() -> AuxCoord: return AuxCoord( - np.array([RADIUS], dtype=np.float32), units="m", long_name="radius_of_vicinity", + np.array([RADIUS], dtype=np.float32), units="m", long_name="radius_of_vicinity" ) @@ -311,10 +311,7 @@ def cube_with_realizations_fixture() -> Cube: ) -TIMESTEPS = [ - datetime.datetime(2017, 11, 9, 12), - datetime.datetime(2017, 11, 9, 15), -] +TIMESTEPS = [datetime.datetime(2017, 11, 9, 12), datetime.datetime(2017, 11, 9, 15)] @pytest.mark.parametrize("land_fixture", [None, "all_land_cube"]) @@ -357,9 +354,7 @@ def test_with_multiple_realizations_and_times( ], ] ) - cube = add_coordinate( - cube, TIMESTEPS, "time", order=[1, 0, 2, 3], is_datetime=True, - ) + cube = add_coordinate(cube, TIMESTEPS, "time", order=[1, 0, 2, 3], is_datetime=True) cube.data[0, 0, 2, 1] = 1.0 cube.data[1, 1, 1, 3] = 1.0 orig_shape = cube.data.copy().shape @@ -370,7 +365,7 @@ def test_with_multiple_realizations_and_times( @pytest.mark.parametrize( - "kwargs", (({"radii": [2000, 5000]}), ({"grid_point_radii": [2, 3, 4, 5]}),) + "kwargs", (({"radii": [2000, 5000]}), ({"grid_point_radii": [2, 3, 4, 5]})) ) def test_coordinate_order_with_multiple_realizations_and_times( cube_with_realizations, kwargs @@ -379,9 +374,7 @@ def test_coordinate_order_with_multiple_realizations_and_times( realizations and times using multiple vicinity radii.""" cube = cube_with_realizations - cube = add_coordinate( - cube, TIMESTEPS, "time", order=[1, 0, 2, 3], is_datetime=True, - ) + cube = add_coordinate(cube, TIMESTEPS, "time", order=[1, 0, 2, 3], is_datetime=True) # Add the expected radius_of_vicinity coordinate dimension size orig_shape = list(cube.data.copy().shape) @@ -450,7 +443,7 @@ def test_with_multiple_times(request, cube_with_realizations, land_fixture): ] ) cube = cube[0] - cube = add_coordinate(cube, TIMESTEPS, "time", is_datetime=True,) + cube = add_coordinate(cube, TIMESTEPS, "time", is_datetime=True) cube.data[0, 2, 1] = 1.0 cube.data[1, 1, 3] = 1.0 orig_shape = cube.data.shape diff --git a/improver_tests/utilities/test_TemporalInterpolation.py b/improver_tests/utilities/test_TemporalInterpolation.py index 147fd47466..f1d796fba5 100644 --- a/improver_tests/utilities/test_TemporalInterpolation.py +++ b/improver_tests/utilities/test_TemporalInterpolation.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for temporal utilities.""" @@ -281,9 +281,11 @@ def test_construct_time_list(kwargs, exception): # times plus any others specified in the kwarg. try: target_times = times.copy() - target_times.append(kwargs["times"]) if kwargs[ - "times" - ] is not None else target_times + ( + target_times.append(kwargs["times"]) + if kwargs["times"] is not None + else target_times + ) except KeyError: pass else: @@ -753,10 +755,10 @@ def test_add_bounds(input_times, expected_time_bounds, expected_fp_bounds): [2.5, 2.5], ), # Equal adjacent period maxes, shorter periods have the same max. - ({"interval_in_minutes": 180, "max": True}, [5, 5], [3, 6], [5, 5],), + ({"interval_in_minutes": 180, "max": True}, [5, 5], [3, 6], [5, 5]), # Equal adjacent period minimums, shorter periods have the same # min. - ({"interval_in_minutes": 180, "min": True}, [5, 5], [3, 6], [5, 5],), + ({"interval_in_minutes": 180, "min": True}, [5, 5], [3, 6], [5, 5]), # Trend of increasing accumulations with time, which is reflected # in the shorter periods generated. ( @@ -767,9 +769,9 @@ def test_add_bounds(input_times, expected_time_bounds, expected_fp_bounds): ), # Trend of increasing maxes with time, which is reflected in the # shorter periods generated. - ({"interval_in_minutes": 180, "max": True}, [3, 9], [3, 6], [6, 9],), + ({"interval_in_minutes": 180, "max": True}, [3, 9], [3, 6], [6, 9]), # Later input period minimum is 9, expect all new periods to be >= 9 - ({"interval_in_minutes": 180, "min": True}, [3, 9], [3, 6], [9, 9],), + ({"interval_in_minutes": 180, "min": True}, [3, 9], [3, 6], [9, 9]), # Trend of increasing accumulations with time, which is reflected # in the shorter periods generated. ( @@ -780,10 +782,10 @@ def test_add_bounds(input_times, expected_time_bounds, expected_fp_bounds): ), # Trend of increasing maxes with time, which is reflected in the # shorter periods generated. - ({"interval_in_minutes": 120, "max": True}, [0, 9], [2, 4, 6], [3, 6, 9],), + ({"interval_in_minutes": 120, "max": True}, [0, 9], [2, 4, 6], [3, 6, 9]), # Trend of increasing maxes with time, which is reflected in the # shorter periods generated. - ({"interval_in_minutes": 120, "min": True}, [0, 9], [2, 4, 6], [9, 9, 9],), + ({"interval_in_minutes": 120, "min": True}, [0, 9], [2, 4, 6], [9, 9, 9]), # Later input period is 0, expect all new periods to be 0 ( {"interval_in_minutes": 120, "accumulation": True}, @@ -792,9 +794,9 @@ def test_add_bounds(input_times, expected_time_bounds, expected_fp_bounds): [0, 0, 0], ), # Later input period max is 0, expect all new periods to be 0 - ({"interval_in_minutes": 120, "max": True}, [9, 0], [2, 4, 6], [0, 0, 0],), + ({"interval_in_minutes": 120, "max": True}, [9, 0], [2, 4, 6], [0, 0, 0]), # Later input period minimum is 0, expect all new periods to be >= 0 - ({"interval_in_minutes": 120, "min": True}, [9, 0], [2, 4, 6], [6, 3, 0],), + ({"interval_in_minutes": 120, "min": True}, [9, 0], [2, 4, 6], [6, 3, 0]), # Equal adjacent accumulations, divided into unequal shorter periods. ( {"times": [datetime.datetime(2017, 11, 1, 4)], "accumulation": True}, @@ -924,7 +926,7 @@ def test_process_return_input(kwargs): # 1 mm/hr and 2 mm/hr at the start and end of the period. This gives # a gradient of 1/6 mm/hr across the period which results in the # expected 3-hour accumulations returned across the period. - ({"interval_in_minutes": 180, "accumulation": True}, [3, 12], [3, 6], [5, 7],), + ({"interval_in_minutes": 180, "accumulation": True}, [3, 12], [3, 6], [5, 7]), # Unequal input periods and accumulations give effective rates of # 2 mm/hr and 1 mm/hr at the start and end of the period. This gives # a gradient of -1/6 mm/hr across the period which results in the @@ -938,7 +940,7 @@ def test_process_return_input(kwargs): # Unequal input periods and accumulations give a consistent effective # rate of 1 mm/hr across the the period. This results in equal # accumulations across the two returned 3-hour periods. - ({"interval_in_minutes": 180, "accumulation": True}, [3, 6], [3, 6], [3, 3],), + ({"interval_in_minutes": 180, "accumulation": True}, [3, 6], [3, 6], [3, 3]), # Unequal input periods and accumulations give a consistent effective # rate of 1 mm/hr across the the period. The unequal output periods # split the total accumulation as expected. diff --git a/improver_tests/utilities/test_cli_utilities.py b/improver_tests/utilities/test_cli_utilities.py index a4b34a9b1f..54a8ac3bd5 100644 --- a/improver_tests/utilities/test_cli_utilities.py +++ b/improver_tests/utilities/test_cli_utilities.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for utilities.cli_utilities.""" diff --git a/improver_tests/utilities/test_compare.py b/improver_tests/utilities/test_compare.py index 2be41269e4..ef358bdc82 100644 --- a/improver_tests/utilities/test_compare.py +++ b/improver_tests/utilities/test_compare.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the compare plugin.""" @@ -238,7 +238,7 @@ def message_collector(message): # Check modifying a simple attribute actual_ds.setncattr("float_number", 3.2) compare.compare_attributes( - "root", actual_ds, expected_ds, ["float_number"], message_collector, + "root", actual_ds, expected_ds, ["float_number"], message_collector ) assert len(messages_reported) == 0 @@ -249,7 +249,7 @@ def message_collector(message): # Check adding another attribute actual_ds.setncattr("extra", "additional") compare.compare_attributes( - "longer name", actual_ds, expected_ds, ["extra"], message_collector, + "longer name", actual_ds, expected_ds, ["extra"], message_collector ) assert len(messages_reported) == 0 @@ -260,7 +260,7 @@ def message_collector(message): # Check removing an attribute actual_ds.delncattr("float_number") compare.compare_attributes( - "root", actual_ds, expected_ds, ["float_number"], message_collector, + "root", actual_ds, expected_ds, ["float_number"], message_collector ) assert len(messages_reported) == 0 diff --git a/improver_tests/utilities/test_cube_checker.py b/improver_tests/utilities/test_cube_checker.py index 5ac33e5581..a9a4fa33e1 100644 --- a/improver_tests/utilities/test_cube_checker.py +++ b/improver_tests/utilities/test_cube_checker.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the cube_checker utility.""" @@ -30,17 +30,13 @@ class Test_check_for_x_and_y_axes(IrisTest): - """Test whether the cube has an x and y axis.""" def setUp(self): """Set up a cube.""" data = np.ones((1, 5, 5), dtype=np.float32) self.cube = set_up_variable_cube( - data, - name="precipitation_amount", - units="kg m^-2", - spatial_grid="equalarea", + data, name="precipitation_amount", units="kg m^-2", spatial_grid="equalarea" ) def test_no_y_coordinate(self): @@ -78,7 +74,6 @@ def test_fail_dimension_requirement(self): class Test_check_cube_coordinates(IrisTest): - """Test check_cube_coordinates successfully promotes scalar coordinates to dimension coordinates in a new cube if they were dimension coordinates in the progenitor cube.""" @@ -87,10 +82,7 @@ def setUp(self): """Set up a cube.""" data = np.ones((1, 16, 16), dtype=np.float32) self.cube = set_up_variable_cube( - data, - name="precipitation_amount", - units="kg m^-2", - spatial_grid="equalarea", + data, name="precipitation_amount", units="kg m^-2", spatial_grid="equalarea" ) self.squeezed_cube = iris.util.squeeze(self.cube) @@ -167,17 +159,13 @@ def test_coord_promotion_missing_scalar(self): class Test_find_dimension_coordinate_mismatch(IrisTest): - """Test if two cubes have the dimension coordinates.""" def setUp(self): """Set up a cube.""" data = np.ones((2, 16, 16), dtype=np.float32) self.cube = set_up_variable_cube( - data, - name="precipitation_amount", - units="kg m^-2", - spatial_grid="equalarea", + data, name="precipitation_amount", units="kg m^-2", spatial_grid="equalarea" ) def test_no_mismatch(self): @@ -418,7 +406,7 @@ def only_one_cube(cubes: List[Cube]): True, "^air_temperature and air_pressure must have time bounds", ), - (only_one_cube, False, "^Need at least 2 cubes to check. Found 1",), + (only_one_cube, False, "^Need at least 2 cubes to check. Found 1"), ), ) def test_time_coord_exceptions( diff --git a/improver_tests/utilities/test_cube_constraints.py b/improver_tests/utilities/test_cube_constraints.py index 034132dec8..c48eafa445 100644 --- a/improver_tests/utilities/test_cube_constraints.py +++ b/improver_tests/utilities/test_cube_constraints.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Utilities for creating Iris constraints.""" diff --git a/improver_tests/utilities/test_enforce_consistency.py b/improver_tests/utilities/test_enforce_consistency.py index d2b848d0f0..565dbbde98 100644 --- a/improver_tests/utilities/test_enforce_consistency.py +++ b/improver_tests/utilities/test_enforce_consistency.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for enforce_consistency utilities.""" @@ -29,7 +29,7 @@ def get_percentiles(value, shape): bounding percentiles. """ return np.broadcast_to( - np.expand_dims([value - 10, value, value + 10], axis=(1, 2),), shape, + np.expand_dims([value - 10, value, value + 10], axis=(1, 2)), shape ) @@ -39,7 +39,7 @@ def get_percentile_forecast(value, shape, name): """ data = get_percentiles(value, shape) forecast_cube = set_up_percentile_cube( - data, percentiles=[10, 50, 90], name=name, units="m s-1", + data, percentiles=[10, 50, 90], name=name, units="m s-1" ) return forecast_cube @@ -322,7 +322,7 @@ def test_single_bound_exceptions( ), ) def test_double_bounds_exceptions( - forecast_type, additive_amount, multiplicative_amount, comparison_operator, msg, + forecast_type, additive_amount, multiplicative_amount, comparison_operator, msg ): """ Test that correct errors are raised when using two bounds. diff --git a/improver_tests/utilities/test_flatten.py b/improver_tests/utilities/test_flatten.py index 1627afa325..8caa7d9bcb 100644 --- a/improver_tests/utilities/test_flatten.py +++ b/improver_tests/utilities/test_flatten.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for flattening an arbitrarily nested iterable.""" diff --git a/improver_tests/utilities/test_indexing_operations.py b/improver_tests/utilities/test_indexing_operations.py index c34c531746..6d2ec15893 100644 --- a/improver_tests/utilities/test_indexing_operations.py +++ b/improver_tests/utilities/test_indexing_operations.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the plugins and functions within indexing_operations.py""" @@ -13,7 +13,6 @@ class Test_choose(IrisTest): - """Test the choose function behaves as expected, giving the same results as the numpy choose method, but without the 32 leading dimensions limit.""" diff --git a/improver_tests/utilities/test_interpolate.py b/improver_tests/utilities/test_interpolate.py index ecf98287c1..33d0a58a3d 100644 --- a/improver_tests/utilities/test_interpolate.py +++ b/improver_tests/utilities/test_interpolate.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the functions within interpolation.py""" @@ -16,7 +16,7 @@ class Test_interpolate_missing_data(IrisTest): """Test the interpolate_missing_data method""" def setUp(self): - """ Set up arrays for testing.""" + """Set up arrays for testing.""" self.data = np.array([[1.0, 1.0, 2.0], [1.0, np.nan, 2.0], [1.0, 2.0, 2.0]]) self.limit_data = np.full((3, 3), 3.0) self.valid_data = np.full((3, 3), True) @@ -48,7 +48,8 @@ def test_mostly_zeros(self): The point of this test is to highlight a case where values outside of the max:min range of the input can be found, if the test tolerance is sufficiently tight. If this test fails with a newer version of Scipy, then the enforcement of this range - in improver.utilitiess.interpolation.InterpolateUsingDifference needs revisiting.""" + in improver.utilitiess.interpolation.InterpolateUsingDifference needs revisiting. + """ data = np.zeros( (18, 18) ) # The smallest array where this behaviour has been found diff --git a/improver_tests/utilities/test_load.py b/improver_tests/utilities/test_load.py index fce91b42b5..7474dcf43b 100644 --- a/improver_tests/utilities/test_load.py +++ b/improver_tests/utilities/test_load.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for loading functionality.""" @@ -25,7 +25,6 @@ class Test_load_cube(IrisTest): - """Test the load function.""" def setUp(self): @@ -240,7 +239,6 @@ def test_merge_multiple(self): class Test_load_cubelist(IrisTest): - """Test the load function.""" def setUp(self): diff --git a/improver_tests/utilities/test_mask.py b/improver_tests/utilities/test_mask.py index eddbfbe6fb..fd21595d54 100644 --- a/improver_tests/utilities/test_mask.py +++ b/improver_tests/utilities/test_mask.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """ Unit tests for the function apply_mask. @@ -59,7 +59,7 @@ def test_basic(wind_gust_cube, mask, switch_coord_order, invert_mask): def test_different_dimensions(wind_gust_cube, mask): - """ Test that the function will raise an error if the mask cube has different + """Test that the function will raise an error if the mask cube has different dimensions to other cube.""" mask = mask[0] input_list = [wind_gust_cube, mask] diff --git a/improver_tests/utilities/test_mathematical_operations.py b/improver_tests/utilities/test_mathematical_operations.py index b65e8cf7a9..286afce132 100644 --- a/improver_tests/utilities/test_mathematical_operations.py +++ b/improver_tests/utilities/test_mathematical_operations.py @@ -1,9 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. -"""Unit tests for the plugins and functions within mathematical_operations.py -""" +"""Unit tests for the plugins and functions within mathematical_operations.py""" import unittest @@ -41,7 +40,6 @@ def _set_up_height_cube(height_points, ascending=True): class Test__repr__(IrisTest): - """Test the repr method.""" def test_basic(self): @@ -57,7 +55,6 @@ def test_basic(self): class Test_ensure_monotonic_increase_in_chosen_direction(IrisTest): - """Test the ensure_monotonic_increase_in_chosen_direction method.""" def setUp(self): @@ -121,7 +118,6 @@ def test_descending_coordinate_negative(self): class Test_prepare_for_integration(IrisTest): - """Test the prepare_for_integration method.""" def setUp(self): @@ -169,7 +165,6 @@ def test_negative_points(self): class Test_perform_integration(IrisTest): - """Test the perform_integration method.""" def setUp(self): @@ -403,7 +398,6 @@ def test_integration_not_performed(self): class Test_process(IrisTest): - """Test the process method.""" def setUp(self): diff --git a/improver_tests/utilities/test_neighbourhood_tools.py b/improver_tests/utilities/test_neighbourhood_tools.py index 8009880d79..13145b27ea 100644 --- a/improver_tests/utilities/test_neighbourhood_tools.py +++ b/improver_tests/utilities/test_neighbourhood_tools.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for spatial padding utilities""" diff --git a/improver_tests/utilities/test_normalise_to_reference.py b/improver_tests/utilities/test_normalise_to_reference.py index fabaa25ceb..c6ce5e6f5b 100644 --- a/improver_tests/utilities/test_normalise_to_reference.py +++ b/improver_tests/utilities/test_normalise_to_reference.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the "forecast_reference_enforcement.normalise_to_reference" function.""" + import iris import numpy as np import pytest diff --git a/improver_tests/utilities/test_pad_spatial.py b/improver_tests/utilities/test_pad_spatial.py index be7da3ee35..5094decf2e 100644 --- a/improver_tests/utilities/test_pad_spatial.py +++ b/improver_tests/utilities/test_pad_spatial.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for spatial padding utilities""" @@ -23,7 +23,6 @@ class Test_pad_coord(IrisTest): - """Test the padding of a coordinate.""" def setUp(self): @@ -159,7 +158,6 @@ def test_values(self): class Test__create_cube_with_padded_data(IrisTest): - """Test creating a new cube using a template cube.""" def setUp(self): @@ -239,7 +237,6 @@ def test_no_y_dimension_coordinate(self): class Test_pad_cube_with_halo(IrisTest): - """Test for padding a cube with a halo.""" def setUp(self): @@ -250,7 +247,7 @@ def setUp(self): self.cube.data[2, 2] = 0 data = np.array( - [[0.0, 0.1, 0.0], [0.1, 0.5, 0.1], [0.0, 0.1, 0.0]], dtype=np.float32, + [[0.0, 0.1, 0.0], [0.1, 0.5, 0.1], [0.0, 0.1, 0.0]], dtype=np.float32 ) self.alternative_cube = self.cube[1:-1, 1:-1].copy(data=data) @@ -487,7 +484,6 @@ def test_values(self): class Test_remove_halo_from_cube(IrisTest): - """Test a halo is removed from the cube data.""" def setUp(self): diff --git a/improver_tests/utilities/test_probability_manipulation.py b/improver_tests/utilities/test_probability_manipulation.py index 8f91ddc980..3b4310dd0e 100644 --- a/improver_tests/utilities/test_probability_manipulation.py +++ b/improver_tests/utilities/test_probability_manipulation.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests of probability_manipulation utilities""" diff --git a/improver_tests/utilities/test_rescale.py b/improver_tests/utilities/test_rescale.py index 335a90125f..21c5651964 100644 --- a/improver_tests/utilities/test_rescale.py +++ b/improver_tests/utilities/test_rescale.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the rescale function from rescale.py.""" @@ -15,7 +15,6 @@ class Test_rescale(IrisTest): - """Test the utilities.rescale rescale function.""" def setUp(self): @@ -82,7 +81,6 @@ def test_inverted_clip(self): class Test_apply_double_scaling(IrisTest): - """Test the apply_double_scaling method.""" def setUp(self): diff --git a/improver_tests/utilities/test_round.py b/improver_tests/utilities/test_round.py index b0682601e2..e06a7b27eb 100644 --- a/improver_tests/utilities/test_round.py +++ b/improver_tests/utilities/test_round.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the "round" module""" - import numpy as np import pytest diff --git a/improver_tests/utilities/test_save.py b/improver_tests/utilities/test_save.py index 0ac12bb5e8..0e9f584b9c 100644 --- a/improver_tests/utilities/test_save.py +++ b/improver_tests/utilities/test_save.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for saving functionality.""" @@ -21,7 +21,7 @@ def set_up_test_cube(): - """ Set up a temperature cube with additional global attributes. """ + """Set up a temperature cube with additional global attributes.""" data = np.linspace(-45.0, 45.0, 9, dtype=np.float32).reshape((1, 3, 3)) + 273.15 attributes = { @@ -40,10 +40,10 @@ def set_up_test_cube(): class Test_save_netcdf(IrisTest): - """ Test function to save iris cubes as NetCDF files. """ + """Test function to save iris cubes as NetCDF files.""" def setUp(self): - """ Set up cube to write, read and check """ + """Set up cube to write, read and check""" self.global_keys_ref = [ "title", "um_version", @@ -67,7 +67,7 @@ def setUp(self): self.cube.cell_methods = self.cell_methods def tearDown(self): - """ Remove temporary directories created for testing. """ + """Remove temporary directories created for testing.""" try: os.remove(self.filepath) except FileNotFoundError: @@ -75,13 +75,13 @@ def tearDown(self): os.rmdir(self.directory) def test_basic_cube(self): - """ Test saves file in required location """ + """Test saves file in required location""" self.assertFalse(os.path.exists(self.filepath)) save_netcdf(self.cube, self.filepath) self.assertTrue(os.path.exists(self.filepath)) def test_compression(self): - """ Test data gets compressed with default complevel 1 when saved """ + """Test data gets compressed with default complevel 1 when saved""" save_netcdf(self.cube, self.filepath) data = Dataset(self.filepath, mode="r") @@ -91,8 +91,8 @@ def test_compression(self): self.assertEqual(filters["complevel"], 1) def test_compression_level(self): - """ Test data gets compressed with complevel provided by compression_level - when saved """ + """Test data gets compressed with complevel provided by compression_level + when saved""" save_netcdf(self.cube, self.filepath, compression_level=3) data = Dataset(self.filepath, mode="r") @@ -102,7 +102,7 @@ def test_compression_level(self): self.assertEqual(filters["complevel"], 3) def test_no_compression(self): - """ Test data does not get compressed when saved with compression_level 0 """ + """Test data does not get compressed when saved with compression_level 0""" save_netcdf(self.cube, self.filepath, compression_level=0) data = Dataset(self.filepath, mode="r") @@ -111,12 +111,12 @@ def test_no_compression(self): self.assertFalse(filters["zlib"]) def test_compression_level_invalid(self): - """ Test ValueError raised when invalid compression_level """ + """Test ValueError raised when invalid compression_level""" with self.assertRaises(ValueError): save_netcdf(self.cube, self.filepath, compression_level="one") def test_compression_level_out_of_range(self): - """ Test ValueError raised when compression_level out of range """ + """Test ValueError raised when compression_level out of range""" with self.assertRaises(ValueError): save_netcdf(self.cube, self.filepath, compression_level=10) @@ -140,14 +140,14 @@ def test_basic_cube_list(self): self.assertEqual(len(read_cubes), 2) def test_cube_data(self): - """ Test valid cube can be read from saved file """ + """Test valid cube can be read from saved file""" save_netcdf(self.cube, self.filepath) cube = load_cube(self.filepath) self.assertTrue(isinstance(cube, iris.cube.Cube)) self.assertArrayEqual(cube.data, self.cube.data) def test_cube_dimensions(self): - """ Test cube dimension coordinates are preserved """ + """Test cube dimension coordinates are preserved""" save_netcdf(self.cube, self.filepath) cube = load_cube(self.filepath) coord_names = [coord.name() for coord in cube.coords(dim_coords=True)] @@ -155,7 +155,7 @@ def test_cube_dimensions(self): self.assertCountEqual(coord_names, reference_names) def test_cell_method_reordering_in_saved_file(self): - """ Test cell methods are in the correct order when written out and + """Test cell methods are in the correct order when written out and read back in.""" self.cube.cell_methods = (self.cell_methods[1], self.cell_methods[0]) save_netcdf(self.cube, self.filepath) @@ -163,7 +163,7 @@ def test_cell_method_reordering_in_saved_file(self): self.assertEqual(cube.cell_methods, self.cell_methods) def test_cf_global_attributes(self): - """ Test that a NetCDF file saved from one cube only contains the + """Test that a NetCDF file saved from one cube only contains the expected global attributes. NOTE Loading the file as an iris.cube.Cube does not distinguish global @@ -175,7 +175,7 @@ def test_cf_global_attributes(self): self.assertTrue(all(key in self.global_keys_ref for key in global_keys)) def test_cf_data_attributes(self): - """ Test that forbidden global metadata are saved as data variable + """Test that forbidden global metadata are saved as data variable attributes """ self.cube.attributes["test_attribute"] = np.arange(12) @@ -189,7 +189,7 @@ def test_cf_data_attributes(self): ) def test_cf_shared_attributes_list(self): - """ Test that a NetCDF file saved from a list of cubes that share + """Test that a NetCDF file saved from a list of cubes that share non-global attributes does not promote these attributes to global. """ cube_list = [self.cube, self.cube] @@ -230,7 +230,7 @@ def test_remove_least_significant_digit(self): @pytest.fixture(name="bitshaving_cube") def bitshaving_cube_fixture(): - """ Sets up a cube with a recurring decimal for bitshaving testing """ + """Sets up a cube with a recurring decimal for bitshaving testing""" cube = set_up_test_cube() # 1/9 fractions are recurring decimal and binary fractions # good for checking number of digits remaining after bitshaving @@ -243,7 +243,7 @@ def bitshaving_cube_fixture(): @pytest.mark.parametrize("lsd", (0, 2, 3)) @pytest.mark.parametrize("compress", (0, 2)) def test_least_significant_digit(bitshaving_cube, tmp_path, lsd, compress): - """ Test the least significant digit for bitshaving output files""" + """Test the least significant digit for bitshaving output files""" filepath = tmp_path / "temp.nc" save_netcdf( bitshaving_cube, @@ -267,10 +267,10 @@ def test_least_significant_digit(bitshaving_cube, tmp_path, lsd, compress): class Test__order_cell_methods(IrisTest): - """ Test function that sorts cube cell_methods before saving. """ + """Test function that sorts cube cell_methods before saving.""" def setUp(self): - """ Set up cube with cell_methods.""" + """Set up cube with cell_methods.""" self.cube = set_up_test_cube() self.cell_methods = ( CellMethod(method="maximum", coords="time", intervals="1 hour"), @@ -279,12 +279,12 @@ def setUp(self): self.cube.cell_methods = self.cell_methods def test_no_reordering_cube(self): - """ Test the order is preserved is no reordering required.""" + """Test the order is preserved is no reordering required.""" _order_cell_methods(self.cube) self.assertEqual(self.cube.cell_methods, self.cell_methods) def test_reordering_cube(self): - """ Test the order is changed when reordering is required.""" + """Test the order is changed when reordering is required.""" self.cube.cell_methods = (self.cell_methods[1], self.cell_methods[0]) # Test that following the manual reorder above the cube cell methods # and the tuple don't match. diff --git a/improver_tests/utilities/test_split_cubes_by_name.py b/improver_tests/utilities/test_split_cubes_by_name.py index 125c70c1d3..e0a646e721 100644 --- a/improver_tests/utilities/test_split_cubes_by_name.py +++ b/improver_tests/utilities/test_split_cubes_by_name.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the "forecast_reference_enforcement.split_cubes_by_name" function.""" + import iris import numpy as np import pytest diff --git a/improver_tests/uv_index/test_uv_index.py b/improver_tests/uv_index/test_uv_index.py index 87796b0077..2385cf01b6 100644 --- a/improver_tests/uv_index/test_uv_index.py +++ b/improver_tests/uv_index/test_uv_index.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the uv_index function.""" @@ -15,8 +15,8 @@ class Test_uv_index(IrisTest): - """ Tests that the uv_index plugin calculates the UV index - correctly. """ + """Tests that the uv_index plugin calculates the UV index + correctly.""" def setUp(self): """Set up cubes for downward uv flux.""" @@ -31,7 +31,7 @@ def setUp(self): ) def test_basic(self): - """ Test that the a basic uv calculation works, using the + """Test that the a basic uv calculation works, using the default scaling factor. Make sure the output is a cube with the expected data.""" scale_factor = 1.0 @@ -40,14 +40,14 @@ def test_basic(self): self.assertArrayEqual(result.data, expected) def test_scale_factor(self): - """ Test the uv calculation works when changing the scale factor. Make + """Test the uv calculation works when changing the scale factor. Make sure the output is a cube with the expected data.""" expected = np.ones_like(self.cube_uv_down.data, dtype=np.float32) result = calculate_uv_index(self.cube_uv_down, scale_factor=10) self.assertArrayEqual(result.data, expected) def test_metadata(self): - """ Tests that the uv index output has the correct metadata (no units, + """Tests that the uv index output has the correct metadata (no units, and name = ultraviolet index).""" result = calculate_uv_index(self.cube_uv_down) self.assertEqual(str(result.standard_name), "ultraviolet_index") @@ -57,14 +57,14 @@ def test_metadata(self): def test_badname_down(self): """Tests that a ValueError is raised if the input uv down - file has the wrong name. """ + file has the wrong name.""" msg = "The radiation flux in UV downward has the wrong name" with self.assertRaisesRegex(ValueError, msg): calculate_uv_index(self.cube_down_badname) def test_negative_input(self): """Tests that a ValueError is raised if the input contains - negative values. """ + negative values.""" negative_data_down = np.full_like( self.cube_uv_down.data, dtype=np.float32, fill_value=-0.1 ) @@ -78,7 +78,7 @@ def test_negative_input(self): def test_nan_input(self): """Tests that a ValueError is raised if the input contains - values that are not a number. """ + values that are not a number.""" self.cube_uv_down.data.fill(np.nan) msg = ( "The radiation flux in UV downward contains data " diff --git a/improver_tests/visibility/test_visibility_combine_cloud_base.py b/improver_tests/visibility/test_visibility_combine_cloud_base.py index 127a629828..fd1f4c3e8a 100644 --- a/improver_tests/visibility/test_visibility_combine_cloud_base.py +++ b/improver_tests/visibility/test_visibility_combine_cloud_base.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for VisibilityCombineCloudBase plugin""" diff --git a/improver_tests/wind_calculations/vertical_updraught/test_VerticalUpdraught.py b/improver_tests/wind_calculations/vertical_updraught/test_VerticalUpdraught.py index b93ea536cb..afbe853b6a 100644 --- a/improver_tests/wind_calculations/vertical_updraught/test_VerticalUpdraught.py +++ b/improver_tests/wind_calculations/vertical_updraught/test_VerticalUpdraught.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Tests for the VerticalUpdraught plugin""" + import re from datetime import datetime from typing import List @@ -221,7 +222,7 @@ def set_mismatched_model_ids(cubes: List[Cube]): (lambda l: l[0].rename("kittens"), "Expected to find cubes of "), (lambda l: l[1].rename("poodles"), "Expected to find cubes of "), (remove_a_cube, "Expected to find cubes of "), - (add_unexpected_cube, re.escape("Unexpected Cube(s) found in inputs: "),), + (add_unexpected_cube, re.escape("Unexpected Cube(s) found in inputs: ")), (spatial_shift, "Spatial coords of input Cubes do not match: "), (lambda l: units_to_kg(l[0]), "Unable to convert from"), (lambda l: units_to_kg(l[1]), "Unable to convert from"), diff --git a/improver_tests/wind_calculations/wind_components/test_ResolveWindComponents.py b/improver_tests/wind_calculations/wind_components/test_ResolveWindComponents.py index 3ebb5e142a..ef86be10e8 100644 --- a/improver_tests/wind_calculations/wind_components/test_ResolveWindComponents.py +++ b/improver_tests/wind_calculations/wind_components/test_ResolveWindComponents.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the wind_components.ResolveWindComponents plugin.""" diff --git a/improver_tests/wind_calculations/wind_direction/test_WindDirection.py b/improver_tests/wind_calculations/wind_direction/test_WindDirection.py index abb29e59f2..ee5b5d1835 100644 --- a/improver_tests/wind_calculations/wind_direction/test_WindDirection.py +++ b/improver_tests/wind_calculations/wind_direction/test_WindDirection.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the wind_direction.WindDirection plugin.""" @@ -341,7 +341,7 @@ def setUp(self): ) def test_basic(self): - """Test that the plugin returns expected data types. """ + """Test that the plugin returns expected data types.""" result_cube = WindDirection().process(self.cube) self.assertIsInstance(result_cube, Cube) @@ -371,7 +371,7 @@ def test_return_single_precision(self): self.assertEqual(result_cube.dtype, np.float32) def test_returns_expected_values(self): - """Test that the function returns correct 2D arrays of floats. """ + """Test that the function returns correct 2D arrays of floats.""" result_cube = WindDirection().process(self.cube) diff --git a/improver_tests/wind_calculations/wind_downscaling/test_FrictionVelocity.py b/improver_tests/wind_calculations/wind_downscaling/test_FrictionVelocity.py index d97018c171..3ce4bd1cce 100644 --- a/improver_tests/wind_calculations/wind_downscaling/test_FrictionVelocity.py +++ b/improver_tests/wind_calculations/wind_downscaling/test_FrictionVelocity.py @@ -1,6 +1,6 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for plugin wind_downscaling.FrictionVelocity""" @@ -14,7 +14,6 @@ class Test_process(IrisTest): - """Test the creation of friction velocity 2D arrays. Note that in the future, use of the Real Missing Data Indicator (RMDI) constant is due to be deprecated in favour of np.nan""" @@ -36,7 +35,7 @@ def setUp(self): self.mask[1 : n_y - 1, 1 : n_x - 1] = True def test_returns_expected_values(self): - """Test that the function returns correct 2D array of floats. """ + """Test that the function returns correct 2D array of floats.""" # Equation is (K=0.4): ustar = K * (u_href / ln(h_ref / z_0)) expected_out = np.array( @@ -56,7 +55,7 @@ def test_returns_expected_values(self): self.assertArrayAlmostEqual(result, expected_out) def test_handles_nan_values(self): - """Test that the function accepts NaN values correctly. """ + """Test that the function accepts NaN values correctly.""" self.u_href[1, 1] = np.nan # Adds NaN value @@ -78,7 +77,7 @@ def test_handles_nan_values(self): def test_handles_zero_values(self): """Function calculates log(href/z_0) - test that the function accepts - zero values in h_ref and z_0 and returns np.nan without crashing.""" + zero values in h_ref and z_0 and returns np.nan without crashing.""" h_ref_zeros = np.full_like(self.h_ref, 0) z_0_zeros = np.full_like(self.z_0, 0) @@ -108,7 +107,7 @@ def test_handles_different_sized_arrays(self): def test_output_is_float32(self): """Test that the plugin returns an array of float 32 type - even when the input arrays are double precision.""" + even when the input arrays are double precision.""" result = FrictionVelocity( self.u_href, self.h_ref, self.z_0, self.mask diff --git a/improver_tests/wind_calculations/wind_downscaling/test_RoughnessCorrection.py b/improver_tests/wind_calculations/wind_downscaling/test_RoughnessCorrection.py index 96198deca2..2b08373853 100644 --- a/improver_tests/wind_calculations/wind_downscaling/test_RoughnessCorrection.py +++ b/improver_tests/wind_calculations/wind_downscaling/test_RoughnessCorrection.py @@ -1,10 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for plugin wind_downscaling.RoughnessCorrection.""" - import datetime import unittest @@ -85,7 +84,6 @@ def make_data_cube(data, name, unit, shape, heights): class TestMultiPoint: - """Test (typically) 3x1 or 3x3 point tests. It constructs cubes for the ancillary fields: @@ -296,7 +294,6 @@ def run_hc_rc(self, wind, height=None): class Test1D(IrisTest): - """Class to test 1 x-y point cubes. This class tests the correct behaviour if np.nan or RMDI are @@ -316,25 +313,25 @@ class Test1D(IrisTest): def test_section0a(self): """Test AoS is RMDI, point should not do anything, uin = uout.""" - landpointtests_hc_rc = TestSinglePoint(AoS=RMDI, heightlevels=self.hls,) + landpointtests_hc_rc = TestSinglePoint(AoS=RMDI, heightlevels=self.hls) land_hc_rc = landpointtests_hc_rc.run_hc_rc(self.uin) self.assertArrayEqual(landpointtests_hc_rc.w_cube, land_hc_rc) def test_section0b(self): """Test AoS is np.nan, point should not do anything, uin = uout.""" - landpointtests_hc_rc = TestSinglePoint(AoS=np.nan, heightlevels=self.hls,) + landpointtests_hc_rc = TestSinglePoint(AoS=np.nan, heightlevels=self.hls) land_hc_rc = landpointtests_hc_rc.run_hc_rc(self.uin) self.assertArrayEqual(landpointtests_hc_rc.w_cube, land_hc_rc) def test_section0c(self): """Test Sigma is RMDI, point should not do anything, uin = uout.""" - landpointtests_hc_rc = TestSinglePoint(Sigma=RMDI, heightlevels=self.hls,) + landpointtests_hc_rc = TestSinglePoint(Sigma=RMDI, heightlevels=self.hls) land_hc_rc = landpointtests_hc_rc.run_hc_rc(self.uin) self.assertArrayEqual(landpointtests_hc_rc.w_cube, land_hc_rc) def test_section0d(self): """Test Sigma is np.nan, point should not do anything, uin = uout.""" - landpointtests_hc_rc = TestSinglePoint(Sigma=np.nan, heightlevels=self.hls,) + landpointtests_hc_rc = TestSinglePoint(Sigma=np.nan, heightlevels=self.hls) land_hc_rc = landpointtests_hc_rc.run_hc_rc(self.uin) self.assertArrayEqual(landpointtests_hc_rc.w_cube, land_hc_rc) @@ -345,7 +342,7 @@ def test_section0e(self): """ landpointtests_hc_rc = TestSinglePoint( - z_0=RMDI, pporog=230.0, heightlevels=self.hls, + z_0=RMDI, pporog=230.0, heightlevels=self.hls ) land_hc_rc = landpointtests_hc_rc.run_hc_rc(self.uin) self.assertArrayEqual(landpointtests_hc_rc.w_cube, land_hc_rc) @@ -357,7 +354,7 @@ def test_section0f(self): """ landpointtests_hc_rc = TestSinglePoint( - z_0=np.nan, pporog=230.0, heightlevels=self.hls, + z_0=np.nan, pporog=230.0, heightlevels=self.hls ) land_hc_rc = landpointtests_hc_rc.run_hc_rc(self.uin) self.assertArrayEqual(landpointtests_hc_rc.w_cube, land_hc_rc) @@ -368,7 +365,7 @@ def test_section0g(self): modeloro < pporo, so point should do positive HC, uin < uout. """ - landpointtests_hc_rc = TestSinglePoint(z_0=RMDI, heightlevels=self.hls,) + landpointtests_hc_rc = TestSinglePoint(z_0=RMDI, heightlevels=self.hls) land_hc_rc = landpointtests_hc_rc.run_hc_rc(self.uin) self.assertTrue((land_hc_rc.data > landpointtests_hc_rc.w_cube.data).all()) @@ -381,7 +378,7 @@ def test_section0h(self): uout[0] = 0 """ - landpointtests_hc_rc = TestSinglePoint(pporog=RMDI, heightlevels=self.hls,) + landpointtests_hc_rc = TestSinglePoint(pporog=RMDI, heightlevels=self.hls) land_hc_rc = landpointtests_hc_rc.run_hc_rc(self.uin) self.assertTrue( (land_hc_rc.data <= landpointtests_hc_rc.w_cube.data).all() @@ -397,7 +394,7 @@ def test_section0i(self): uout[0] = 0 """ - landpointtests_hc_rc = TestSinglePoint(pporog=np.nan, heightlevels=self.hls,) + landpointtests_hc_rc = TestSinglePoint(pporog=np.nan, heightlevels=self.hls) land_hc_rc = landpointtests_hc_rc.run_hc_rc(self.uin) self.assertTrue( (land_hc_rc.data <= landpointtests_hc_rc.w_cube.data).all() @@ -413,7 +410,7 @@ def test_section0j(self): uout[0] = 0 """ - landpointtests_hc_rc = TestSinglePoint(modelorog=RMDI, heightlevels=self.hls,) + landpointtests_hc_rc = TestSinglePoint(modelorog=RMDI, heightlevels=self.hls) land_hc_rc = landpointtests_hc_rc.run_hc_rc(self.uin) self.assertTrue( (land_hc_rc.data <= landpointtests_hc_rc.w_cube.data).all() @@ -563,7 +560,6 @@ def test_section1g(self): class Test2D(IrisTest): - """Test multi-point wind corrections. Section 2 are multiple point, multiple time tests diff --git a/improver_tests/wind_calculations/wind_gust_diagnostic/test_WindGustDiagnostic.py b/improver_tests/wind_calculations/wind_gust_diagnostic/test_WindGustDiagnostic.py index 806fadc43f..bd88665ec8 100644 --- a/improver_tests/wind_calculations/wind_gust_diagnostic/test_WindGustDiagnostic.py +++ b/improver_tests/wind_calculations/wind_gust_diagnostic/test_WindGustDiagnostic.py @@ -1,8 +1,9 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. """Unit tests for the windgust_diagnostic.WindGustDiagnostic plugin.""" + import unittest from datetime import datetime @@ -43,7 +44,6 @@ def create_wind_percentile_cube(data=None, perc_values=None, name="wind_speed_of class Test__init__(IrisTest): - """Test the __init__ method.""" def test_basic(self): @@ -54,7 +54,6 @@ def test_basic(self): class Test__repr__(IrisTest): - """Test the repr method.""" def test_basic(self): @@ -65,7 +64,6 @@ def test_basic(self): class Test_add_metadata(IrisTest): - """Test the add_metadata method.""" def setUp(self): @@ -73,13 +71,13 @@ def setUp(self): self.cube_wg = create_wind_percentile_cube() def test_basic(self): - """Test that the function returns a Cube. """ + """Test that the function returns a Cube.""" plugin = WindGustDiagnostic(50.0, 95.0) result = plugin.add_metadata(self.cube_wg) self.assertIsInstance(result, Cube) def test_metadata(self): - """Test that the metadata is set as expected """ + """Test that the metadata is set as expected""" plugin = WindGustDiagnostic(50.0, 80.0) result = plugin.add_metadata(self.cube_wg) self.assertEqual(result.standard_name, "wind_speed_of_gust") @@ -102,7 +100,6 @@ def test_diagnostic_extreme_txt(self): class Test_extract_percentile_data(IrisTest): - """Test the extract_percentile_data method.""" def setUp(self): @@ -165,7 +162,6 @@ def test_returns_correct_cube_and_coord(self): class Test_process(IrisTest): - """Test the creation of wind-gust diagnostic by the plugin.""" def setUp(self): @@ -186,13 +182,13 @@ def setUp(self): ) def test_basic(self): - """Test that the plugin returns a Cube. """ + """Test that the plugin returns a Cube.""" plugin = WindGustDiagnostic(self.wg_perc, self.ws_perc) result = plugin(self.cube_wg, self.cube_ws) self.assertIsInstance(result, Cube) def test_raises_error_for_mismatching_perc_coords(self): - """Test raises an error for mismatching perc coords. """ + """Test raises an error for mismatching perc coords.""" plugin = WindGustDiagnostic(self.wg_perc, self.ws_perc) self.cube_wg.coord("percentile").rename("percentile_dummy") msg = ( @@ -203,7 +199,7 @@ def test_raises_error_for_mismatching_perc_coords(self): plugin(self.cube_wg, self.cube_ws) def test_raises_error_for_no_time_coord(self): - """Test raises Value Error if cubes have no time coordinate """ + """Test raises Value Error if cubes have no time coordinate""" cube_wg = self.cube_wg[:, 0, ::] cube_ws = self.cube_ws[:, 0, ::] cube_wg.remove_coord("time") @@ -214,7 +210,7 @@ def test_raises_error_for_no_time_coord(self): plugin(cube_wg, cube_ws) def test_raises_error_points_mismatch_and_no_bounds(self): - """Test raises Value Error if points mismatch and no bounds """ + """Test raises Value Error if points mismatch and no bounds""" # offset times by half an hour (in seconds) self.cube_wg.coord("time").points = self.cube_wg.coord("time").points + 30 * 60 plugin = WindGustDiagnostic(self.wg_perc, self.ws_perc) @@ -223,7 +219,7 @@ def test_raises_error_points_mismatch_and_no_bounds(self): plugin(self.cube_wg, self.cube_ws) def test_raises_error_points_mismatch_and_bounds(self): - """Test raises Value Error if both points and bounds mismatch """ + """Test raises Value Error if both points and bounds mismatch""" # offset by 4 hours (in seconds) self.cube_wg.coord("time").points = ( self.cube_wg.coord("time").points + 4 * 60 * 60 @@ -239,7 +235,7 @@ def test_raises_error_points_mismatch_and_bounds(self): plugin(self.cube_wg, self.cube_ws) def test_no_error_if_ws_point_in_bounds(self): - """Test raises no Value Error if wind-speed point in bounds """ + """Test raises no Value Error if wind-speed point in bounds""" self.cube_wg.coord("time").points = self.cube_wg.coord("time").points + 30 * 60 times = self.cube_wg.coord("time").points self.cube_wg.coord("time").bounds = [ @@ -251,7 +247,7 @@ def test_no_error_if_ws_point_in_bounds(self): self.assertIsInstance(result, Cube) def test_returns_wind_gust_diagnostic(self): - """Test that the plugin returns a Cube. """ + """Test that the plugin returns a Cube.""" plugin = WindGustDiagnostic(self.wg_perc, self.ws_perc) result = plugin(self.cube_wg, self.cube_ws) expected_data = np.zeros((2, 2, 2), dtype=np.float32) diff --git a/init_check b/init_check new file mode 100755 index 0000000000..777493ac56 --- /dev/null +++ b/init_check @@ -0,0 +1,18 @@ +#!/bin/bash + +found_error=0 +script_root=$(dirname "$0") + +for dirpath in "$@"; do + if [ ! -d "$dirpath" ]; then + dirpath=$(dirname "$dirpath") + fi + if [ ! -f "$dirpath/__init__.py" ]; then + found_error=1 + echo "Missing __init__.py in $dirpath, adding it now..." + touch "$dirpath/__init__.py" + fi +done + +exit ${found_error} + diff --git a/pyproject.toml b/pyproject.toml index 1c8a595819..d79eef4746 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,9 +1,10 @@ -[tool.black] -target-version = ['py36'] +[tool.ruff] +target-version = "py37" -[tool.isort] -multi_line_output = 3 -include_trailing_comma = true -force_grid_wrap = 0 -use_parentheses = true -line_length = 88 +[tool.ruff.lint] +extend-select = ["E", "F", "W", "I"] # add C90 later +ignore = ["E203", "E731", "E501", "E741"] # remove "E501", "E741" later + +[tool.ruff.format] +# Enable reformatting of code snippets in docstrings. +docstring-code-format = true diff --git a/setup.cfg b/setup.cfg index 74a7564144..c5d7d18c1a 100644 --- a/setup.cfg +++ b/setup.cfg @@ -28,11 +28,6 @@ exclude = improver_tests improver_tests.* -[flake8] -max-line-length = 100 -select = C,E,F,W -extend-ignore = E203,E731,W503 - [mypy] ignore_missing_imports = True exclude = cli diff --git a/setup.py b/setup.py index 0ac3c2907e..8095c50e08 100644 --- a/setup.py +++ b/setup.py @@ -1,8 +1,8 @@ -# (C) Crown copyright, Met Office. All rights reserved. +# (C) Crown Copyright, Met Office. All rights reserved. # -# This file is part of IMPROVER and is released under a BSD 3-Clause license. +# This file is part of 'IMPROVER' and is released under the BSD 3-Clause license. # See LICENSE in the root of the repository for full licensing details. from setuptools import setup if __name__ == "__main__": - setup(use_scm_version={"version_scheme": "post-release"},) + setup(use_scm_version={"version_scheme": "post-release"})