diff --git a/.ci/azure/docs.yml b/.ci/azure/docs.yml index 1c5a982e7b..ef05fde13a 100644 --- a/.ci/azure/docs.yml +++ b/.ci/azure/docs.yml @@ -5,7 +5,7 @@ jobs: pool: vmImage: ubuntu-latest variables: - python.version: "3.11" + python.version: "3.12" timeoutInMinutes: 240 steps: # Checkout simpeg repo. diff --git a/.ci/azure/pypi.yml b/.ci/azure/pypi.yml index 237f5c4b1d..818df28436 100644 --- a/.ci/azure/pypi.yml +++ b/.ci/azure/pypi.yml @@ -12,7 +12,7 @@ jobs: - task: UsePythonVersion@0 inputs: - versionSpec: "3.11" + versionSpec: "3.12" displayName: "Setup Python" - bash: | @@ -57,7 +57,7 @@ jobs: - task: UsePythonVersion@0 inputs: - versionSpec: "3.11" + versionSpec: "3.12" displayName: "Setup Python" - bash: | diff --git a/.ci/azure/style.yml b/.ci/azure/style.yml index 59e6334475..e8865e9eb2 100644 --- a/.ci/azure/style.yml +++ b/.ci/azure/style.yml @@ -6,7 +6,7 @@ jobs: steps: - task: UsePythonVersion@0 inputs: - versionSpec: "3.11" + versionSpec: "3.12" - bash: .ci/install_style.sh displayName: "Install dependencies to run the checks" - script: make black @@ -19,7 +19,7 @@ jobs: steps: - task: UsePythonVersion@0 inputs: - versionSpec: "3.11" + versionSpec: "3.12" - bash: .ci/install_style.sh displayName: "Install dependencies to run the checks" - script: make flake @@ -32,10 +32,23 @@ jobs: steps: - task: UsePythonVersion@0 inputs: - versionSpec: "3.11" + versionSpec: "3.12" - bash: .ci/install_style.sh displayName: "Install dependencies to run the checks" - script: make flake-all displayName: "Run flake8" env: FLAKE8_OPTS: "--exit-zero" + + - job: + displayName: Run style checks with Ruff + pool: + vmImage: ubuntu-latest + steps: + - task: UsePythonVersion@0 + inputs: + versionSpec: "3.12" + - bash: .ci/install_style.sh + displayName: "Install dependencies to run the checks" + - script: make ruff + displayName: "Run ruff" diff --git a/.ci/azure/test.yml b/.ci/azure/test.yml index 403a4d69f6..3f5de2cd37 100644 --- a/.ci/azure/test.yml +++ b/.ci/azure/test.yml @@ -1,6 +1,6 @@ parameters: os : ['ubuntu-latest'] - py_vers: ['3.11'] + py_vers: ['3.12'] test: ['tests/em', 'tests/base tests/flow tests/seis tests/utils', 'tests/meta', diff --git a/.gitattributes b/.gitattributes index 82bf71c1c5..96e5ecc751 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,3 @@ +* text=auto + .git_archival.txt export-subst \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/release-checklist.md b/.github/ISSUE_TEMPLATE/release-checklist.md index 33a3c64690..5727fa90ca 100644 --- a/.github/ISSUE_TEMPLATE/release-checklist.md +++ b/.github/ISSUE_TEMPLATE/release-checklist.md @@ -40,8 +40,8 @@ assignees: "" - [ ] Copy the content of `notes.rst` to a new file `docs/content/release/-notes.rst`. - [ ] Edit the release notes file, following the template below and the previous release notes. - [ ] Add the new release notes to the list in `docs/content/release/index.rst`. -- [ ] **Open a PR** with the new release notes. -- [ ] Manually view the built documentation by downloading the Azure `html_doc` artifact and check for formatting and errors. +- [ ] Create a new branch called `changelog-v` and commit the + changes in `docs/content/release`
@@ -97,6 +97,7 @@ Pull Requests ============= .. + paste list of PRs that were copied to `notes.rst` ``` @@ -116,8 +117,28 @@ Edit the `docs/_static/versions.json` file and: - [ ] Double-check the changes. - [ ] Commit the changes to the same branch. -### Merge the PR +### Optionally: Python version compatibility + +If this releases drops support of an old Python version: + +- [ ] Open the `docs/content/user-guide/getting-started/version-compatibility.rst` file and go to the `Supported Python versions` section. +- [ ] Make sure that the current latest version is listed there along with the corresponding Python version that this release will drop support for. +> [!TIP] +> For example, if the latest release to the date is `v0.25.2`, we are about to release `v0.26.0`, and we are dropping support for Python 3.11, then we need to identify `v0.25.0` as the last version to support Python 3.11: +> +> ```rst +> * - **Python version** +> - **Last compatible release** +> ... +> * - 3.11 +> - 0.25.2 +> ``` + +### Create a PR and merge it + +- [ ] Open a PR merging the new branch into `main`. +- [ ] Manually view the built documentation by downloading the Azure `html_doc` artifact and check for formatting and errors. - [ ] **Merge that PR.** ## Make the new release @@ -134,7 +155,7 @@ After publishing the release, Azure will automatically push the new version to P After they finish: -- [ ] Check the new version is available in PyPI: https://pypi.org/project/SimPEG/ . +- [ ] Check the new version is available in PyPI: https://pypi.org/project/simpeg - [ ] Check the new documentation is online: https://docs.simpeg.xyz For the new version to be available in conda-forge, we need to update the [conda-forge/simpeg-feedstock](https://github.com/conda-forge/simpeg-feedstock) repository. Within the same day of the release a new PR will be automatically open in that repository. So: diff --git a/.github/dependabot.yml b/.github/dependabot.yml index f668184542..22009ca175 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -30,4 +30,4 @@ updates: groups: pre-commit-hooks: patterns: - - "*" + - "*" \ No newline at end of file diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index cd17e1eb9a..dbbb50824a 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -38,4 +38,4 @@ Feel free to remove lines from this template that do not apply to you pull reque +--> \ No newline at end of file diff --git a/.github/workflows/test-latest.yml b/.github/workflows/test-latest.yml new file mode 100644 index 0000000000..bbc116a9e9 --- /dev/null +++ b/.github/workflows/test-latest.yml @@ -0,0 +1,96 @@ +# Test SimPEG against latest Python and dependencies versions +# =========================================================== + +name: Test SimPEG against latest Python + +on: + workflow_dispatch: + # Manually triggered event. Allow to select Python version in the web interface. + inputs: + python: + description: "Python version" + required: true + default: "3.15" + type: string + + schedule: + # Run at midnight of every Monday on default branch + - cron: "0 0 * * 1" + timezone: "UTC" + +permissions: {} + +# Use bash by default in all jobs +defaults: + run: + # The -l {0} is necessary for conda environments to be activated + # But this breaks on MacOS if using actions/setup-python: + # https://github.com/actions/setup-python/issues/132 + # -e makes sure builds fail if any command fails + shell: bash -e -o pipefail -l {0} + +jobs: + + test: + name: Test (latest) + runs-on: ubuntu-latest + strategy: + # Allow single workshops in the matrix to fail and continue running the rest. + fail-fast: false + matrix: + test_target: + - tests/base tests/flow tests/meta tests/utils + - tests/em + - tests/examples + - tests/pf + # Test dask on its own to avoid modifying the implementation of any other tests + - tests/dask + env: + # Define the Python version conditionally: + # if it was manually triggered, use the inputs.python variable, else use a default value. + PYTHON: ${{ inputs.python || '3.15' }} + ENVIRONMENT: .ci/environment_test.yml + + steps: + # Checks-out your repository under $GITHUB_WORKSPACE + - name: Checkout + uses: actions/checkout@v7 + with: + # Need to fetch more than the last commit so that setuptools-scm can + # create the correct version string. If the number of commits since + # the last release is greater than this, the version still be wrong. + # Increase if necessary. + fetch-depth: 100 + # The GitHub token is preserved by default but this job doesn't need + # to be able to push to GitHub. + persist-credentials: false + + # Need the tags so that setuptools-scm can form a valid version number + - name: Fetch git tags + run: git fetch origin 'refs/tags/*:refs/tags/*' + + - name: Setup caching for conda packages + uses: actions/cache@v6 + with: + path: ~/conda_pkgs_dir + key: conda-${{ env.PYTHON }}-${{ hashFiles(env.ENVIRONMENT) }} + + - name: Setup Miniforge + uses: conda-incubator/setup-miniconda@be893c923ea9cf1cf7cd510fbdde27c7e18cbdcb + with: + python-version: ${{ env.PYTHON }} + miniforge-version: latest + channels: conda-forge + conda-remove-defaults: "true" + activate-environment: simpeg-test + environment-file: ${{ env.ENVIRONMENT }} + + - name: List installed packages + run: conda list + + - name: Install the package + run: python -m pip install --no-deps . + + - name: Run tests + run: | + pytest -v --cov --cov-config="pyproject.toml" -W "ignore::DeprecationWarning" ${{ matrix.test_target }} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3329c7d633..06f2f19caf 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,20 +1,14 @@ -default_language_version: - python: python3 -default_stages: [pre-commit,pre-push] -fail_fast: false - repos: - repo: https://github.com/psf/black-pre-commit-mirror - rev: 25.1.0 + rev: 26.3.1 hooks: - id: black - language_version: python3.12 - + language_version: python3 - repo: https://github.com/pycqa/flake8 - rev: 7.1.2 + rev: 7.0.0 hooks: - id: flake8 - language_version: python3.12 + language_version: python3 additional_dependencies: - flake8-bugbear==23.12.2 - flake8-builtins==2.2.0 @@ -22,18 +16,7 @@ repos: - flake8-rst-docstrings==0.3.0 - flake8-docstrings==1.7.0 - flake8-pyproject==1.2.3 - - repo: https://github.com/MiraGeoscience/pre-commit-hooks - rev: v1.1.0 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.16.6 hooks: - - id: prepare-commit-msg - - id: check-commit-msg - - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v5.0.0 - hooks: - - id: check-json - exclude_types: [jupyter] - - id: check-toml - - id: check-yaml - - id: check-added-large-files - - id: check-merge-conflict - - id: detect-private-key + - id: ruff-check diff --git a/Makefile b/Makefile index 2ede57730f..9014991ff0 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ STYLE_CHECK_FILES = simpeg examples tutorials tests GITHUB_ACTIONS=.github/workflows -.PHONY: help docs clean check black flake flake-all check-actions +.PHONY: help docs clean check black flake flake-all ruff check-actions help: @echo "Commands:" @@ -10,6 +10,7 @@ help: @echo " black checks code style with black" @echo " flake checks code style with flake8" @echo " flake-all checks code style with flake8 (full set of rules)" + @echo " ruff checks code style with ruff" @echo " check-actions lint GitHub Actions workflows (with zizmor)" @echo "" @@ -20,7 +21,7 @@ clean: cd docs;make clean find . -name "*.pyc" | xargs -I {} rm -v "{}" -check: black flake +check: black flake ruff check-actions black: black --version @@ -34,5 +35,8 @@ flake-all: flake8 --version flake8 ${FLAKE8_OPTS} --ignore "" ${STYLE_CHECK_FILES} +ruff: + ruff check ${STYLE_CHECK_FILES} + check-actions: zizmor ${GITHUB_ACTIONS} diff --git a/docs/_static/versions.json b/docs/_static/versions.json index c5a34bd9c5..f0274e9164 100644 --- a/docs/_static/versions.json +++ b/docs/_static/versions.json @@ -4,11 +4,26 @@ "url": "https://docs.simpeg.xyz/dev/" }, { - "name": "v0.25.0 (latest)", - "version": "0.25.0", - "url": "https://docs.simpeg.xyz/v0.25.0/", + "name": "v0.26.0 (latest)", + "version": "0.26.0", + "url": "https://docs.simpeg.xyz/v0.26.0/", "preferred": true }, + { + "name": "v0.25.2", + "version": "0.25.2", + "url": "https://docs.simpeg.xyz/v0.25.2/" + }, + { + "name": "v0.25.1", + "version": "0.25.1", + "url": "https://docs.simpeg.xyz/v0.25.1/" + }, + { + "name": "v0.25.0", + "version": "0.25.0", + "url": "https://docs.simpeg.xyz/v0.25.0/" + }, { "name": "v0.24.0", "version": "0.24.0", diff --git a/docs/conf.py b/docs/conf.py index d3f6ad339b..4959fad714 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -445,8 +445,10 @@ def linkcode_resolve(domain, info): "matplotlib": ("https://matplotlib.org/stable/", None), "properties": ("https://propertiespy.readthedocs.io/en/latest/", None), "discretize": ("https://discretize.simpeg.xyz/en/main/", None), - "pymatsolver": ("https://pymatsolver.readthedocs.io/en/latest/", None), + "pymatsolver": ("https://simpeg.xyz/pymatsolver/", None), "sklearn": ("https://scikit-learn.org/stable/", None), + "pytest": ("https://docs.pytest.org/en/stable/", None), + "typing_extensions": ("https://typing-extensions.readthedocs.io/en/latest", None), } numpydoc_xref_param_type = True @@ -482,7 +484,7 @@ def linkcode_resolve(domain, info): # path to your examples scripts "examples_dirs": ["../examples"] + tutorial_dirs, "gallery_dirs": ["content/user-guide/examples"] + tut_gallery_dirs, - "within_subsection_order": FileNameSortKey, + "within_subsection_order": "FileNameSortKey", "filename_pattern": "\.py", "backreferences_dir": "content/api/generated/backreferences", "doc_module": "simpeg", @@ -585,3 +587,29 @@ def build_redirects(): "content/user_guide": "../content/user-guide/index.html", } ) + + +def build_contributing_redirects() -> dict: + """ + Build dictionary for redirects after moving the contributors guide. + + Redirects old links from ``"content/user-guide/getting-started/contributing"`` to + ``"content/user-guide/contributing"``. + """ + files = [ + "working-with-github.html", + "setting-up-environment.html", + "code-style.html", + "documentation.html", + "testing.html", + "pull-requests.html", + "advanced.html", + ] + old = "content/user-guide/getting-started/contributing" + new = "../../contributing" + redirects = {f"{old}/{f}": f"{new}/{f}" for f in files} + redirects[f"{old}/index.html"] = f"{new}/introduction.html" + return redirects + + +redirects.update(build_contributing_redirects()) diff --git a/docs/content/release/0.25.1-notes.rst b/docs/content/release/0.25.1-notes.rst new file mode 100644 index 0000000000..716710ecbd --- /dev/null +++ b/docs/content/release/0.25.1-notes.rst @@ -0,0 +1,88 @@ +.. _0.25.1_notes: + +============================ +SimPEG v0.25.1 Release Notes +============================ + +February 12th, 2026 + +.. contents:: Highlights + :depth: 3 + +Updates +======= + +In this patch release we included a few bugfixes: + +- allow complex mu for forward time-domain em1d by `@jcapriot `__ in + https://github.com/simpeg/simpeg/pull/1739 +- Relaxes LogisticSigmoidMap bound restrictions by `@jcapriot `__ in + https://github.com/simpeg/simpeg/pull/1741 +- Temporary patch GMMs to be compatible with sklearn 1.8.0 by + `@santisoler `__ in https://github.com/simpeg/simpeg/pull/1742 +- Fix bug in apparent conductivity by `@dccowan `__ in + https://github.com/simpeg/simpeg/pull/1736 +- Fix bug in IP effects on EM1D simulations by `@GrindingTheophile `__ in + https://github.com/simpeg/simpeg/pull/1729 +- Hide ``BreakingChangeWarning`` from ``get_indices_block`` by + `@santisoler `__ in https://github.com/simpeg/simpeg/pull/1746 +- Fix bug in VRM effects on EM1D simulations by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1748 +- Fix for issue #1712 by `@TomSHudsonFST `__ in + https://github.com/simpeg/simpeg/pull/1738 + +And some improvements to the documentation: + +- Fix argument name in ``UpdateSensitivityWeights`` docs by `@santisoler `__ + in https://github.com/simpeg/simpeg/pull/1737 +- Improve docs of GMM classes by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1743 +- Improve docs of ``Survey.drape_electrodes_on_topography`` by + `@santisoler `__ in https://github.com/simpeg/simpeg/pull/1749 + + +Contributors +============ + +This is a combination of contributors and reviewers who have made contributions +towards this release (in no particular order): + +* `@dccowan `__ +* `@GrindingTheophile `__ +* `@jcapriot `__ +* `@santisoler `__ +* `@TomSHudsonFST `__ + +We would like to highlight the work made by new contributors: + +- `@GrindingTheophile `__ made their first contribution in + https://github.com/simpeg/simpeg/pull/1729 +- `@TomSHudsonFST `__ made their first contribution in + https://github.com/simpeg/simpeg/pull/1738 + + +Pull Requests +============= + +- Fix argument name in ``UpdateSensitivityWeights`` docs by `@santisoler `__ + in https://github.com/simpeg/simpeg/pull/1737 +- allow complex mu for forward time-domain em1d by `@jcapriot `__ in + https://github.com/simpeg/simpeg/pull/1739 +- Relaxes LogisticSigmoidMap bound restrictions by `@jcapriot `__ in + https://github.com/simpeg/simpeg/pull/1741 +- Temporary patch GMMs to be compatible with sklearn 1.8.0 by + `@santisoler `__ in https://github.com/simpeg/simpeg/pull/1742 +- Fix bug in apparent conductivity by `@dccowan `__ in + https://github.com/simpeg/simpeg/pull/1736 +- Improve docs of GMM classes by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1743 +- Fix bug in IP effects on EM1D simulations by `@GrindingTheophile `__ in + https://github.com/simpeg/simpeg/pull/1729 +- Hide ``BreakingChangeWarning`` from ``get_indices_block`` by + `@santisoler `__ in https://github.com/simpeg/simpeg/pull/1746 +- Fix bug in VRM effects on EM1D simulations by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1748 +- Fix for issue #1712 by `@TomSHudsonFST `__ in + https://github.com/simpeg/simpeg/pull/1738 +- Improve docs of ``Survey.drape_electrodes_on_topography`` by + `@santisoler `__ in https://github.com/simpeg/simpeg/pull/1749 diff --git a/docs/content/release/0.25.2-notes.rst b/docs/content/release/0.25.2-notes.rst new file mode 100644 index 0000000000..51c2ea4377 --- /dev/null +++ b/docs/content/release/0.25.2-notes.rst @@ -0,0 +1,26 @@ +.. _0.25.2_notes: + +============================ +SimPEG v0.25.2 Release Notes +============================ + +March 16th, 2026 + +Bug fixes and patches +===================== + +- Add patches to support Numpy 2.4 by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1759 +- Replace LaTeX ``align`` for ``aligned`` in math directives by + `@santisoler `__ in https://github.com/simpeg/simpeg/pull/1758 +- Improve type hints in ``distance_weighting`` by + `@santisoler `__ in https://github.com/simpeg/simpeg/pull/1756 + +Contributors +============ + +This is a combination of contributors and reviewers who have made contributions +towards this release (in no particular order): + +* `@santisoler `__ +* `@jcapriot `__ diff --git a/docs/content/release/0.26.0-notes.rst b/docs/content/release/0.26.0-notes.rst new file mode 100644 index 0000000000..f02cbce370 --- /dev/null +++ b/docs/content/release/0.26.0-notes.rst @@ -0,0 +1,288 @@ +.. _0.26.0_notes: + +=========================== +SimPEG 0.26.0 Release Notes +=========================== + +October 26th, 2026 + +.. contents:: Highlights + :depth: 3 + +Updates +======= + +New features +------------ + +Extended support to Python 3.15 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We extended support to Python 3.15 and Numpy 2.5. Starting from this release, we are running scheduled tests of SimPEG against the latest supported Python version and its dependencies. + +Improvements to Natural Sources EM +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This release ships several improvements and additions to the natural source electromagnetic (NSEM) simulations, sources, and receivers. + +We extended the capabilities of the +:class:`~simpeg.electromagnetics.natural_source.receivers.Impedance`, +:class:`~simpeg.electromagnetics.natural_source.receivers.Tipper`, +and +:class:`~simpeg.electromagnetics.natural_source.receivers.Admittance` +for 2D NSEM problems, making it possible to invert for Tipper and admittance data in 2D. +See more details in https://github.com/simpeg/simpeg/pull/1684. + +The 3D NSEM simulations that use the primary-secondary formulation now implement more suitable boundary conditions for the 1D NSEM problem that gets solved to build the primary field and the right-hand side. +See https://github.com/simpeg/simpeg/pull/1661 for more details. + +The number of padding cells that get added during 1D MT simulations are now estimated based on a certain number of skin depths. This makes the 1D MT simulations more robust for any type of mesh. +See more details in https://github.com/simpeg/simpeg/pull/1769. + +Add new NSEM receivers used to predict different rotation invariant transfer functions such as Root Gram Determinant, Cross Product Amplitude, Horizontal Determinant. +The apparent conductivity +:class:`~simpeg.electromagnetics.natural_source.receivers.ApparentConductivity` +receiver can be configured to generate the apparent conductivity datum through different transfer functions. + +Add new natural source receiver classes +:class:`~simpeg.electromagnetics.natural_source.receivers.RootGramDeterminant`, +:class:`~simpeg.electromagnetics.natural_source.receivers.CrossProductAmplitude`, +and :class:`~simpeg.electromagnetics.natural_source.receivers.HorizontalDeterminant`, +that can generate rotation invariant transfer functions as datum. +They are +primarily intended to be used for airborne NSEM systems, but can be used for +general survey configurations. Introduces a breaking change in the formula used +by :class:`~simpeg.electromagnetics.natural_source.receivers.ApparentConductivity` +to compute its datum. +Also, add a new formula argument to the +:class:`~simpeg.electromagnetics.natural_source.receivers.ApparentConductivity` +receiver to choose which method should be used to compute the transfer functions. +See more information in https://github.com/simpeg/simpeg/pull/1779. + + +Thin plate and line conductors +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This release ships a nice addition to our electromagnetic simulations: +we introduced a new set of *hierarchical* 2D and 3D simulations for DC, +frequency domain (FEM) and time domain (TDEM) that can take edge and face +conductivities as physical properties, allowing users to forward model and +invert for thin plate and line conductors. +A few examples of these classes are: +:class:`resistivity.Simulation3DHierarchicalNodal `, +:class:`frequency_domain.Simulation3DHierarchicalElectricField `, +and +:class:`time_domain.Simulation3DHierarchicalMagneticFluxDensity `. + +In the pre-existing DC and EM simulations we assign physical properties (like +conductivity, resistivity, chargeability parameters, etc.) to mesh cells. But +these new simluations allow us to assign conductivities to edges and faces in +the mesh, enabling users to model and invert for thin plate or line features. + +See more details in https://github.com/simpeg/simpeg/pull/1296. + + +Improvements to simulations that use ``multiprocessing`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We applied some improvements to increase robustness and memory efficiency in simulations that make use of ``multiprocessing`` for parallelization: + +- Enhance robustness and error handling in multiprocessing simulations + by `@jcapriot `__ in https://github.com/simpeg/simpeg/pull/1776 +- Make multiprocessing potential field kernel build using shared memory + by `@jcapriot `__ in https://github.com/simpeg/simpeg/pull/1816 + +General improvements and optimizations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Finally, we list here some other general improvements and optimizations that were applied to several parts of the codebase: + +- Optimize ``deriv`` method in parametric maps by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1754 +- Better map shapes by `@jcapriot `__ in + https://github.com/simpeg/simpeg/pull/1787 +- Store TDEM factorizations by `@jcapriot `__ in + https://github.com/simpeg/simpeg/pull/1832 +- Nsem recursive add zyx by `@dccowan `__ in + https://github.com/simpeg/simpeg/pull/1766 + +Documentation +------------- + +We moved the :ref:`Contributing Guide ` to its own separated section within the :ref:`User Guide `, and we included a new page explaining the process of :ref:`deprecating and removing code `. + +The documentation also received some minor fixes in style and some mathematical expressions. + + +Bugfixes +-------- + +This release introduces the following bugfixes: + +- Fix line feeds in natural_source/simulation.py to be LF instead by + `@jcapriot `__ in https://github.com/simpeg/simpeg/pull/1772 +- Make ``simpeg.utils.download`` respect the ``verbose`` argument by + `@manduinca `__ in https://github.com/simpeg/simpeg/pull/1777 +- Fix Maxwell equation in FDEM module description by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1778 +- Fix bug in ``getJ`` method of FDEM simulations by `@lheagy `__ in + https://github.com/simpeg/simpeg/pull/1822 +- Fix line current inconsistency between EB and HJ formulations by + `@lheagy `__ in https://github.com/simpeg/simpeg/pull/1812 +- Fix NSEM TreeMesh side columns, scalar ``sigma_primary``, FDEM + multi-source ``b``, and array ``mu`` by `@jcapriot `__ in + https://github.com/simpeg/simpeg/pull/1815 +- TileMap –> use the discretize volume averaging by `@lheagy `__ in + https://github.com/simpeg/simpeg/pull/1770 + + +Breaking changes +---------------- + +This release drops support for Python 3.11 (see `#1802 `__) since it reaches its end-of-life by the end of this month. + +We removed some deprecated bits of code that were due for this minor release: + +- Remove the ``warn`` argument in ``get_default_solver`` in https://github.com/simpeg/simpeg/pull/1797 +- Removed deprecated directives submodules in https://github.com/simpeg/simpeg/pull/1798 +- Remove deprecated properties of optimizers in https://github.com/simpeg/simpeg/pull/1799 +- Remove deprecated properties from directives in https://github.com/simpeg/simpeg/pull/1800 + +And we introduced some breaking changes while fixing some bugs and adding more features: + +- We fixed an inconsistency between the direction of the line currents between EB and HJ formulations in TDEM and FDEM simulations. We updated the HJ implementation of the line current so the current flows in the same direction as in the EB formulation. See https://github.com/simpeg/simpeg/pull/1812 for more details. +- https://github.com/simpeg/simpeg/pull/1779 introduced a change in how the + :class:`~simpeg.electromagnetics.natural_source.receivers.ApparentConductivity` receiver computes the apparent conductivity datum by default. + +Contributors +============ + +* `@dccowan `__ +* `@jcapriot `__ +* `@lheagy `__ +* `@manduinca `__ +* `@RylanDS7 `__ +* `@santisoler `__ + +We would like to highlight the work made by new contributors: + +- `@RylanDS7 `__ made their first contribution in + https://github.com/simpeg/simpeg/pull/1774 +- `@manduinca `__ made their first contribution in + https://github.com/simpeg/simpeg/pull/1777 + + +Pull Requests +============= + +- Update link to PyPI in release checklist by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1755 +- NSEM receivers for 2D simulation by `@dccowan `__ in + https://github.com/simpeg/simpeg/pull/1684 +- Add patches to support Numpy 2.4 by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1759 +- Replace LaTeX ``align`` for ``aligned`` in math directives by + `@santisoler `__ in https://github.com/simpeg/simpeg/pull/1758 +- Improve type hints in ``distance_weighting`` by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1756 +- Cherry-pick changelog for v0.25.2 by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1762 +- Improved right-hand side for NSEM primary secondary by `@dccowan `__ in + https://github.com/simpeg/simpeg/pull/1661 +- Remove unused functions in NSEM source utils by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1763 +- TileMap –> use the discretize volume averaging by `@lheagy `__ in + https://github.com/simpeg/simpeg/pull/1770 +- Add allow-unsafe-pr-checkout: true by `@jcapriot `__ in + https://github.com/simpeg/simpeg/pull/1773 +- Fix line feeds in natural_source/simulation.py to be LF instead by + `@jcapriot `__ in https://github.com/simpeg/simpeg/pull/1772 +- Fix math definition of RHS in FDEM simulations by `@RylanDS7 `__ in + https://github.com/simpeg/simpeg/pull/1774 +- Nsem recursive add zyx by `@dccowan `__ in + https://github.com/simpeg/simpeg/pull/1766 +- Stable padding for 1D MT solutions by `@dccowan `__ in + https://github.com/simpeg/simpeg/pull/1769 +- Make ``simpeg.utils.download`` respect the ``verbose`` argument by + `@manduinca `__ in https://github.com/simpeg/simpeg/pull/1777 +- Remove non-existing function from API reference by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1784 +- Move Contributing guide to its own section by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1781 +- Minor fixes to Contributing guide by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1782 +- Fix some ``numpydocstyle`` issues by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1785 +- Update URL to ``pymatsolver`` for ``intersphinx`` by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1783 +- Make ``sphinx-gallery`` configuration pickable by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1786 +- Use dependabot to check for updates in GitHub Actions by `@santisoler `__ + in https://github.com/simpeg/simpeg/pull/1789 +- Remove Action that runs ``reviewdog`` in PRs by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1795 +- Bump actions/checkout from 4 to 7 by `@dependabot `__ [bot] in + https://github.com/simpeg/simpeg/pull/1791 +- Bump actions/setup-python from 5 to 7 by `@dependabot `__ [bot] in + https://github.com/simpeg/simpeg/pull/1790 +- Drop support for Python 3.11 by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1802 +- Add Actions workflow to test against latest dependencies by + `@santisoler `__ in https://github.com/simpeg/simpeg/pull/1807 +- Run Ruff to check some ``pydocstyle`` errors by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1788 +- Bump black from 24.3.0 to 26.3.1 by `@dependabot `__ [bot] in + https://github.com/simpeg/simpeg/pull/1809 +- Extend Black target-version up to py314 by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1810 +- Remove the ``warn`` argument in ``get_default_solver`` by `@santisoler `__ + in https://github.com/simpeg/simpeg/pull/1797 +- Bump conda-incubator/setup-miniconda from 4.0.1 to 4.1.0 by + `@dependabot `__ [bot] in https://github.com/simpeg/simpeg/pull/1811 +- Removed deprecated directives submodules by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1798 +- Remove deprecated properties of optimizers by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1799 +- Replace the deprecated ``typing.Type`` for ``type`` by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1801 +- Remove deprecated properties from directives by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1800 +- Fix Maxwell equation in FDEM module description by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1778 +- Bump Python version to 3.14 in ``environment.yml`` by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1813 +- Add page on deprecating code to Contributing Guide by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1808 +- Enhance robustness and error handling in multiprocessing simulations + by `@jcapriot `__ in https://github.com/simpeg/simpeg/pull/1776 +- Make multiprocessing potential field kernel build using shared memory + by `@jcapriot `__ in https://github.com/simpeg/simpeg/pull/1816 +- Replace deprecated refine_tree_xyz across tests by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1466 +- Replace ``refine_tree_xyz`` in latest magnetic tests by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1819 +- Add rotation invariant transfer functions by `@dccowan `__ in + https://github.com/simpeg/simpeg/pull/1779 +- Replace ``refine_tree_xyz`` in examples by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1820 +- Fix bug in ``getJ`` method of FDEM simulations by `@lheagy `__ in + https://github.com/simpeg/simpeg/pull/1822 +- Minor updates to the release checklist by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1828 +- EMsimulation face and edge conductivities by `@dccowan `__ in + https://github.com/simpeg/simpeg/pull/1296 +- Fix line current inconsistency between EB and HJ formulations by + `@lheagy `__ in https://github.com/simpeg/simpeg/pull/1812 +- Replace deprecated ``discretize.utils.closest_points_index`` by + `@santisoler `__ in https://github.com/simpeg/simpeg/pull/1827 +- Optimize ``deriv`` method in parametric maps by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1754 +- Better map shapes by `@jcapriot `__ in + https://github.com/simpeg/simpeg/pull/1787 +- Fix NSEM TreeMesh side columns, scalar ``sigma_primary``, FDEM + multi-source ``b``, and array ``mu`` by `@jcapriot `__ in + https://github.com/simpeg/simpeg/pull/1815 +- Store TDEM factorizations by `@jcapriot `__ in + https://github.com/simpeg/simpeg/pull/1832 +- Bump Python to 3.15 in test against latest versions by `@santisoler `__ in + https://github.com/simpeg/simpeg/pull/1833 diff --git a/docs/content/release/index.rst b/docs/content/release/index.rst index dfa6fc1f20..18d45e08c8 100644 --- a/docs/content/release/index.rst +++ b/docs/content/release/index.rst @@ -7,6 +7,9 @@ Release Notes .. toctree:: :maxdepth: 2 + 0.26.0 <0.26.0-notes> + 0.25.2 <0.25.2-notes> + 0.25.1 <0.25.1-notes> 0.25.0 <0.25.0-notes> 0.24.0 <0.24.0-notes> 0.23.0 <0.23.0-notes> diff --git a/docs/content/user-guide/getting-started/contributing/advanced.rst b/docs/content/user-guide/contributing/advanced.rst similarity index 100% rename from docs/content/user-guide/getting-started/contributing/advanced.rst rename to docs/content/user-guide/contributing/advanced.rst diff --git a/docs/content/user-guide/contributing/code-style.rst b/docs/content/user-guide/contributing/code-style.rst new file mode 100644 index 0000000000..fee2139889 --- /dev/null +++ b/docs/content/user-guide/contributing/code-style.rst @@ -0,0 +1,59 @@ +.. _code-style: + +Code style +========== + +Consistency makes code more readable and easier for collaborators to jump in. SimPEG uses Black_ to autoformat its codebase, and flake8_ and Ruff_ to lint its code and enforce style rules. +Black_ can automatically format SimPEG's codebase to ensure it complies with Black code style. +flake8_ and Ruff_ perform style checks, raise warnings on code that could lead towards bugs, performs checks on consistent documentation formatting, and identifies poor coding practices. + +.. hint:: + + If you :ref:`configure pre-commit `, it will + automatically run Black, flake8, and Ruff on every commit. + +One can manually run Black_, flake8_, and Ruff_ anytime. + +- Run ``black`` on SimPEG directories that contain Python source files: + + .. code:: bash + + black . + +- Run ``flake8`` on the whole project with: + + .. code:: bash + + flake8 + +- Run ``ruff`` on the whole project with: + + .. code:: bash + + ruff check + +.. important:: + + Following code style rules can be challenging for new contributors. These + rules are meant to ease the development process, not to generate an obstacle + to contribute. Please, don't hesistate to **ask for help** if your + contribution raises some flake8 errors. And **feel free to push** code that + **don't follow our code style 100%** in :ref:`pull-requests`. Other + developers will be there to help you solve them. + +.. note:: + + SimPEG is currently not `PEP 8 `_ + compliant and is not following all flake8 rules, but we are working towards + it and would appreciate contributions that do too! + +.. hint:: + + Configurations for Black_, flake8_, and Ruff_ live inside the ``pyproject.toml`` file, under the ``tool`` section. + Refer to their respective documentation pages to learn how each tool can be configured, and what each different rule checks for. + + +.. _Black: https://black.readthedocs.io/ +.. _flake8: https://flake8.pycqa.org/ +.. _Ruff: https://docs.astral.sh/ +.. _pre-commit: https://pre-commit.com/ diff --git a/docs/content/user-guide/contributing/deprecations.rst b/docs/content/user-guide/contributing/deprecations.rst new file mode 100644 index 0000000000..403a9ac400 --- /dev/null +++ b/docs/content/user-guide/contributing/deprecations.rst @@ -0,0 +1,325 @@ +.. _deprecations: + +Deprecating code +================ + +During the development of SimPEG we might run into situations in which we would like to change the way users interact with a particular piece of code, for example: + +* renaming a function or class, +* renaming an argument or attribute, +* reorganizing objects into another submodule. + +Applying such changes at once would introduce a *breaking change*, i.e. a change that breaks backward compatibility. This means that users' code written with a previous version of SimPEG will fail when they update to the next version. + +Encoutering breaking changes can be frustrating. For this reason, any breaking change that removes a piece of code will be introduced through a **deprecation cycle**. Any deprecation cycle consists broadly in the following steps: + +1. **Deprecate** the bit of code where the breaking change will be introduced. +2. Wait **two minor releases**. +3. **Remove** the deprecated bit of code (introduce a *breaking change*). + +The goal is for users to get warnings on a future breaking change and instructions on how to update their code before the breaking change is finally introduced. + +Deprecation +----------- + +*Deprecation* is the act of discouraging the use of a particular bit of code, argument, attribute, property, etc. + +We keep deprecated code in our code base during a sensible amount of time (usually two minor releases), make sure that it behaves in the same way as before, and keep its tests to guarantee that its behavior won't change until the breaking change is introduced. + +We raise a ``warnings.FutureWarning`` any time that bit of code is accessed or used. Such warning should: + +* warn them about its future removal or change, +* let them know in which future version the breaking change will get introduced, +* provide instructions on how to update their code. + +.. hint:: + + We use ``warnings.FutureWarning`` to warn users about deprecations and future removals because this type of warnings are shown by default. + Python also ships a :class:`warnings.DeprecationWarning`, which is intended for Python developers. + By default, all :class:`warnings.DeprecationWarning` are filtered and not shown. + + +Deprecating functions or classes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Python offers built-in utilities to ease the deprecation process. +We can use the :func:`warnings.deprecated` (or :func:`typing_extensions.deprecated` for Python < 3.13) decorator to deprecate functions, classes, and methods. + +For example, consider the ``gettopoCC`` function: + +.. code:: python + + def gettopoCC(mesh, ind_active, option="top"): + ... + +that we want to rename to a PEP8 compliant name, like ``get_discrete_topography`` that will live in ``simpeg.utils.get_discrete_topography``. We can use the +:func:`~warnings.deprecated` decorator to deprecate it: + +.. code:: python + + from warnings import deprecated + + @deprecated( + "The `gettopoCC` function is deprecated, and will be removed in SimPEG v0.27.0. " + "This functionality has been replaced by the 'get_discrete_topography' " + "function, which can be imported from simpeg.utils.", + category=FutureWarning, + ) + def gettopoCC(mesh, ind_active, option="top"): + ... + +Anytime that the ``gettopoCC`` is called, we'll get the following warning: + +.. code:: python + + mesh, ind_active = ..., ... + gettopoCC(mesh, ind_active) + +.. code:: + + FutureWarning: The `gettopoCC` function is deprecated, and will be removed in SimPEG v0.27.0. This functionality has been replaced by the 'get_discrete_topography' function, which can be imported from simpeg.utils. + +A similar procedure can be applied to classes: + +.. code:: python + + @deprecated( + "The `Simulation3D` class is deprecatd. " + "It will be removed in SimPEG v0.28.0. " + "Please use SimulationMagnetic instead." + ) + class Simulation3D: + + ... + +methods: + +.. code:: python + + class SimulationMagnetic: + + @deprecated( + "The `get_indActive` method is deprecated and will be removed in " + "SimPEG v0.29.0. " + "Please use the `active_cells` property instead." + ) + def get_indActive(self): + ... + + @property + def active_cells(self): + ... + +and properties: + +.. code:: python + + class SimulationMagnetic: + + @property + @deprecated( + "The `indActive` property is deprecated and will be removed in " + "SimPEG v0.29.0. " + "Please use the `active_cells` property instead." + ) + def indActive(self): + ... + + @indActive.setter + @deprecated( + "The `indActive` property is deprecated and will be removed in " + "SimPEG v0.29.0. " + "Please use the `active_cells` property instead." + ) + def indActive(self, value): + ... + + @property + def active_cells(self): + ... + + @active_cells.setter + def active_cells(self, value): + ... + +Deprecating arguments +~~~~~~~~~~~~~~~~~~~~~ + +When renaming an argument from a function or method we'll need to ensure to raise a +``warnings.FutureWarning`` within its body. For example, consider an ``InjectActiveCells`` map that takes ``indActive`` as argument for its constructor: + +.. code:: python + + from simpeg.maps import IdentityMap + + class InjectActiveCells(IdentityMap): + + def __init__(self, mesh, indActive=None): + self.indActive = indActive + ... + +We want to rename the ``indActive`` argument in favor of ``active_cells``. We can do so by deprecating the ``indActive`` argument first: + +.. code:: python + + import warnings + + from simpeg.maps import IdentityMap + + class InjectActiveCells(IdentityMap): + + def __init__(self, mesh, active_cells=None, **kwargs): + if "indActive" in kwargs: + # Warn about deprecation + msg = ( + "Argument 'indActive' is deprecated and will be removed in " + "SimPEG v0.27.0. Use the 'active_cells' argument instead." + ) + warnings.warn(msg, category=FutureWarning) + + # Raise error if both arguments are passed + if active_cells is not None: + msg = "Invalid arguments: cannot pass 'active_cells' and 'indActive' simultanously." + raise TypeError(msg) + + # Assign active_cells to the passed indActive + self.active_cells = kwargs.pop("indActive") + else: + self.active_cells = active_cells + + # Raise error if users passed any other argument through kwargs + if kwargs: + args = "', '".join(list(kwargs.keys())) + msg = f"Invalid arguments '{args}' passed." + raise TypeError(msg) + + +.. important:: + + It's recommended to add tests to check the expected behaviour of the function + to ensure that the warnings and errors are corretly raised, and the arguments + correctly processed. + + +Testing the deprecations +~~~~~~~~~~~~~~~~~~~~~~~~ + +It's recommended to test the deprecation warnings are raised when deprecating a bit of code. +We can easily check that with the :func:`pytest.warns` context manager. +For example, we could test if the previous ``InjectActiveCells`` map warns when passing ``indActive`` as argument: + +.. code:: python + + import re + import pytest + + def test_deprecated_indactive(): + """Test FutureWarning after passing indActive to InjectActiveCells.""" + mesh = ... + active_cells = ... + match = re.escape("Argument 'indActive' is deprecated and will be removed ") + with pytest.warns(FutureWarning, match=match): + InjectActiveCells(mesh, indActive=active_cells) + +If ``InjectActiveCells.__init__`` throws a ``warnings.FutureWarning`` with a message that matches the passed pattern, the tests passes. +Otherwise, the test will fail. + + +Documenting deprecations +~~~~~~~~~~~~~~~~~~~~~~~~ + +When deprecating a function, class, or argument it's a good practice to document such deprecation. We can use the ``deprecated`` admonition. +For example, we can add such admonition when deprecating a function, method, or class: + +.. code:: python + + @deprecated( + "The `gettopoCC` function is deprecated, and will be removed in SimPEG v0.27.0. " + "This functionality has been replaced by the 'get_discrete_topography' " + "function, which can be imported from simpeg.utils.", + category=FutureWarning, + ) + def gettopoCC(mesh, ind_active, option="top"): + """ + Generate discrete topography locations from mesh and active cells. + + .. deprecated:: 0.25.0 + + The ``gettopoCC`` function is deprecated and will be + removed in SimPEG v0.27.0. This function has been replaced by the + :func:`simpeg.utils.get_discrete_topography` function. + + Parameters + ---------- + """ + ... + + +.. note:: + + Note that we can add the version in which the deprecation got introduced in the ``.. deprecated::`` line. + + +The same admonition can be added when deprecating arguments: + +.. code:: python + + class InjectActiveCells(IdentityMap): + """ + Map active cells model to all cell of a mesh. + + Parameters + ---------- + mesh : discretize.BaseMesh + A discxretize mesh. + active_cells : numpy.ndarray + Active cells array. Can be a boolean ``numpy.ndarray`` of length *mesh.nC* + or a ``numpy.ndarray`` of ``int`` containing the indices of the active cells. + ind_active : numpy.ndarray + Active cells array. Can be a boolean ``numpy.ndarray`` of length *mesh.nC* + or a ``numpy.ndarray`` of ``int`` containing the indices of the active cells. + .. deprecated:: 0.25.0 + + The ``indActive`` argument is deprecated and will be removed in + SimPEG v0.27.0. Use the ``active_cells`` argument instead. + ... + """ + + def __init__(self, mesh, active_cells=None, **kwargs): + ... + +Removals +-------- + +When removing a bit of code it's usually a good practice to raise an error when the old object is accessed, along with information about in which version it got removed and instructions on how to update their code. This way, even if the user missed the deprecation warning, they will receive some information. +For example, we can raise a warning if the removed ``Simulation3D`` class is instantiated: + + +.. code:: python + + class Simulation3D: + + def __init__(self, *args, **kwargs): + msg = ( + "The Simulation3D class has been removed in SimPEG v0.28.0. " + "Use SimulationMagnetic instead." + ) + raise AttributeError(msg) + + +We should also add a test making sure that the ``Simulation3D`` class cannot be instantiated anymore. +We can use the :func:`pytest.raises` context manager for that: + + +.. code:: python + + def test_removed_simulation_3d(): + """Test error after instantiating the removed ``Simulation3D`` class.""" + with pytest.raises(AttributeError, match="The Simulation3D class has been removed"): + Simulation3D() + + +.. important:: + + Do not remove deprecated bits of code as part of another Pull Request that implements a new feature or fixes the bug. + Removals of code should live in their own Pull Request, so it's easy to track down when and how that bit of code was removed. diff --git a/docs/content/user-guide/getting-started/contributing/documentation.rst b/docs/content/user-guide/contributing/documentation.rst similarity index 100% rename from docs/content/user-guide/getting-started/contributing/documentation.rst rename to docs/content/user-guide/contributing/documentation.rst diff --git a/docs/content/user-guide/getting-started/contributing/index.rst b/docs/content/user-guide/contributing/introduction.rst similarity index 95% rename from docs/content/user-guide/getting-started/contributing/index.rst rename to docs/content/user-guide/contributing/introduction.rst index cb26c41c54..af8948b131 100644 --- a/docs/content/user-guide/getting-started/contributing/index.rst +++ b/docs/content/user-guide/contributing/introduction.rst @@ -71,18 +71,6 @@ fixes a bug, adds a new feature, improves the documentation or extends our tests. In the following pages you'll find information on how to get started to contribute with new code to SimPEG. -.. toctree:: - :maxdepth: 1 - - working-with-github - setting-up-environment - code-style - documentation - testing - pull-requests - advanced - - Licensing ~~~~~~~~~ diff --git a/docs/content/user-guide/getting-started/contributing/pull-requests.rst b/docs/content/user-guide/contributing/pull-requests.rst similarity index 92% rename from docs/content/user-guide/getting-started/contributing/pull-requests.rst rename to docs/content/user-guide/contributing/pull-requests.rst index 75ee05bcdd..126e058949 100644 --- a/docs/content/user-guide/getting-started/contributing/pull-requests.rst +++ b/docs/content/user-guide/contributing/pull-requests.rst @@ -37,11 +37,11 @@ it might take some time for us to get your PR. Merging a Pull Request ---------------------- -The ``@simpeg/simpeg-admin`` will merge a Pull Request to the `main` branch +The ``@simpeg/simpeg-admin`` will merge a Pull Request to the ``main`` branch using the `Squash and Merge `_ -strategy: all commits made to the PR branch will be _squashed_ to a single -commit that will be added to `main`. +strategy: all commits made to the PR branch will be *squashed* to a single +commit that will be added to ``main``. SimPEG admins will ensure that the commit message is descriptive and comprehensive. Contributors can help by providing a descriptive and diff --git a/docs/content/user-guide/getting-started/contributing/setting-up-environment.rst b/docs/content/user-guide/contributing/setting-up-environment.rst similarity index 86% rename from docs/content/user-guide/getting-started/contributing/setting-up-environment.rst rename to docs/content/user-guide/contributing/setting-up-environment.rst index c5dd3a95ce..9776b51010 100644 --- a/docs/content/user-guide/getting-started/contributing/setting-up-environment.rst +++ b/docs/content/user-guide/contributing/setting-up-environment.rst @@ -84,26 +84,17 @@ This practice also allows you to uninstall SimPEG if so desired: Check your installation ----------------------- -You should be able to open a terminal within simpeg/tutorials and run an -example, i.e. +You should be able to import SimPEG by opening a terminal or a Jupyter Notebook and running: -.. code:: - - python 02-linear_inversion/plot_inv_1_inversion_lsq.py - -or you can download and run the :ref:`notebook from the docs -`. +.. code:: python -.. image:: ../../tutorials/02-linear_inversion/images/sphx_glr_plot_inv_1_inversion_lsq_003.png + import simpeg -You are now set up to SimPEG! - -.. note:: +You can check the installed version by accesing ``simpeg.__version__``: - If all is not well, please submit an issue_ and `change this file`_! +.. code:: python -.. _issue: https://github.com/simpeg/simpeg/issues -.. _change this file: https://github.com/simpeg/simpeg/edit/main/docs/content/getting_started/contributing/setting-up-environment.rst + print(simpeg.__version__) .. _configure-pre-commit: diff --git a/docs/content/user-guide/getting-started/contributing/testing.rst b/docs/content/user-guide/contributing/testing.rst similarity index 100% rename from docs/content/user-guide/getting-started/contributing/testing.rst rename to docs/content/user-guide/contributing/testing.rst diff --git a/docs/content/user-guide/getting-started/contributing/working-with-github.rst b/docs/content/user-guide/contributing/working-with-github.rst similarity index 93% rename from docs/content/user-guide/getting-started/contributing/working-with-github.rst rename to docs/content/user-guide/contributing/working-with-github.rst index 979cab63ef..8317d49518 100644 --- a/docs/content/user-guide/getting-started/contributing/working-with-github.rst +++ b/docs/content/user-guide/contributing/working-with-github.rst @@ -25,7 +25,7 @@ There are two ways you can clone a repository: 2. Using a desktop client such as SourceTree_ or GitKraken_. - .. image:: ../../../../images/sourceTreeSimPEG.png + .. image:: ../../../images/sourceTreeSimPEG.png :align: center :width: 400 :target: https://www.sourcetreeapp.com/ @@ -34,7 +34,7 @@ There are two ways you can clone a repository: it is also handy to set up the remote account so it remembers your github_ user name and password - .. image:: ../../../../images/sourceTreeRemote.png + .. image:: ../../../images/sourceTreeRemote.png :align: center :width: 400 diff --git a/docs/content/user-guide/getting-started/contributing/code-style.rst b/docs/content/user-guide/getting-started/contributing/code-style.rst deleted file mode 100644 index 3202d48ac2..0000000000 --- a/docs/content/user-guide/getting-started/contributing/code-style.rst +++ /dev/null @@ -1,48 +0,0 @@ -.. _code-style: - -Code style -========== - -Consistency makes code more readable and easier for collaborators to jump in. -SimPEG uses Black_ to autoformat its codebase, and flake8_ to lint its code and -enforce style rules. Black_ can automatically format SimPEG's codebase to -ensure it complies with Black code style. flake8_ performs style checks, raises -warnings on code that could lead towards bugs, performs checks on consistent -documentation formatting, and identifies poor coding practices. - -.. hint:: - - If you :ref:`configure pre-commit `, it will - automatically run Black and flake8 on every commit. - -One can manually run Black_ and flake8_ anytime. -Run ``black`` on SimPEG directories that contain Python source files: - -.. code:: - - black . - -Run ``flake8`` on the whole project with: - -.. code:: - - flake8 - -.. important:: - - Following code style rules can be challenging for new contributors. These - rules are meant to ease the development process, not to generate an obstacle - to contribute. Please, don't hesistate to **ask for help** if your - contribution raises some flake8 errors. And **feel free to push** code that - **don't follow our code style 100%** in :ref:`pull-requests`. Other - developers will be there to help you solve them. - -.. note:: - - SimPEG is currently not `PEP 8 `_ - compliant and is not following all flake8 rules, but we are working towards - it and would appreciate contributions that do too! - -.. _Black: https://black.readthedocs.io/ -.. _flake8: https://flake8.pycqa.org/ -.. _pre-commit: https://pre-commit.com/ diff --git a/docs/content/user-guide/getting-started/version-compatibility.rst b/docs/content/user-guide/getting-started/version-compatibility.rst index b4d5117c6d..9d3c203962 100644 --- a/docs/content/user-guide/getting-started/version-compatibility.rst +++ b/docs/content/user-guide/getting-started/version-compatibility.rst @@ -36,3 +36,5 @@ following releases to ensure compatibility: - 0.22.2 * - 3.10 - 0.24.0 + * - 3.11 + - 0.25.2 diff --git a/docs/content/user-guide/how-to-guide/choosing-solvers.rst b/docs/content/user-guide/how-to-guide/choosing-solvers.rst index b46c12da9e..6228e70768 100644 --- a/docs/content/user-guide/how-to-guide/choosing-solvers.rst +++ b/docs/content/user-guide/how-to-guide/choosing-solvers.rst @@ -20,18 +20,9 @@ The choice of an appropriate solver can affect the computation time required to solve the PDE. Generally we recommend using direct solvers over iterative solvers for SimPEG, but be aware that direct solvers have much larger memory requirements. -The ``Pardiso`` solver wraps the `oneMKL PARDISO -`_ -solver available for x86_64 CPUs. - -The ``Mumps`` solver wraps `MUMPS -`_, a fast solver available for -all CPU brands, including Apple silicon architecture. - -The ``SolverLU`` wraps SciPy's :func:`scipy.sparse.linalg.splu`. The -performance of this solver is not up to the level of ``Mumps`` and ``Pardiso``. -Usage of the ``SolveLU`` is recommended only when it's not possible to use -other faster solvers. +- The :class:`~pymatsolver.Pardiso` solver wraps the `oneMKL PARDISO `_ solver available for x86_64 CPUs. +- The :class:`~pymatsolver.Mumps` solver wraps `MUMPS `_, a fast solver available for all CPU brands, including Apple silicon architecture. +- The :class:`~pymatsolver.SolverLU` wraps SciPy's :func:`scipy.sparse.linalg.splu`. The performance of this solver is not up to the level of :class:`~pymatsolver.Mumps` and :class:`~pymatsolver.Pardiso`. Usage of the :class:`~pymatsolver.SolveLU` is recommended only when it's not possible to use other faster solvers. The default solver @@ -75,18 +66,18 @@ We can then use this solver in a simulation: .. note:: - The priority list used to choose a default solver is: + The priority list used to choose a default solver is: - 1) ``Pardiso`` - 2) ``Mumps`` - 3) ``SolverLU`` + 1) :class:`pymatsolver.Pardiso` + 2) :class:`pymatsolver.Mumps` + 3) :class:`pymatsolver.SolverLU` Setting solvers manually ------------------------ Alternatively, we can manually set a solver. For example, if we want to use -``Mumps`` in our DC resistivity simulation, we can import +MUMPS in our DC resistivity simulation, we can import :class:`pymatsolver.Mumps` and pass it to our simulation: .. code:: python @@ -99,12 +90,14 @@ Alternatively, we can manually set a solver. For example, if we want to use .. note:: - When sharing your notebook or script with a colleague, keep in mind that - your code might not work if ``Pardiso`` is not available in their system. + When sharing this code with a colleague, keep in mind that + it might not work if MUMPS is not available in their system. For such scenarios, we recommend using the :func:`simpeg.utils.get_default_solver` function, that will always return a suitable solver for the current system. -Ultimately, choosing the best solver is a mixture of the problem you are solving and your current system. Experiment with different solvers yourself to choose the best. +Ultimately, choosing the best solver is a mixture of the problem you are solving +and your current system. Experiment with different solvers yourself to choose +the best. diff --git a/docs/content/user-guide/index.rst b/docs/content/user-guide/index.rst index 8ca423fb58..b8a7aa9f3e 100644 --- a/docs/content/user-guide/index.rst +++ b/docs/content/user-guide/index.rst @@ -17,7 +17,6 @@ For details on the available classes and functions in SimPEG, please visit the getting-started/about-simpeg.rst getting-started/big_picture getting-started/installing - getting-started/contributing/index.rst getting-started/citing.rst getting-started/version-compatibility.rst @@ -29,6 +28,21 @@ For details on the available classes and functions in SimPEG, please visit the how-to-guide/choosing-solvers how-to-guide/move-mesh-to-survey.rst +.. toctree:: + :glob: + :maxdepth: 1 + :caption: Contributing + + contributing/introduction.rst + contributing/working-with-github.rst + contributing/setting-up-environment.rst + contributing/code-style.rst + contributing/documentation.rst + contributing/testing.rst + contributing/pull-requests.rst + contributing/deprecations.rst + contributing/advanced.rst + .. toctree:: :glob: :maxdepth: 1 diff --git a/environment.yml b/environment.yml index 6f72ad3242..b126c62178 100644 --- a/environment.yml +++ b/environment.yml @@ -3,7 +3,7 @@ channels: - conda-forge dependencies: # dependencies - - python=3.11 + - python=3.14 - numpy>=1.22 - scipy>=1.12 - pymatsolver>=0.3 @@ -51,7 +51,7 @@ dependencies: # style checking - pre-commit - - black==24.3.0 + - black==26.3.1 - flake8==7.0.0 - flake8-pyproject==1.2.3 - flake8-bugbear==23.12.2 @@ -60,6 +60,7 @@ dependencies: - flake8-rst-docstrings==0.3.0 - flake8-docstrings==1.7.0 - zizmor # lint GitHub Actions workflows + - ruff # recommended - jupyter diff --git a/examples/02-gravity/plot_inv_grav_tiled.py b/examples/02-gravity/plot_inv_grav_tiled.py index 2178532cc3..238752d32c 100644 --- a/examples/02-gravity/plot_inv_grav_tiled.py +++ b/examples/02-gravity/plot_inv_grav_tiled.py @@ -21,7 +21,7 @@ directives, inversion, ) -from discretize.utils import mesh_builder_xyz, refine_tree_xyz, active_from_xyz +from discretize.utils import mesh_builder_xyz, active_from_xyz from simpeg import utils @@ -61,7 +61,6 @@ # Mesh parameters h = [5, 5, 5] padDist = np.ones((3, 2)) * 100 -octree_levels = [8, 4] # Create tiles local_indices = [rxLoc[:, 0] <= 0, rxLoc[:, 0] > 0] @@ -76,11 +75,10 @@ local_mesh = mesh_builder_xyz( topo, h, padding_distance=padDist, depth_core=100, mesh_type="tree" ) - local_mesh = refine_tree_xyz( - local_mesh, + local_mesh.refine_surface( local_survey.receiver_locations, - method="surface", - octree_levels=octree_levels, + level=-1, + padding_cells_by_level=3, finalize=True, ) @@ -197,7 +195,7 @@ inject_local * (local_map * model), normal="Y", ax=ax, grid=True ) ax.set_aspect("equal") - ax.set_title(f"Mesh {ii+1}. Active cells {local_map.local_active.sum()}") + ax.set_title(f"Mesh {ii + 1}. Active cells {local_map.local_active.sum()}") # Create active map to go from reduce set to full @@ -242,7 +240,7 @@ irls_cooling_factor=1.5, misfit_tolerance=1e-2, ) -saveDict = directives.SaveOutputEveryIteration(save_txt=False) +saveDict = directives.SaveOutputEveryIteration(on_disk=False) update_Jacobi = directives.UpdatePreconditioner() sensitivity_weights = directives.UpdateSensitivityWeights(every_iteration=False) inv = inversion.BaseInversion( diff --git a/examples/03-magnetics/plot_inv_mag_MVI_Sparse_TreeMesh.py b/examples/03-magnetics/plot_inv_mag_MVI_Sparse_TreeMesh.py index 02088a0950..cc47c4661e 100644 --- a/examples/03-magnetics/plot_inv_mag_MVI_Sparse_TreeMesh.py +++ b/examples/03-magnetics/plot_inv_mag_MVI_Sparse_TreeMesh.py @@ -35,7 +35,6 @@ import numpy as np import matplotlib.pyplot as plt - # sphinx_gallery_thumbnail_number = 3 ############################################################################### diff --git a/examples/03-magnetics/plot_inv_mag_MVI_VectorAmplitude.py b/examples/03-magnetics/plot_inv_mag_MVI_VectorAmplitude.py index 5cf55b5eeb..79851836d8 100644 --- a/examples/03-magnetics/plot_inv_mag_MVI_VectorAmplitude.py +++ b/examples/03-magnetics/plot_inv_mag_MVI_VectorAmplitude.py @@ -24,12 +24,11 @@ from simpeg import utils from simpeg.utils import mkvc, sdiag -from discretize.utils import mesh_builder_xyz, refine_tree_xyz, active_from_xyz +from discretize.utils import mesh_builder_xyz, active_from_xyz from simpeg.potential_fields import magnetics import numpy as np import matplotlib.pyplot as plt - # sphinx_gallery_thumbnail_number = 3 ############################################################################### @@ -85,9 +84,7 @@ mesh = mesh_builder_xyz( xyzLoc, h, padding_distance=padDist, depth_core=100, mesh_type="tree" ) -mesh = refine_tree_xyz( - mesh, topo, method="surface", octree_levels=[2, 6], finalize=True -) +mesh.refine_surface(topo, level=-1, padding_cells_by_level=[3, 3], finalize=True) # Define an active cells from topo @@ -241,7 +238,6 @@ plt.show() -print("END") # Plot the final predicted data and the residual # plt.figure() # ax = plt.subplot(1, 2, 1) diff --git a/examples/03-magnetics/plot_inv_mag_nonLinear_Amplitude.py b/examples/03-magnetics/plot_inv_mag_nonLinear_Amplitude.py index 643df614ca..77d0906909 100644 --- a/examples/03-magnetics/plot_inv_mag_nonLinear_Amplitude.py +++ b/examples/03-magnetics/plot_inv_mag_nonLinear_Amplitude.py @@ -34,7 +34,7 @@ from simpeg.potential_fields import magnetics from simpeg import utils from simpeg.utils import mkvc -from discretize.utils import mesh_builder_xyz, refine_tree_xyz, active_from_xyz +from discretize.utils import mesh_builder_xyz, active_from_xyz # sphinx_gallery_thumbnail_number = 4 @@ -111,9 +111,7 @@ mesh = mesh_builder_xyz( rxLoc, h, padding_distance=padDist, depth_core=100, mesh_type="tree" ) -mesh = refine_tree_xyz( - mesh, topo, method="surface", octree_levels=[4, 4], finalize=True -) +mesh.refine_surface(topo, level=-1, padding_cells_by_level=[3, 2], finalize=True) # Define the active cells from topo actv = active_from_xyz(mesh, topo) diff --git a/examples/04-dcip/plot_dc_analytic.py b/examples/04-dcip/plot_dc_analytic.py index b926c247a3..e9724195c4 100644 --- a/examples/04-dcip/plot_dc_analytic.py +++ b/examples/04-dcip/plot_dc_analytic.py @@ -12,7 +12,6 @@ import matplotlib.pyplot as plt from simpeg.electromagnetics.static import resistivity as DC - cs = 25.0 hx = [(cs, 7, -1.3), (cs, 21), (cs, 7, 1.3)] hy = [(cs, 7, -1.3), (cs, 21), (cs, 7, 1.3)] diff --git a/examples/05-fdem/plot_0_fdem_analytic.py b/examples/05-fdem/plot_0_fdem_analytic.py index 24f3ecc75c..09b12c81ea 100644 --- a/examples/05-fdem/plot_0_fdem_analytic.py +++ b/examples/05-fdem/plot_0_fdem_analytic.py @@ -24,7 +24,6 @@ import matplotlib.pyplot as plt from matplotlib.colors import LogNorm - ##################################################################### # Magnetic Fields for a Magnetic Dipole Source # -------------------------------------------- diff --git a/examples/05-fdem/plot_inv_fdem_loop_loop_2Dinversion.py b/examples/05-fdem/plot_inv_fdem_loop_loop_2Dinversion.py index 99bb11c07b..9fb392d9f2 100644 --- a/examples/05-fdem/plot_inv_fdem_loop_loop_2Dinversion.py +++ b/examples/05-fdem/plot_inv_fdem_loop_loop_2Dinversion.py @@ -93,12 +93,12 @@ def interface(x): npady = 7 # number of padding cells in the y-direction npadz = 11 # number of padding cells in the z-direction -core_domain_x = np.r_[-11.5, 11.5] # extent of uniform cells in the x-direction -core_domain_z = np.r_[-2.0, 0.0] # extent of uniform cells in the z-direction +xmin, xmax = -11.5, 11.5 # extent of uniform cells in the x-direction +zmin, zmax = -2.0, 0.0 # extent of uniform cells in the z-direction # number of cells in the core region -ncx = int(np.diff(core_domain_x) / csx) -ncz = int(np.diff(core_domain_z) / csz) +ncx = int((xmax - xmin) / csx) +ncz = int((zmax - zmin) / csx) # create a 3D tensor mesh mesh = discretize.TensorMesh( diff --git a/examples/06-tdem/plot_0_tdem_analytic.py b/examples/06-tdem/plot_0_tdem_analytic.py index 736d792fb5..7836c8315a 100644 --- a/examples/06-tdem/plot_0_tdem_analytic.py +++ b/examples/06-tdem/plot_0_tdem_analytic.py @@ -24,7 +24,6 @@ import matplotlib.pyplot as plt from matplotlib.colors import LogNorm - ##################################################################### # Magnetic Fields for a Transient Magnetic Dipole Source # ------------------------------------------------------ diff --git a/examples/08-vrm/plot_fwd_vrm.py b/examples/08-vrm/plot_fwd_vrm.py index 9b87566329..0eca69d12a 100644 --- a/examples/08-vrm/plot_fwd_vrm.py +++ b/examples/08-vrm/plot_fwd_vrm.py @@ -22,7 +22,6 @@ import matplotlib.pyplot as plt import matplotlib as mpl - ########################################################################## # Defining the mesh # ----------------- diff --git a/examples/08-vrm/plot_inv_vrm_eq.py b/examples/08-vrm/plot_inv_vrm_eq.py index 60e9176edb..a5a985d46b 100644 --- a/examples/08-vrm/plot_inv_vrm_eq.py +++ b/examples/08-vrm/plot_inv_vrm_eq.py @@ -33,7 +33,6 @@ import matplotlib.pyplot as plt import matplotlib as mpl - ########################################################################## # Defining the mesh # ----------------- diff --git a/examples/_archived/plot_inv_grav_linear.py b/examples/_archived/plot_inv_grav_linear.py index 68752be2ee..ed83134fde 100644 --- a/examples/_archived/plot_inv_grav_linear.py +++ b/examples/_archived/plot_inv_grav_linear.py @@ -126,7 +126,7 @@ def run(plotIt=True): irls_cooling_factor=1.5, misfit_tolerance=1e-2, ) - saveDict = directives.SaveOutputEveryIteration(save_txt=False) + saveDict = directives.SaveOutputEveryIteration(on_disk=False) update_Jacobi = directives.UpdatePreconditioner() sensitivity_weights = directives.UpdateSensitivityWeights(every_iteration=False) inv = inversion.BaseInversion( diff --git a/examples/_archived/plot_inv_mag_linear.py b/examples/_archived/plot_inv_mag_linear.py index 438ab3dea2..ed3d752691 100644 --- a/examples/_archived/plot_inv_mag_linear.py +++ b/examples/_archived/plot_inv_mag_linear.py @@ -129,7 +129,7 @@ def run(plotIt=True): # Use pick a threshold parameter empirically based on the distribution of # model parameters IRLS = directives.UpdateIRLS(f_min_change=1e-3, max_irls_iterations=40) - saveDict = directives.SaveOutputEveryIteration(save_txt=False) + saveDict = directives.SaveOutputEveryIteration(on_disk=False) update_Jacobi = directives.UpdatePreconditioner() # Add sensitivity weights sensitivity_weights = directives.UpdateSensitivityWeights(every_iteration=False) diff --git a/pyproject.toml b/pyproject.toml index 0d389d5cc8..b2cc10df22 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,6 +15,7 @@ authors = [ ] keywords = ["geophysics", "inverse problem"] + dependencies = [ "discretize>=0.11", "geoana>=0.7.0", @@ -63,10 +64,9 @@ sklearn = ["scikit-learn>=1.2"] pandas = ["pandas"] all = [ "simpeg[dask,choclo,plotting,reporting,sklearn,pandas]" - ] # all optional *runtime* dependencies (not related to development) style = [ - "black==24.3.0", + "black==26.3.1", "flake8==7.0.0", "flake8-bugbear==23.12.2", "flake8-builtins==2.2.0", @@ -74,6 +74,7 @@ style = [ "flake8-rst-docstrings==0.3.0", "flake8-docstrings==1.7.0", "flake8-pyproject==1.2.3", + "ruff==0.16.6", ] docs = [ "sphinx", @@ -90,14 +91,8 @@ docs = [ "memory_profiler", "python-kaleido", ] -tests = [ - "simpeg[all,docs]", - "pytest", - "pytest-cov", -] -dev = [ - "simpeg[all,style,docs,tests]", -] # the whole kit and caboodle +tests = ["simpeg[all,docs]", "pytest", "pytest-cov"] +dev = ["simpeg[all,style,docs,tests]"] # the whole kit and caboodle [tool.setuptools] py-modules = ['SimPEG'] @@ -113,6 +108,8 @@ local_scheme = "node-and-date" [tool.coverage.run] branch = true source = ["simpeg", "tests", "examples", "tutorials"] +concurrency = ["thread", "multiprocessing"] +parallel = true [tool.coverage.report] ignore_errors = false @@ -141,13 +138,21 @@ exclude_also = [ directory = "coverage_html_report" [tool.black] -required-version = '25.1.0' -target-version = ['py38', 'py39', 'py310', 'py311'] +required-version = '26.3.1' +target-version = ["py312", "py313", "py314"] + [tool.flake8] extend-ignore = [ # Default ignores by flake (added here for when ignore gets overwritten) - 'E121','E123','E126','E226','E24','E704','W503','W504', + 'E121', + 'E123', + 'E126', + 'E226', + 'E24', + 'E704', + 'W503', + 'W504', # Too many leading '#' for block comment 'E266', # Line too long (82 > 79 characters) @@ -253,21 +258,35 @@ ignore = [ 'RST499', ] -rst-roles = [ - 'class', - 'func', - 'mod', - 'meth', - 'ref', +rst-roles = ['class', 'func', 'mod', 'meth', 'ref'] + + +[tool.ruff] +line-length = 88 +indent-width = 4 + +[tool.ruff.lint] +# Select only these rules. +select = [ + "D406", # Section name should end with a newline + "D406", # Missing dashed underline after section + "D408", # Section underline should be in the line following the section's name + "D409", # Section underline should match the length of its name ] + +[tool.ruff.lint.pydocstyle] +# Make ruff to check for numpydoc style in our docs +convention = "numpy" + # pyproject.toml [tool.pytest.ini_options] filterwarnings = [ - "ignore::simpeg.utils.solver_utils.DefaultSolverWarning", "error:You are running a pytest without setting a random seed.*:UserWarning", "error:The `index_dictionary` property has been deprecated:FutureWarning", 'error:The `simpeg\.directives\.[a-z_]+` submodule has been deprecated', 'error:Casting complex values to real discards the imaginary part', + 'ignore::simpeg.utils.BreakingChangeWarning', + "error:The closest_points_index utilty function has been moved to:DeprecationWarning", ] xfail_strict = true diff --git a/simpeg/__init__.py b/simpeg/__init__.py index baf84190d3..685d95bfbe 100644 --- a/simpeg/__init__.py +++ b/simpeg/__init__.py @@ -75,6 +75,8 @@ maps.ExpMap maps.IdentityMap maps.InjectActiveCells + maps.InjectActiveFaces + maps.InjectActiveEdges maps.LinearMap maps.LogisticSigmoidMap maps.LogMap diff --git a/simpeg/base/__init__.py b/simpeg/base/__init__.py index d7425ebd92..a04d86848d 100644 --- a/simpeg/base/__init__.py +++ b/simpeg/base/__init__.py @@ -2,5 +2,10 @@ BasePDESimulation, BaseElectricalPDESimulation, BaseMagneticPDESimulation, + BaseElectricalEdgePropertyPDESimulation, + BaseElectricalFacePropertyPDESimulation, + BaseHierarchicalElectricalSimulation, with_property_mass_matrices, + with_surface_property_mass_matrices, + with_line_property_mass_matrices, ) diff --git a/simpeg/base/pde_simulation.py b/simpeg/base/pde_simulation.py index 7afa6d2e2d..2c1d569678 100644 --- a/simpeg/base/pde_simulation.py +++ b/simpeg/base/pde_simulation.py @@ -1,22 +1,28 @@ +"""Base classes for PDE simulations.""" + import inspect import warnings import numpy as np import pymatsolver import scipy.sparse as sp -from discretize.utils import Zero, TensorType +from discretize.utils import Zero, TensorType, sdinv import discretize.base from ..simulation import BaseSimulation from .. import props from scipy.constants import mu_0 - +from scipy.sparse import spmatrix, diags from ..utils import validate_type, get_default_solver, get_logger, PerformanceWarning def _inner_mat_mul_op(M, u, v=None, adjoint=False): + """Get inner product matrix multiplication.""" u = np.squeeze(u) if sp.issparse(M): if v is not None: + if isinstance(v, spmatrix) and u.ndim == 1: + return M.T @ (diags(u) @ v) + if v.ndim > 1: v = np.squeeze(v) if u.ndim > 1: @@ -80,14 +86,13 @@ def _inner_mat_mul_op(M, u, v=None, adjoint=False): return Mu @ (prop_deriv @ v) else: raise TypeError( - "The stashed property derivative is an unexpected type. Expected either a `tuple` or a " - f"sparse matrix. Received a {type(M)}." + "The stashed property derivative is an unexpected type. Expected either" + f" a `tuple` or a sparse matrix. Received a {type(M)}." ) def with_property_mass_matrices(property_name): - """ - This decorator will automatically populate all of the property mass matrices. + """Generate decorator that automatically populates the mass matrices. Given the property "prop", this will add properties and functions to the class representing all of the possible mass matrix operations on the mesh. @@ -108,9 +113,7 @@ def decorator(cls): @property def Mcc_prop(self): - """ - Cell center property inner product matrix. - """ + """Get cell center property inner product matrix.""" stash_name = f"_Mcc_{arg}" if getattr(self, stash_name, None) is None: prop = getattr(self, arg.lower()) @@ -122,9 +125,7 @@ def Mcc_prop(self): @property def Mn_prop(self): - """ - Node property inner product matrix. - """ + """Get node property inner product matrix.""" stash_name = f"_Mn_{arg}" if getattr(self, stash_name, None) is None: prop = getattr(self, arg.lower()) @@ -137,9 +138,7 @@ def Mn_prop(self): @property def Mf_prop(self): - """ - Face property inner product matrix. - """ + """Get face property inner product matrix.""" stash_name = f"_Mf_{arg}" if getattr(self, stash_name, None) is None: prop = getattr(self, arg.lower()) @@ -151,9 +150,7 @@ def Mf_prop(self): @property def Me_prop(self): - """ - Edge property inner product matrix. - """ + """Get edge property inner product matrix.""" stash_name = f"_Me_{arg}" if getattr(self, stash_name, None) is None: prop = getattr(self, arg.lower()) @@ -165,9 +162,7 @@ def Me_prop(self): @property def MccI_prop(self): - """ - Cell center property inner product inverse matrix. - """ + """Get cell center property inner product inverse matrix.""" stash_name = f"_MccI_{arg}" if getattr(self, stash_name, None) is None: prop = getattr(self, arg.lower()) @@ -179,9 +174,7 @@ def MccI_prop(self): @property def MnI_prop(self): - """ - Node property inner product inverse matrix. - """ + """Get node property inner product inverse matrix.""" stash_name = f"_MnI_{arg}" if getattr(self, stash_name, None) is None: prop = getattr(self, arg.lower()) @@ -196,9 +189,7 @@ def MnI_prop(self): @property def MfI_prop(self): - """ - Face property inner product inverse matrix. - """ + """Get face property inner product inverse matrix.""" stash_name = f"_MfI_{arg}" if getattr(self, stash_name, None) is None: prop = getattr(self, arg.lower()) @@ -212,9 +203,7 @@ def MfI_prop(self): @property def MeI_prop(self): - """ - Edge property inner product inverse matrix. - """ + """Get edge property inner product inverse matrix.""" stash_name = f"_MeI_{arg}" if getattr(self, stash_name, None) is None: prop = getattr(self, arg.lower()) @@ -227,9 +216,7 @@ def MeI_prop(self): setattr(cls, f"Me{arg}I", MeI_prop) def MccDeriv_prop(self, u, v=None, adjoint=False): - """ - Derivative of `MccProperty` with respect to the model. - """ + """Get derivative of `MccProperty` with respect to the model.""" if getattr(self, f"{arg.lower()}Map") is None: return Zero() if isinstance(u, Zero) or isinstance(v, Zero): @@ -246,9 +233,7 @@ def MccDeriv_prop(self, u, v=None, adjoint=False): setattr(cls, f"Mcc{arg}Deriv", MccDeriv_prop) def MnDeriv_prop(self, u, v=None, adjoint=False): - """ - Derivative of `MnProperty` with respect to the model. - """ + """Get derivative of `MnProperty` with respect to the model.""" if getattr(self, f"{arg.lower()}Map") is None: return Zero() if isinstance(u, Zero) or isinstance(v, Zero): @@ -266,9 +251,7 @@ def MnDeriv_prop(self, u, v=None, adjoint=False): setattr(cls, f"Mn{arg}Deriv", MnDeriv_prop) def MfDeriv_prop(self, u, v=None, adjoint=False): - """ - Derivative of `MfProperty` with respect to the model. - """ + """Get derivative of `MfProperty` with respect to the model.""" if getattr(self, f"{arg.lower()}Map") is None: return Zero() if isinstance(u, Zero) or isinstance(v, Zero): @@ -296,9 +279,7 @@ def MfDeriv_prop(self, u, v=None, adjoint=False): setattr(cls, f"Mf{arg}Deriv", MfDeriv_prop) def MeDeriv_prop(self, u, v=None, adjoint=False): - """ - Derivative of `MeProperty` with respect to the model. - """ + """Get derivative of `MeProperty` with respect to the model.""" if getattr(self, f"{arg.lower()}Map") is None: return Zero() if isinstance(u, Zero) or isinstance(v, Zero): @@ -325,9 +306,7 @@ def MeDeriv_prop(self, u, v=None, adjoint=False): setattr(cls, f"Me{arg}Deriv", MeDeriv_prop) def MccIDeriv_prop(self, u, v=None, adjoint=False): - """ - Derivative of `MccPropertyI` with respect to the model. - """ + """Get derivative of `MccPropertyI` with respect to the model.""" if getattr(self, f"{arg.lower()}Map") is None: return Zero() if isinstance(u, Zero) or isinstance(v, Zero): @@ -341,9 +320,7 @@ def MccIDeriv_prop(self, u, v=None, adjoint=False): setattr(cls, f"Mcc{arg}IDeriv", MccIDeriv_prop) def MnIDeriv_prop(self, u, v=None, adjoint=False): - """ - Derivative of `MnPropertyI` with respect to the model. - """ + """Get derivative of `MnPropertyI` with respect to the model.""" if getattr(self, f"{arg.lower()}Map") is None: return Zero() if isinstance(u, Zero) or isinstance(v, Zero): @@ -357,9 +334,7 @@ def MnIDeriv_prop(self, u, v=None, adjoint=False): setattr(cls, f"Mn{arg}IDeriv", MnIDeriv_prop) def MfIDeriv_prop(self, u, v=None, adjoint=False): - """I - Derivative of `MfPropertyI` with respect to the model. - """ + """Get derivative of `MfPropertyI` with respect to the model.""" if getattr(self, f"{arg.lower()}Map") is None: return Zero() if isinstance(u, Zero) or isinstance(v, Zero): @@ -373,9 +348,7 @@ def MfIDeriv_prop(self, u, v=None, adjoint=False): setattr(cls, f"Mf{arg}IDeriv", MfIDeriv_prop) def MeIDeriv_prop(self, u, v=None, adjoint=False): - """ - Derivative of `MePropertyI` with respect to the model. - """ + """Get derivative of `MePropertyI` with respect to the model.""" if getattr(self, f"{arg.lower()}Map") is None: return Zero() if isinstance(u, Zero) or isinstance(v, Zero): @@ -412,6 +385,263 @@ def _clear_on_prop_update(self): return decorator +def with_surface_property_mass_matrices(property_name): + """Generate decorator that automatically populates the face property mass matrices. + + Given the property "prop", this will add properties and functions to the class + representing all of the possible mass matrix operations on the mesh. + + For a given property, "prop", they will be named: + + * _Me_prop + * _Me_prop_deriv + * _MeI_prop + * _MeI_prop_deriv + * _Mf_prop + * _Mf_prop_deriv + * _MfI_prop + * _MfI_prop_deriv + + Parameters + ---------- + property_name : str + The name of property that users will use when interacting with the class. + E.g. 'face_conductance'. + """ + + def decorator(cls): + arg = property_name.lower() + + @property + def Mf_prop(self): + """Get face property inner product surface matrix.""" + stash_name = f"__Mf_{arg}" + if getattr(self, stash_name, None) is None: + prop = getattr(self, property_name.lower()) + M_prop = self.mesh.get_face_inner_product_surface(model=prop) + setattr(self, stash_name, M_prop) + return getattr(self, stash_name) + + setattr(cls, f"_Mf_{arg}", Mf_prop) + + @property + def Me_prop(self): + """Get edge property inner product surface matrix.""" + stash_name = f"__Me_{arg}" + if getattr(self, stash_name, None) is None: + prop = getattr(self, property_name.lower()) + M_prop = self.mesh.get_edge_inner_product_surface(model=prop) + setattr(self, stash_name, M_prop) + return getattr(self, stash_name) + + setattr(cls, f"_Me_{arg}", Me_prop) + + @property + def MfI_prop(self): + """Get face property inner product inverse matrix.""" + stash_name = f"__MfI_{arg}" + if getattr(self, stash_name, None) is None: + prop = getattr(self, property_name.lower()) + M_prop = self.mesh.get_face_inner_product_surface( + model=prop, invert_matrix=True + ) + setattr(self, stash_name, M_prop) + return getattr(self, stash_name) + + setattr(cls, f"_MfI_{arg}", MfI_prop) + + @property + def MeI_prop(self): + """Get edge property inner product inverse matrix.""" + stash_name = f"__MeI_{arg}" + if getattr(self, stash_name, None) is None: + prop = getattr(self, property_name.lower()) + M_prop = self.mesh.get_edge_inner_product_surface( + model=prop, invert_matrix=True + ) + setattr(self, stash_name, M_prop) + return getattr(self, stash_name) + + setattr(cls, f"_MeI_{arg}", MeI_prop) + + def Mf_prop_deriv(self, u, v=None, adjoint=False): + """Get derivative of `MfProperty` with respect to the model.""" + if getattr(self, f"{property_name.lower()}_map") is None: + return Zero() + if isinstance(u, Zero) or isinstance(v, Zero): + return Zero() + stash_name = f"__Mf_{arg}_deriv" + if getattr(self, stash_name, None) is None: + M_prop_deriv = self.mesh.get_face_inner_product_surface_deriv( + np.ones(self.mesh.n_faces) + )(np.ones(self.mesh.n_faces)) * getattr( + self, f"{property_name.lower()}_deriv" + ) + setattr(self, stash_name, M_prop_deriv) + return _inner_mat_mul_op(getattr(self, stash_name), u, v=v, adjoint=adjoint) + + setattr(cls, f"_Mf_{arg}_deriv", Mf_prop_deriv) + + def Me_prop_deriv(self, u, v=None, adjoint=False): + """Get derivative of `MeProperty` with respect to the model.""" + if getattr(self, f"{property_name.lower()}_map") is None: + return Zero() + if isinstance(u, Zero) or isinstance(v, Zero): + return Zero() + stash_name = f"__Me_{arg}_deriv" + if getattr(self, stash_name, None) is None: + M_prop_deriv = self.mesh.get_edge_inner_product_surface_deriv( + np.ones(self.mesh.n_faces) + )(np.ones(self.mesh.n_edges)) * getattr( + self, f"{property_name.lower()}_deriv" + ) + setattr(self, stash_name, M_prop_deriv) + return _inner_mat_mul_op(getattr(self, stash_name), u, v=v, adjoint=adjoint) + + setattr(cls, f"_Me_{arg}_deriv", Me_prop_deriv) + + def MfI_prop_deriv(self, u, v=None, adjoint=False): + """Get derivative of `MfPropertyI` with respect to the model.""" + if getattr(self, f"{property_name.lower()}_map") is None: + return Zero() + if isinstance(u, Zero) or isinstance(v, Zero): + return Zero() + + MI_prop = getattr(self, f"_MfI_{arg}") + u = MI_prop @ (MI_prop @ -u) + M_prop_deriv = getattr(self, f"_Mf_{arg}_deriv") + return M_prop_deriv(u, v, adjoint=adjoint) + + setattr(cls, f"_MfI_{arg}_deriv", MfI_prop_deriv) + + def MeI_prop_deriv(self, u, v=None, adjoint=False): + """Get derivative of `MePropertyI` with respect to the model.""" + if getattr(self, f"{property_name.lower()}_map") is None: + return Zero() + if isinstance(u, Zero) or isinstance(v, Zero): + return Zero() + + MI_prop = getattr(self, f"_MeI_{arg}") + u = MI_prop @ (MI_prop @ -u) + M_prop_deriv = getattr(self, f"_Me_{arg}_deriv") + return M_prop_deriv(u, v, adjoint=adjoint) + + setattr(cls, f"_MeI_{arg}_deriv", MeI_prop_deriv) + + @property + def _clear_on_prop_update(self): + items = [ + f"__Mf_{arg}", + f"__Me_{arg}", + f"__MfI_{arg}", + f"__MeI_{arg}", + f"__Mf_{arg}_deriv", + f"__Me_{arg}_deriv", + ] + return items + + setattr(cls, f"_clear_on_{arg.lower()}_update", _clear_on_prop_update) + return cls + + return decorator + + +def with_line_property_mass_matrices(property_name): + """Generate decorator that automatically populates the line property mass matrices. + + Given the property "prop", this will add properties and functions to the class + representing all of the possible mass matrix operations on the mesh. + + For a given property, "prop", they will be named: + + * _Me_prop + * _Me_prop_deriv + * _MeI_prop + * _MeI_prop_deriv + + Parameters + ---------- + property_name : str + The name of property that users will use when interacting with the class. + E.g. 'edge_area_conductivity'. + """ + + def decorator(cls): + arg = property_name.lower() + + @property + def Me_prop(self): + """Get edge property inner product line matrix.""" + stash_name = f"__Me_{arg}" + if getattr(self, stash_name, None) is None: + prop = getattr(self, property_name.lower()) + M_prop = self.mesh.get_edge_inner_product_line(model=prop) + setattr(self, stash_name, M_prop) + return getattr(self, stash_name) + + setattr(cls, f"_Me_{arg}", Me_prop) + + @property + def MeI_prop(self): + """Get edge property inner product inverse matrix.""" + stash_name = f"__MeI_{arg}" + if getattr(self, stash_name, None) is None: + prop = getattr(self, property_name.lower()) + M_prop = self.mesh.get_edge_inner_product_line( + model=prop, invert_matrix=True + ) + setattr(self, stash_name, M_prop) + return getattr(self, stash_name) + + setattr(cls, f"_MeI_{arg}", MeI_prop) + + def Me_prop_deriv(self, u, v=None, adjoint=False): + """Get derivative of `MeProperty` with respect to the model.""" + if getattr(self, f"{property_name.lower()}_map") is None: + return Zero() + if isinstance(u, Zero) or isinstance(v, Zero): + return Zero() + stash_name = f"__Me_{arg}_deriv" + if getattr(self, stash_name, None) is None: + M_prop_deriv = self.mesh.get_edge_inner_product_line_deriv( + np.ones(self.mesh.n_edges) + )(np.ones(self.mesh.n_edges)) * getattr( + self, f"{property_name.lower()}_deriv" + ) + setattr(self, stash_name, M_prop_deriv) + return _inner_mat_mul_op(getattr(self, stash_name), u, v=v, adjoint=adjoint) + + setattr(cls, f"_Me_{arg}_deriv", Me_prop_deriv) + + def MeI_prop_deriv(self, u, v=None, adjoint=False): + """Get derivative of `MePropertyI` with respect to the model.""" + if getattr(self, f"{property_name.lower()}_map") is None: + return Zero() + if isinstance(u, Zero) or isinstance(v, Zero): + return Zero() + + MI_prop = getattr(self, f"_MeI_{arg}") + u = MI_prop @ (MI_prop @ -u) + M_prop_deriv = getattr(self, f"_Me_{arg}_deriv") + return M_prop_deriv(u, v, adjoint=adjoint) + + setattr(cls, f"_MeI_{arg}_deriv", MeI_prop_deriv) + + @property + def _clear_on_prop_update(self): + items = [ + f"__Me_{arg}", + f"__MeI_{arg}", + f"__Me_{arg}_deriv", + ] + return items + + setattr(cls, f"_clear_on_{arg}_update", _clear_on_prop_update) + return cls + + return decorator + + class BasePDESimulation(BaseSimulation): """Base simulation for PDE solutions. @@ -514,12 +744,13 @@ def solver(self, cls): @property def solver_opts(self): - """Solver-specific parameters. + """Set solver-specific parameters. The parameters specific to the solver set with the ``solver`` property are set - upon instantiation. The ``solver_opts`` property is used to set solver-specific properties. - This is done by providing a ``dict`` that contains appropriate pairs of keyword arguments - and parameter values. Please visit `pymatsolver `__ + upon instantiation. The ``solver_opts`` property is used to set solver-specific + properties. This is done by providing a ``dict`` that contains appropriate pairs + of keyword arguments and parameter values. Please visit + `pymatsolver `__ to learn more about solvers and their parameters. Returns @@ -535,22 +766,19 @@ def solver_opts(self, value): @property def Vol(self): + """Get volumes.""" return self.Mcc @property def Mcc(self): - """ - Cell center inner product matrix. - """ + """Get cell inner product matrix.""" if getattr(self, "_Mcc", None) is None: self._Mcc = sp.diags(self.mesh.cell_volumes, format="csr") return self._Mcc @property def Mn(self): - """ - Node inner product matrix. - """ + """Get node inner product matrix.""" if getattr(self, "_Mn", None) is None: vol = self.mesh.cell_volumes self._Mn = sp.diags(self.mesh.aveN2CC.T * vol, format="csr") @@ -558,33 +786,28 @@ def Mn(self): @property def Mf(self): - """ - Face inner product matrix. - """ + """Get face inner product matrix.""" if getattr(self, "_Mf", None) is None: self._Mf = self.mesh.get_face_inner_product() return self._Mf @property def Me(self): - """ - Edge inner product matrix. - """ + """Get edge inner product matrix.""" if getattr(self, "_Me", None) is None: self._Me = self.mesh.get_edge_inner_product() return self._Me @property def MccI(self): + """Get inverse of cell inner product matrix.""" if getattr(self, "_MccI", None) is None: self._MccI = sp.diags(1.0 / self.mesh.cell_volumes, format="csr") return self._MccI @property def MnI(self): - """ - Node inner product inverse matrix. - """ + """Get inverse of node inner product matrix.""" if getattr(self, "_MnI", None) is None: vol = self.mesh.cell_volumes self._MnI = sp.diags(1.0 / (self.mesh.aveN2CC.T * vol), format="csr") @@ -592,18 +815,14 @@ def MnI(self): @property def MfI(self): - """ - Face inner product inverse matrix. - """ + """Get inverse of face inner product matrix.""" if getattr(self, "_MfI", None) is None: self._MfI = self.mesh.get_face_inner_product(invert_matrix=True) return self._MfI @property def MeI(self): - """ - Edge inner product inverse matrix. - """ + """Get inverse of edge inner product matrix.""" if getattr(self, "_MeI", None) is None: self._MeI = self.mesh.get_edge_inner_product(invert_matrix=True) return self._MeI @@ -612,6 +831,8 @@ def MeI(self): @with_property_mass_matrices("sigma") @with_property_mass_matrices("rho") class BaseElectricalPDESimulation(BasePDESimulation): + """Base class for PDE simulations with electrical properties.""" + sigma, sigmaMap, sigmaDeriv = props.Invertible("Electrical conductivity (S/m)") rho, rhoMap, rhoDeriv = props.Invertible("Electrical resistivity (Ohm m)") props.Reciprocal(sigma, rho) @@ -627,9 +848,6 @@ def __init__( @property def _delete_on_model_update(self): - """ - matrices to be deleted if the model for conductivity/resistivity is updated - """ toDelete = super()._delete_on_model_update if self.sigmaMap is not None or self.rhoMap is not None: toDelete = ( @@ -638,6 +856,7 @@ def _delete_on_model_update(self): return toDelete def __setattr__(self, name, value): + """Set items to delete on updating cell centered electric properties.""" super().__setattr__(name, value) if name in ["sigma", "rho"]: for mat in self._clear_on_sigma_update + self._clear_on_rho_update: @@ -648,6 +867,8 @@ def __setattr__(self, name, value): @with_property_mass_matrices("mu") @with_property_mass_matrices("mui") class BaseMagneticPDESimulation(BasePDESimulation): + """Base class for PDE simulations with magnetic properties.""" + mu, muMap, muDeriv = props.Invertible( "Magnetic Permeability (H/m)", ) @@ -662,6 +883,7 @@ def __init__(self, mesh, mu=mu_0, muMap=None, mui=None, muiMap=None, **kwargs): self.muiMap = muiMap def __setattr__(self, name, value): + """Set items to delete on updating magnetic permeabilities.""" super().__setattr__(name, value) if name in ["mu", "mui"]: for mat in self._clear_on_mu_update + self._clear_on_mui_update: @@ -670,10 +892,171 @@ def __setattr__(self, name, value): @property def _delete_on_model_update(self): - """ - items to be deleted if the model for Magnetic Permeability is updated - """ + """Set items to delete on updating magnetic permeabilities.""" toDelete = super()._delete_on_model_update if self.muMap is not None or self.muiMap is not None: toDelete = toDelete + self._clear_on_mu_update + self._clear_on_mui_update return toDelete + + +@with_line_property_mass_matrices("edge_area_conductance") +class BaseElectricalEdgePropertyPDESimulation(BaseElectricalPDESimulation): + """Base class for simulations with edge electrical properties. + + An electrical simulation can inherit this class and it will replace MeSigma + operations with the heirarchical operators. + """ + + edge_area_conductance, edge_area_conductance_map, edge_area_conductance_deriv = ( + props.Invertible( + "Electrical conductivity times cross-sectional area on edge elements (Sm).", + optional=True, + ) + ) + + def __init__( + self, + mesh, + survey=None, + *, + edge_area_conductance=None, + edge_area_conductance_map=None, + **kwargs, + ): + super().__init__(mesh=mesh, survey=survey, **kwargs) + self.edge_area_conductance = edge_area_conductance + self.edge_area_conductance_map = edge_area_conductance_map + + def __setattr__(self, name, value): + super().__setattr__(name, value) + if name == "edge_area_conductance": + for mat in self._clear_on_edge_area_conductance_update: + if hasattr(self, mat): + delattr(self, mat) + + @property + def _delete_on_model_update(self): + """Set items to delete on updating edge electric properties.""" + toDelete = super()._delete_on_model_update + if self.edge_area_conductance_map is not None: + toDelete = toDelete + self._clear_on_edge_area_conductance_update + return toDelete + + +@with_surface_property_mass_matrices("face_conductance") +class BaseElectricalFacePropertyPDESimulation(BaseElectricalPDESimulation): + """Base class for simulations with face electrical properties. + + An electrical simulation can inherit this class and it will replace MeSigma + operations with the heirarchical operators. + """ + + face_conductance, face_conductance_map, face_conductance_deriv = props.Invertible( + "Electrical conductivity times thickness on face elements (S).", + optional=True, + ) + + def __init__( # noqa D107 + self, + mesh, + survey=None, + *, + face_conductance=None, + face_conductance_map=None, + **kwargs, + ): + super().__init__(mesh=mesh, survey=survey, **kwargs) + self.face_conductance = face_conductance + self.face_conductance_map = face_conductance_map + + def __setattr__(self, name, value): + """Set items to delete on updating face electric properties.""" + super().__setattr__(name, value) + if name == "face_conductance": + for mat in self._clear_on_face_conductance_update: + if hasattr(self, mat): + delattr(self, mat) + + @property + def _delete_on_model_update(self): + """Set items to delete on updating face electric properties.""" + toDelete = super()._delete_on_model_update + if self.face_conductance_map is not None: + toDelete = toDelete + self._clear_on_face_conductance_update + return toDelete + + +class BaseHierarchicalElectricalSimulation( + BaseElectricalEdgePropertyPDESimulation, BaseElectricalFacePropertyPDESimulation +): + """Base class for all hierarchical EM simulations. + + An electrical simulation can inherit this class and it will replace MeSigma + operations with the heirarchical operators. + """ + + _clean_on_h_prop_update = ["_MeSigmaHierarchical", "_MeSigmaHierarchicalI"] + + @property + def MeSigma(self): + """Get conductivity inner-product matrix.""" + if getattr(self, "_MeSigmaHierarchical", None) is None: + M_prop = super().MeSigma + if self.face_conductance is not None: + M_prop += self._Me_face_conductance + if self.edge_area_conductance is not None: + M_prop += self._Me_edge_area_conductance + self._MeSigmaHierarchical = M_prop + return self._MeSigmaHierarchical + + @property + def MeSigmaI(self): + """Get inverse of conductivity inner-product matrix.""" + if getattr(self, "_MeSigmaHierarchicalI", None) is None: + if isinstance(self.mesh, discretize.base.BaseRegularMesh): + if TensorType(self.mesh, self.sigma) == 3: + # Same failure as inverting the other property matrices. + raise Exception("Solver needed to invert A.") + M_prop = sdinv(self.MeSigma) + else: + raise NotImplementedError( + f"Inverse of physical property matrix 'MeSigma' " + f"not supported for {type(self.mesh)} meshes." + ) + self._MeSigmaHierarchicalI = M_prop + return self._MeSigmaHierarchicalI + + def MeSigmaDeriv(self, u, v=None, adjoint=False): + """Compute derivative operation for conductivity inner-product matrix.""" + out = super().MeSigmaDeriv(u, v, adjoint=adjoint) + if self.face_conductance_map is not None: + out += self._Me_face_conductance_deriv(u, v, adjoint=adjoint) + if self.edge_area_conductance_map is not None: + out += self._Me_edge_area_conductance_deriv(u, v, adjoint=adjoint) + return out + + def MeSigmaIDeriv(self, u, v=None, adjoint=False): + """Compute derivative operation for inversion of conductivity inner-product matrix.""" + MI_prop = self.MeSigmaI + u = MI_prop @ (MI_prop @ -u) + return self.MeSigmaDeriv(u, v, adjoint=adjoint) + + @property + def _delete_on_model_update(self): + toDelete = super()._delete_on_model_update + if ( + self.sigmaMap is not None + or self.rhoMap is not None + or self.face_conductance_map is not None + or self.edge_area_conductance_map is not None + ): + toDelete = toDelete + self._clean_on_h_prop_update + return toDelete + + def __setattr__(self, name, value): + """Set items to delete on updating hierarchical electric properties.""" + super().__setattr__(name, value) + if name in ["sigma", "rho", "face_conductance", "edge_area_conductance"]: + for mat in self._clean_on_h_prop_update: + if hasattr(self, mat): + delattr(self, mat) diff --git a/simpeg/data.py b/simpeg/data.py index a3e95b06e3..db85e71743 100644 --- a/simpeg/data.py +++ b/simpeg/data.py @@ -4,7 +4,6 @@ from .survey import BaseSurvey from .utils import mkvc, validate_ndarray_with_shape, validate_float, validate_type - __all__ = ["Data", "SyntheticData"] @@ -371,7 +370,7 @@ def dclean(self): numpy.ndarray Notes - -------- + ----- This array should be indexing the data object using a tuple of the survey's sources and receivers. diff --git a/simpeg/directives/_directives.py b/simpeg/directives/_directives.py index 0b00ec29c2..38fd60bf03 100644 --- a/simpeg/directives/_directives.py +++ b/simpeg/directives/_directives.py @@ -1766,12 +1766,8 @@ def _mkdir_and_check_output_file(self, should_exist=False): @property def fileName(self): - warnings.warn( - "'fileName' has been deprecated and will be removed in SimPEG 0.26.0 use 'file_abs_path'", - FutureWarning, - stacklevel=2, - ) - return self.file_abs_path.stem + msg = "'fileName' has been removed, use 'file_abs_path' instead." + raise AttributeError(msg) @property @abstractmethod @@ -1861,9 +1857,6 @@ class SaveOutputEveryIteration(SaveEveryIteration): """ def __init__(self, on_disk=True, **kwargs): - if (save_txt := kwargs.pop("save_txt", None)) is not None: - self.save_txt = save_txt - on_disk = self.save_txt super().__init__(on_disk=on_disk, **kwargs) def initialize(self): @@ -1904,7 +1897,7 @@ def file_abs_path(self) -> pathlib.Path | None: SaveEveryIteration.on_disk, "save_txt", removal_version="0.26.0", - future_warn=True, + error=True, ) def endIter(self): @@ -2109,16 +2102,13 @@ class SaveOutputDictEveryIteration(SaveEveryIteration): # Initialize the output dict def __init__(self, on_disk=False, **kwargs): - if (save_on_disk := kwargs.pop("saveOnDisk", None)) is not None: - self.saveOnDisk = save_on_disk - on_disk = self.saveOnDisk super().__init__(on_disk=on_disk, **kwargs) saveOnDisk = deprecate_property( SaveEveryIteration.on_disk, "saveOnDisk", removal_version="0.26.0", - future_warn=True, + error=True, ) @property diff --git a/simpeg/directives/directives.py b/simpeg/directives/directives.py deleted file mode 100644 index c40e514918..0000000000 --- a/simpeg/directives/directives.py +++ /dev/null @@ -1,18 +0,0 @@ -""" -Backward compatibility with the ``simpeg.directives.directives`` submodule. - -This file will be deleted when the ``simpeg.directives.directives`` submodule is -removed. -""" - -import warnings -from ._directives import * # noqa: F403,F401 - -warnings.warn( - "The `simpeg.directives.directives` submodule has been deprecated, " - "and will be removed in SimPEG v0.26.0." - "Import any directive class directly from the `simpeg.directives` module. " - "E.g.: `from simpeg.directives import BetaSchedule`", - FutureWarning, - stacklevel=2, -) diff --git a/simpeg/directives/pgi_directives.py b/simpeg/directives/pgi_directives.py deleted file mode 100644 index ec0108210c..0000000000 --- a/simpeg/directives/pgi_directives.py +++ /dev/null @@ -1,18 +0,0 @@ -""" -Backward compatibility with the ``simpeg.directives.pgi_directives`` submodule. - -This file will be deleted when the ``simpeg.directives.pgi_directives`` submodule is -removed. -""" - -import warnings -from ._pgi_directives import * # noqa: F403,F401 - -warnings.warn( - "The `simpeg.directives.pgi_directives` submodule has been deprecated, " - "and will be removed in SimPEG v0.26.0." - "Import any directive class directly from the `simpeg.directives` module. " - "E.g.: `from simpeg.directives import PGI_UpdateParameters`. ", - FutureWarning, - stacklevel=2, -) diff --git a/simpeg/directives/sim_directives.py b/simpeg/directives/sim_directives.py deleted file mode 100644 index e2c3f8a5f3..0000000000 --- a/simpeg/directives/sim_directives.py +++ /dev/null @@ -1,18 +0,0 @@ -""" -Backward compatibility with the ``simpeg.directives.sim_directives`` submodule. - -This file will be deleted when the ``simpeg.directives.sim_directives`` submodule -is removed. -""" - -import warnings -from ._sim_directives import * # noqa: F403,F401 - -warnings.warn( - "The `simpeg.directives.sim_directives` submodule has been deprecated, " - "and will be removed in SimPEG v0.26.0." - "Import any directive class directly from the `simpeg.directives` module. " - "E.g.: `from simpeg.directives import PairedBetaEstimate_ByEig`", - FutureWarning, - stacklevel=2, -) diff --git a/simpeg/electromagnetics/analytics/DC.py b/simpeg/electromagnetics/analytics/DC.py index b6fe116ec1..8e569cb88e 100644 --- a/simpeg/electromagnetics/analytics/DC.py +++ b/simpeg/electromagnetics/analytics/DC.py @@ -152,7 +152,7 @@ def DCAnalyticSphere( halfspace=False, ): """ - Parameters: + Parameters :param array txloc: A (+) current electrode location (x, y, z) :param array xc: x center of depressed sphere diff --git a/simpeg/electromagnetics/base_1d.py b/simpeg/electromagnetics/base_1d.py index 77e5c28053..1587946e25 100644 --- a/simpeg/electromagnetics/base_1d.py +++ b/simpeg/electromagnetics/base_1d.py @@ -237,16 +237,42 @@ def compute_complex_sigma(self, frequencies): r""" Computes the complex conductivity matrix using Pelton's Cole-Cole model: + Parameters + ---------- + frequencies : (n_frequencies,) array + Array with frequencies. + + .. important:: + + For IP cases (non-null chargeability), computations assume + conductivity/frequency at infinite frequency were passed + (see notes below). + + Returns + ------- + out : (n_layers, n_frequencies) array + A 2D array of complex conductivities for all layers. + + Notes + ----- + Complex conductivity is obtained following (Pelton, 1978): + .. math :: - \sigma (\omega ) = \sigma \Bigg [ - 1 - \eta \Bigg ( \frac{1}{1 + (1-\eta ) (1 + i\omega \tau)^c} \Bigg ) - \Bigg ] + \sigma (\omega ) = \sigma_{\infty} \Bigg ( + 1 - \frac{\eta}{1 + (1-\eta ) (i\omega \tau)^c} + \Bigg ) - :param numpy.array frequencies: np.array(N,) containing frequencies - :rtype: numpy.ndarray: np.array(n_layer, n_frequency) - :return: complex conductivity matrix + where :math:`\eta`, :math:`\tau` and :math:`c` are the model + chargeability (V/V), relaxation time (s) and frequency exponent (-) + This formulation relies on the conductivity at infinite frequency + :math:`\sigma_{\infty}` which lightly differs from Pelton's — based on + the conductivity at 0 frequency :math:`\sigma_0`: + + .. math :: + + \sigma_0 = ( 1 - \eta ) \sigma_{\infty} """ n_layer = self.n_layer n_frequency = len(frequencies) @@ -255,7 +281,7 @@ def compute_complex_sigma(self, frequencies): sigma = np.tile(self.sigma.reshape([-1, 1]), (1, n_frequency)) # No IP effect - if np.all(self.eta) == 0.0: + if np.all(self.eta == 0.0): return sigma # IP effect @@ -285,6 +311,20 @@ def compute_complex_mu(self, frequencies): Computes the complex magnetic permeability matrix assuming a log-uniform distribution of time-relaxation constants: + Parameters + ---------- + frequencies : (n_frequencies,) array + Array with frequencies. + + Returns + ------- + out : (n_layers, n_frequencies) array + The complex magnetic susceptibility matrix. + + Notes + ----- + Formulation is: + .. math:: \chi (\omega ) = \chi + \Delta \chi \Bigg [ @@ -292,9 +332,6 @@ def compute_complex_mu(self, frequencies): ln \Bigg ( \frac{1 + i\omega \tau_2}{1 + i\omega tau_1} ) \Bigg ) \Bigg ] - :param numpy.array frequencies: np.array(N,) containing frequencies - :rtype: numpy.ndarray: np.array(n_layer, n_frequency) - :return: complex magnetic susceptibility matrix """ if np.isscalar(self.mu): @@ -309,7 +346,7 @@ def compute_complex_mu(self, frequencies): mu = np.tile(mu.reshape([-1, 1]), (1, n_frequency)) # No magnetic viscosity - if np.all(self.dchi) == 0.0: + if np.all(self.dchi == 0.0): return mu # Magnetic viscosity diff --git a/simpeg/electromagnetics/frequency_domain/__init__.py b/simpeg/electromagnetics/frequency_domain/__init__.py index e2f9422515..b1bb73eaa3 100644 --- a/simpeg/electromagnetics/frequency_domain/__init__.py +++ b/simpeg/electromagnetics/frequency_domain/__init__.py @@ -9,10 +9,10 @@ Fourier convention is used, this module is used to solve problems of the form: .. math:: - \begin{align} - \nabla \times \vec{E} + i\omega \vec{B} &= - i \omega \vec{S}_m \\ + \begin{aligned} + \nabla \times \vec{E} + i\omega \vec{B} &= \vec{S}_m \\ \nabla \times \vec{H} - \vec{J} &= \vec{S}_e - \end{align} + \end{aligned} where the constitutive relations between fields and fluxes are given by: @@ -34,6 +34,8 @@ Simulation3DMagneticFluxDensity Simulation3DCurrentDensity Simulation3DMagneticField + Simulation3DHierarchicalElectricField + Simulation3DHierarchicalMagneticFluxDensity Receivers @@ -100,6 +102,8 @@ Simulation3DMagneticFluxDensity, Simulation3DCurrentDensity, Simulation3DMagneticField, + Simulation3DHierarchicalElectricField, + Simulation3DHierarchicalMagneticFluxDensity, ) from .simulation_1d import Simulation1DLayered from .fields import ( diff --git a/simpeg/electromagnetics/frequency_domain/fields.py b/simpeg/electromagnetics/frequency_domain/fields.py index 136010d7ef..68dd45cfcf 100644 --- a/simpeg/electromagnetics/frequency_domain/fields.py +++ b/simpeg/electromagnetics/frequency_domain/fields.py @@ -20,8 +20,8 @@ class FieldsFDEM(Fields): simulation : .BaseFDEMSimulation The FDEM simulation object used to compute the discrete field solution. - Example - ------- + Examples + -------- We want to access the fields for a discrete solution with :math:`\mathbf{e}` discretized to edges and :math:`\mathbf{b}` discretized to faces. To extract the fields for all sources: @@ -347,8 +347,8 @@ class Fields3DElectricField(FieldsFDEM): simulation : .frequency_domain.Simulation3DElectricField The FDEM simulation object associated with the fields. - Example - ------- + Examples + -------- The ``Fields3DElectricField`` object stores the total electric field solution on mesh edges. To extract the discrete electric fields and magnetic flux densities for all sources: @@ -519,6 +519,7 @@ def _bSecondary(self, eSolution, source_list): if not isinstance(s_m, Zero) and s_m.ndim == 1: s_m = s_m[:, None] b[:, i:ii] = b[:, i:ii] + 1.0 / (1j * omega(src.frequency)) * s_m + i = ii return b def _bDeriv_u(self, src, du_dm_v, adjoint=False): @@ -713,8 +714,8 @@ class Fields3DMagneticFluxDensity(FieldsFDEM): simulation : .frequency_domain.Simulation3DMagneticFluxDensity The FDEM simulation object associated with the fields. - Example - ------- + Examples + -------- The ``Fields3DMagneticFluxDensity`` object stores the total magnetic flux density solution on mesh faces. To extract the discrete electric fields and magnetic flux densities for all sources: @@ -1081,8 +1082,8 @@ class Fields3DCurrentDensity(FieldsFDEM): simulation : .frequency_domain.Simulation3DCurrentDensity The FDEM simulation object associated with the fields. - Example - ------- + Examples + -------- The ``Fields3DCurrentDensity`` object stores the total current density solution on mesh faces. To extract the discrete current density and magnetic field: @@ -1510,8 +1511,8 @@ class Fields3DMagneticField(FieldsFDEM): simulation : .frequency_domain.Simulation3DMagneticField The FDEM simulation object associated with the fields. - Example - ------- + Examples + -------- The ``Fields3DMagneticField`` object stores the total magnetic field solution on mesh edges. To extract the discrete current density and magnetic field: diff --git a/simpeg/electromagnetics/frequency_domain/simulation.py b/simpeg/electromagnetics/frequency_domain/simulation.py index d092226196..372778320b 100644 --- a/simpeg/electromagnetics/frequency_domain/simulation.py +++ b/simpeg/electromagnetics/frequency_domain/simulation.py @@ -1,9 +1,12 @@ +"""3D FDEM simulation classes.""" + import numpy as np import scipy.sparse as sp -from discretize.utils import Zero +from discretize.utils import Zero, mkvc from ... import props -from ...utils import mkvc, validate_type +from ...utils import validate_type +from ...base import BaseHierarchicalElectricalSimulation from ..base import BaseEMSimulation from ..utils import omega from .survey import Survey @@ -26,10 +29,10 @@ class BaseFDEMSimulation(BaseEMSimulation): Maxwell's equations are expressed as: .. math:: - \begin{align} + \begin{aligned} \nabla \times \vec{E} + i\omega \vec{B} &= - i \omega \vec{S}_m \\ \nabla \times \vec{H} - \vec{J} &= \vec{S}_e - \end{align} + \end{aligned} where the constitutive relations between fields and fluxes are given by: @@ -55,8 +58,9 @@ class BaseFDEMSimulation(BaseEMSimulation): frequency is discarded after the fields are computed at that frequency. If ``False``, the factorizations of the system matrices for all frequencies are stored. permittivity : (n_cells,) numpy.ndarray, optional - Dielectric permittivity (F/m) defined on the entire mesh. If ``None``, electric displacement - is ignored. Please note that `permittivity` is not an invertible property, and that future + Dielectric permittivity (F/m) defined on the entire mesh. If ``None``, + electric displacement is ignored. Please note that `permittivity` is not an + invertible property, and that future development will result in the deprecation of this propery. storeJ : bool, optional Whether to compute and store the sensitivity matrix. @@ -65,7 +69,7 @@ class BaseFDEMSimulation(BaseEMSimulation): fieldsPair = FieldsFDEM permittivity = props.PhysicalProperty("Dielectric permittivity (F/m)") - def __init__( + def __init__( # noqa D107 self, mesh, survey=None, @@ -147,9 +151,7 @@ def _get_admittivity(self, freq): def _get_face_admittivity_property_matrix( self, freq, invert_model=False, invert_matrix=False ): - """ - Face inner product matrix with permittivity and resistivity - """ + """Face inner product matrix with permittivity and resistivity.""" yhat = self._get_admittivity(freq) return self.mesh.get_face_inner_product( yhat, invert_model=invert_model, invert_matrix=invert_matrix @@ -158,9 +160,7 @@ def _get_face_admittivity_property_matrix( def _get_edge_admittivity_property_matrix( self, freq, invert_model=False, invert_matrix=False ): - """ - Face inner product matrix with permittivity and resistivity - """ + """Face inner product matrix with permittivity and resistivity.""" yhat = self._get_admittivity(freq) return self.mesh.get_edge_inner_product( yhat, invert_model=invert_model, invert_matrix=invert_matrix @@ -180,7 +180,6 @@ def fields(self, m=None): .frequency_domain.fields.FieldsFDEM The FDEM fields object. """ - if m is not None: self.model = m @@ -234,7 +233,6 @@ def Jvec(self, m, v, f=None): (n_data,) numpy.ndarray The sensitivity matrix times a vector. """ - if f is None: f = self.fields(m) @@ -287,7 +285,6 @@ def Jtvec(self, m, v, f=None): (n_param,) numpy.ndarray The adjoint sensitivity matrix times a vector. """ - if f is None: f = self.fields(m) @@ -382,8 +379,8 @@ def getJ(self, m, f=None): if not isinstance(dRHS_dmT, Zero): du_dmT += dRHS_dmT - if not isinstance(df_dmT[0], Zero): - du_dmT += np.hstack(df_dmT) + if not isinstance(df_dmT, Zero): + du_dmT += df_dmT block = np.array(du_dmT, dtype=complex).real.T @@ -440,7 +437,7 @@ def getJtJdiag(self, m, W=None, f=None): # @profile def getSourceTerm(self, freq): - r"""Returns the discrete source terms for the frequency provided. + r"""Return the discrete source terms for the frequency provided. This method computes and returns the discrete magnetic and electric source terms for all soundings at the frequency provided. The exact shape and @@ -464,9 +461,11 @@ def getSourceTerm(self, freq): Returns ------- s_m : numpy.ndarray - The magnetic sources terms. (n_faces, n_sources) for EB-formulations. (n_edges, n_sources) for HJ-formulations. + The magnetic sources terms. (n_faces, n_sources) for EB-formulations. + (n_edges, n_sources) for HJ-formulations. s_e : numpy.ndarray - The electric sources terms. (n_edges, n_sources) for EB-formulations. (n_faces, n_sources) for HJ-formulations. + The electric sources terms. (n_edges, n_sources) for EB-formulations. + (n_faces, n_sources) for HJ-formulations. """ Srcs = self.survey.get_sources_by_frequency(freq) n_fields = sum(src._fields_per_source for src in Srcs) @@ -530,9 +529,10 @@ class Simulation3DElectricField(BaseFDEMSimulation): frequency is discarded after the fields are computed at that frequency. If ``False``, the factorizations of the system matrices for all frequencies are stored. permittivity : (n_cells,) numpy.ndarray, optional - Dielectric permittivity (F/m) defined on the entire mesh. If ``None``, electric displacement - is ignored. Please note that `permittivity` is not an invertible property, and that future - development will result in the deprecation of this propery. + Dielectric permittivity (F/m) defined on the entire mesh. If ``None``, + electric displacement + is ignored. Please note that `permittivity` is not an invertible property, and that + future development will result in the deprecation of this propery. storeJ : bool, optional Whether to compute and store the sensitivity matrix. @@ -542,10 +542,10 @@ class Simulation3DElectricField(BaseFDEMSimulation): :math:`+i\omega t` Fourier convention is used: .. math:: - \begin{align} - &\nabla \times \vec{E} + i\omega \vec{B} = - i \omega \vec{S}_m \\ + \begin{aligned} + &\nabla \times \vec{E} + i\omega \vec{B} = \vec{S}_m \\ &\nabla \times \vec{H} - \vec{J} = \vec{S}_e - \end{align} + \end{aligned} where :math:`\vec{S}_e` is an electric source term that defines a source current density, and :math:`\vec{S}_m` magnetic source term that defines a source magnetic flux density. @@ -556,19 +556,22 @@ class Simulation3DElectricField(BaseFDEMSimulation): \vec{J} &= \sigma \vec{E} \\ \vec{H} &= \mu^{-1} \vec{B} - We then take the inner products of all previous expressions with a vector test function :math:`\vec{u}`. - Through vector calculus identities and the divergence theorem, we obtain: + We then take the inner products of all previous expressions with a vector test + function :math:`\vec{u}`. Through vector calculus identities and the divergence theorem, + we obtain: .. math:: & \int_\Omega \vec{u} \cdot (\nabla \times \vec{E}) \, dv + i \omega \int_\Omega \vec{u} \cdot \vec{B} \, dv - = - i \omega \int_\Omega \vec{u} \cdot \vec{S}_m \, dv \\ + = \int_\Omega \vec{u} \cdot \vec{S}_m \, dv \\ & \int_\Omega (\nabla \times \vec{u}) \cdot \vec{H} \, dv - \oint_{\partial \Omega} \vec{u} \cdot (\vec{H} \times \hat{n}) \, da - \int_\Omega \vec{u} \cdot \vec{J} \, dv = \int_\Omega \vec{u} \cdot \vec{S}_j \, dv \\ - & \int_\Omega \vec{u} \cdot \vec{J} \, dv = \int_\Omega \vec{u} \cdot \sigma \vec{E} \, dv \\ - & \int_\Omega \vec{u} \cdot \vec{H} \, dv = \int_\Omega \vec{u} \cdot \mu^{-1} \vec{B} \, dv + & \int_\Omega \vec{u} \cdot \vec{J} \, dv = + \int_\Omega \vec{u} \cdot \sigma \vec{E} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{H} \, dv = + \int_\Omega \vec{u} \cdot \mu^{-1} \vec{B} \, dv Assuming natural boundary conditions, the surface integral is zero. @@ -581,7 +584,8 @@ class Simulation3DElectricField(BaseFDEMSimulation): set of discrete inner-products: .. math:: - &\mathbf{u_f^T M_f C e} + i \omega \mathbf{u_f^T M_f b} = - i \omega \mathbf{u_f^T M_f s_m} \\ + &\mathbf{u_f^T M_f C e} + i \omega \mathbf{u_f^T M_f b} = + \mathbf{u_f^T M_f s_m} \\ &\mathbf{u_e^T C^T M_f h} - \mathbf{u_e^T M_e j} = \mathbf{u_e^T s_e} \\ &\mathbf{u_e^T M_e j} = \mathbf{u_e^T M_{e \sigma} e} \\ &\mathbf{u_f^T M_f h} = \mathbf{u_f^T M_{f \mu} b} @@ -589,13 +593,17 @@ class Simulation3DElectricField(BaseFDEMSimulation): where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively * :math:`\mathbf{M_e}` is the edge inner-product matrix * :math:`\mathbf{M_f}` is the face inner-product matrix - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse permeabilities projected to faces + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces - By cancelling like-terms and combining the discrete expressions to solve for the electric field, we obtain: + By cancelling like-terms and combining the discrete expressions to solve for the electric + field, we obtain: .. math:: \mathbf{A \, e} = \mathbf{q} @@ -603,7 +611,7 @@ class Simulation3DElectricField(BaseFDEMSimulation): where * :math:`\mathbf{A} = \mathbf{C^T M_{f\frac{1}{\mu}} C} + i\omega \mathbf{M_{e\sigma}}` - * :math:`\mathbf{q} = - i \omega \mathbf{s_e} - i \omega \mathbf{C^T M_{f\frac{1}{\mu}} s_m }` + * :math:`\mathbf{q} = -i\omega \mathbf{s_e} + \mathbf{C^T M_{f\frac{1}{\mu}} s_m }` """ @@ -612,7 +620,7 @@ class Simulation3DElectricField(BaseFDEMSimulation): fieldsPair = Fields3DElectricField def getA(self, freq): - r"""System matrix for the frequency provided. + r"""Get system matrix for the frequency provided. This method returns the system matrix for the frequency provided: @@ -621,8 +629,10 @@ def getA(self, freq): where - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse permeabilities projected to faces + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DElectricField` for a full description of the formulation. @@ -637,7 +647,6 @@ def getA(self, freq): (n_edges, n_edges) sp.sparse.csr_matrix The system matrix. """ - MfMui = self.MfMui C = self.mesh.edge_curl @@ -651,7 +660,7 @@ def getA(self, freq): return A def getADeriv_sigma(self, freq, u, v, adjoint=False): - r"""Conductivity derivative operation for the system matrix times a vector. + r"""Get conductivity derivative operation for the system matrix times a vector. The system matrix at each frequency is given by: @@ -660,23 +669,28 @@ def getADeriv_sigma(self, freq, u, v, adjoint=False): where - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse permeabilities projected to faces + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DElectricField` for a full description of the formulation. - Where :math:`\mathbf{m}_\boldsymbol{\sigma}` are the set of model parameters defining the conductivity, - :math:`\mathbf{v}` is a vector and :math:`\mathbf{e}` is the discrete electric field solution, this method assumes - the discrete solution is fixed and returns + Where :math:`\mathbf{m}_\boldsymbol{\sigma}` are the set of model parameters defining + the conductivity, :math:`\mathbf{v}` is a vector and :math:`\mathbf{e}` is the + discrete electric field solution, this method assumes the discrete solution is fixed + and returns .. math:: - \frac{\partial (\mathbf{A \, e})}{\partial \mathbf{m}_\boldsymbol{\sigma}} \, \mathbf{v} + \frac{\partial (\mathbf{A \, e})}{\partial \mathbf{m}_\boldsymbol{\sigma}} + \, \mathbf{v} Or the adjoint operation .. math:: - \frac{\partial (\mathbf{A \, e})}{\partial \mathbf{m}_\boldsymbol{\sigma}}^T \, \mathbf{v} + \frac{\partial (\mathbf{A \, e})}{\partial \mathbf{m}_\boldsymbol{\sigma}}^T + \, \mathbf{v} Parameters ---------- @@ -685,7 +699,8 @@ def getADeriv_sigma(self, freq, u, v, adjoint=False): u : (n_edges,) numpy.ndarray The solution for the fields for the current model at the specified frequency. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint + operation. adjoint : bool Whether to perform the adjoint operation. @@ -695,12 +710,11 @@ def getADeriv_sigma(self, freq, u, v, adjoint=False): Derivative of system matrix times a vector. (n_edges,) for the standard operation. (n_param,) for the adjoint operation. """ - dMe_dsig_v = self.MeSigmaDeriv(u, v, adjoint) return 1j * omega(freq) * dMe_dsig_v def getADeriv_mui(self, freq, u, v, adjoint=False): - r"""Inverse permeability derivative operation for the system matrix times a vector. + r"""Get inverse permeability derivative operation for the system matrix times a vector. The system matrix at each frequency is given by: @@ -709,23 +723,27 @@ def getADeriv_mui(self, freq, u, v, adjoint=False): where - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse permeabilities projected to faces + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DElectricField` for a full description of the formulation. - Where :math:`\mathbf{m}_\boldsymbol{\mu}` are the set of model parameters defining the permeability, - :math:`\mathbf{v}` is a vector and :math:`\mathbf{e}` is the discrete electric field solution, this method assumes - the discrete solution is fixed and returns + Where :math:`\mathbf{m}_\boldsymbol{\mu}` are the set of model parameters defining the + permeability, :math:`\mathbf{v}` is a vector and :math:`\mathbf{e}` is the discrete + electric field solution, this method assumes the discrete solution is fixed and returns .. math:: - \frac{\partial (\mathbf{A \, e})}{\partial \mathbf{m}_\boldsymbol{\mu}} \, \mathbf{v} + \frac{\partial (\mathbf{A \, e})}{\partial \mathbf{m}_\boldsymbol{\mu}} + \, \mathbf{v} Or the adjoint operation .. math:: - \frac{\partial (\mathbf{A \, e})}{\partial \mathbf{m}_\boldsymbol{\mu}}^T \, \mathbf{v} + \frac{\partial (\mathbf{A \, e})}{\partial \mathbf{m}_\boldsymbol{\mu}}^T + \, \mathbf{v} Parameters ---------- @@ -734,7 +752,8 @@ def getADeriv_mui(self, freq, u, v, adjoint=False): u : (n_edges,) numpy.ndarray The solution for the fields for the current model at the specified frequency. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_edges,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -744,7 +763,6 @@ def getADeriv_mui(self, freq, u, v, adjoint=False): Derivative of system matrix times a vector. (n_edges,) for the standard operation. (n_param,) for the adjoint operation. """ - C = self.mesh.edge_curl if adjoint: @@ -753,7 +771,7 @@ def getADeriv_mui(self, freq, u, v, adjoint=False): return C.T * (self.MfMuiDeriv(C * u) * v) def getADeriv(self, freq, u, v, adjoint=False): - r"""Derivative operation for the system matrix times a vector. + r"""Get derivative operation for the system matrix times a vector. The system matrix at each frequency is given by: @@ -762,15 +780,17 @@ def getADeriv(self, freq, u, v, adjoint=False): where - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse permeabilities projected to faces + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DElectricField` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters defining the electromagnetic properties - :math:`\mathbf{v}` is a vector and :math:`\mathbf{e}` is the discrete electric field solution, this method assumes - the discrete solution is fixed and returns + Where :math:`\mathbf{m}` are the set of model parameters defining the electromagnetic + properties :math:`\mathbf{v}` is a vector and :math:`\mathbf{e}` is the discrete + electric field solution, this method assumes the discrete solution is fixed and returns .. math:: \frac{\partial (\mathbf{A \, e})}{\partial \mathbf{m}} \, \mathbf{v} @@ -787,7 +807,8 @@ def getADeriv(self, freq, u, v, adjoint=False): u : (n_edges,) numpy.ndarray The solution for the fields for the current model at the specified frequency. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_edges,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -804,19 +825,21 @@ def getADeriv(self, freq, u, v, adjoint=False): ) def getRHS(self, freq): - r"""Right-hand sides for the given frequency. + r"""Get right-hand sides for the given frequency. This method returns the right-hand sides for the frequency provided. The right-hand side for each source is constructed according to: .. math:: - \mathbf{q} = - i \omega \mathbf{s_e} - i \omega \mathbf{C^T M_{f\frac{1}{\mu}} s_m } + \mathbf{q} = - i \omega \mathbf{s_e} + \mathbf{C^T M_{f\frac{1}{\mu}} s_m } where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrices for inverse permeabilities projected to faces + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrices for inverse + permeabilities projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DElectricField` for a full description of the formulation. @@ -831,7 +854,6 @@ def getRHS(self, freq): (n_edges, n_sources) numpy.ndarray The right-hand sides. """ - s_m, s_e = self.getSourceTerm(freq) C = self.mesh.edge_curl MfMui = self.MfMui @@ -839,24 +861,26 @@ def getRHS(self, freq): return C.T * (MfMui * s_m) - 1j * omega(freq) * s_e def getRHSDeriv(self, freq, src, v, adjoint=False): - r"""Derivative of the right-hand side times a vector for a given source and frequency. + r"""Get right-hand side derivative times a vector for a given source and frequency. The right-hand side for each source is constructed according to: .. math:: - \mathbf{q} = -i \omega \mathbf{s_e} - i \omega \mathbf{C^T M_{f\frac{1}{\mu}} s_m } + \mathbf{q} = -i \omega \mathbf{s_e} + \mathbf{C^T M_{f\frac{1}{\mu}} s_m } where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrices for inverse permeabilities projected to faces + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic + and electric source terms, respectively + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrices for inverse + permeabilities projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DElectricField` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` is a vector, - this method returns + Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` + is a vector, this method returns .. math:: \frac{\partial \mathbf{q_k}}{\partial \mathbf{m}} \, \mathbf{v} @@ -873,17 +897,17 @@ def getRHSDeriv(self, freq, src, v, adjoint=False): src : .frequency_domain.sources.BaseFDEMSrc The FDEM source object. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_edges,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. Returns ------- numpy.ndarray - Derivative of the right-hand sides times a vector. (n_edges,) for the standard operation. - (n_param,) for the adjoint operation. + Derivative of the right-hand sides times a vector. (n_edges,) for the standard + operation. (n_param,) for the adjoint operation. """ - C = self.mesh.edge_curl MfMui = self.MfMui s_m, s_e = self.getSourceTerm(freq, source=src) @@ -920,9 +944,10 @@ class Simulation3DMagneticFluxDensity(BaseFDEMSimulation): frequency is discarded after the fields are computed at that frequency. If ``False``, the factorizations of the system matrices for all frequencies are stored. permittivity : (n_cells,) numpy.ndarray, optional - Dielectric permittivity (F/m) defined on the entire mesh. If ``None``, electric displacement - is ignored. Please note that `permittivity` is not an invertible property, and that future - development will result in the deprecation of this propery. + Dielectric permittivity (F/m) defined on the entire mesh. If ``None``, + electric displacement + is ignored. Please note that `permittivity` is not an invertible property, + and that future development will result in the deprecation of this propery. storeJ : bool, optional Whether to compute and store the sensitivity matrix. @@ -932,10 +957,10 @@ class Simulation3DMagneticFluxDensity(BaseFDEMSimulation): :math:`+i\omega t` Fourier convention is used: .. math:: - \begin{align} - &\nabla \times \vec{E} + i\omega \vec{B} = - i \omega \vec{S}_m \\ + \begin{aligned} + &\nabla \times \vec{E} + i\omega \vec{B} = \vec{S}_m \\ &\nabla \times \vec{H} - \vec{J} = \vec{S}_e - \end{align} + \end{aligned} where :math:`\vec{S}_e` is an electric source term that defines a source current density, and :math:`\vec{S}_m` magnetic source term that defines a source magnetic flux density. @@ -946,19 +971,22 @@ class Simulation3DMagneticFluxDensity(BaseFDEMSimulation): \vec{J} &= \sigma \vec{E} \\ \vec{H} &= \mu^{-1} \vec{B} - We then take the inner products of all previous expressions with a vector test function :math:`\vec{u}`. - Through vector calculus identities and the divergence theorem, we obtain: + We then take the inner products of all previous expressions with a vector test + function :math:`\vec{u}`. Through vector calculus identities and the divergence theorem, + we obtain: .. math:: & \int_\Omega \vec{u} \cdot (\nabla \times \vec{E}) \, dv + i \omega \int_\Omega \vec{u} \cdot \vec{B} \, dv - = - i \omega \int_\Omega \vec{u} \cdot \vec{S}_m \, dv \\ + = \int_\Omega \vec{u} \cdot \vec{S}_m \, dv \\ & \int_\Omega (\nabla \times \vec{u}) \cdot \vec{H} \, dv - \oint_{\partial \Omega} \vec{u} \cdot (\vec{H} \times \hat{n}) \, da - \int_\Omega \vec{u} \cdot \vec{J} \, dv = \int_\Omega \vec{u} \cdot \vec{S}_j \, dv \\ - & \int_\Omega \vec{u} \cdot \vec{J} \, dv = \int_\Omega \vec{u} \cdot \sigma \vec{E} \, dv \\ - & \int_\Omega \vec{u} \cdot \vec{H} \, dv = \int_\Omega \vec{u} \cdot \mu^{-1} \vec{B} \, dv + & \int_\Omega \vec{u} \cdot \vec{J} \, dv = + \int_\Omega \vec{u} \cdot \sigma \vec{E} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{H} \, dv = + \int_\Omega \vec{u} \cdot \mu^{-1} \vec{B} \, dv Assuming natural boundary conditions, the surface integral is zero. @@ -971,7 +999,8 @@ class Simulation3DMagneticFluxDensity(BaseFDEMSimulation): set of discrete inner-products: .. math:: - &\mathbf{u_f^T M_f C e} + i \omega \mathbf{u_f^T M_f b} = - i \omega \mathbf{u_f^T M_f s_m} \\ + &\mathbf{u_f^T M_f C e} + i \omega \mathbf{u_f^T M_f b} = + \mathbf{u_f^T M_f s_m} \\ &\mathbf{u_e^T C^T M_f h} - \mathbf{u_e^T M_e j} = \mathbf{u_e^T s_e} \\ &\mathbf{u_e^T M_e j} = \mathbf{u_e^T M_{e\sigma} e} \\ &\mathbf{u_f^T M_f h} = \mathbf{u_f^T M_{f \mu} b} @@ -979,21 +1008,25 @@ class Simulation3DMagneticFluxDensity(BaseFDEMSimulation): where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively * :math:`\mathbf{M_e}` is the edge inner-product matrix * :math:`\mathbf{M_f}` is the face inner-product matrix - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse permeabilities projected to faces + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces - By cancelling like-terms and combining the discrete expressions to solve for the magnetic flux density, we obtain: + By cancelling like-terms and combining the discrete expressions to solve for the + magnetic flux density, we obtain: .. math:: \mathbf{A \, b} = \mathbf{q} where - * :math:`\mathbf{A} = \mathbf{C M_{e\sigma}^{-1} C^T M_{f\frac{1}{\mu}}} + i\omega \mathbf{I}` - * :math:`\mathbf{q} = \mathbf{C M_{e\sigma}^{-1} s_e} - i \omega \mathbf{s_m}` + * :math:`\mathbf{A}=\mathbf{C M_{e\sigma}^{-1}C^T M_{f\frac{1}{\mu}}}+i\omega \mathbf{I}` + * :math:`\mathbf{q}=\mathbf{C M_{e\sigma}^{-1} s_e} + \mathbf{s_m}` """ @@ -1002,7 +1035,7 @@ class Simulation3DMagneticFluxDensity(BaseFDEMSimulation): fieldsPair = Fields3DMagneticFluxDensity def getA(self, freq): - r"""System matrix for the frequency provided. + r"""Get system matrix for the frequency provided. This method returns the system matrix for the frequency provided: @@ -1013,8 +1046,10 @@ def getA(self, freq): * :math:`\mathbf{I}` is the identity matrix * :math:`\mathbf{C}` is the curl operator - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse permeabilities projected to faces + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DMagneticFluxDensity` for a full description of the formulation. @@ -1029,7 +1064,6 @@ def getA(self, freq): (n_faces, n_faces) sp.sparse.csr_matrix The system matrix. """ - MfMui = self.MfMui C = self.mesh.edge_curl iomega = 1j * omega(freq) * sp.eye(self.mesh.nF) @@ -1048,7 +1082,7 @@ def getA(self, freq): return A def getADeriv_sigma(self, freq, u, v, adjoint=False): - r"""Conductivity derivative operation for the system matrix times a vector. + r"""Get conductivity derivative operation for the system matrix times a vector. The system matrix at each frequency is given by: @@ -1059,23 +1093,28 @@ def getADeriv_sigma(self, freq, u, v, adjoint=False): * :math:`\mathbf{I}` is the identity matrix * :math:`\mathbf{C}` is the curl operator - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse permeabilities projected to faces + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DMagneticFluxDensity` for a full description of the formulation. - Where :math:`\mathbf{m}_\boldsymbol{\sigma}` are the set of model parameters defining the conductivity, - :math:`\mathbf{v}` is a vector and :math:`\mathbf{b}` is the discrete magnetic flux density solution, + Where :math:`\mathbf{m}_\boldsymbol{\sigma}` are the set of model parameters defining + the conductivity, :math:`\mathbf{v}` is a vector and :math:`\mathbf{b}` is the + discrete magnetic flux density solution, this method assumes the discrete solution is fixed and returns .. math:: - \frac{\partial (\mathbf{A \, b})}{\partial \mathbf{m}_\boldsymbol{\sigma}} \, \mathbf{v} + \frac{\partial (\mathbf{A \, b})}{\partial \mathbf{m}_\boldsymbol{\sigma}} + \, \mathbf{v} Or the adjoint operation .. math:: - \frac{\partial (\mathbf{A \, b})}{\partial \mathbf{m}_\boldsymbol{\sigma}}^T \, \mathbf{v} + \frac{\partial (\mathbf{A \, b})}{\partial \mathbf{m}_\boldsymbol{\sigma}}^T + \, \mathbf{v} Parameters ---------- @@ -1084,7 +1123,8 @@ def getADeriv_sigma(self, freq, u, v, adjoint=False): u : (n_faces,) numpy.ndarray The solution for the fields for the current model at the specified frequency. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -1094,7 +1134,6 @@ def getADeriv_sigma(self, freq, u, v, adjoint=False): Derivative of system matrix times a vector. (n_faces,) for the standard operation. (n_param,) for the adjoint operation. """ - MfMui = self.MfMui C = self.mesh.edge_curl MeSigmaIDeriv = self.MeSigmaIDeriv @@ -1109,7 +1148,7 @@ def getADeriv_sigma(self, freq, u, v, adjoint=False): # return C * (MeSigmaIDeriv * v) def getADeriv_mui(self, freq, u, v, adjoint=False): - r"""Inverse permeability derivative operation for the system matrix times a vector. + r"""Get inverse permeability derivative operation for the system matrix times a vector. The system matrix at each frequency is given by: @@ -1120,23 +1159,28 @@ def getADeriv_mui(self, freq, u, v, adjoint=False): * :math:`\mathbf{I}` is the identity matrix * :math:`\mathbf{C}` is the curl operator - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse permeabilities projected to faces + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DMagneticFluxDensity` for a full description of the formulation. - Where :math:`\mathbf{m}_\boldsymbol{\mu}` are the set of model parameters defining the permeability, - :math:`\mathbf{v}` is a vector and :math:`\mathbf{b}` is the discrete magnetic flux density solution, + Where :math:`\mathbf{m}_\boldsymbol{\mu}` are the set of model parameters defining + the permeability, :math:`\mathbf{v}` is a vector and :math:`\mathbf{b}` is the + discrete magnetic flux density solution, this method assumes the discrete solution is fixed and returns .. math:: - \frac{\partial (\mathbf{A \, b})}{\partial \mathbf{m}_\boldsymbol{\mu}} \, \mathbf{v} + \frac{\partial (\mathbf{A \, b})}{\partial \mathbf{m}_\boldsymbol{\mu}} + \, \mathbf{v} Or the adjoint operation .. math:: - \frac{\partial (\mathbf{A \, b})}{\partial \mathbf{m}_\boldsymbol{\mu}}^T \, \mathbf{v} + \frac{\partial (\mathbf{A \, b})}{\partial \mathbf{m}_\boldsymbol{\mu}}^T + \, \mathbf{v} Parameters ---------- @@ -1145,7 +1189,8 @@ def getADeriv_mui(self, freq, u, v, adjoint=False): u : (n_faces,) numpy.ndarray The solution for the fields for the current model at the specified frequency. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -1164,7 +1209,7 @@ def getADeriv_mui(self, freq, u, v, adjoint=False): return C * (MeSigmaI * (C.T * (MfMuiDeriv * v))) def getADeriv(self, freq, u, v, adjoint=False): - r"""Derivative operation for the system matrix times a vector. + r"""Get derivative operation for the system matrix times a vector. The system matrix at each frequency is given by: @@ -1175,14 +1220,17 @@ def getADeriv(self, freq, u, v, adjoint=False): * :math:`\mathbf{I}` is the identity matrix * :math:`\mathbf{C}` is the curl operator - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse permeabilities projected to faces + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DMagneticFluxDensity` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters defining the electromagnetic properties, - :math:`\mathbf{v}` is a vector and :math:`\mathbf{b}` is the discrete magnetic flux density solution, + Where :math:`\mathbf{m}` are the set of model parameters defining the electromagnetic + properties, :math:`\mathbf{v}` is a vector and :math:`\mathbf{b}` is the discrete + magnetic flux density solution, this method assumes the discrete solution is fixed and returns .. math:: @@ -1200,7 +1248,8 @@ def getADeriv(self, freq, u, v, adjoint=False): u : (n_faces,) numpy.ndarray The solution for the fields for the current model at the specified frequency. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -1223,19 +1272,21 @@ def getADeriv(self, freq, u, v, adjoint=False): return ADeriv def getRHS(self, freq): - r"""Right-hand sides for the given frequency. + r"""Get right-hand sides for the given frequency. This method returns the right-hand sides for the frequency provided. The right-hand side for each source is constructed according to: .. math:: - \mathbf{q} = \mathbf{C M_{e\sigma}^{-1} s_e} - i \omega \mathbf{s_m } + \mathbf{q} = \mathbf{C M_{e\sigma}^{-1} s_e} + \mathbf{s_m } where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic + and electric source terms, respectively + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for + conductivities projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DMagneticFluxDensity` for a full description of the formulation. @@ -1250,7 +1301,6 @@ def getRHS(self, freq): (n_faces, n_sources) numpy.ndarray The right-hand sides. """ - s_m, s_e = self.getSourceTerm(freq) C = self.mesh.edge_curl @@ -1270,24 +1320,26 @@ def getRHS(self, freq): return RHS def getRHSDeriv(self, freq, src, v, adjoint=False): - r"""Derivative of the right-hand side times a vector for a given source and frequency. + r"""Get right-hand side derivative times a vector for a given source and frequency. The right-hand side for each source is constructed according to: .. math:: - \mathbf{q} = \mathbf{C M_{e\sigma}^{-1} s_e} - i \omega \mathbf{s_m } + \mathbf{q} = \mathbf{C M_{e\sigma}^{-1} s_e} + \mathbf{s_m } where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic + and electric source terms, respectively + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DMagneticFluxDensity` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` is a vector, - this method returns + Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` + is a vector, this method returns .. math:: \frac{\partial \mathbf{q_k}}{\partial \mathbf{m}} \, \mathbf{v} @@ -1304,17 +1356,17 @@ def getRHSDeriv(self, freq, src, v, adjoint=False): src : .frequency_domain.sources.BaseFDEMSrc The FDEM source object. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) + for the adjoint operation. adjoint : bool Whether to perform the adjoint operation. Returns ------- numpy.ndarray - Derivative of the right-hand sides times a vector. (n_faces,) for the standard operation. - (n_param,) for the adjoint operation. + Derivative of the right-hand sides times a vector. (n_faces,) for the + standard operation. (n_param,) for the adjoint operation. """ - C = self.mesh.edge_curl s_m, s_e = src.eval(self) MfMui = self.MfMui @@ -1364,8 +1416,9 @@ class Simulation3DCurrentDensity(BaseFDEMSimulation): frequency is discarded after the fields are computed at that frequency. If ``False``, the factorizations of the system matrices for all frequencies are stored. permittivity : (n_cells,) numpy.ndarray, optional - Dielectric permittivity (F/m) defined on the entire mesh. If ``None``, electric displacement - is ignored. Please note that `permittivity` is not an invertible property, and that future + Dielectric permittivity (F/m) defined on the entire mesh. If ``None``, electric + displacement is ignored. Please note that `permittivity` is not an invertible + property, and that future development will result in the deprecation of this propery. storeJ : bool, optional Whether to compute and store the sensitivity matrix. @@ -1376,10 +1429,10 @@ class Simulation3DCurrentDensity(BaseFDEMSimulation): :math:`+i\omega t` Fourier convention is used: .. math:: - \begin{align} - &\nabla \times \vec{E} + i\omega \vec{B} = - i \omega \vec{S}_m \\ + \begin{aligned} + &\nabla \times \vec{E} + i\omega \vec{B} = \vec{S}_m \\ &\nabla \times \vec{H} - \vec{J} = \vec{S}_e - \end{align} + \end{aligned} where :math:`\vec{S}_e` is an electric source term that defines a source current density, and :math:`\vec{S}_m` magnetic source term that defines a source magnetic flux density. @@ -1391,18 +1444,22 @@ class Simulation3DCurrentDensity(BaseFDEMSimulation): \vec{E} &= \rho \vec{J} \\ \vec{B} &= \mu \vec{H} - We then take the inner products of all previous expressions with a vector test function :math:`\vec{u}`. - Through vector calculus identities and the divergence theorem, we obtain: + We then take the inner products of all previous expressions with a vector test + function :math:`\vec{u}`. Through vector calculus identities and the divergence + theorem, we obtain: .. math:: & \int_\Omega (\nabla \times \vec{u}) \cdot \vec{E} \; dv - \oint_{\partial \Omega} \vec{u} \cdot (\vec{E} \times \hat{n} ) \, da + i \omega \int_\Omega \vec{u} \cdot \vec{B} \, dv - = - i \omega \int_\Omega \vec{u} \cdot \vec{S}_m dv \\ + = \int_\Omega \vec{u} \cdot \vec{S}_m dv \\ & \int_\Omega \vec{u} \cdot (\nabla \times \vec{H} ) \, dv - - \int_\Omega \vec{u} \cdot \vec{J} \, dv = \int_\Omega \vec{u} \cdot \vec{S}_j \, dv\\ - & \int_\Omega \vec{u} \cdot \vec{E} \, dv = \int_\Omega \vec{u} \cdot \rho \vec{J} \, dv \\ - & \int_\Omega \vec{u} \cdot \vec{B} \, dv = \int_\Omega \vec{u} \cdot \mu \vec{H} \, dv + - \int_\Omega \vec{u} \cdot \vec{J} \, dv = + \int_\Omega \vec{u} \cdot \vec{S}_j \, dv\\ + & \int_\Omega \vec{u} \cdot \vec{E} \, dv = + \int_\Omega \vec{u} \cdot \rho \vec{J} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{B} \, dv = + \int_\Omega \vec{u} \cdot \mu \vec{H} \, dv Assuming natural boundary conditions, the surface integral is zero. @@ -1415,21 +1472,26 @@ class Simulation3DCurrentDensity(BaseFDEMSimulation): set of discrete inner-products: .. math:: - &\mathbf{u_e^T C^T M_f \, e } + i \omega \mathbf{u_e^T M_e b} = - i\omega \mathbf{u_e^T s_m} \\ - &\mathbf{u_f^T C \, h} - \mathbf{u_f^T j} = \mathbf{u_f^T s_e} \\ + &\mathbf{u_e^T C^T M_f \, e } + i \omega \mathbf{u_e^T M_e b} = + \mathbf{u_e^T s_m} \\ + &\mathbf{u_f^T M_f \, C \, h} - \mathbf{u_f^T M_f \, j} = \mathbf{u_f^T M_f\, s_e} \\ &\mathbf{u_f^T M_f e} = \mathbf{u_f^T M_{f\rho} j} \\ &\mathbf{u_e^T M_e b} = \mathbf{u_e^T M_{e \mu} h} where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively * :math:`\mathbf{M_e}` is the edge inner-product matrix * :math:`\mathbf{M_f}` is the face inner-product matrix - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected to faces - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected + to faces + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected + to edges - By cancelling like-terms and combining the discrete expressions to solve for the current density, we obtain: + By cancelling like-terms and combining the discrete expressions to solve for the + current density, we obtain: .. math:: \mathbf{A \, j} = \mathbf{q} @@ -1437,7 +1499,7 @@ class Simulation3DCurrentDensity(BaseFDEMSimulation): where * :math:`\mathbf{A} = \mathbf{C M_{e\mu}^{-1} C^T M_{f\rho} + i\omega \mathbf{I}` - * :math:`\mathbf{q} = - i \omega \mathbf{s_e} - i \omega \mathbf{C M_{e\mu}^{-1} s_m}` + * :math:`\mathbf{q} = - i \omega \mathbf{s_e} + \mathbf{C M_{e\mu}^{-1} s_m}` """ @@ -1454,7 +1516,7 @@ def __init__( self.permittivity = permittivity def getA(self, freq): - r"""System matrix for the frequency provided. + r"""Get system matrix for the frequency provided. This method returns the system matrix for the frequency provided. The system matrix at each frequency is given by: @@ -1464,8 +1526,10 @@ def getA(self, freq): where - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected to faces - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities + projected to faces + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DCurrentDensity` for a full description of the formulation. @@ -1480,7 +1544,6 @@ def getA(self, freq): (n_faces, n_faces) sp.sparse.csr_matrix The system matrix. """ - MeMuI = self.MeMuI MfRho = self.MfRho C = self.mesh.edge_curl @@ -1499,7 +1562,7 @@ def getA(self, freq): return A def getADeriv_rho(self, freq, u, v, adjoint=False): - r"""Resistivity derivative operation for the system matrix times a vector. + r"""Get resistivity derivative operation for the system matrix times a vector. The system matrix at each frequency is given by: @@ -1508,23 +1571,28 @@ def getADeriv_rho(self, freq, u, v, adjoint=False): where - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected to faces - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities + projected to faces + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DCurrentDensity` for a full description of the formulation. - Where :math:`\mathbf{m}_\boldsymbol{\rho}` are the set of model parameters defining the resistivity, - :math:`\mathbf{v}` is a vector and :math:`\mathbf{j}` is the discrete current density solution, this method assumes + Where :math:`\mathbf{m}_\boldsymbol{\rho}` are the set of model parameters defining + the resistivity, :math:`\mathbf{v}` is a vector and :math:`\mathbf{j}` is the discrete + current density solution, this method assumes the discrete solution is fixed and returns .. math:: - \frac{\partial (\mathbf{A \, j})}{\partial \mathbf{m}_\boldsymbol{\sigma}} \, \mathbf{v} + \frac{\partial (\mathbf{A \, j})}{\partial \mathbf{m}_\boldsymbol{\sigma}} + \, \mathbf{v} Or the adjoint operation .. math:: - \frac{\partial (\mathbf{A \, j})}{\partial \mathbf{m}_\boldsymbol{\sigma}}^T \, \mathbf{v} + \frac{\partial (\mathbf{A \, j})}{\partial \mathbf{m}_\boldsymbol{\sigma}}^T + \, \mathbf{v} Parameters ---------- @@ -1533,7 +1601,8 @@ def getADeriv_rho(self, freq, u, v, adjoint=False): u : (n_faces,) numpy.ndarray The solution for the fields for the current model at the specified frequency. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -1543,7 +1612,6 @@ def getADeriv_rho(self, freq, u, v, adjoint=False): Derivative of system matrix times a vector. (n_faces,) for the standard operation. (n_param,) for the adjoint operation. """ - MeMuI = self.MeMuI C = self.mesh.edge_curl @@ -1553,7 +1621,7 @@ def getADeriv_rho(self, freq, u, v, adjoint=False): return C * (MeMuI * (C.T * (self.MfRhoDeriv(u, v, adjoint)))) def getADeriv_mu(self, freq, u, v, adjoint=False): - r"""Permeability derivative operation for the system matrix times a vector. + r"""Get permeability derivative operation for the system matrix times a vector. The system matrix at each frequency is given by: @@ -1562,23 +1630,28 @@ def getADeriv_mu(self, freq, u, v, adjoint=False): where - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected to faces - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities + projected to faces + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DCurrentDensity` for a full description of the formulation. - Where :math:`\mathbf{m}_\boldsymbol{\mu}` are the set of model parameters defining the permeability, - :math:`\mathbf{v}` is a vector and :math:`\mathbf{j}` is the discrete current density solution, this method assumes + Where :math:`\mathbf{m}_\boldsymbol{\mu}` are the set of model parameters defining + the permeability, :math:`\mathbf{v}` is a vector and :math:`\mathbf{j}` is the + discrete current density solution, this method assumes the discrete solution is fixed and returns .. math:: - \frac{\partial (\mathbf{A \, j})}{\partial \mathbf{m}_\boldsymbol{\mu}} \, \mathbf{v} + \frac{\partial (\mathbf{A \, j})}{\partial \mathbf{m}_\boldsymbol{\mu}} \, + \mathbf{v} Or the adjoint operation .. math:: - \frac{\partial (\mathbf{A \, j})}{\partial \mathbf{m}_\boldsymbol{\mu}}^T \, \mathbf{v} + \frac{\partial (\mathbf{A \, j})}{\partial \mathbf{m}_\boldsymbol{\mu}}^T \, + \mathbf{v} Parameters ---------- @@ -1587,7 +1660,8 @@ def getADeriv_mu(self, freq, u, v, adjoint=False): u : (n_faces,) numpy.ndarray The solution for the fields for the current model at the specified frequency. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -1602,7 +1676,7 @@ def getADeriv_mu(self, freq, u, v, adjoint=False): MeMuIDeriv = self.MeMuIDeriv(C.T * (MfRho * u)) - if adjoint is True: + if adjoint: # if self._makeASymmetric: # v = MfRho * v return MeMuIDeriv.T * (C.T * v) @@ -1613,7 +1687,7 @@ def getADeriv_mu(self, freq, u, v, adjoint=False): return Aderiv def getADeriv(self, freq, u, v, adjoint=False): - r"""Derivative operation for the system matrix times a vector. + r"""Get derivative operation for the system matrix times a vector. The system matrix at each frequency is given by: @@ -1622,14 +1696,17 @@ def getADeriv(self, freq, u, v, adjoint=False): where - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected to faces - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities + projected to faces + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DCurrentDensity` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters defining the electromagnetic properties, - :math:`\mathbf{v}` is a vector and :math:`\mathbf{j}` is the discrete current density solution, this method assumes + Where :math:`\mathbf{m}` are the set of model parameters defining the + electromagnetic properties, :math:`\mathbf{v}` is a vector and :math:`\mathbf{j}` + is the discrete current density solution, this method assumes the discrete solution is fixed and returns .. math:: @@ -1647,7 +1724,8 @@ def getADeriv(self, freq, u, v, adjoint=False): u : (n_faces,) numpy.ndarray The solution for the fields for the current model at the specified frequency. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -1670,19 +1748,21 @@ def getADeriv(self, freq, u, v, adjoint=False): return ADeriv def getRHS(self, freq): - r"""Right-hand sides for the given frequency. + r"""Get right-hand sides for the given frequency. This method returns the right-hand sides for the frequency provided. The right-hand side for each source is constructed according to: .. math:: - \mathbf{q} = - i \omega \mathbf{s_e} - i \omega \mathbf{C M_{e\mu}^{-1} s_m} + \mathbf{q} = - i \omega \mathbf{s_e} + \mathbf{C M_{e\mu}^{-1} s_m} where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrices for permeabilities projected to edges + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic + and electric source terms, respectively + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrices for permeabilities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DCurrentDensity` for a full description of the formulation. @@ -1697,7 +1777,6 @@ def getRHS(self, freq): (n_faces, n_sources) numpy.ndarray The right-hand sides. """ - s_m, s_e = self.getSourceTerm(freq) C = self.mesh.edge_curl MeMuI = self.MeMuI @@ -1710,24 +1789,26 @@ def getRHS(self, freq): return RHS def getRHSDeriv(self, freq, src, v, adjoint=False): - r"""Derivative of the right-hand side times a vector for a given source and frequency. + r"""Get right-hand side derivative times a vector for a given source and frequency. The right-hand side for each source is constructed according to: .. math:: - \mathbf{q} = - i \omega \mathbf{s_e} - i \omega \mathbf{C M_{e\mu}^{-1} s_m} + \mathbf{q} = - i \omega \mathbf{s_e} + \mathbf{C M_{e\mu}^{-1} s_m} where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrices for permeabilities projected to edges + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrices for permeabilities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DCurrentDensity` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` is a vector, - this method returns + Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` + is a vector, this method returns .. math:: \frac{\partial \mathbf{q_k}}{\partial \mathbf{m}} \, \mathbf{v} @@ -1744,22 +1825,22 @@ def getRHSDeriv(self, freq, src, v, adjoint=False): src : .frequency_domain.sources.BaseFDEMSrc The FDEM source object. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. Returns ------- numpy.ndarray - Derivative of the right-hand sides times a vector. (n_faces,) for the standard operation. + Derivative of the right-hand sides times a vector. (n_faces,) for the + standard operation. (n_param,) for the adjoint operation. """ - # RHS = C * (MeMuI * s_m) - 1j * omega(freq) * s_e # if self._makeASymmetric is True: # MfRho = self.MfRho # return MfRho.T*RHS - C = self.mesh.edge_curl MeMuI = self.MeMuI MeMuIDeriv = self.MeMuIDeriv @@ -1807,8 +1888,9 @@ class Simulation3DMagneticField(BaseFDEMSimulation): frequency is discarded after the fields are computed at that frequency. If ``False``, the factorizations of the system matrices for all frequencies are stored. permittivity : (n_cells,) numpy.ndarray, optional - Dielectric permittivity (F/m) defined on the entire mesh. If ``None``, electric displacement - is ignored. Please note that `permittivity` is not an invertible property, and that future + Dielectric permittivity (F/m) defined on the entire mesh. If ``None``, + electric displacement is ignored. Please note that `permittivity` is not an + invertible property, and that future development will result in the deprecation of this propery. storeJ : bool, optional Whether to compute and store the sensitivity matrix. @@ -1819,10 +1901,10 @@ class Simulation3DMagneticField(BaseFDEMSimulation): :math:`+i\omega t` Fourier convention is used: .. math:: - \begin{align} - &\nabla \times \vec{E} + i\omega \vec{B} = - i \omega \vec{S}_m \\ + \begin{aligned} + &\nabla \times \vec{E} + i\omega \vec{B} = \vec{S}_m \\ &\nabla \times \vec{H} - \vec{J} = \vec{S}_e - \end{align} + \end{aligned} where :math:`\vec{S}_e` is an electric source term that defines a source current density, and :math:`\vec{S}_m` magnetic source term that defines a source magnetic flux density. @@ -1834,18 +1916,22 @@ class Simulation3DMagneticField(BaseFDEMSimulation): \vec{E} &= \rho \vec{J} \\ \vec{B} &= \mu \vec{H} - We then take the inner products of all previous expressions with a vector test function :math:`\vec{u}`. + We then take the inner products of all previous expressions with a vector test + function :math:`\vec{u}`. Through vector calculus identities and the divergence theorem, we obtain: .. math:: & \int_\Omega (\nabla \times \vec{u}) \cdot \vec{E} \; dv - \oint_{\partial \Omega} \vec{u} \cdot (\vec{E} \times \hat{n} ) \, da + i \omega \int_\Omega \vec{u} \cdot \vec{B} \, dv - = - i \omega \int_\Omega \vec{u} \cdot \vec{S}_m dv \\ + = \int_\Omega \vec{u} \cdot \vec{S}_m dv \\ & \int_\Omega \vec{u} \cdot (\nabla \times \vec{H} ) \, dv - - \int_\Omega \vec{u} \cdot \vec{J} \, dv = \int_\Omega \vec{u} \cdot \vec{S}_j \, dv\\ - & \int_\Omega \vec{u} \cdot \vec{E} \, dv = \int_\Omega \vec{u} \cdot \rho \vec{J} \, dv \\ - & \int_\Omega \vec{u} \cdot \vec{B} \, dv = \int_\Omega \vec{u} \cdot \mu \vec{H} \, dv + - \int_\Omega \vec{u} \cdot \vec{J} \, dv = + \int_\Omega \vec{u} \cdot \vec{S}_j \, dv\\ + & \int_\Omega \vec{u} \cdot \vec{E} \, dv = + \int_\Omega \vec{u} \cdot \rho \vec{J} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{B} \, dv = + \int_\Omega \vec{u} \cdot \mu \vec{H} \, dv Assuming natural boundary conditions, the surface integral is zero. @@ -1858,21 +1944,26 @@ class Simulation3DMagneticField(BaseFDEMSimulation): set of discrete inner-products: .. math:: - &\mathbf{u_e^T C^T M_f \, e } + i \omega \mathbf{u_e^T M_e b} = - i\omega \mathbf{u_e^T s_m} \\ - &\mathbf{u_f^T C \, h} - \mathbf{u_f^T j} = \mathbf{u_f^T s_e} \\ + &\mathbf{u_e^T C^T M_f \, e } + i \omega \mathbf{u_e^T M_e b} = + \mathbf{u_e^T s_m} \\ + &\mathbf{u_f^T M_f \, C \, h} - \mathbf{u_f^T M_f \, j} = \mathbf{u_f^T M_f \, s_e} \\ &\mathbf{u_f^T M_f e} = \mathbf{u_f^T M_{f\rho} j} \\ &\mathbf{u_e^T M_e b} = \mathbf{u_e^T M_{e \mu} h} where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively * :math:`\mathbf{M_e}` is the edge inner-product matrix * :math:`\mathbf{M_f}` is the face inner-product matrix - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected to faces - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities + projected to faces + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities + projected to edges - By cancelling like-terms and combining the discrete expressions to solve for the magnetic field, we obtain: + By cancelling like-terms and combining the discrete expressions to solve for the + magnetic field, we obtain: .. math:: \mathbf{A \, h} = \mathbf{q} @@ -1880,7 +1971,7 @@ class Simulation3DMagneticField(BaseFDEMSimulation): where * :math:`\mathbf{A} = \mathbf{C^T M_{f\rho} C} + i\omega \mathbf{M_{e\mu}}` - * :math:`\mathbf{q} = \mathbf{C^T M_{f\rho} s_e} - i\omega \mathbf{s_m}` + * :math:`\mathbf{q} = \mathbf{C^T M_{f\rho} s_e} + \mathbf{s_m}` """ @@ -1899,8 +1990,10 @@ def getA(self, freq): where - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected to faces - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities + projected to faces + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DMagneticField` for a full description of the formulation. @@ -1915,7 +2008,6 @@ def getA(self, freq): (n_edges, n_edges) sp.sparse.csr_matrix The system matrix. """ - MeMu = self.MeMu C = self.mesh.edge_curl @@ -1929,7 +2021,7 @@ def getA(self, freq): return C.T.tocsr() * (Mfyhati * C) + 1j * omega(freq) * MeMu def getADeriv_rho(self, freq, u, v, adjoint=False): - r"""Resistivity derivative operation for the system matrix times a vector. + r"""Get resistivity derivative operation for the system matrix times a vector. The system matrix at each frequency is given by: @@ -1938,23 +2030,28 @@ def getADeriv_rho(self, freq, u, v, adjoint=False): where - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected to faces - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities + projected to faces + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DMagneticField` for a full description of the formulation. - Where :math:`\mathbf{m}_\boldsymbol{\sigma}` are the set of model parameters defining the conductivity, - :math:`\mathbf{v}` is a vector and :math:`\mathbf{h}` is the discrete magnetic field solution, this method assumes + Where :math:`\mathbf{m}_\boldsymbol{\sigma}` are the set of model parameters + defining the conductivity, :math:`\mathbf{v}` is a vector and :math:`\mathbf{h}` + is the discrete magnetic field solution, this method assumes the discrete solution is fixed and returns .. math:: - \frac{\partial (\mathbf{A \, h})}{\partial \mathbf{m}_\boldsymbol{\sigma}} \, \mathbf{v} + \frac{\partial (\mathbf{A \, h})}{\partial \mathbf{m}_\boldsymbol{\sigma}} + \, \mathbf{v} Or the adjoint operation .. math:: - \frac{\partial (\mathbf{A \, h})}{\partial \mathbf{m}_\boldsymbol{\sigma}}^T \, \mathbf{v} + \frac{\partial (\mathbf{A \, h})}{\partial \mathbf{m}_\boldsymbol{\sigma}}^T + \, \mathbf{v} Parameters ---------- @@ -1963,7 +2060,8 @@ def getADeriv_rho(self, freq, u, v, adjoint=False): u : (n_edges,) numpy.ndarray The solution for the fields for the current model at the specified frequency. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_edges,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -1979,7 +2077,7 @@ def getADeriv_rho(self, freq, u, v, adjoint=False): return C.T * self.MfRhoDeriv(C * u, v, adjoint) def getADeriv_mu(self, freq, u, v, adjoint=False): - r"""Permeability derivative operation for the system matrix times a vector. + r"""Get permeability derivative operation for the system matrix times a vector. The system matrix at each frequency is given by: @@ -1988,23 +2086,28 @@ def getADeriv_mu(self, freq, u, v, adjoint=False): where - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected to faces - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities + projected to faces + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DMagneticField` for a full description of the formulation. - Where :math:`\mathbf{m}_\boldsymbol{\mu}` are the set of model parameters defining the permeability, - :math:`\mathbf{v}` is a vector and :math:`\mathbf{h}` is the discrete magnetic field solution, this method assumes - the discrete solution is fixed and returns + Where :math:`\mathbf{m}_\boldsymbol{\mu}` are the set of model parameters defining + the permeability, :math:`\mathbf{v}` is a vector and :math:`\mathbf{h}` is the + discrete magnetic field solution, this method assumes the discrete solution is + fixed and returns .. math:: - \frac{\partial (\mathbf{A \, h})}{\partial \mathbf{m}_\boldsymbol{\mu}} \, \mathbf{v} + \frac{\partial (\mathbf{A \, h})}{\partial \mathbf{m}_\boldsymbol{\mu}} + \, \mathbf{v} Or the adjoint operation .. math:: - \frac{\partial (\mathbf{A \, h})}{\partial \mathbf{m}_\boldsymbol{\mu}}^T \, \mathbf{v} + \frac{\partial (\mathbf{A \, h})}{\partial \mathbf{m}_\boldsymbol{\mu}}^T + \, \mathbf{v} Parameters ---------- @@ -2013,7 +2116,8 @@ def getADeriv_mu(self, freq, u, v, adjoint=False): u : (n_edges,) numpy.ndarray The solution for the fields for the current model at the specified frequency. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_edges,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -2025,13 +2129,13 @@ def getADeriv_mu(self, freq, u, v, adjoint=False): """ MeMuDeriv = self.MeMuDeriv(u) - if adjoint is True: + if adjoint: return 1j * omega(freq) * (MeMuDeriv.T * v) return 1j * omega(freq) * (MeMuDeriv * v) def getADeriv(self, freq, u, v, adjoint=False): - r"""Derivative operation for the system matrix times a vector. + r"""Get derivative operation for the system matrix times a vector. The system matrix at each frequency is given by: @@ -2040,15 +2144,17 @@ def getADeriv(self, freq, u, v, adjoint=False): where - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected to faces - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities + projected to faces + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DMagneticField` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters defining the electromagnetic properties, - :math:`\mathbf{v}` is a vector and :math:`\mathbf{h}` is the discrete electric field solution, this method assumes - the discrete solution is fixed and returns + Where :math:`\mathbf{m}` are the set of model parameters defining the electromagnetic + properties, :math:`\mathbf{v}` is a vector and :math:`\mathbf{h}` is the discrete + electric field solution, this method assumes the discrete solution is fixed and returns .. math:: \frac{\partial (\mathbf{A \, h})}{\partial \mathbf{m}} \, \mathbf{v} @@ -2065,7 +2171,8 @@ def getADeriv(self, freq, u, v, adjoint=False): u : (n_edges,) numpy.ndarray The solution for the fields for the current model at the specified frequency. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_edges,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -2080,20 +2187,23 @@ def getADeriv(self, freq, u, v, adjoint=False): ) def getRHS(self, freq): - r"""Right-hand sides for the given frequency. + r"""Get right-hand sides for the given frequency. This method returns the right-hand sides for the frequency provided. The right-hand side for each source is constructed according to: .. math:: - \mathbf{q} = \mathbf{C^T M_{f\rho} s_e} - i\omega \mathbf{s_m} + \mathbf{q} = \mathbf{C^T M_{f\rho} s_e} + \mathbf{s_m} where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrices for permeabilities projected to edges - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrices for resistivities projected to faces + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic + and electric source terms, respectively + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrices for permeabilities + projected to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrices for resistivities + projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DMagneticField` for a full description of the formulation. @@ -2108,7 +2218,6 @@ def getRHS(self, freq): (n_edges, n_sources) numpy.ndarray The right-hand sides. """ - s_m, s_e = self.getSourceTerm(freq) C = self.mesh.edge_curl @@ -2122,25 +2231,28 @@ def getRHS(self, freq): return s_m + C.T * (Mfyhati * s_e) def getRHSDeriv(self, freq, src, v, adjoint=False): - r"""Derivative of the right-hand side times a vector for a given source and frequency. + r"""Get right-hand side derivative times a vector for a given source and frequency. The right-hand side for each source is constructed according to: .. math:: - \mathbf{q} = \mathbf{C^T M_{f\rho} s_e} - i\omega \mathbf{s_m} + \mathbf{q} = \mathbf{C^T M_{f\rho} s_e} + \mathbf{s_m} where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrices for permeabilities projected to edges - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrices for resistivities projected to faces + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic + and electric source terms, respectively + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrices for permeabilities + projected to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrices for resistivities + projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DMagneticField` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` is a vector, - this method returns + Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` + is a vector, this method returns .. math:: \frac{\partial \mathbf{q_k}}{\partial \mathbf{m}} \, \mathbf{v} @@ -2157,17 +2269,18 @@ def getRHSDeriv(self, freq, src, v, adjoint=False): src : .frequency_domain.sources.BaseFDEMSrc The FDEM source object. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. + (n_edges,) for the adjoint operation. adjoint : bool Whether to perform the adjoint operation. Returns ------- numpy.ndarray - Derivative of the right-hand sides times a vector. (n_edges,) for the standard operation. + Derivative of the right-hand sides times a vector. (n_edges,) + for the standard operation. (n_param,) for the adjoint operation. """ - _, s_e = src.eval(self) C = self.mesh.edge_curl MfRho = self.MfRho @@ -2185,3 +2298,255 @@ def getRHSDeriv(self, freq, src, v, adjoint=False): s_mDeriv, s_eDeriv = src.evalDeriv(self, adjoint=adjoint) return RHSDeriv + s_mDeriv(v) + C.T * (MfRho * s_eDeriv(v)) + + +############################################################################### +# Hierarchical # +############################################################################### +class Simulation3DHierarchicalElectricField( + BaseHierarchicalElectricalSimulation, Simulation3DElectricField +): + r"""3D hierarchical FDEM simulation in terms of the electric field. + + This simulation solves for the electric field at each frequency. + In this formulation, the electric fields are defined on mesh edges and the + magnetic flux density is defined on mesh faces; i.e. it is an EB formulation. + This simulation adopts the hierarchical framework wherein: + + * Thick structures are parameterized as conductivities at cell centers. This property + and the corresponding mapping are set with `sigma` and `sigmaMap`. + * Sheet-like structures can be parameterized as conductances on mesh faces. This property + and the corresponding mapping are set with `face_conductance` and `face_conductance_map`. + * Wire-like structures can be parameterized as area-integrated conductivities on + mesh edges. This property and the corresponding mapping as set with + `edge_area_conductance` and `edge_area_conductance_map`. + + See the *Notes* section for a comprehensive description of the formulation. + + Notes + ----- + Here, we start with the Maxwell's equations in the frequency-domain where a + :math:`+i\omega t` Fourier convention is used: + + .. math:: + \begin{aligned} + &\nabla \times \vec{E} + i\omega \vec{B} = \vec{S}_m \\ + &\nabla \times \vec{H} - \vec{J} = \vec{S}_e + \end{aligned} + + where :math:`\vec{S}_e` is an electric source term that defines a source current density, + and :math:`\vec{S}_m` magnetic source term that defines a source magnetic flux density. + We define the constitutive relations for the electrical conductivity :math:`\sigma` + and magnetic permeability :math:`\mu` as: + + .. math:: + \vec{J} &= \sigma \vec{E} \\ + \vec{H} &= \mu^{-1} \vec{B} + + We then take the inner products of all previous expressions with a vector test function + math:`\vec{u}`. Through vector calculus identities and the divergence theorem, we obtain: + + .. math:: + & \int_\Omega \vec{u} \cdot (\nabla \times \vec{E}) \, dv + + i \omega \int_\Omega \vec{u} \cdot \vec{B} \, dv + = \int_\Omega \vec{u} \cdot \vec{S}_m \, dv \\ + & \int_\Omega (\nabla \times \vec{u}) \cdot \vec{H} \, dv + - \oint_{\partial \Omega} \vec{u} \cdot (\vec{H} \times \hat{n}) \, da + - \int_\Omega \vec{u} \cdot \vec{J} \, dv + = \int_\Omega \vec{u} \cdot \vec{S}_j \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{J} \, dv = + \int_\Omega \vec{u} \cdot \sigma \vec{E} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{H} \, dv = + \int_\Omega \vec{u} \cdot \mu^{-1} \vec{B} \, dv + + Assuming natural boundary conditions, the surface integral is zero. + + The hierarchical approach assumes the existence of infinitesimally thin plate-like + regions between adjacent mesh faces and infinitesimally thin wire-like regions + between adjacent mesh edges. We re-express the inner-product with Ohm's law as follows: + + .. math:: + \int_\Omega \vec{u} \cdot \vec{j} \, dv =& + \sum_{n}^{nc} \int \vec{u} \cdot \sigma_n \vec{e} \, dv \\ + &+ \sum_{n}^{nf} \int \vec{u} \cdot \tau_n \vec{e} \, da \\ + &+ \sum_{n}^{ne} \int \vec{u} \cdot \kappa_n \vec{e} \, d\ell + + where :math:`\sigma_n` is the conductivity in cell *n*, :math:`\tau_n` is the face + conductance on face *n*, and :math:`\kappa_n` is the area-integrated conductivity + on edge *n*. + + The above expressions are discretized in space according to the finite volume method. + The discrete electric fields :math:`\mathbf{e}` are defined on mesh edges, + and the discrete magnetic flux densities :math:`\mathbf{b}` are defined on mesh faces. + This implies :math:`\mathbf{j}` must be defined on mesh edges and :math:`\mathbf{h}` must + be defined on mesh faces. Where :math:`\mathbf{u_e}` and :math:`\mathbf{u_f}` represent + test functions discretized to edges and faces, respectively, we obtain the following + set of discrete inner-products: + + .. math:: + &\mathbf{u_f^T M_f C e} + i \omega \mathbf{u_f^T M_f b} = + \mathbf{u_f^T M_f s_m} \\ + &\mathbf{u_e^T C^T M_f h} - \mathbf{u_e^T M_e j} = \mathbf{u_e^T s_e} \\ + &\mathbf{u_e^T M_e j} = \mathbf{u_e^T M_{e \Sigma} e} \\ + &\mathbf{u_f^T M_f h} = \mathbf{u_f^T M_{f \mu} b} + + where + + .. math:: + \mathbf{M_{e\Sigma}} = \mathbf{M_{e\sigma} + M_{e\tau} + M_{e\kappa}} + + and + + * :math:`\mathbf{C}` is the discrete curl operator + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic + and electric source terms, respectively + * :math:`\mathbf{M_e}` is the edge inner-product matrix + * :math:`\mathbf{M_f}` is the face inner-product matrix + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{e\tau}}` is the inner-product matrix for conductances + projected to edges + * :math:`\mathbf{M_{e\kappa}}` is the inner-product matrix for area integrated + conductivities projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces + + By cancelling like-terms and combining the discrete expressions to solve for + the electric field, we obtain: + + .. math:: + \mathbf{A \, e} = \mathbf{q} + + where + + * :math:`\mathbf{A}=\mathbf{C^T M_{f\frac{1}{\mu}} C}+i\omega \mathbf{M_{e\Sigma}}` + * :math:`\mathbf{q} = -i\omega \mathbf{s_e} + \mathbf{C^T M_{f\frac{1}{\mu}} s_m }` + + """ + + pass + + +class Simulation3DHierarchicalMagneticFluxDensity( + BaseHierarchicalElectricalSimulation, Simulation3DMagneticFluxDensity +): + r"""3D hierarchical FDEM simulation in terms of the magnetic flux field. + + This simulation solves for the magnetic flux density at each frequency. + In this formulation, the electric fields are defined on mesh edges and the + magnetic flux density is defined on mesh faces; i.e. it is an EB formulation. + This simulation adopts the hierarchical framework wherein: + + * Thick structures are parameterized as conductivities at cell centers. This property + and the corresponding mapping are set with `sigma` and `sigmaMap`. + * Sheet-like structures can be parameterized as conductances on mesh faces. This property + and the corresponding mapping are set with `face_conductance` and `face_conductance_map`. + * Wire-like structures can be parameterized as area-integrated conductivities on + mesh edges. This property and the corresponding mapping as set with + `edge_area_conductance` and `edge_area_conductance_map`. + + See the *Notes* section for a comprehensive description of the formulation. + + Notes + ----- + Here, we start with the Maxwell's equations in the frequency-domain where a + :math:`+i\omega t` Fourier convention is used: + + .. math:: + \begin{aligned} + &\nabla \times \vec{E} + i\omega \vec{B} = \vec{S}_m \\ + &\nabla \times \vec{H} - \vec{J} = \vec{S}_e + \end{aligned} + + where :math:`\vec{S}_e` is an electric source term that defines a source current density, + and :math:`\vec{S}_m` magnetic source term that defines a source magnetic flux density. + We define the constitutive relations for the electrical conductivity :math:`\sigma` + and magnetic permeability :math:`\mu` as: + + .. math:: + \vec{J} &= \sigma \vec{E} \\ + \vec{H} &= \mu^{-1} \vec{B} + + We then take the inner products of all previous expressions with a vector + test function :math:`\vec{u}`. + Through vector calculus identities and the divergence theorem, we obtain: + + .. math:: + & \int_\Omega \vec{u} \cdot (\nabla \times \vec{E}) \, dv + + i \omega \int_\Omega \vec{u} \cdot \vec{B} \, dv + = \int_\Omega \vec{u} \cdot \vec{S}_m \, dv \\ + & \int_\Omega (\nabla \times \vec{u}) \cdot \vec{H} \, dv + - \oint_{\partial \Omega} \vec{u} \cdot (\vec{H} \times \hat{n}) \, da + - \int_\Omega \vec{u} \cdot \vec{J} \, dv + = \int_\Omega \vec{u} \cdot \vec{S}_j \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{J} \, dv = + \int_\Omega \vec{u} \cdot \sigma \vec{E} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{H} \, dv = + \int_\Omega \vec{u} \cdot \mu^{-1} \vec{B} \, dv + + Assuming natural boundary conditions, the surface integral is zero. + + The hierarchical approach assumes the existence of infinitesimally thin plate-like + regions between adjacent mesh faces and infinitesimally thin wire-like regions + between adjacent mesh edges. We re-express the inner-product with Ohm's law as follows: + + .. math:: + \int_\Omega \vec{u} \cdot \vec{j} \, dv =& + \sum_{n}^{nc} \int \vec{u} \cdot \sigma_n \vec{e} \, dv \\ + &+ \sum_{n}^{nf} \int \vec{u} \cdot \tau_n \vec{e} \, da \\ + &+ \sum_{n}^{ne} \int \vec{u} \cdot \kappa_n \vec{e} \, d\ell + + where :math:`\sigma_n` is the conductivity in cell *n*, :math:`\tau_n` is the face + conductance on face *n*, and :math:`\kappa_n` is the area-integrated conductivity + on edge *n*. + + The above expressions are discretized in space according to the finite volume method. + The discrete electric fields :math:`\mathbf{e}` are defined on mesh edges, + and the discrete magnetic flux densities :math:`\mathbf{b}` are defined on mesh faces. + This implies :math:`\mathbf{j}` must be defined on mesh edges and :math:`\mathbf{h}` must + be defined on mesh faces. Where :math:`\mathbf{u_e}` and :math:`\mathbf{u_f}` represent + test functions discretized to edges and faces, respectively, we obtain the following + set of discrete inner-products: + + .. math:: + &\mathbf{u_f^T M_f C e} + i \omega \mathbf{u_f^T M_f b} = + \mathbf{u_f^T M_f s_m} \\ + &\mathbf{u_e^T C^T M_f h} - \mathbf{u_e^T M_e j} = \mathbf{u_e^T s_e} \\ + &\mathbf{u_e^T M_e j} = \mathbf{u_e^T M_{e\Sigma} e} \\ + &\mathbf{u_f^T M_f h} = \mathbf{u_f^T M_{f \mu} b} + + where: + + .. math:: + \mathbf{M_{e\Sigma}} = \mathbf{M_{e\sigma} + M_{e\tau} + M_{e\kappa}} + + and + + * :math:`\mathbf{C}` is the discrete curl operator + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic + and electric source terms, respectively + * :math:`\mathbf{M_e}` is the edge inner-product matrix + * :math:`\mathbf{M_f}` is the face inner-product matrix + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for electrical conductivities + projected to edges + * :math:`\mathbf{M_{e\tau}}` is the inner-product matrix for conductances + projected to edges + * :math:`\mathbf{M_{e\kappa}}` is the inner-product matrix for area integrated + conductivities projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces + + By cancelling like-terms and combining the discrete expressions to solve for the + magnetic flux density, we obtain: + + .. math:: + \mathbf{A \, b} = \mathbf{q} + + where + + * :math:`\mathbf{A}=\mathbf{C M_{e\Sigma}^{-1}C^T M_{f\frac{1}{\mu}}}+i\omega \mathbf{I}` + * :math:`\mathbf{q}=\mathbf{C M_{e\Sigma}^{-1}s_e} + \mathbf{s_m}` + + """ + + pass diff --git a/simpeg/electromagnetics/frequency_domain/simulation_1d.py b/simpeg/electromagnetics/frequency_domain/simulation_1d.py index c51e8e3d33..4d4b708fc3 100644 --- a/simpeg/electromagnetics/frequency_domain/simulation_1d.py +++ b/simpeg/electromagnetics/frequency_domain/simulation_1d.py @@ -6,7 +6,6 @@ from geoana.kernels.tranverse_electric_reflections import rTE_forward, rTE_gradient - ####################################################################### # SIMULATION FOR A SINGLE SOUNDING ####################################################################### diff --git a/simpeg/electromagnetics/frequency_domain/sources.py b/simpeg/electromagnetics/frequency_domain/sources.py index dc6624823b..3a578e1cee 100644 --- a/simpeg/electromagnetics/frequency_domain/sources.py +++ b/simpeg/electromagnetics/frequency_domain/sources.py @@ -359,7 +359,9 @@ class MagDipole(BaseFDEMSrc): \mathbf{M_{\sigma}^e} \mathbf{e^S} = -\mathbf{C}^T \mathbf{{M_{\mu^{-1}}^f}^S} \mathbf{b^P}} - To obtain $\mathbf{b^P}$, we compute it by taking the curl of the vector potential due to a point dipole. This is provided by :py:meth:`geoana.em.static.MagneticDipoleWholeSpace.vector_potential`. Specifically, + To obtain $\mathbf{b^P}$, we compute it by taking the curl of the vector potential + due to a point dipole. This is provided by + :py:meth:`geoana.em.static.MagneticDipoleWholeSpace.vector_potential`. Specifically, .. math:: diff --git a/simpeg/electromagnetics/natural_source/fields.py b/simpeg/electromagnetics/natural_source/fields.py index 3ba8507807..926db2ed34 100644 --- a/simpeg/electromagnetics/natural_source/fields.py +++ b/simpeg/electromagnetics/natural_source/fields.py @@ -7,7 +7,6 @@ from ...utils import spzeros, Identity, Zero from ..utils import omega - # ############## # # Fields # # ############## @@ -55,24 +54,24 @@ def _eDeriv_u(self, src, du_dm_v, adjoint=False): def _eDeriv_m(self, src, v, adjoint=False): return Zero() + def _mui(self): + mui = self.simulation.mui + if np.ndim(mui) > 0: + # one value per cell, broadcast along the columns of the fields + mui = mui[:, None] + return mui + def _h(self, eSolution, source_list): omegas = np.array([omega(src.frequency) for src in source_list]) e = self._e(eSolution, source_list) - if self.simulation.muiMap is not None: - mui = self.simulation.mui[:, None] - else: - mui = self.simulation.mui - v = mui * (self._C * e) + v = self._mui() * (self._C * e) return v / (1j * omegas) def _hDeriv_u(self, src, du_dm_v, adjoint=False): if du_dm_v.ndim == 1: du_dm_v = du_dm_v[:, None] om = omega(src.frequency) - if self.simulation.muiMap is not None: - mui = self.simulation.mui[:, None] - else: - mui = self.simulation.mui + mui = self._mui() if adjoint: y = self._eDeriv_u(src, self._C.T * (mui * du_dm_v), adjoint=adjoint) return np.squeeze(y) / (1j * om) @@ -109,22 +108,24 @@ def _hDeriv_u(self, src, du_dm_v, adjoint=False): def _hDeriv_m(self, src, v, adjoint=False): return Zero() + def _rho(self): + rho = self.simulation.rho + if np.ndim(rho) > 0: + # one value per cell, broadcast along the columns of the fields + rho = rho[:, None] + return rho + def _e(self, hSolution, source_list): - return self.simulation.rho[:, None] * ( - self._C * self._h(hSolution, source_list) - ) + return self._rho() * (self._C * self._h(hSolution, source_list)) def _eDeriv_u(self, src, du_dm_v, adjoint=False): if du_dm_v.ndim == 1: du_dm_v = du_dm_v[:, None] + rho = self._rho() if adjoint: - y = self._hDeriv_u( - src, self._C.T * (self.simulation.rho[:, None] * du_dm_v), adjoint=True - ) + y = self._hDeriv_u(src, self._C.T * (rho * du_dm_v), adjoint=True) return np.squeeze(y) - y = self.simulation.rho[:, None] * ( - self._C @ (self._hDeriv_u(src, du_dm_v, adjoint=False)) - ) + y = rho * (self._C @ (self._hDeriv_u(src, du_dm_v, adjoint=False))) return np.squeeze(y) def _eDeriv_m(self, src, v, adjoint=False): diff --git a/simpeg/electromagnetics/natural_source/receivers.py b/simpeg/electromagnetics/natural_source/receivers.py index 65c1bba789..768dbb38c5 100644 --- a/simpeg/electromagnetics/natural_source/receivers.py +++ b/simpeg/electromagnetics/natural_source/receivers.py @@ -1,3 +1,5 @@ +"""Natural source EM receivers.""" + from ...utils.code_utils import ( validate_string, validate_type, @@ -8,6 +10,7 @@ from scipy.constants import mu_0 from scipy.sparse import csr_matrix from ...survey import BaseRx +from simpeg.utils import mkvc def _alpha(src): @@ -116,7 +119,7 @@ def getP(self, mesh, projected_grid, location_id=0): scipy.sparse.csr_matrix P, the interpolation matrix. """ - key = (mesh.n_cells, projected_grid, location_id) + key = (mesh, projected_grid, location_id) if key in self._Ps: return self._Ps[key] locs = self._locations[location_id] @@ -154,6 +157,39 @@ def locations_h(self): return self._locations[1] +class _BaseOrientationInvariant(BaseNaturalSourceRx): + """Intermediate class for receivers for orientation invariant transfer functions.""" + + def __init__( # noqa: D107 + self, + locations1, + locations2=None, + base_type="magnetic", + storeProjections=False, + ): + super().__init__( + locations1=locations1, + locations2=locations2, + storeProjections=storeProjections, + ) + self.base_type = base_type + + @property + def base_type(self): + r"""Whether a 'magnetic' or 'electric' base station is used. + + Returns + ------- + str + Base station type; i.e. "magnetic" or "electric" + """ + return self._base_type + + @base_type.setter + def base_type(self, var): + self._base_type = validate_string("base_type", var, ["magnetic", "electric"]) + + class Impedance(_ElectricAndMagneticReceiver): r"""Receiver class for 1D, 2D and 3D impedance data. @@ -209,7 +245,7 @@ class Impedance(_ElectricAndMagneticReceiver): - 'rho': Apparent resistivity (:math:`\Omega m`) - 'phase': Phase angle (degrees) - 'complex': The complex impedance is returned. Do not use for inversion! - storeProjections : bool + storeProjections : bool, optional Whether to cache to internal projection matrices. """ @@ -324,11 +360,11 @@ def _eval_impedance(self, src, mesh, f): PH = self.getP(mesh, h_loc) elif mesh.dim == 2: if self.orientation == "xy": - PE = self.getP(mesh, "Ex") - PH = self.getP(mesh, "CC") + PE = self.getP(mesh, "Ex", 0) + PH = self.getP(mesh, "CC", 1) elif self.orientation == "yx": - PE = self.getP(mesh, "CC") - PH = self.getP(mesh, "Ex") + PE = self.getP(mesh, "CC", 0) + PH = self.getP(mesh, "Ex", 1) top = PE @ e[:, 0] bot = PH @ h[:, 0] @@ -374,11 +410,11 @@ def _eval_impedance_deriv(self, src, mesh, f, du_dm_v=None, v=None, adjoint=Fals PH = self.getP(mesh, h_loc) elif mesh.dim == 2: if self.orientation == "xy": - PE = self.getP(mesh, "Ex") - PH = self.getP(mesh, "CC") + PE = self.getP(mesh, "Ex", 0) + PH = self.getP(mesh, "CC", 1) elif self.orientation == "yx": - PE = self.getP(mesh, "CC") - PH = self.getP(mesh, "Ex") + PE = self.getP(mesh, "CC", 0) + PH = self.getP(mesh, "Ex", 1) top = PE @ e[:, 0] bot = PH @ h[:, 0] @@ -402,8 +438,9 @@ def _eval_impedance_deriv(self, src, mesh, f, du_dm_v=None, v=None, adjoint=Fals v = -1j * v # Work backwards! - gtop_v = np.c_[v] / bot[:, None] - gbot_v = -imp[:, None] * np.c_[v] / bot[:, None] + gtop_v = v / bot + gbot_v = -imp * v / bot + n_d = self.nD if mesh.dim == 3: ghx_v = np.einsum( @@ -424,6 +461,12 @@ def _eval_impedance_deriv(self, src, mesh, f, du_dm_v=None, v=None, adjoint=Fals else: ghx_v -= gh_v + if v.ndim == 2: + # collapse into a long list of n_d vectors + ghx_v = ghx_v.reshape((n_d, -1)) + ghy_v = ghy_v.reshape((n_d, -1)) + ge_v = ge_v.reshape((n_d, -1)) + gh_v = Phx.T @ csr_matrix(ghx_v) + Phy.T @ csr_matrix(ghy_v) ge_v = Pe.T @ csr_matrix(ge_v) else: @@ -598,7 +641,7 @@ class Tipper(BaseNaturalSourceRx): locations_base : (n_loc, n_dim) array_like, optional Locations where the base station magnetic fields are measured. Defaults to the same locations as the roving magnetic fields measurements, - `locations_r`. + `locations_h`. orientation : {'xx', 'yx', 'zx', 'zy', 'yy', 'zy'} Specifies the tipper element :math:`T_{ij}` corresponding to the data. component : {'real', 'imag', 'complex'} @@ -607,7 +650,7 @@ class Tipper(BaseNaturalSourceRx): - 'real': Real component of the tipper (unitless) - 'imag': Imaginary component of the tipper (unitless) - 'complex': The complex tipper is returned. Do not use for inversion! - storeProjections : bool + storeProjections : bool, optional Whether to cache to internal projection matrices. """ @@ -704,100 +747,151 @@ def _eval_tipper(self, src, mesh, f): # will grab both primary and secondary and sum them! h = f[src, "h"] - Phx = self.getP(mesh, "Fx", 1) - Phy = self.getP(mesh, "Fy", 1) - Pho = self.getP(mesh, "F" + self.orientation[0], 0) + # Only Tzx + if mesh.dim == 2: + + Phx = self.getP(mesh, "Ex", 1) + Phz = self.getP(mesh, "Ey", 0) - hx = Phx @ h - hy = Phy @ h - ho = Pho @ h + hz = Phz @ h[:, 0] + hx = Phx @ h[:, 0] + + return hz / hx - if self.orientation[1] == "x": - h = -hy else: - h = hx - top = h[:, 0] * ho[:, 1] - h[:, 1] * ho[:, 0] - bot = hx[:, 0] * hy[:, 1] - hx[:, 1] * hy[:, 0] - return top / bot + Phx = self.getP(mesh, "Fx", 1) + Phy = self.getP(mesh, "Fy", 1) + Pho = self.getP(mesh, "F" + self.orientation[0], 0) + + hx = Phx @ h + hy = Phy @ h + ho = Pho @ h + + if self.orientation[1] == "x": + h = -hy + else: + h = hx + + top = h[:, 0] * ho[:, 1] - h[:, 1] * ho[:, 0] + bot = hx[:, 0] * hy[:, 1] - hx[:, 1] * hy[:, 0] + + return top / bot def _eval_tipper_deriv(self, src, mesh, f, du_dm_v=None, v=None, adjoint=False): # will grab both primary and secondary and sum them! + h = f[src, "h"] - if not isinstance(f, np.ndarray): - h = f[src, "h"] - else: - h = f + if mesh.dim == 2: + + Phx = self.getP(mesh, "Ex", 1) + Phz = self.getP(mesh, "Ey", 0) - Phx = self.getP(mesh, "Fx", 1) - Phy = self.getP(mesh, "Fy", 1) - Phz = self.getP(mesh, "Fz", 0) - hx = Phx @ h - hy = Phy @ h - hz = Phz @ h + hz = Phz @ h[:, 0] + hx = Phx @ h[:, 0] + + tip = hz / hx - if self.orientation[1] == "x": - h = -hy else: - h = hx - top = h[:, 0] * hz[:, 1] - h[:, 1] * hz[:, 0] - bot = hx[:, 0] * hy[:, 1] - hx[:, 1] * hy[:, 0] - imp = top / bot + Phx = self.getP(mesh, "Fx", 1) + Phy = self.getP(mesh, "Fy", 1) + Pho = self.getP(mesh, "F" + self.orientation[0], 0) + + hx = Phx @ h + hy = Phy @ h + ho = Pho @ h + + if self.orientation[1] == "x": + h = -hy + else: + h = hx + + top = h[:, 0] * ho[:, 1] - h[:, 1] * ho[:, 0] + bot = hx[:, 0] * hy[:, 1] - hx[:, 1] * hy[:, 0] + + tip = top / bot + # ADJOINT if adjoint: - # Work backwards! - gtop_v = np.c_[v] / bot[:, None] - gbot_v = -imp[:, None] * np.c_[v] / bot[:, None] - ghx_v = np.einsum("ij,ik->ijk", gbot_v, np.c_[hy[:, 1], -hy[:, 0]]).reshape( - (hy.shape[0], -1) - ) - ghy_v = np.einsum("ij,ik->ijk", gbot_v, np.c_[-hx[:, 1], hx[:, 0]]).reshape( - (hx.shape[0], -1) - ) - ghz_v = np.einsum("ij,ik->ijk", gtop_v, np.c_[-h[:, 1], h[:, 0]]).reshape( - (h.shape[0], -1) - ) - gh_v = np.einsum("ij,ik->ijk", gtop_v, np.c_[hz[:, 1], -hz[:, 0]]).reshape( - (hz.shape[0], -1) - ) + n_d = self.nD + + if mesh.dim == 2: + + ghz_v = v / hx + ghx_v = -tip * v / hx + gh_v = Phx.T @ ghx_v + Phz.T @ ghz_v - if self.orientation[1] == "x": - ghy_v -= gh_v else: - ghx_v += gh_v + gtop_v = np.c_[v] / bot[:, None] + gbot_v = -tip[:, None] * np.c_[v] / bot[:, None] + + ghx_v = np.einsum( + "ij,ik->ijk", gbot_v, np.c_[hy[:, 1], -hy[:, 0]] + ).reshape((hy.shape[0], -1)) + ghy_v = np.einsum( + "ij,ik->ijk", gbot_v, np.c_[-hx[:, 1], hx[:, 0]] + ).reshape((hx.shape[0], -1)) + gho_v = np.einsum( + "ij,ik->ijk", gtop_v, np.c_[-h[:, 1], h[:, 0]] + ).reshape((h.shape[0], -1)) + gh_v = np.einsum( + "ij,ik->ijk", gtop_v, np.c_[ho[:, 1], -ho[:, 0]] + ).reshape((ho.shape[0], -1)) + if self.orientation[1] == "x": + ghy_v -= gh_v + else: + ghx_v += gh_v + + if v.ndim == 2: + # collapse into a long list of n_d vectors + ghx_v = ghx_v.reshape((n_d, -1)) + ghy_v = ghy_v.reshape((n_d, -1)) + gho_v = gho_v.reshape((n_d, -1)) + + gh_v = ( + Phx.T @ csr_matrix(ghx_v) + + Phy.T @ csr_matrix(ghy_v) + + Pho.T @ csr_matrix(gho_v) + ) - gh_v = ( - Phx.T @ csr_matrix(ghx_v) - + Phy.T @ csr_matrix(ghy_v) - + Phz.T @ csr_matrix(ghz_v) - ) return f._hDeriv(src, None, gh_v, adjoint=True) + # JVEC dh_v = f._hDeriv(src, du_dm_v, v, adjoint=False) - dhx_v = Phx @ dh_v - dhy_v = Phy @ dh_v - dhz_v = Phz @ dh_v - if self.orientation[1] == "x": - dh_v = -dhy_v + + if mesh.dim == 2: + + dhx_v = Phx @ dh_v + dhz_v = Phz @ dh_v + + return (dhz_v - tip * dhx_v) / hx + else: - dh_v = dhx_v - dtop_v = ( - h[:, 0] * dhz_v[:, 1] - + dh_v[:, 0] * hz[:, 1] - - h[:, 1] * dhz_v[:, 0] - - dh_v[:, 1] * hz[:, 0] - ) - dbot_v = ( - hx[:, 0] * dhy_v[:, 1] - + dhx_v[:, 0] * hy[:, 1] - - hx[:, 1] * dhy_v[:, 0] - - dhx_v[:, 1] * hy[:, 0] - ) + dhx_v = Phx @ dh_v + dhy_v = Phy @ dh_v + dho_v = Pho @ dh_v + if self.orientation[1] == "x": + dh_v = -dhy_v + else: + dh_v = dhx_v + + dtop_v = ( + h[:, 0] * dho_v[:, 1] + + dh_v[:, 0] * ho[:, 1] + - h[:, 1] * dho_v[:, 0] + - dh_v[:, 1] * ho[:, 0] + ) + dbot_v = ( + hx[:, 0] * dhy_v[:, 1] + + dhx_v[:, 0] * hy[:, 1] + - hx[:, 1] * dhy_v[:, 0] + - dhx_v[:, 1] * hy[:, 0] + ) - return (bot * dtop_v - top * dbot_v) / (bot * bot) + return (bot * dtop_v - top * dbot_v) / (bot * bot) def eval(self, src, mesh, f): # noqa: A003 tip = self._eval_tipper(src, mesh, f) @@ -859,7 +953,7 @@ class Admittance(_ElectricAndMagneticReceiver): - 'real': Real component of the admittance (A/V) - 'imag': Imaginary component of the admittance (A/V) - 'complex': The complex admittance is returned. Do not use for inversion! - storeProjections : bool + storeProjections : bool, optional Whether to cache to internal projection matrices. """ @@ -932,56 +1026,85 @@ def component(self, var): ) def _eval_admittance(self, src, mesh, f): - if mesh.dim < 3: + if mesh.dim == 1: raise NotImplementedError( - "Admittance receiver not implemented for dim < 3." + "Admittance receiver not implemented for dim == 1." ) e = f[src, "e"] h = f[src, "h"] - ex = self.getP(mesh, "Ex", 0) @ e - ey = self.getP(mesh, "Ey", 0) @ e + if mesh.dim == 2: + if self.orientation == "yx": + PE = self.getP(mesh, "Ex", 0) + PH = self.getP(mesh, "CC", 1) + elif self.orientation == "xy": + PE = self.getP(mesh, "CC", 0) + PH = self.getP(mesh, "Ex", 1) - h = self.getP(mesh, "F" + self.orientation[0], 1) @ h + top = PH @ h[:, 0] + bot = PE @ e[:, 0] - if self.orientation[1] == "x": - top = h[:, 0] * ey[:, 1] - h[:, 1] * ex[:, 1] else: - top = -h[:, 0] * ey[:, 0] + h[:, 1] * ex[:, 0] - bot = ex[:, 0] * ey[:, 1] - ex[:, 1] * ey[:, 0] + ex = self.getP(mesh, "Ex", 0) @ e + ey = self.getP(mesh, "Ey", 0) @ e + + h = self.getP(mesh, "F" + self.orientation[0], 1) @ h + + if self.orientation[1] == "x": + top = h[:, 0] * ey[:, 1] - h[:, 1] * ex[:, 1] + else: + top = -h[:, 0] * ey[:, 0] + h[:, 1] * ex[:, 0] + + bot = ex[:, 0] * ey[:, 1] - ex[:, 1] * ey[:, 0] return top / bot def _eval_admittance_deriv(self, src, mesh, f, du_dm_v=None, v=None, adjoint=False): - if mesh.dim < 3: + if mesh.dim == 1: raise NotImplementedError( - "Admittance receiver not implemented for dim < 3." + "Admittance receiver not implemented for dim == 1." ) - # Compute admittances + # COMPUTE ADMITTANCES e = f[src, "e"] h = f[src, "h"] - Pex = self.getP(mesh, "Ex", 0) - Pey = self.getP(mesh, "Ey", 0) - Ph = self.getP(mesh, "F" + self.orientation[0], 1) + if mesh.dim == 2: + if self.orientation == "yx": + Pe = self.getP(mesh, "Ex", 0) + Ph = self.getP(mesh, "CC", 1) + elif self.orientation == "xy": + Pe = self.getP(mesh, "CC", 0) + Ph = self.getP(mesh, "Ex", 1) - ex = Pex @ e - ey = Pey @ e - h = Ph @ h + top = Ph @ h[:, 0] + bot = Pe @ e[:, 0] + adm = top / bot - if self.orientation[1] == "x": - p_ind = 1 fact = 1.0 + else: - p_ind = 0 - fact = -1.0 - top = fact * (h[:, 0] * ey[:, p_ind] - h[:, 1] * ex[:, p_ind]) - bot = ex[:, 0] * ey[:, 1] - ex[:, 1] * ey[:, 0] - adm = top / bot + Pex = self.getP(mesh, "Ex", 0) + Pey = self.getP(mesh, "Ey", 0) + Ph = self.getP(mesh, "F" + self.orientation[0], 1) + + ex = Pex @ e + ey = Pey @ e + h = Ph @ h + + if self.orientation[1] == "x": + p_ind = 1 + fact = 1.0 + else: + p_ind = 0 + fact = -1.0 + + top = fact * (h[:, 0] * ey[:, p_ind] - h[:, 1] * ex[:, p_ind]) + bot = ex[:, 0] * ey[:, 1] - ex[:, 1] * ey[:, 0] + adm = top / bot # ADJOINT if adjoint: @@ -992,14 +1115,21 @@ def _eval_admittance_deriv(self, src, mesh, f, du_dm_v=None, v=None, adjoint=Fal a_v = fact * v / bot # term 1 b_v = -adm * v / bot # term 2 - ex_v = np.c_[ey[:, 1], -ey[:, 0]] * b_v[:, None] # terms dex in bot - ey_v = np.c_[-ex[:, 1], ex[:, 0]] * b_v[:, None] # terms dey in bot - ex_v[:, p_ind] -= h[:, 1] * a_v # add terms dex in top - ey_v[:, p_ind] += h[:, 0] * a_v # add terms dey in top - e_v = Pex.T @ ex_v + Pey.T @ ey_v + if mesh.dim == 2: + + h_v = Ph.T @ a_v + e_v = Pe.T @ b_v + + else: + + ex_v = np.c_[ey[:, 1], -ey[:, 0]] * b_v[:, None] # terms dex in bot + ey_v = np.c_[-ex[:, 1], ex[:, 0]] * b_v[:, None] # terms dey in bot + ex_v[:, p_ind] -= h[:, 1] * a_v # add terms dex in top + ey_v[:, p_ind] += h[:, 0] * a_v # add terms dey in top + e_v = Pex.T @ ex_v + Pey.T @ ey_v - h_v = np.c_[ey[:, p_ind], -ex[:, p_ind]] * a_v[:, None] # h in top - h_v = Ph.T @ h_v + h_v = np.c_[ey[:, p_ind], -ex[:, p_ind]] * a_v[:, None] # h in top + h_v = Ph.T @ h_v fu_e_v, fm_e_v = f._eDeriv(src, None, e_v, adjoint=True) fu_h_v, fm_h_v = f._hDeriv(src, None, h_v, adjoint=True) @@ -1007,25 +1137,34 @@ def _eval_admittance_deriv(self, src, mesh, f, du_dm_v=None, v=None, adjoint=Fal return fu_e_v + fu_h_v, fm_e_v + fm_h_v # JVEC - de_v = f._eDeriv(src, du_dm_v, v, adjoint=False) - dh_v = Ph @ f._hDeriv(src, du_dm_v, v, adjoint=False) + if mesh.dim == 2: - dex_v = Pex @ de_v - dey_v = Pey @ de_v + de_v = Pe @ f._eDeriv(src, du_dm_v, v, adjoint=False) + dh_v = Ph @ f._hDeriv(src, du_dm_v, v, adjoint=False) - dtop_v = fact * ( - h[:, 0] * dey_v[:, p_ind] - + dh_v[:, 0] * ey[:, p_ind] - - h[:, 1] * dex_v[:, p_ind] - - dh_v[:, 1] * ex[:, p_ind] - ) - dbot_v = ( - ex[:, 0] * dey_v[:, 1] - + dex_v[:, 0] * ey[:, 1] - - ex[:, 1] * dey_v[:, 0] - - dex_v[:, 1] * ey[:, 0] - ) - adm_deriv = (bot * dtop_v - top * dbot_v) / (bot * bot) + adm_deriv = (dh_v - adm * de_v) / bot + + else: + + de_v = f._eDeriv(src, du_dm_v, v, adjoint=False) + dh_v = Ph @ f._hDeriv(src, du_dm_v, v, adjoint=False) + + dex_v = Pex @ de_v + dey_v = Pey @ de_v + + dtop_v = fact * ( + h[:, 0] * dey_v[:, p_ind] + + dh_v[:, 0] * ey[:, p_ind] + - h[:, 1] * dex_v[:, p_ind] + - dh_v[:, 1] * ex[:, p_ind] + ) + dbot_v = ( + ex[:, 0] * dey_v[:, 1] + + dex_v[:, 0] * ey[:, 1] + - ex[:, 1] * dey_v[:, 0] + - dex_v[:, 1] * ey[:, 0] + ) + adm_deriv = (bot * dtop_v - top * dbot_v) / (bot * bot) return getattr(adm_deriv, self.component) @@ -1047,212 +1186,1247 @@ def evalDeriv(self, src, mesh, f, du_dm_v=None, v=None, adjoint=False): ) -class ApparentConductivity(_ElectricAndMagneticReceiver): - r"""Receiver class for simulating apparent conductivity data (3D problems only). - - This class is used to simulate an apparent conductivity datum, in S/m, as defined by: - - .. math:: - \sigma_{app} = \mu_0 \omega \dfrac{\bar{H}^2}{ \bar{E} ^2} - - where :math:`\omega` is the angular frequency in rad/s, +def _eval_root_gram_determinant(receiver, src, mesh, f): + """Evaluate the square root of the determinant of the Gram matrix. - .. math:: - \bar{H} \big |^2 = \big | \vec{H}^{(x)} \big |^2 + \big | \vec{H}^{(y)} \big |^2 + The definition of the datum is provided in the documentation for the + ``RootGramDeterminant`` receiver class. - and + Parameters + ---------- + receiver : simpeg.electromagnetics.frequency_domain.receivers.BaseRx + An NSEM receiver. + src : simpeg.electromagnetics.frequency_domain.sources.BaseFDEMSrc + An NSEM source. + mesh : discretize.base.BaseMesh + Mesh on which the forward problem is discretized. + f : simpeg.electromagnetics.frequency_domain.fields.FieldFDEM + The NSEM fields. + """ + if mesh.dim < 3: + raise NotImplementedError( + "'RootGramDeterminant' transfer function only for 3D simulation." + ) - .. math:: - \bar{E}^2= \Big [ \big | E_x^{(x)} \big |^2 + \big | E_y^{(x)} \big |^2 \Big ] - = \Big [ \big | E_x^{(y)} \big |^2 + \big | E_y^{(y)} \big |^2 \Big ] + h = f[src, "h"] + hx = receiver.getP(mesh, "Fx", 0) @ h + hy = receiver.getP(mesh, "Fy", 0) @ h + hz = receiver.getP(mesh, "Fz", 0) @ h + + match receiver._base_type: + case "magnetic": + bx = receiver.getP(mesh, "Fx", 1) @ h + by = receiver.getP(mesh, "Fy", 1) @ h + case "electric": + e = f[src, "e"] + bx = receiver.getP(mesh, "Ex", 1) @ e + by = receiver.getP(mesh, "Ey", 1) @ e + case _: # pragma: nocover + raise ValueError() + + # abs(det(H H*)) + top = ( + (np.abs(hx[:, 0] ** 2) + np.abs(hy[:, 0] ** 2) + np.abs(hz[:, 0] ** 2)) + * (np.abs(hx[:, 1] ** 2) + np.abs(hy[:, 1] ** 2) + np.abs(hz[:, 1] ** 2)) + ) - np.abs( + hx[:, 0] * hx[:, 1].conjugate() + + hy[:, 0] * hy[:, 1].conjugate() + + hz[:, 0] * hz[:, 1].conjugate() + ) ** 2 + + # abs(det(B B*)) = abs(det(B))**2 + bot = np.abs(bx[:, 0] * by[:, 1] - bx[:, 1] * by[:, 0]) ** 2 + + return np.sqrt(top / bot) + + +def _eval_root_gram_determinant_deriv( + receiver, src, mesh, f, du_dm_v=None, v=None, adjoint=False, scale=1.0 +): + """Evaluate the derivative for the square root of the determinant of the Gram matrix. + + The definition of the datum is provided in the documentation for the + ``RootGramDeterminant`` receiver class. Parameters ---------- - locations_e : (n_loc, n_dim) array_like - Locations where the electric fields are measured. - locations_h : (n_loc, n_dim) array_like, optional - Locations where the magnetic fields are measured. Defaults to the same - locations as electric field measurements, `locations_e`. - storeProjections : bool - Whether to cache to internal projection matrices. - - Notes - ----- - It is important to take the amplitudes of the fields resulting from x and y planewave - polarizations separately, then summing. Adding the fields from x and y planewaves then - summing can result in simulated anomalies which do not presented entirely over - conductive/resistive targets. + receiver : simpeg.electromagnetics.frequency_domain.receivers.BaseRx + An NSEM receiver. + src : simpeg.electromagnetics.frequency_domain.sources.BaseFDEMSrc + An NSEM source. + mesh : discretize.base.BaseMesh + Mesh on which the forward problem is discretized. + f : simpeg.electromagnetics.frequency_domain.fields.FieldFDEM + The NSEM fields. + du_dm_v : numpy.ndarray + The derivative of the fields on the mesh with respect to the model, + times a vector. + v : numpy.ndarray, optional + The vector which being multiplied. + adjoint : bool + If ``True``, return the ajoint. + scale : float, optional + Apply scaling constant to derivative within the function. """ + if mesh.dim < 3: + raise NotImplementedError( + "'AmplitudeSquared' transfer function only for 3D simulation." + ) - def __init__(self, locations_e, locations_h=None, storeProjections=False): - if locations_h is None: - locations_h = locations_e - super().__init__( - locations1=locations_e, - locations2=locations_h, - storeProjections=storeProjections, + h = f[src, "h"] + Phx = receiver.getP(mesh, "Fx", 0) + Phy = receiver.getP(mesh, "Fy", 0) + Phz = receiver.getP(mesh, "Fz", 0) + + hx = Phx @ h + hy = Phy @ h + hz = Phz @ h + + match receiver._base_type: + case "magnetic": + Pbx = receiver.getP(mesh, "Fx", 1) + Pby = receiver.getP(mesh, "Fy", 1) + bx = Pbx @ h + by = Pby @ h + case "electric": + Pbx = receiver.getP(mesh, "Ex", 1) + Pby = receiver.getP(mesh, "Ey", 1) + e = f[src, "e"] + bx = Pbx @ e + by = Pby @ e + case _: # pragma: nocover + raise ValueError() + + # Entries of HH*. Note that vec_h21 = conj(vec_h12) + vec_h11 = np.abs(hx[:, 0]) ** 2 + np.abs(hy[:, 0]) ** 2 + np.abs(hz[:, 0]) ** 2 + vec_h22 = np.abs(hx[:, 1]) ** 2 + np.abs(hy[:, 1]) ** 2 + np.abs(hz[:, 1]) ** 2 + vec_h12 = ( + hx[:, 0] * hx[:, 1].conjugate() + + hy[:, 0] * hy[:, 1].conjugate() + + hz[:, 0] * hz[:, 1].conjugate() + ) + top = vec_h11 * vec_h22 - np.abs(vec_h12) ** 2 # abs(det(H H*)) + + vec_b11 = np.abs(bx[:, 0]) ** 2 + np.abs(by[:, 0]) ** 2 + vec_b22 = np.abs(bx[:, 1]) ** 2 + np.abs(by[:, 1]) ** 2 + vec_b12 = bx[:, 0] * bx[:, 1].conjugate() + by[:, 0] * by[:, 1].conjugate() + bot = vec_b11 * vec_b22 - np.abs(vec_b12) ** 2 # abs(det(H H*)) + + factor = 0.5 * scale / np.sqrt(top / bot) + + # ADJOINT + if adjoint: + + # J_T * v = d_top_T * a_v + d_bot_T * b + a_v = factor * v / bot # term 1 + b_v = -factor * top * v / bot**2 # term 2 + + a_v = np.repeat(mkvc(a_v, n_dims=2), 2, axis=-1) + b_v = np.repeat(mkvc(b_v, n_dims=2), 2, axis=-1) + + # derivatives for det(HH*) + px = ( + np.c_[ + vec_h22 * hx[:, 0].conjugate() - (vec_h12 * hx[:, 1]).conjugate(), + vec_h11 * hx[:, 1].conjugate() - vec_h12 * hx[:, 0].conjugate(), + ] + * a_v + ) + py = ( + np.c_[ + vec_h22 * hy[:, 0].conjugate() - (vec_h12 * hy[:, 1]).conjugate(), + vec_h11 * hy[:, 1].conjugate() - vec_h12 * hy[:, 0].conjugate(), + ] + * a_v + ) + pz = ( + np.c_[ + vec_h22 * hz[:, 0].conjugate() - (vec_h12 * hz[:, 1]).conjugate(), + vec_h11 * hz[:, 1].conjugate() - vec_h12 * hz[:, 0].conjugate(), + ] + * a_v ) - def _eval_apparent_conductivity(self, src, mesh, f): - if mesh.dim < 3: - raise NotImplementedError( - "ApparentConductivity receiver not implemented for dim < 3." + # derivatives for det(BB*) + qx = ( + np.c_[ + vec_b22 * bx[:, 0].conjugate() - (vec_b12 * bx[:, 1]).conjugate(), + vec_b11 * bx[:, 1].conjugate() - vec_b12 * bx[:, 0].conjugate(), + ] + * b_v + ) + qy = ( + np.c_[ + vec_b22 * by[:, 0].conjugate() - (vec_b12 * by[:, 1]).conjugate(), + vec_b11 * by[:, 1].conjugate() - vec_b12 * by[:, 0].conjugate(), + ] + * b_v + ) + + h_v = 2 * (Phx.T @ px + Phy.T @ py + Phz.T @ pz) + b_v = 2 * (Pbx.T @ qx + Pby.T @ qy) + + match receiver._base_type: + case "magnetic": + return f._hDeriv(src, None, h_v + b_v, adjoint=True) + case "electric": + fu_b_v, fm_b_v = f._eDeriv(src, None, b_v, adjoint=True) + fu_h_v, fm_h_v = f._hDeriv(src, None, h_v, adjoint=True) + return fu_b_v + fu_h_v, fm_b_v + fm_h_v + case _: # pragma: nocover + raise ValueError() + + # JVEC + dh_v = f._hDeriv(src, du_dm_v, v, adjoint=False) + dhx_v = Phx @ dh_v + dhy_v = Phy @ dh_v + dhz_v = Phz @ dh_v + + match receiver._base_type: + case "magnetic": + db_v = dh_v + case "electric": + db_v = f._eDeriv(src, du_dm_v, v, adjoint=False) + case _: # pragma: nocover + raise ValueError() + + dbx_v = Pbx @ db_v + dby_v = Pby @ db_v + + # When taking derivative of hh* wrt the model, imaginary components + # cancel and its 2x the real of the conjugate x the deriv + dtop_v = ( + ( + 2 + * vec_h11 + * ( + hx[:, 1].conjugate() * dhx_v[:, 1] + + hy[:, 1].conjugate() * dhy_v[:, 1] + + hz[:, 1].conjugate() * dhz_v[:, 1] + ) + ).real + + ( + 2 + * vec_h22 + * ( + hx[:, 0].conjugate() * dhx_v[:, 0] + + hy[:, 0].conjugate() * dhy_v[:, 0] + + hz[:, 0].conjugate() * dhz_v[:, 0] ) + ).real + - ( + 2 + * vec_h12.conjugate() + * ( + hx[:, 1].conjugate() * dhx_v[:, 0] + + hy[:, 1].conjugate() * dhy_v[:, 0] + + hz[:, 1].conjugate() * dhz_v[:, 0] + + hx[:, 0] * dhx_v[:, 1].conjugate() + + hy[:, 0] * dhy_v[:, 1].conjugate() + + hz[:, 0] * dhz_v[:, 1].conjugate() + ) + ).real + ) + + dbot_v = ( + ( + 2 + * vec_b11 + * (bx[:, 1].conjugate() * dbx_v[:, 1] + by[:, 1].conjugate() * dby_v[:, 1]) + ).real + + ( + 2 + * vec_b22 + * (bx[:, 0].conjugate() * dbx_v[:, 0] + by[:, 0].conjugate() * dby_v[:, 0]) + ).real + - ( + 2 + * vec_b12.conjugate() + * ( + bx[:, 1].conjugate() * dbx_v[:, 0] + + by[:, 1].conjugate() * dby_v[:, 0] + + bx[:, 0] * dbx_v[:, 1].conjugate() + + by[:, 0] * dby_v[:, 1].conjugate() + ) + ).real + ) - e = f[src, "e"] - h = f[src, "h"] + return factor * (bot * dtop_v - top * dbot_v) / (bot * bot) - ex = self.getP(mesh, "Ex", 0) @ e - ey = self.getP(mesh, "Ey", 0) @ e - hx = self.getP(mesh, "Fx", 1) @ h - hy = self.getP(mesh, "Fy", 1) @ h - hz = self.getP(mesh, "Fz", 1) @ h - top = np.sum(np.abs(hx) ** 2 + np.abs(hy) ** 2 + np.abs(hz) ** 2, axis=-1) - bot = np.sum(np.abs(ex) ** 2 + np.abs(ey) ** 2, axis=-1) +def _eval_cross_product_amplitude(receiver, src, mesh, f): + """Evaluate the cross product amplitude. - return (2 * np.pi * src.frequency * mu_0) * top / bot + The definition of the datum is provided in the documentation for the + ``CrossProductAmplitude`` receiver class. - def _eval_apparent_conductivity_deriv( - self, src, mesh, f, du_dm_v=None, v=None, adjoint=False - ): - if mesh.dim < 3: - raise NotImplementedError( - "Admittance receiver not implemented for dim < 3." - ) + Parameters + ---------- + receiver : simpeg.electromagnetics.frequency_domain.receivers.BaseRx + An NSEM receiver. + src : simpeg.electromagnetics.frequency_domain.sources.BaseFDEMSrc + An NSEM source. + mesh : discretize.base.BaseMesh + Mesh on which the forward problem is discretized. + f : simpeg.electromagnetics.frequency_domain.fields.FieldFDEM + The NSEM fields. + """ + if mesh.dim < 3: + raise NotImplementedError( + "'CrossProductAmplitude' transfer function only for 3D simulation." + ) - # Compute admittances - e = f[src, "e"] - h = f[src, "h"] + h = f[src, "h"] + hx = receiver.getP(mesh, "Fx", 0) @ h + hy = receiver.getP(mesh, "Fy", 0) @ h + hz = receiver.getP(mesh, "Fz", 0) @ h - Pex = self.getP(mesh, "Ex", 0) - Pey = self.getP(mesh, "Ey", 0) - Phx = self.getP(mesh, "Fx", 1) - Phy = self.getP(mesh, "Fy", 1) - Phz = self.getP(mesh, "Fz", 1) + match receiver._base_type: + case "magnetic": + bx = receiver.getP(mesh, "Fx", 1) @ h + by = receiver.getP(mesh, "Fy", 1) @ h + case "electric": + e = f[src, "e"] + bx = receiver.getP(mesh, "Ex", 1) @ e + by = receiver.getP(mesh, "Ey", 1) @ e + case _: # pragma: nocover + raise ValueError() - ex = Pex @ e - ey = Pey @ e - hx = Phx @ h - hy = Phy @ h - hz = Phz @ h + top_12 = np.abs(hx[:, 0] * hy[:, 1] - hy[:, 0] * hx[:, 1]) ** 2 # abs(det(H12))**2 + top_13 = np.abs(hx[:, 0] * hz[:, 1] - hz[:, 0] * hx[:, 1]) ** 2 # abs(det(H13))**2 + top_23 = np.abs(hy[:, 0] * hz[:, 1] - hz[:, 0] * hy[:, 1]) ** 2 # abs(det(H23))**2 - fact = 2 * np.pi * src.frequency * mu_0 - top = np.sum(np.abs(hx) ** 2 + np.abs(hy) ** 2 + np.abs(hz) ** 2, axis=-1) - bot = np.sum(np.abs(ex) ** 2 + np.abs(ey) ** 2, axis=-1) + # abs(det(B B*)) = abs(det(B))**2 + bot = np.abs(bx[:, 0] * by[:, 1] - bx[:, 1] * by[:, 0]) ** 2 - # ADJOINT - if adjoint: - # Compute: J_T * v = d_top_T * a_v + d_bot_T * b - a_v = fact * np.c_[v] / bot[:, None] # term 1 - b_v = np.c_[v] * (-fact * top / (bot**2))[:, None] # term 2 - - ghx_v = np.einsum("ij,ik->ijk", a_v, hx).reshape((hx.shape[0], -1)) - ghy_v = np.einsum("ij,ik->ijk", a_v, hy).reshape((hy.shape[0], -1)) - ghz_v = np.einsum("ij,ik->ijk", a_v, hz).reshape((hz.shape[0], -1)) - gex_v = np.einsum("ij,ik->ijk", b_v, ex).reshape((ex.shape[0], -1)) - gey_v = np.einsum("ij,ik->ijk", b_v, ey).reshape((ey.shape[0], -1)) - e_v = ( - 2 * (Pex.T @ csr_matrix(gex_v) + Pey.T @ csr_matrix(gey_v)).conjugate() - ) - h_v = ( - 2 - * ( - Phx.T @ csr_matrix(ghx_v) - + Phy.T @ csr_matrix(ghy_v) - + Phz.T @ csr_matrix(ghz_v) - ).conjugate() - ) + return np.sqrt((top_12 + top_13 + top_23) / bot) - fu_e_v, fm_e_v = f._eDeriv(src, None, e_v, adjoint=True) - fu_h_v, fm_h_v = f._hDeriv(src, None, h_v, adjoint=True) - return fu_e_v + fu_h_v, fm_e_v + fm_h_v +def _eval_cross_product_amplitude_deriv( + receiver, src, mesh, f, du_dm_v=None, v=None, adjoint=False, scale=1.0 +): + """Evaluate the derivative for the amplitude of the cross product. - # JVEC - de_v = f._eDeriv(src, du_dm_v, v, adjoint=False) - dh_v = f._hDeriv(src, du_dm_v, v, adjoint=False) + The definition of the datum is provided in the documentation for the + ``CrossProductAmplitude`` receiver class. - dex_v = Pex @ de_v - dey_v = Pey @ de_v - dhx_v = Phx @ dh_v - dhy_v = Phy @ dh_v - dhz_v = Phz @ dh_v - - # Imaginary components cancel and its 2x the real of the conjugate x the deriv - dtop_v = 2 * np.sum( - ( - hx.conjugate() * dhx_v + hy.conjugate() * dhy_v + hz.conjugate() * dhz_v - ).real, - axis=-1, + Parameters + ---------- + receiver : simpeg.electromagnetics.frequency_domain.receivers.BaseRx + An NSEM receiver. + src : simpeg.electromagnetics.frequency_domain.sources.BaseFDEMSrc + An NSEM source. + mesh : discretize.base.BaseMesh + Mesh on which the forward problem is discretized. + f : simpeg.electromagnetics.frequency_domain.fields.FieldFDEM + The NSEM fields. + du_dm_v : numpy.ndarray + The derivative of the fields on the mesh with respect to the model, + times a vector. + v : numpy.ndarray, optional + The vector which being multiplied. + adjoint : bool + If ``True``, return the ajoint. + scale : float, optional + Apply scaling constant to derivative within the function. + """ + if mesh.dim < 3: + raise NotImplementedError( + "'AmplitudeSquared' transfer function only for 3D simulation." ) - dbot_v = 2 * np.sum( - (ex.conjugate() * dex_v + ey.conjugate() * dey_v).real, axis=-1 + + h = f[src, "h"] + Phx = receiver.getP(mesh, "Fx", 0) + Phy = receiver.getP(mesh, "Fy", 0) + Phz = receiver.getP(mesh, "Fz", 0) + + hx = Phx @ h + hy = Phy @ h + hz = Phz @ h + + match receiver._base_type: + case "magnetic": + Pbx = receiver.getP(mesh, "Fx", 1) + Pby = receiver.getP(mesh, "Fy", 1) + bx = Pbx @ h + by = Pby @ h + case "electric": + Pbx = receiver.getP(mesh, "Ex", 1) + Pby = receiver.getP(mesh, "Ey", 1) + e = f[src, "e"] + bx = Pbx @ e + by = Pby @ e + case _: # pragma: nocover + raise ValueError() + + # Entries of HH*. Note that vec_h21 = conj(vec_h12) + det_h12 = hx[:, 0] * hy[:, 1] - hy[:, 0] * hx[:, 1] # det(H12) + det_h13 = hx[:, 0] * hz[:, 1] - hz[:, 0] * hx[:, 1] # det(H13) + det_h23 = hy[:, 0] * hz[:, 1] - hz[:, 0] * hy[:, 1] # det(H23) + top = np.abs(det_h12) ** 2 + np.abs(det_h13) ** 2 + np.abs(det_h23) ** 2 + + # abs(det(B B*)) = abs(det(B))**2 + det_b = bx[:, 0] * by[:, 1] - bx[:, 1] * by[:, 0] + bot = np.abs(det_b) ** 2 + + factor = 0.5 * scale / np.sqrt(top / bot) + + # ADJOINT + if adjoint: + a_v = np.c_[v] / (bot / factor)[:, None] # term 1 + b_v = np.c_[v] * (-factor * top / (bot**2))[:, None] # term 2 + + # derivatives for det(HH*) + px = np.einsum( + "ij,ik->ijk", + a_v, + np.c_[ + det_h12.conjugate() * hy[:, 1] + det_h13.conjugate() * hz[:, 1], + -det_h12.conjugate() * hy[:, 0] - det_h13.conjugate() * hz[:, 0], + ], + ).reshape((hx.shape[0], -1)) + py = np.einsum( + "ij,ik->ijk", + a_v, + np.c_[ + -det_h12.conjugate() * hx[:, 1] + det_h23.conjugate() * hz[:, 1], + det_h12.conjugate() * hx[:, 0] - det_h23.conjugate() * hz[:, 0], + ], + ).reshape((hy.shape[0], -1)) + pz = np.einsum( + "ij,ik->ijk", + a_v, + np.c_[ + -det_h13.conjugate() * hx[:, 1] - det_h23.conjugate() * hy[:, 1], + det_h13.conjugate() * hx[:, 0] + det_h23.conjugate() * hy[:, 0], + ], + ).reshape((hz.shape[0], -1)) + + # derivatives for det(BB*) + qx = np.einsum( + "ij,ik->ijk", + b_v, + np.c_[det_b.conjugate() * by[:, 1], -det_b.conjugate() * by[:, 0]], + ).reshape((bx.shape[0], -1)) + qy = np.einsum( + "ij,ik->ijk", + b_v, + np.c_[-det_b.conjugate() * bx[:, 1], det_b.conjugate() * bx[:, 0]], + ).reshape((by.shape[0], -1)) + + h_v = 2 * ( + Phx.T @ csr_matrix(px) + Phy.T @ csr_matrix(py) + Phz.T @ csr_matrix(pz) ) + b_v = 2 * (Pbx.T @ csr_matrix(qx) + Pby.T @ csr_matrix(qy)) + + match receiver._base_type: + case "magnetic": + return f._hDeriv(src, None, h_v + b_v, adjoint=True) + case "electric": + fu_b_v, fm_b_v = f._eDeriv(src, None, b_v, adjoint=True) + fu_h_v, fm_h_v = f._hDeriv(src, None, h_v, adjoint=True) + return fu_b_v + fu_h_v, fm_b_v + fm_h_v + case _: # pragma: nocover + raise ValueError() + + # JVEC + dh_v = f._hDeriv(src, du_dm_v, v, adjoint=False) + dhx_v = Phx @ dh_v + dhy_v = Phy @ dh_v + dhz_v = Phz @ dh_v + + if receiver._base_type == "magnetic": + db_v = dh_v + else: + db_v = f._eDeriv(src, du_dm_v, v, adjoint=False) + + dbx_v = Pbx @ db_v + dby_v = Pby @ db_v + + # cancel and its 2x the real of the conjugate x the deriv + dtop_v = ( + 2 + * ( + det_h12.conjugate() + * ( + dhx_v[:, 0] * hy[:, 1] + + hx[:, 0] * dhy_v[:, 1] + - dhy_v[:, 0] * hx[:, 1] + - hy[:, 0] * dhx_v[:, 1] + ) + + det_h13.conjugate() + * ( + dhx_v[:, 0] * hz[:, 1] + + hx[:, 0] * dhz_v[:, 1] + - dhz_v[:, 0] * hx[:, 1] + - hz[:, 0] * dhx_v[:, 1] + ) + + det_h23.conjugate() + * ( + dhy_v[:, 0] * hz[:, 1] + + hy[:, 0] * dhz_v[:, 1] + - dhz_v[:, 0] * hy[:, 1] + - hz[:, 0] * dhy_v[:, 1] + ) + ).real + ) + + dbot_v = ( + 2 + * ( + det_b.conjugate() + * ( + dbx_v[:, 0] * by[:, 1] + + bx[:, 0] * dby_v[:, 1] + - dby_v[:, 0] * bx[:, 1] + - by[:, 0] * dbx_v[:, 1] + ) + ).real + ) - return fact * (bot * dtop_v - top * dbot_v) / (bot * bot) + return factor * (bot * dtop_v - top * dbot_v) / (bot * bot) - def eval(self, src, mesh, f): # noqa: A003 - """Compute receiver data from the discrete field solution. - Parameters - ---------- - src : .frequency_domain.sources.BaseFDEMSrc - NSEM source. - mesh : discretize.TensorMesh - Mesh on which the discretize solution is obtained. - f : simpeg.electromagnetics.frequency_domain.fields.FieldsFDEM - NSEM fields object of the source. +def _eval_horizontal_determinant(receiver, src, mesh, f): + """Evaluate the determinant of the horizontal transfer functions. - Returns - ------- - numpy.ndarray - Evaluated data for the receiver. - """ - return self._eval_apparent_conductivity(src, mesh, f) + The definition of the datum is provided in the documentation for the + ``HorizontalDeterminant`` receiver class. - def evalDeriv(self, src, mesh, f, du_dm_v=None, v=None, adjoint=False): - r"""Derivative of data with respect to the fields. + Parameters + ---------- + receiver : simpeg.electromagnetics.frequency_domain.receivers.BaseRx + An NSEM receiver. + src : simpeg.electromagnetics.frequency_domain.sources.BaseFDEMSrc + An NSEM source. + mesh : discretize.base.BaseMesh + Mesh on which the forward problem is discretized. + f : simpeg.electromagnetics.frequency_domain.fields.FieldFDEM + The NSEM fields. + """ + if mesh.dim < 3: + raise NotImplementedError( + "'AmplitudeRatio' transfer function only for 3D simulation." + ) - Let :math:`\mathbf{d}` represent the data corresponding the receiver object. - And let :math:`\mathbf{u}` represent the discrete numerical solution of the - fields on the mesh. Where :math:`\mathbf{P}` is a projection function that - maps from the fields to the data, i.e.: + h = f[src, "h"] + hx = receiver.getP(mesh, "Fx", 0) @ h + hy = receiver.getP(mesh, "Fy", 0) @ h - .. math:: - \mathbf{d} = \mathbf{P}(\mathbf{u}) + match receiver._base_type: + case "magnetic": + bx = receiver.getP(mesh, "Fx", 1) @ h + by = receiver.getP(mesh, "Fy", 1) @ h + case "electric": + e = f[src, "e"] + bx = receiver.getP(mesh, "Ex", 1) @ e + by = receiver.getP(mesh, "Ey", 1) @ e + case _: # pragma: nocover + raise ValueError() - this method computes and returns the derivative: + top = hx[:, 0] * hy[:, 1] - hx[:, 1] * hy[:, 0] + bot = bx[:, 0] * by[:, 1] - bx[:, 1] * by[:, 0] - .. math:: - \dfrac{\partial \mathbf{d}}{\partial \mathbf{u}} = - \dfrac{\partial [ \mathbf{P} (\mathbf{u}) ]}{\partial \mathbf{u}} + if receiver._component == "amp": + return np.abs(top / bot) + return top / bot - Parameters - ---------- - src : .frequency_domain.sources.BaseFDEMSrc - The NSEM source. - mesh : discretize.TensorMesh - Mesh on which the discretize solution is obtained. - f : simpeg.electromagnetics.frequency_domain.fields.FieldsFDEM - NSEM fields object for the source. - du_dm_v : None, optional - Supply pre-computed derivative? - v : numpy.ndarray, optional - Vector of size - adjoint : bool, optional - Whether to compute the ajoint operation. - Returns - ------- - numpy.ndarray - Calculated derivative (n_data,) if `adjoint` is ``False``, - and (n_param, 2) if `adjoint` is ``True``, for both polarizations. - """ - return self._eval_apparent_conductivity_deriv( - src, mesh, f, du_dm_v=du_dm_v, v=v, adjoint=adjoint +def _eval_horizontal_determinant_deriv( + receiver, src, mesh, f, du_dm_v=None, v=None, adjoint=False, scale=1.0 +): + """Evaluate the derivative for the horizontal determinant transfer function. + + The definition of the datum is provided in the documentation for the + ``HorizontalDeterminant`` receiver class. + + Parameters + ---------- + receiver : simpeg.electromagnetics.frequency_domain.receivers.BaseRx + An NSEM receiver. + src : simpeg.electromagnetics.frequency_domain.sources.BaseFDEMSrc + An NSEM source. + mesh : discretize.base.BaseMesh + Mesh on which the forward problem is discretized. + f : simpeg.electromagnetics.frequency_domain.fields.FieldFDEM + The NSEM fields. + du_dm_v : numpy.ndarray + The derivative of the fields on the mesh with respect to the model, + times a vector. + v : numpy.ndarray, optional + The vector which being multiplied. + adjoint : bool + If ``True``, return the ajoint. + scale : float, optional + Apply scaling constant to derivative within the function. + """ + if mesh.dim < 3: + raise NotImplementedError( + "'HorizontalDeterminant' transfer function only for 3D simulation." ) + h = f[src, "h"] + Phx = receiver.getP(mesh, "Fx", 0) + Phy = receiver.getP(mesh, "Fy", 0) + + hx = Phx @ h + hy = Phy @ h + + match receiver._base_type: + case "magnetic": + Pbx = receiver.getP(mesh, "Fx", 1) + Pby = receiver.getP(mesh, "Fy", 1) + bx = Pbx @ h + by = Pby @ h + case "electric": + Pbx = receiver.getP(mesh, "Ex", 1) + Pby = receiver.getP(mesh, "Ey", 1) + e = f[src, "e"] + bx = Pbx @ e + by = Pby @ e + case _: # pragma: nocover + raise ValueError() + + top = hx[:, 0] * hy[:, 1] - hx[:, 1] * hy[:, 0] + bot = bx[:, 0] * by[:, 1] - bx[:, 1] * by[:, 0] + + # ADJOINT + if adjoint: + + if receiver._component == "amp": + factor = scale * top / bot + v = (factor.real - 1j * factor.imag) * v / np.abs(top / bot) + elif receiver.component == "imag": + v = -1j * v + + # J_T * v = d_top_T * a_v + d_bot_T * b + a_v = v / bot # term 1 + b_v = -top * v / bot**2 # term 2 + + hx_v = np.c_[hy[:, 1], -hy[:, 0]] * a_v[:, None] # terms dex in bot + hy_v = np.c_[-hx[:, 1], hx[:, 0]] * a_v[:, None] # terms dey in bot + h_v = Phx.T @ hx_v + Phy.T @ hy_v + + bx_v = np.c_[by[:, 1], -by[:, 0]] * b_v[:, None] # terms dex in bot + by_v = np.c_[-bx[:, 1], bx[:, 0]] * b_v[:, None] # terms dey in bot + b_v = Pbx.T @ bx_v + Pby.T @ by_v + + match receiver._base_type: + case "magnetic": + return f._hDeriv(src, None, h_v + b_v, adjoint=True) + case "electric": + fu_b_v, fm_b_v = f._eDeriv(src, None, b_v, adjoint=True) + fu_h_v, fm_h_v = f._hDeriv(src, None, h_v, adjoint=True) + return fu_b_v + fu_h_v, fm_b_v + fm_h_v + case _: # pragma: nocover + raise ValueError() + + # JVEC + dh_v = f._hDeriv(src, du_dm_v, v, adjoint=False) + dhx_v = Phx @ dh_v + dhy_v = Phy @ dh_v + + match receiver._base_type: + case "magnetic": + db_v = dh_v + case "electric": + db_v = f._eDeriv(src, du_dm_v, v, adjoint=False) + case _: # pragma: nocover + raise ValueError() + + dbx_v = Pbx @ db_v + dby_v = Pby @ db_v + + dtop_v = ( + hx[:, 0] * dhy_v[:, 1] + + dhx_v[:, 0] * hy[:, 1] + - hy[:, 0] * dhx_v[:, 1] + - dhy_v[:, 0] * hx[:, 1] + ) + dbot_v = ( + bx[:, 0] * dby_v[:, 1] + + dbx_v[:, 0] * by[:, 1] + - by[:, 0] * dbx_v[:, 1] + - dby_v[:, 0] * bx[:, 1] + ) + + deriv = (bot * dtop_v - top * dbot_v) / (bot * bot) + + if receiver._component == "amp": + factor = scale * top / bot + return (factor.real * deriv.real + factor.imag * deriv.imag) / np.abs(top / bot) + + return getattr(deriv, receiver.component) + + +class RootGramDeterminant(_BaseOrientationInvariant): + r"""Orientation invariant transfer function using the root Gram matrix determinant. + + Receiver class for simulating a data that are invariant to sensor orientation + for either an electric or magnetic base station. The datum is based on taking + the amplitude of the determinant of Gram matrix for transfer functions + derived from three-component airborne magnetic fields. For a magnetic base + station the quantity is unitless. For an electric base station, the units + are :math:`A^2/V^2`. + See the *Notes* section for a formal definition of the datum. + + Parameters + ---------- + locations_h : (n_loc, n_dim) array_like + Locations where the roving magnetic fields are measured. + locations_base : (n_loc, n_dim) array_like, optional + Locations where the base station magnetic fields are measured. Defaults to + the same locations as the roving magnetic fields measurements, + `locations_h`. + base_type : {'magnetic', 'electric'}, optional + Whether magnetic or electric fields are measured at the base station. + For magnetic fields, the quantity is unitless. For electric fields, + the quantity has units A/V. + storeProjections : bool, optional + Whether to cache to internal projection matrices. + + Notes + ----- + + Magnetic base station + ~~~~~~~~~~~~~~~~~~~~~ + Consider an acquisition system that measures 3-component magnetic fields + in the air and magnetic fields at a base station. The fundamental set of + transfer functions (i.e. tippers) that can be generated from these + measurements is given by: + + .. math:: + + \begin{bmatrix} + T_{xx} & T_{yx} & T_{zx} \\ + T_{xy} & T_{yy} & T_{zy} + \end{bmatrix} + = + \begin{bmatrix} + H_x^{(x)} & H_y^{(x)} + \\ H_x^{(y)} & H_y^{(y)} + \end{bmatrix}_b^{-1} + \, + \begin{bmatrix} + H_x^{(x)} & H_y^{(x)} & H_z^{(x)} \\ + H_x^{(y)} & H_y^{(y)} & H_z^{(y)} + \end{bmatrix}_r + + where subscript :math:`b` denotes the base station location and subscript + :math:`r` denotes the mobile receiver location. + + For this system, the orientation invariant transfer function is defined as: + + .. math:: + + \widehat{\mathbf{T}} = \bigg ( + \frac{\det (\mathbf{H_r H_r^\dagger}) }{\det (\mathbf{H_b H_b^\dagger})} + \bigg )^{1/2} + + where :math:`\dagger` denotes the Hermitian. + + + Electric base station + ~~~~~~~~~~~~~~~~~~~~~ + Now consider an acquisition system that measures 3-component magnetic fields + in the air and electric fields at a base station. The fundamental set of + transfer functions (i.e. admittances) that can be generated from these + measurements is given by: + + .. math:: + + \begin{bmatrix} + Y_{xx} & Y_{yx} & Y_{zx} \\ + Y_{xy} & Y_{yy} & Y_{zy} + \end{bmatrix} + = + \begin{bmatrix} + E_x^{(x)} & E_y^{(x)} \\ + E_x^{(y)} & E_y^{(y)} + \end{bmatrix}_b^{-1} + \, + \begin{bmatrix} + H_x^{(x)} & H_y^{(x)} & H_z^{(x)} \\ + H_x^{(y)} & H_y^{(y)} & H_z^{(y)} + \end{bmatrix}_r + + For this system, the orientation invariant transfer function is defined as: + + .. math:: + + \widehat{\mathbf{Y}} = \bigg ( + \frac{\det (\mathbf{H_r H_r^\dagger}) }{\det (\mathbf{E_b E_b^\dagger})} + \bigg )^{1/2} + + """ + + _loc_names = ("Roving magnetic field", "Base station field") + + def __init__( + self, + locations_h, + locations_base=None, + base_type="magnetic", + storeProjections=False, + ): + if locations_base is None: + locations_base = locations_h + super().__init__( + locations1=locations_h, + locations2=locations_base, + base_type=base_type, + storeProjections=storeProjections, + ) + + @property + def locations_h(self): + """Roving magnetic field measurement locations. + + Returns + ------- + numpy.ndarray + Roving locations where the magnetic field is measured for all receiver data. + """ + return self._locations[0] + + @property + def locations_base(self): + """Base station magnetic field measurement locations. + + Returns + ------- + numpy.ndarray + Base station locations where the horizontal magnetic fields are measured. + """ + return self._locations[1] + + def eval(self, src, mesh, f): # noqa: A003 D102 + # Docstring inherited from parent class (BaseNaturalSourceRX) + return _eval_root_gram_determinant(self, src, mesh, f) + + def evalDeriv( # noqa: D102 + self, src, mesh, f, du_dm_v=None, v=None, adjoint=False + ): + # Docstring inherited from parent class (BaseNaturalSourceRX). + return _eval_root_gram_determinant_deriv( + self, src, mesh, f, du_dm_v=du_dm_v, v=v, adjoint=adjoint + ) + + +class CrossProductAmplitude(RootGramDeterminant): + r"""Orientation invariant transfer function from the cross-product amplitude. + + Receiver class for simulating a data that are invariant to sensor orientation + for either an electric or magnetic base station. The datum is based on taking + the amplitude of the determinant of the cross-product of transfer functions + derived from three-component airborne magnetic fields. For a magnetic base + station the quantity is unitless. For an electric base station, the units + are :math:`A^2/V^2`. + See the *Notes* section for a formal definition of the datum. + + Parameters + ---------- + locations_h : (n_loc, n_dim) array_like + Locations where the roving magnetic fields are measured. + locations_base : (n_loc, n_dim) array_like, optional + Locations where the base station magnetic fields are measured. Defaults to + the same locations as the roving magnetic fields measurements, + `locations_h`. + base_type : {'magnetic', 'electric'}, optional + Whether magnetic or electric fields are measured at the base station. + For magnetic fields, the quantity is unitless. For electric fields, + the quantity has units A/V. + storeProjections : bool, optional + Whether to cache to internal projection matrices. + + Notes + ----- + + Magnetic base station + ~~~~~~~~~~~~~~~~~~~~~ + Consider an acquisition system that measures 3-component magnetic fields + in the air and magnetic fields at a base station. The fundamental set of + transfer functions (i.e. tippers) that can be generated from these + measurements is given by: + + .. math:: + + \begin{bmatrix} + T_{xx} & T_{yx} & T_{zx} \\ + T_{xy} & T_{yy} & T_{zy} + \end{bmatrix} + = + \begin{bmatrix} + H_x^{(x)} & H_y^{(x)} \\ + H_x^{(y)} & H_y^{(y)} + \end{bmatrix}_b^{-1} + \, + \begin{bmatrix} + H_x^{(x)} & H_y^{(x)} & H_z^{(x)} \\ + H_x^{(y)} & H_y^{(y)} & H_z^{(y)} + \end{bmatrix}_r + + where subscript :math:`b` denotes the base station location and subscript + :math:`r` denotes the mobile receiver location. + + For this system, the orientation invariant transfer function is defined as: + + .. math:: + + | \mathbf{T} | = \bigg ( + p_x p_x^\ast + p_y p_y^\ast + p_z p_z^\ast + \bigg )^{1/2} + + where :math:`\ast` denotes the complex conjugate and + + .. math:: + + \begin{split} + p_x &= T_{yx}T_{zy} - T_{zx}T_{yy}\\ + p_y &= T_{zx}T_{xy} - T_{xx}T_{zy}\\ + p_z &= T_{xx}T_{yy} - T_{yx}T_{xy} + \end{split} + + Electric base station + ~~~~~~~~~~~~~~~~~~~~~ + Now consider an acquisition system that measures 3-component magnetic fields + in the air and electric fields at a base station. The fundamental set of + transfer functions (i.e. admittances) that can be generated from these + measurements is given by: + + .. math:: + \begin{bmatrix} + Y_{xx} & Y_{yx} & Y_{zx} \\ + Y_{xy} & Y_{yy} & Y_{zy} + \end{bmatrix} + = + \begin{bmatrix} + E_x^{(x)} & E_y^{(x)} \\ + E_x^{(y)} & E_y^{(y)} + \end{bmatrix}_b^{-1} + \, + \begin{bmatrix} + H_x^{(x)} & H_y^{(x)} & H_z^{(x)} \\ + H_x^{(y)} & H_y^{(y)} & H_z^{(y)} + \end{bmatrix}_r + + For this system, the orientation invariant transfer function is defined as: + + .. math:: + | \mathbf{Y} | = \bigg ( + q_x q_x^\ast + q_y q_y^\ast + q_z q_z^\ast + \bigg )^{1/2} + + where :math:`\ast` denotes the complex conjugate and + + .. math:: + \begin{split} + p_x &= Y_{yx}Y_{zy} - Y_{zx}Y_{yy}\\ + p_y &= Y_{zx}Y_{xy} - Y_{xx}Y_{zy}\\ + p_z &= Y_{xx}Y_{yy} - Y_{yx}Y_{xy} + \end{split} + """ + + _loc_names = ("Roving magnetic field", "Base station field") + + def __init__( + self, + locations_h, + locations_base=None, + base_type="magnetic", + storeProjections=False, + ): + super().__init__( + locations_h=locations_h, + locations_base=locations_base, + base_type=base_type, + storeProjections=storeProjections, + ) + + def eval(self, src, mesh, f): # noqa: D102 A003 + # Docstring inherited from parent class (BaseNaturalSourceRX). + return _eval_cross_product_amplitude(self, src, mesh, f) + + def evalDeriv( # noqa: D102 + self, src, mesh, f, du_dm_v=None, v=None, adjoint=False + ): + # Docstring inherited from parent class (BaseNaturalSourceRX). + return _eval_cross_product_amplitude_deriv( + self, src, mesh, f, du_dm_v=du_dm_v, v=v, adjoint=adjoint + ) + + +class HorizontalDeterminant(RootGramDeterminant): + r"""Determinant of the horizontal transfer functions. + + Receiver class for simulating a data that are invariant to airborne sensor + orientation about the tow cable for either an electric or magnetic base station. + The datum is derived by taking the determinant of the horizontal transfer + functions. For a magnetic base station the quantity is unitless. For an electric + base station, the units are :math:`A^2/V^2`. + See the *Notes* section for a formal definition of the datum. + + Parameters + ---------- + locations_h : (n_loc, n_dim) array_like + Locations where the roving magnetic fields are measured. + locations_base : (n_loc, n_dim) array_like, optional + Locations where the base station magnetic fields are measured. Defaults to + the same locations as the roving magnetic fields measurements, + `locations_h`. + base_type : {'magnetic', 'electric'}, optional + Whether magnetic or electric fields are measured at the base station. + For magnetic fields, the quantity is unitless. For electric fields, + the quantity has units $A^2/V^2$. + component : {'real', 'imag'}, optional + Define the receiver to measure the real or imaginary component: + - 'real': Real component + - 'imag': Imaginary component + storeProjections : bool, optional + Whether to cache to internal projection matrices. + + Notes + ----- + + Magnetic base station + ~~~~~~~~~~~~~~~~~~~~~ + Consider an acquisition system that measures 3-component magnetic fields + in the air and magnetic fields at a base station. The fundamental set of + transfer functions (i.e. tippers) that can be generated from these + measurements is given by: + + .. math:: + + \begin{bmatrix} + T_{xx} & T_{yx} & T_{zx} \\ + T_{xy} & T_{yy} & T_{zy} + \end{bmatrix} + = + \begin{bmatrix} + H_x^{(x)} & H_y^{(x)} \\ + H_x^{(y)} & H_y^{(y)} + \end{bmatrix}_b^{-1} + \, + \begin{bmatrix} + H_x^{(x)} & H_y^{(x)} & H_z^{(x)} \\ + H_x^{(y)} & H_y^{(y)} & H_z^{(y)} + \end{bmatrix}_r + + where subscript :math:`b` denotes the base station location and subscript + :math:`r` denotes the mobile receiver location. + + For this system, the horizontal determinant transfer function is defined as: + + .. math:: + + \det(T_H) = T_{xx}T_{yy} - T_{yx}T_{xy} + + Electric base station + ~~~~~~~~~~~~~~~~~~~~~ + Now consider an acquisition system that measures 3-component magnetic fields + in the air and electric fields at a base station. The fundamental set of + transfer functions (i.e. admittances) that can be generated from these + measurements is given by: + + .. math:: + + \begin{bmatrix} + Y_{xx} & Y_{yx} & Y_{zx} \\ + Y_{xy} & Y_{yy} & Y_{zy} + \end{bmatrix} + = + \begin{bmatrix} + E_x^{(x)} & E_y^{(x)} \\ + E_x^{(y)} & E_y^{(y)} + \end{bmatrix}_b^{-1} + \, + \begin{bmatrix} + H_x^{(x)} & H_y^{(x)} & H_z^{(x)} \\ + H_x^{(y)} & H_y^{(y)} & H_z^{(y)} + \end{bmatrix}_r + + For this system, the horizontal determinant transfer function is defined as: + + .. math:: + + \det(Y_H) = Y_{xx}Y_{yy} - Y_{yx}Y_{xy} + + """ + + _loc_names = ("Roving magnetic field", "Base station field") + + def __init__( + self, + locations_h, + locations_base=None, + base_type="magnetic", + component="real", + storeProjections=False, + ): + super().__init__( + locations_h=locations_h, + locations_base=locations_base, + base_type=base_type, + storeProjections=storeProjections, + ) + self.component = component + + @property + def component(self): + r"""Data type; i.e. "real", "imag", "amp". + + The `component` property specifies + whether the data are: + - 'real': Real component + - 'imag': Imaginary component + - 'amp': Amplitude + + Returns + ------- + str + Data type; i.e. "real", "imag", "amp". + """ + return self._component + + @component.setter + def component(self, var): + self._component = validate_string( + "component", + var, + [ + ("real", "re", "in-phase", "in phase"), + ("imag", "imaginary", "im", "out-of-phase", "out of phase"), + ("amp", "ampl", "amplitude"), + ], + ) + + def eval(self, src, mesh, f): # noqa: A003 D102 + # Doctring inherited from parent class (BaseNaturalSourceRx + vals = _eval_horizontal_determinant(self, src, mesh, f) + if self.component == "complex": + return vals + if self.component == "amp": + return np.abs(vals) + return getattr(vals, self.component) + + def evalDeriv( # noqa: D102 + self, src, mesh, f, du_dm_v=None, v=None, adjoint=False + ): + # Doctring inherited from parent class (BaseNaturalSourceRx) + if self.component == "complex": + raise NotImplementedError( + "complex valued data derivative is not implemented." + ) + + return _eval_horizontal_determinant_deriv( + self, src, mesh, f, du_dm_v=du_dm_v, v=v, adjoint=adjoint + ) + + +class ApparentConductivity(_ElectricAndMagneticReceiver): + r"""Receiver class for simulating apparent conductivity data (3D problems only). + + This class is used to simulate an apparent conductivity datum, in S/m. + + .. warning:: Breaking change + + From SimPEG v0.26.0 onward, a new set of formulae have been adopted to + compute apparent conductivities. These more accurately reflect how apparent + conductivities can be computed from NSEM fields. + + Parameters + ---------- + locations_e : (n_loc, n_dim) array_like + Locations where the electric fields are measured. + locations_h : (n_loc, n_dim) array_like, optional + Locations where the magnetic fields are measured. Defaults to the same + locations as electric field measurements, `locations_e`. + formula : {"root_gram_determinant", "cross_product_amplitude", "horizontal_determinant"} + The formula used to generate the appparent conductivity datum. + storeProjections : bool, optional + Whether to cache to internal projection matrices. + """ + + _base_type = "electric" + _component = "amp" + + def __init__( + self, + locations_e, + locations_h=None, + formula="cross_product_amplitude", + storeProjections=False, + ): + if locations_h is None: + locations_h = locations_e + super().__init__( + locations1=locations_e, + locations2=locations_h, + storeProjections=storeProjections, + ) + self.formula = formula + + @property + def formula(self): + r"""Equation used to generate the apparent conductivity datum. + + The `formula` property specifies + whether the data are derived using: + - 'root_gram_determinant': Root Gram determinant of the admittance matrix + - 'cross_product_amplitude': Cross product amplitude of the admittance matrix + - 'horizontal_determinant': Determinant of the horizontal admittances + + Returns + ------- + str + Data type; i.e. "root_gram_determinant", "cross_product_amplitude", or + "horizontal_determinant". + """ + return self._formula + + @formula.setter + def formula(self, var): + self._formula = validate_string( + "formula", + var, + [ + "root_gram_determinant", + "cross_product_amplitude", + "horizontal_determinant", + ], + ) + + def eval(self, src, mesh, f): # noqa: A003 D102 + # Docstring inherited from parent class + # scaling by w*mu_0 happens inside function + if self._formula == "root_gram_determinant": + return _eval_root_gram_determinant(self, src, mesh, f) / _alpha(src) + if self._formula == "cross_product_amplitude": + return _eval_cross_product_amplitude(self, src, mesh, f) / _alpha(src) + if self._formula == "horizontal_determinant": + return _eval_horizontal_determinant(self, src, mesh, f) / _alpha(src) + raise ValueError() # pragma: nocover + + def evalDeriv( # noqa: A003 D102 + self, src, mesh, f, du_dm_v=None, v=None, adjoint=False + ): + # Docstring inherited from parent class + # scaling by w*mu_0 happens inside function + scale = _alpha(src) ** -1 + if self._formula == "root_gram_determinant": + return _eval_root_gram_determinant_deriv( + self, src, mesh, f, du_dm_v=du_dm_v, v=v, adjoint=adjoint, scale=scale + ) + if self._formula == "cross_product_amplitude": + return _eval_cross_product_amplitude_deriv( + self, src, mesh, f, du_dm_v=du_dm_v, v=v, adjoint=adjoint, scale=scale + ) + if self._formula == "horizontal_determinant": + return _eval_horizontal_determinant_deriv( + self, src, mesh, f, du_dm_v=du_dm_v, v=v, adjoint=adjoint, scale=scale + ) + raise ValueError() # pragma: nocover + @deprecate_class(removal_version="0.24.0", error=True, replace_docstring=False) class PointNaturalSource(Impedance): diff --git a/simpeg/electromagnetics/natural_source/simulation.py b/simpeg/electromagnetics/natural_source/simulation.py index a7cf938a2b..954ed12e66 100644 --- a/simpeg/electromagnetics/natural_source/simulation.py +++ b/simpeg/electromagnetics/natural_source/simulation.py @@ -1,790 +1,799 @@ -import numpy as np -from discretize import TensorMesh, TreeMesh -from discretize.utils import Zero - -from ...utils import mkvc -from ... import maps -from ..frequency_domain.simulation import BaseFDEMSimulation, Simulation3DElectricField -from ..frequency_domain.survey import Survey -from ..utils import omega -from .sources import Planewave -from .fields import ( - Fields1DPrimarySecondary, - Fields1DElectricField, - Fields1DMagneticField, - Fields2DElectricField, - Fields2DMagneticField, -) - - -def _centers_to_widths(centers): - centers = np.asarray(centers) - d = np.empty_like(centers) - n = centers.shape[-1] - d[..., 0] = 2 * centers[..., 0] - for i in range(1, n): - d[..., i] = 2 * (centers[..., i] - centers[..., i - 1]) - d[..., i - 1] - return d - - -################################### -# 1D problems -################################### - - -class Simulation1DElectricField(BaseFDEMSimulation): - r""" - 1D finite volume simulation for the natural source electromagnetic problem. - - This corresponds to the TE mode 2D simulation where the electric field is - located at cell centers and the magnetic flux is on edges. - - We are solving the discrete version of - - .. math:: - - \partial_z E_y = i \omega \mu_0 H_x = 0 - - sigma E_y = \partial_z H_x - - with default boundary conditions that $H_x[z_max] = 1$ (a plane wave source at - the top of the domain), and $H_x[z_min] = 0$. - - When we discretize, we obtain: - - where the Magnetic field is defined on edges, and the electric field is - defined on cell centers. - """ - - _solutionType = "eSolution" - _formulation = "EB" # electric-field component is on cell-centers - fieldsPair = Fields1DElectricField - - def __init__(self, mesh, **kwargs): - if mesh.dim > 1: - raise ValueError( - f"The mesh must be a 1D mesh. The provided mesh has dimension {mesh.dim}" - ) - - super().__init__(mesh, **kwargs) - - self._rhs = mesh.boundary_node_vector_integral * [0 + 0j, 1 + 0j] - - def getA(self, freq): - r""" - System matrix - - .. math:: - - \mathbf{A} = - \mathbf{G}^\top \mathbf{M}^e_{\mu^{-1}} \mathbf{G} - + 1\omega \mathbf{M}^f_\sigma - """ - - G = self.mesh.nodal_gradient - MeMui = self.MeMui - MfSigma = self.MfSigma - - return G.T.tocsr() @ MeMui @ G + 1j * omega(freq) * MfSigma - - def getADeriv_sigma(self, freq, u, v, adjoint=False): - return 1j * omega(freq) * self.MfSigmaDeriv(u, v, adjoint=adjoint) - - def getADeriv_mui(self, freq, u, v, adjoint=False): - G = self.mesh.nodal_gradient - if adjoint: - return self.MeMuiDeriv(G * u, G * v, adjoint) - return G.T * self.MeMuiDeriv(G * u, v, adjoint) - - def getRHS(self, freq): - """ - Right hand side constructed using Dirichlet boundary conditions - """ - return 1j * omega(freq) * self._rhs - - def getRHSDeriv(self, freq, src, v, adjoint=False): - return Zero() - - def getADeriv(self, freq, u, v, adjoint=False): - return self.getADeriv_sigma(freq, u, v, adjoint) + self.getADeriv_mui( - freq, u, v, adjoint - ) - - def getJ(self, m, f=None): - r"""Generate the full sensitivity matrix. - - .. important:: - - This method hasn't been implemented yet for this class. - - Raises - ------- - NotImplementedError - """ - msg = ( - "The getJ method hasn't been implemented for the " - f"{type(self).__name__} yet." - ) - raise NotImplementedError(msg) - - -class Simulation1DMagneticField(BaseFDEMSimulation): - """ - 1D finite volume simulation for the natural source electromagnetic problem. - - This corresponds to the TM mode 2D simulation where the magnetic field is - located at faces (nodes) and the electric field is on edges (cell_centers). - """ - - _solutionType = "hSolution" - _formulation = "HJ" - fieldsPair = Fields1DMagneticField - - def __init__(self, mesh, **kwargs): - if mesh.dim > 1: - raise ValueError( - f"The mesh must be a 1D mesh. The provided mesh has dimension {mesh.dim}" - ) - - super().__init__(mesh, **kwargs) - - # corresponds to a dirichlet boundaries at the top (= 1 ) and bottom(=0) - # for the y component of electric field - self._rhs = -mesh.boundary_node_vector_integral * [0 + 0j, 1 + 0j] - - def getA(self, freq): - """ - system matrix - """ - G = self.mesh.nodal_gradient - MeRho = self.MeRho - MnMu = self.MnMu - - return G.T.tocsr() @ MeRho @ G + 1j * omega(freq) * MnMu - - def getADeriv_rho(self, freq, u, v, adjoint=False): - G = self.mesh.nodal_gradient - if adjoint: - return self.MeRhoDeriv(G * u, G * v, adjoint) - return G.T * self.MeRhoDeriv(G * u, v, adjoint) - - def getADeriv_mu(self, freq, u, v, adjoint=False): - MnMuDeriv = self.MnMuDeriv(u) - if adjoint is True: - return 1j * omega(freq) * (MnMuDeriv.T * v) - - return 1j * omega(freq) * (MnMuDeriv * v) - - def getRHS(self, freq): - """ - right hand side - """ - return self._rhs - - def getRHSDeriv(self, freq, src, v, adjoint=False): - return Zero() - - def getADeriv(self, freq, u, v, adjoint=False): - return self.getADeriv_rho(freq, u, v, adjoint) + self.getADeriv_mu( - freq, u, v, adjoint - ) - - def getJ(self, m, f=None): - r"""Generate the full sensitivity matrix. - - .. important:: - - This method hasn't been implemented yet for this class. - - Raises - ------- - NotImplementedError - """ - msg = ( - "The getJ method hasn't been implemented for the " - f"{type(self).__name__} yet." - ) - raise NotImplementedError(msg) - - -class Simulation1DPrimarySecondary(Simulation1DElectricField): - r""" - A NSEM problem solving a e formulation and primary/secondary fields decomposition. - - By eliminating the magnetic flux density using - - .. math :: - - \mathbf{b} = \frac{1}{i \omega} \left(-\mathbf{C} \mathbf{e} \right) - - - we can write Maxwell's equations as a second order system in - :math:`\mathbf{e}` only: - - .. math :: - - \left[ - \mathbf{C}^{\top} \mathbf{M_{\mu^{-1}}^e } \mathbf{C} - + i \omega \mathbf{M_{\sigma}^f} - \right] - \mathbf{e}_{s} - = i \omega \mathbf{M_{\sigma_{s}}^f } \mathbf{e}_{p} - - which we solve for :math:`\mathbf{e_s}`. - The total field :math:`\mathbf{e} = \mathbf{e_p} + \mathbf{e_s}`. - - The primary field is estimated from a background model (commonly half space ). - """ - - fieldsPair = Fields1DPrimarySecondary - - def __init__(self, mesh, survey=None, sigmaPrimary=None, **kwargs): - super().__init__(mesh=mesh, survey=survey, **kwargs) - self.sigmaPrimary = sigmaPrimary - - @property - def sigmaPrimary(self): - """ - A background model, use for the calculation of the primary fields. - - """ - return self._sigmaPrimary - - @sigmaPrimary.setter - def sigmaPrimary(self, val): - # Note: TODO add logic for val, make sure it is the correct size. - self._sigmaPrimary = val - - def getADeriv(self, freq, u, v, adjoint=False): - """ - The derivative of A wrt sigma - """ - # Only select the yx polarization - return super().getADeriv(freq, u[:, 1], v, adjoint=adjoint) - - def getRHS(self, freq): - """ - Function to return the right hand side for the system. - - :param float freq: Frequency - :rtype: numpy.ndarray - :return: RHS for 1 polarizations, primary fields (nF, 1) - """ - - # Get sources for the frequncy(polarizations) - src = self.survey.get_sources_by_frequency(freq)[0] - # Only select the yx polarization - S_e = mkvc(src.s_e(self)[:, 1], 2) - return -1j * omega(freq) * S_e - - def getRHSDeriv(self, freq, src, v, adjoint=False): - """ - The derivative of the RHS wrt sigma - """ - S_eDeriv = src.s_eDeriv_m(self, v, adjoint) - return -1j * omega(freq) * S_eDeriv - - -################################### -# 2D problems -################################### -class Simulation2DElectricField(BaseFDEMSimulation): - """ - A - """ - - _solutionType = "eSolution" - _formulation = "EB" - fieldsPair = Fields2DElectricField - - def __init__(self, mesh, h_bc=None, **kwargs): - if mesh.dim != 2: - raise ValueError( - f"The mesh must be a 2D mesh. The provided mesh has dimension {mesh.dim}" - ) - - super().__init__(mesh, **kwargs) - - for src in self.survey.source_list: - for rx in src.receiver_list: - if rx.orientation != "xy": - raise TypeError( - "natural_source.Simulation2DElectricField only supports xy oriented" - " receivers. Please use the Simulation2DMagneticField class for" - " those receivers." - ) - - if h_bc is None: - if isinstance(mesh, (TensorMesh, TreeMesh)): - b_e = mesh.boundary_edges - top = np.where(b_e[:, 1] == mesh.nodes_y[-1]) - bot = np.where(b_e[:, 1] == mesh.nodes_y[0]) - left = np.where(b_e[:, 0] == mesh.nodes_x[0]) - right = np.where(b_e[:, 0] == mesh.nodes_x[-1]) - - if isinstance(mesh, TensorMesh): - h_l = h_r = mesh.h[1] - is_b = np.zeros(mesh.shape_cells, dtype=bool) - is_b[0, :] = True - P_l = maps.Projection(mesh.n_cells, is_b.reshape(-1, order="F")) - is_b[0, :] = False - is_b[-1, :] = True - P_r = maps.Projection(mesh.n_cells, is_b.reshape(-1, order="F")) - else: - h_l = _centers_to_widths(b_e[left][:, 1]) - h_r = _centers_to_widths(b_e[right][:, 1]) - b_l, b_r, _, __ = mesh.cell_boundary_indices - P_l = maps.Projection(mesh.n_cells, b_l) - P_r = maps.Projection(mesh.n_cells, b_r) - - self._b_inds = (left, right, bot, top) - self._P_l = P_l - self._P_r = P_r - - map_l_kwargs = {} - map_r_kwargs = {} - if self.sigmaMap is not None: - map_l_kwargs["sigmaMap"] = P_l * self.sigmaMap - map_r_kwargs["sigmaMap"] = P_r * self.sigmaMap - if self.muiMap is not None: - map_l_kwargs["muiMap"] = P_l * self.muiMap - map_r_kwargs["muiMap"] = P_r * self.muiMap - - # create a survey with 1 source per frequency (no receivers) - frequencies = self.survey.frequencies - survey = Survey([Planewave([], freq) for freq in frequencies]) - self._sim_left = Simulation1DElectricField( - TensorMesh((h_l,), (mesh.nodes_y[0],)), - survey=survey, - solver=self.solver, - **map_l_kwargs, - ) - self._sim_right = Simulation1DElectricField( - TensorMesh((h_r,), (mesh.nodes_y[0],)), - survey=survey, - solver=self.solver, - **map_r_kwargs, - ) - else: - raise NotImplementedError( - f"Unable to infer 1D mesh from {type(mesh)}. You must supply custom" - " boundary conditions for the electric field." - ) - self._h_bc = None - else: - n_be = mesh.boundary_edges.shape[0] - for freq in self.survey.frequencies: - try: - h = h_bc[freq] - if len(h) != n_be: - raise ValueError( - f"Boundary condition item for frequency {freq} is incorrect length." - f" Should be the same length as number of boundary_edges, {n_be}, " - f" saw a length of {len(h)}" - ) - except TypeError: - raise TypeError( - "h_bc must be a dictionary of numpy arrays indexed by frequency." - ) - except IndexError: - raise TypeError( - "h_bc must be a dictionary of numpy arrays indexed by frequency. Did not" - f" find key {freq}." - ) - except KeyError: - raise KeyError( - "h_bc must be a dictionary of numpy arrays indexed by frequency. Did not" - f" find key {freq}." - ) - self._h_bc = h_bc - self._M_bc = mesh.boundary_edge_vector_integral - - def getA(self, freq): - r""" - System matrix - - .. math:: - - \mathbf{A} = - \mathbf{C}^\top \mathbf{M}^{cc}_{\mu} \mathbf{C} - + 1\omega \mathbf{M}^e_\sigma - - """ - C = self.mesh.edge_curl - Mcc_mui = self.MccMui - Me_sigma = self.MeSigma - - return C.T.tocsr() @ Mcc_mui @ C + 1j * omega(freq) * Me_sigma - - def getRHS(self, freq): - """ - Right hand side constructed using Dirichlet boundary conditions - """ - M_bc = self._M_bc - if self._h_bc is None: - # left and right have the same 1D survey - src = self._sim_left.survey.get_sources_by_frequency(freq)[0] - f_left, f_right = self.boundary_fields() - h_bc = np.zeros(M_bc.shape[1], dtype=complex) - left, right, bot, top = self._b_inds - h_bc[top] = 1.0 - h_bc[left] = f_left[src, "h"][:, 0] - h_bc[right] = f_right[src, "h"][:, 0] - else: - h_bc = self._h_bc[freq] - return 1j * omega(freq) * (M_bc @ h_bc) - - def getADeriv_sigma(self, freq, u, v, adjoint=False): - return 1j * omega(freq) * self.MeSigmaDeriv(u, v, adjoint=adjoint) - - def getADeriv_mui(self, freq, u, v, adjoint=False): - C = self.mesh.edge_curl - if adjoint: - return self.MccMuiDeriv(C * u, C * v, adjoint) - return C.T * self.MccMuiDeriv(C * u, v, adjoint) - - def getADeriv(self, freq, u, v, adjoint=False): - return self.getADeriv_sigma(freq, u, v, adjoint) + self.getADeriv_mui( - freq, u, v, adjoint - ) - - def getRHSDeriv(self, freq, src, v, adjoint=False): - if self._h_bc is not None: - return Zero() - M_bc = self._M_bc - f_left, f_right = self.boundary_fields() - left, right, _, __ = self._b_inds - src_1d = self._sim_left.survey.get_sources_by_frequency(freq)[0] - - # derivatives from the Jv func of the 1D sim - if not adjoint: - h_bc_dm_v = np.zeros(M_bc.shape[1], dtype=complex) - h_bc_dm_v[left] = f_left.field_deriv_m("h", freq, src_1d, v, adjoint=False) - h_bc_dm_v[right] = f_right.field_deriv_m( - "h", freq, src_1d, v, adjoint=False - ) - - return 1j * omega(freq) * (M_bc @ h_bc_dm_v) - else: - v_dm = M_bc.T @ v - v_left, v_right = v_dm[left], v_dm[right] - df_dmT = f_left.field_deriv_m("h", freq, src_1d, v_left, adjoint=True) - df_dmT += f_right.field_deriv_m("h", freq, src_1d, v_right, adjoint=True) - - return 1j * omega(freq) * df_dmT - - def boundary_fields(self, model=None): - "Returns the 1D field objects at the boundaries" - if getattr(self, "_boundary_fields", None) is None: - if model is None: - model = self.model - sim = self._sim_left - if self.muiMap is None: - try: - sim.mui = self._P_l @ self.mui - except Exception: - sim.mui = self.mui - if self.sigmaMap is None: - try: - sim.sigma = self._P_l @ self.sigma - except Exception: - sim.sigma = self.sigma - f_left = sim.fields(model) - - sim = self._sim_right - if self.muiMap is None: - try: - sim.mui = self._P_r @ self.mui - except Exception: - sim.mui = self.mui - if self.sigmaMap is None: - try: - sim.sigma = self._P_r @ self.sigma - except Exception: - sim.sigma = self.sigma - f_right = sim.fields(model) - - self._boundary_fields = (f_left, f_right) - return self._boundary_fields - - @property - def _delete_on_model_update(self): - items = super()._delete_on_model_update - items.append("_boundary_fields") - return items - - -class Simulation2DMagneticField(BaseFDEMSimulation): - """ - A - """ - - _solutionType = "hSolution" - _formulation = "HJ" - fieldsPair = Fields2DMagneticField - - def __init__(self, mesh, e_bc=None, **kwargs): - if mesh.dim != 2: - raise ValueError( - f"The mesh must be a 2D mesh. The provided mesh has dimension {mesh.dim}" - ) - - super().__init__(mesh, **kwargs) - - for src in self.survey.source_list: - for rx in src.receiver_list: - if rx.orientation != "yx": - raise TypeError( - "natural_source.Simulation2DMagneticField only supports yx oriented" - " receivers. Please use the Simulation2DElectricField class for" - " those receivers." - ) - - if e_bc is None: - if isinstance(mesh, (TensorMesh, TreeMesh)): - b_e = mesh.boundary_edges - top = np.where(b_e[:, 1] == mesh.nodes_y[-1]) - bot = np.where(b_e[:, 1] == mesh.nodes_y[0]) - left = np.where(b_e[:, 0] == mesh.nodes_x[0]) - right = np.where(b_e[:, 0] == mesh.nodes_x[-1]) - - if isinstance(mesh, TensorMesh): - h_l = h_r = mesh.h[1] - is_b = np.zeros(mesh.shape_cells, dtype=bool) - is_b[0, :] = True - P_l = maps.Projection(mesh.n_cells, is_b.reshape(-1, order="F")) - is_b[0, :] = False - is_b[-1, :] = True - P_r = maps.Projection(mesh.n_cells, is_b.reshape(-1, order="F")) - else: - h_l = _centers_to_widths(b_e[left][:, 1]) - h_r = _centers_to_widths(b_e[right][:, 1]) - b_l, b_r, _, __ = mesh.cell_boundary_indices - P_l = maps.Projection(mesh.n_cells, b_l) - P_r = maps.Projection(mesh.n_cells, b_r) - - self._b_inds = (left, right, bot, top) - self._P_l = P_l - self._P_r = P_r - - map_l_kwargs = {} - map_r_kwargs = {} - if self.rhoMap is not None: - map_l_kwargs["rhoMap"] = P_l * self.rhoMap - map_r_kwargs["rhoMap"] = P_r * self.rhoMap - if self.muMap is not None: - map_l_kwargs["muMap"] = P_l * self.muMap - map_r_kwargs["muMap"] = P_r * self.muMap - - # create a survey with 1 source per frequency (no receivers) - frequencies = self.survey.frequencies - survey = Survey([Planewave([], freq) for freq in frequencies]) - self._sim_left = Simulation1DMagneticField( - TensorMesh((h_l,), (mesh.nodes_y[0],)), - survey=survey, - solver=self.solver, - **map_l_kwargs, - ) - self._sim_right = Simulation1DMagneticField( - TensorMesh((h_r,), (mesh.nodes_y[0],)), - survey=survey, - solver=self.solver, - **map_r_kwargs, - ) - else: - raise NotImplementedError( - f"Unable to infer 1D mesh from {type(mesh)}. You must supply custom" - " boundary conditions for the electric field." - ) - self._e_bc = None - else: - n_be = mesh.boundary_edges.shape[0] - for freq in self.survey.frequencies: - try: - e = e_bc[freq] - if len(e) != n_be: - raise ValueError( - f"Boundary condition item for frequency {freq} is incorrect length." - f" Should be the same length as number of boundary_edges, {n_be}, " - f" saw a length of {len(e)}" - ) - except TypeError: - raise TypeError( - "e_bc must be a dictionary of numpy arrays indexed by frequency." - ) - except IndexError: - raise TypeError( - "e_bc must be a dictionary of numpy arrays indexed by frequency." - ) - except KeyError: - raise KeyError( - "e_bc must be a dictionary of numpy arrays indexed by frequency. Did not" - f" find key {freq}." - ) - self._e_bc = e_bc - self._M_bc = mesh.boundary_edge_vector_integral - - def getA(self, freq): - r""" - System matrix - - .. math:: - - \mathbf{A} = - \mathbf{C}^\top \mathbf{M}^{cc}_{\rho} \mathbf{C} - + 1\omega \mathbf{M}^e_\mu - """ - C = self.mesh.edge_curl - Mcc_rho = self.MccRho - Me_mu = self.MeMu - - return C.T.tocsr() @ Mcc_rho @ C + 1j * omega(freq) * Me_mu - - def getRHS(self, freq): - """ - Right hand side constructed using Dirichlet boundary conditions - """ - M_bc = self._M_bc - if self._e_bc is None: - # left and right have the same 1D survey - src = self._sim_left.survey.get_sources_by_frequency(freq)[0] - f_left, f_right = self.boundary_fields() - e_bc = np.zeros(M_bc.shape[1], dtype=complex) - left, right, bot, top = self._b_inds - e_bc[top] = 1.0 - e_bc[left] = f_left[src, "e"][:, 0] - e_bc[right] = f_right[src, "e"][:, 0] - else: - e_bc = self._e_bc[freq] - return -M_bc @ e_bc - - def getADeriv_rho(self, freq, u, v, adjoint=False): - C = self.mesh.edge_curl - if adjoint: - return self.MccRhoDeriv(C * u, C * v, adjoint) - return C.T * self.MccRhoDeriv(C * u, v, adjoint) - - def getADeriv_mu(self, freq, u, v, adjoint=False): - return 1j * omega(freq) * self.MeMuDeriv(u, v, adjoint=adjoint) - - def getADeriv(self, freq, u, v, adjoint=False): - return self.getADeriv_rho(freq, u, v, adjoint) + self.getADeriv_mu( - freq, u, v, adjoint - ) - - def getRHSDeriv(self, freq, src, v, adjoint=False): - if self._e_bc is not None: - return Zero() - M_bc = self._M_bc - f_left, f_right = self.boundary_fields() - left, right, _, __ = self._b_inds - src_1d = self._sim_left.survey.get_sources_by_frequency(freq)[0] - - # derivatives from the Jv func of the 1D sim - if not adjoint: - e_bc_dm_v = np.zeros(M_bc.shape[1], dtype=complex) - e_bc_dm_v[left] = f_left.field_deriv_m("e", freq, src_1d, v, adjoint=False) - e_bc_dm_v[right] = f_right.field_deriv_m( - "e", freq, src_1d, v, adjoint=False - ) - return -(M_bc @ e_bc_dm_v) - else: - v_dm = -(M_bc.T @ v) - v_left, v_right = v_dm[left], v_dm[right] - df_dmT = f_left.field_deriv_m("e", freq, src_1d, v_left, adjoint=True) - df_dmT += f_right.field_deriv_m("e", freq, src_1d, v_right, adjoint=True) - return df_dmT - - def boundary_fields(self, model=None): - "Returns the 1D field objects at the boundaries" - if getattr(self, "_boundary_fields", None) is None: - if model is None: - model = self.model - sim = self._sim_left - if self.muMap is None: - try: - sim.mu = self._P_l @ self.mu - except Exception: - sim.mu = self.mu - if self.rhoMap is None: - try: - sim.rho = self._P_l @ self.rho - except Exception: - sim.rho = self.rho - f_left = sim.fields(model) - - sim = self._sim_right - if self.muMap is None: - try: - sim.mu = self._P_r @ self.mu - except Exception: - sim.mu = self.mu - if self.rhoMap is None: - try: - sim.rho = self._P_r @ self.rho - except Exception: - sim.rho = self.rho - f_right = sim.fields(model) - - self._boundary_fields = (f_left, f_right) - return self._boundary_fields - - @property - def _delete_on_model_update(self): - items = super()._delete_on_model_update - items.append("_boundary_fields") - return items - - -################################### -# 3D problems -################################### - - -class Simulation3DPrimarySecondary(Simulation3DElectricField): - r""" - A NSEM problem solving a e formulation and a primary/secondary fields decomposition. - - By eliminating the magnetic flux density using - - .. math :: - - \mathbf{b} = \frac{1}{i \omega} \left(-\mathbf{C} \mathbf{e} \right) - - - we can write Maxwell's equations as a second order system in - :math:`\mathbf{e}` only: - - .. math :: - - \left[ - \mathbf{C}^{\top} \mathbf{M_{\mu^{-1}}^f} \mathbf{C} - + i \omega \mathbf{M_{\sigma}^e} - \right] - \mathbf{e}_{s} - = i \omega \mathbf{M_{\sigma_{p}}^e} \mathbf{e}_{p} - - which we solve for :math:`\mathbf{e_s}`. - The total field :math:`\mathbf{e} = \mathbf{e_p} + \mathbf{e_s}`. - - The primary field is estimated from a background model (commonly as a 1D model). - """ - - def __init__(self, mesh, survey=None, sigmaPrimary=None, **kwargs): - super().__init__(mesh=mesh, survey=survey, **kwargs) - self.sigmaPrimary = sigmaPrimary - - # fieldsPair = Fields3DPrimarySecondary - - @property - def sigmaPrimary(self): - """ - A background model, use for the calculation of the primary fields. - - """ - return self._sigmaPrimary - - @sigmaPrimary.setter - def sigmaPrimary(self, val): - # Note: TODO add logic for val, make sure it is the correct size. - self._sigmaPrimary = val +import numpy as np +from discretize import TensorMesh, TreeMesh +from discretize.utils import Zero + +from ...utils import mkvc +from ... import maps +from ..frequency_domain.simulation import BaseFDEMSimulation, Simulation3DElectricField +from ..frequency_domain.survey import Survey +from ..utils import omega +from .sources import Planewave +from .receivers import Impedance, Tipper, Admittance +from .fields import ( + Fields1DPrimarySecondary, + Fields1DElectricField, + Fields1DMagneticField, + Fields2DElectricField, + Fields2DMagneticField, +) + + +def _centers_to_widths(centers): + """Cell widths from cell centers measured from the start of the first cell.""" + centers = np.asarray(centers) + d = np.empty_like(centers) + n = centers.shape[-1] + d[..., 0] = 2 * centers[..., 0] + for i in range(1, n): + d[..., i] = 2 * (centers[..., i] - centers[..., i - 1]) - d[..., i - 1] + return d + + +################################### +# 1D problems +################################### + + +class Simulation1DElectricField(BaseFDEMSimulation): + r""" + 1D finite volume simulation for the natural source electromagnetic problem. + + This corresponds to the TE mode 2D simulation where the electric field is + located on nodes and the magnetic field at cell centers. + + We are solving the discrete version of + + .. math:: + + \partial_z E_y = i \omega \mu_0 H_x = 0 + + sigma E_y = \partial_z H_x + + with default boundary conditions that $H_x[z_max] = 1$ (a plane wave source at + the top of the domain), and $H_x[z_min] = 0$. + + When we discretize, we obtain: + + where the electric field is defined on nodes, and the magnetic field is + defined on cell centers. + """ + + _solutionType = "eSolution" + _formulation = "EB" # electric-field component is on nodes + fieldsPair = Fields1DElectricField + + def __init__(self, mesh, **kwargs): + if mesh.dim > 1: + raise ValueError( + f"The mesh must be a 1D mesh. The provided mesh has dimension {mesh.dim}" + ) + + super().__init__(mesh, **kwargs) + + self._rhs = mesh.boundary_node_vector_integral * [0 + 0j, 1 + 0j] + + def getA(self, freq): + r""" + System matrix + + .. math:: + + \mathbf{A} = + \mathbf{G}^\top \mathbf{M}^e_{\mu^{-1}} \mathbf{G} + + 1\omega \mathbf{M}^f_\sigma + """ + + G = self.mesh.nodal_gradient + MeMui = self.MeMui + MfSigma = self.MfSigma + + return G.T.tocsr() @ MeMui @ G + 1j * omega(freq) * MfSigma + + def getADeriv_sigma(self, freq, u, v, adjoint=False): + return 1j * omega(freq) * self.MfSigmaDeriv(u, v, adjoint=adjoint) + + def getADeriv_mui(self, freq, u, v, adjoint=False): + G = self.mesh.nodal_gradient + if adjoint: + return self.MeMuiDeriv(G * u, G * v, adjoint) + return G.T * self.MeMuiDeriv(G * u, v, adjoint) + + def getRHS(self, freq): + """ + Right hand side constructed using Dirichlet boundary conditions + """ + return 1j * omega(freq) * self._rhs + + def getRHSDeriv(self, freq, src, v, adjoint=False): + return Zero() + + def getADeriv(self, freq, u, v, adjoint=False): + return self.getADeriv_sigma(freq, u, v, adjoint) + self.getADeriv_mui( + freq, u, v, adjoint + ) + + def getJ(self, m, f=None): + r"""Generate the full sensitivity matrix. + + .. important:: + + This method hasn't been implemented yet for this class. + + Raises + ------ + NotImplementedError + """ + msg = ( + "The getJ method hasn't been implemented for the " + f"{type(self).__name__} yet." + ) + raise NotImplementedError(msg) + + +class Simulation1DMagneticField(BaseFDEMSimulation): + """ + 1D finite volume simulation for the natural source electromagnetic problem. + + This corresponds to the TM mode 2D simulation where the magnetic field is + located at faces (nodes) and the electric field is on edges (cell_centers). + """ + + _solutionType = "hSolution" + _formulation = "HJ" + fieldsPair = Fields1DMagneticField + + def __init__(self, mesh, **kwargs): + if mesh.dim > 1: + raise ValueError( + f"The mesh must be a 1D mesh. The provided mesh has dimension {mesh.dim}" + ) + + super().__init__(mesh, **kwargs) + + # corresponds to a dirichlet boundaries at the top (= 1 ) and bottom(=0) + # for the y component of electric field + self._rhs = -mesh.boundary_node_vector_integral * [0 + 0j, 1 + 0j] + + def getA(self, freq): + """ + system matrix + """ + G = self.mesh.nodal_gradient + MeRho = self.MeRho + MnMu = self.MnMu + + return G.T.tocsr() @ MeRho @ G + 1j * omega(freq) * MnMu + + def getADeriv_rho(self, freq, u, v, adjoint=False): + G = self.mesh.nodal_gradient + if adjoint: + return self.MeRhoDeriv(G * u, G * v, adjoint) + return G.T * self.MeRhoDeriv(G * u, v, adjoint) + + def getADeriv_mu(self, freq, u, v, adjoint=False): + MnMuDeriv = self.MnMuDeriv(u) + if adjoint is True: + return 1j * omega(freq) * (MnMuDeriv.T * v) + + return 1j * omega(freq) * (MnMuDeriv * v) + + def getRHS(self, freq): + """ + right hand side + """ + return self._rhs + + def getRHSDeriv(self, freq, src, v, adjoint=False): + return Zero() + + def getADeriv(self, freq, u, v, adjoint=False): + return self.getADeriv_rho(freq, u, v, adjoint) + self.getADeriv_mu( + freq, u, v, adjoint + ) + + def getJ(self, m, f=None): + r"""Generate the full sensitivity matrix. + + .. important:: + + This method hasn't been implemented yet for this class. + + Raises + ------ + NotImplementedError + """ + msg = ( + "The getJ method hasn't been implemented for the " + f"{type(self).__name__} yet." + ) + raise NotImplementedError(msg) + + +class Simulation1DPrimarySecondary(Simulation1DElectricField): + r""" + A NSEM problem solving a e formulation and primary/secondary fields decomposition. + + By eliminating the magnetic flux density using + + .. math :: + + \mathbf{b} = \frac{1}{i \omega} \left(-\mathbf{C} \mathbf{e} \right) + + + we can write Maxwell's equations as a second order system in + :math:`\mathbf{e}` only: + + .. math :: + + \left[ + \mathbf{C}^{\top} \mathbf{M_{\mu^{-1}}^e } \mathbf{C} + + i \omega \mathbf{M_{\sigma}^f} + \right] + \mathbf{e}_{s} + = i \omega \mathbf{M_{\sigma_{s}}^f } \mathbf{e}_{p} + + which we solve for :math:`\mathbf{e_s}`. + The total field :math:`\mathbf{e} = \mathbf{e_p} + \mathbf{e_s}`. + + The primary field is estimated from a background model (commonly half space ). + """ + + fieldsPair = Fields1DPrimarySecondary + + def __init__(self, mesh, survey=None, sigmaPrimary=None, **kwargs): + super().__init__(mesh=mesh, survey=survey, **kwargs) + self.sigmaPrimary = sigmaPrimary + + @property + def sigmaPrimary(self): + """ + A background model, use for the calculation of the primary fields. + + """ + return self._sigmaPrimary + + @sigmaPrimary.setter + def sigmaPrimary(self, val): + # Note: TODO add logic for val, make sure it is the correct size. + self._sigmaPrimary = val + + def getADeriv(self, freq, u, v, adjoint=False): + """ + The derivative of A wrt sigma + """ + # Only select the yx polarization + return super().getADeriv(freq, u[:, 1], v, adjoint=adjoint) + + def getRHS(self, freq): + """ + Function to return the right hand side for the system. + + :param float freq: Frequency + :rtype: numpy.ndarray + :return: RHS for 1 polarizations, primary fields (nF, 1) + """ + + # Get sources for the frequncy(polarizations) + src = self.survey.get_sources_by_frequency(freq)[0] + # Only select the yx polarization + S_e = mkvc(src.s_e(self)[:, 1], 2) + return -1j * omega(freq) * S_e + + def getRHSDeriv(self, freq, src, v, adjoint=False): + """ + The derivative of the RHS wrt sigma + """ + S_eDeriv = src.s_eDeriv_m(self, v, adjoint) + return -1j * omega(freq) * S_eDeriv + + +################################### +# 2D problems +################################### +class Simulation2DElectricField(BaseFDEMSimulation): + """ + A + """ + + _solutionType = "eSolution" + _formulation = "EB" + fieldsPair = Fields2DElectricField + + def __init__(self, mesh, h_bc=None, **kwargs): + if mesh.dim != 2: + raise ValueError( + f"The mesh must be a 2D mesh. The provided mesh has dimension {mesh.dim}" + ) + + super().__init__(mesh, **kwargs) + + for src in self.survey.source_list: + for rx in src.receiver_list: + if not ( + (rx.orientation == "xy" and isinstance(rx, Impedance)) + or (rx.orientation == "yx" and isinstance(rx, Admittance)) + ): + raise TypeError( + "natural_source.Simulation2DElectricField only supports Impedance for" + " an xy receiver orientation OR Admittance for a yx receiver" + " orientation. Please provide a survey with valid receivers." + ) + + if h_bc is None: + if isinstance(mesh, (TensorMesh, TreeMesh)): + b_e = mesh.boundary_edges + top = np.where(b_e[:, 1] == mesh.nodes_y[-1]) + bot = np.where(b_e[:, 1] == mesh.nodes_y[0]) + left = np.where(b_e[:, 0] == mesh.nodes_x[0]) + right = np.where(b_e[:, 0] == mesh.nodes_x[-1]) + + if isinstance(mesh, TensorMesh): + h_l = h_r = mesh.h[1] + is_b = np.zeros(mesh.shape_cells, dtype=bool) + is_b[0, :] = True + P_l = maps.Projection(mesh.n_cells, is_b.reshape(-1, order="F")) + is_b[0, :] = False + is_b[-1, :] = True + P_r = maps.Projection(mesh.n_cells, is_b.reshape(-1, order="F")) + else: + h_l = _centers_to_widths(b_e[left][:, 1] - mesh.nodes_y[0]) + h_r = _centers_to_widths(b_e[right][:, 1] - mesh.nodes_y[0]) + b_l, b_r, _, __ = mesh.cell_boundary_indices + P_l = maps.Projection(mesh.n_cells, b_l) + P_r = maps.Projection(mesh.n_cells, b_r) + + self._b_inds = (left, right, bot, top) + self._P_l = P_l + self._P_r = P_r + + map_l_kwargs = {} + map_r_kwargs = {} + if self.sigmaMap is not None: + map_l_kwargs["sigmaMap"] = P_l * self.sigmaMap + map_r_kwargs["sigmaMap"] = P_r * self.sigmaMap + if self.muiMap is not None: + map_l_kwargs["muiMap"] = P_l * self.muiMap + map_r_kwargs["muiMap"] = P_r * self.muiMap + + # create a survey with 1 source per frequency (no receivers) + frequencies = self.survey.frequencies + survey = Survey([Planewave([], freq) for freq in frequencies]) + self._sim_left = Simulation1DElectricField( + TensorMesh((h_l,), (mesh.nodes_y[0],)), + survey=survey, + solver=self.solver, + **map_l_kwargs, + ) + self._sim_right = Simulation1DElectricField( + TensorMesh((h_r,), (mesh.nodes_y[0],)), + survey=survey, + solver=self.solver, + **map_r_kwargs, + ) + else: + raise NotImplementedError( + f"Unable to infer 1D mesh from {type(mesh)}. You must supply custom" + " boundary conditions for the electric field." + ) + self._h_bc = None + else: + n_be = mesh.boundary_edges.shape[0] + for freq in self.survey.frequencies: + try: + h = h_bc[freq] + if len(h) != n_be: + raise ValueError( + f"Boundary condition item for frequency {freq} is incorrect length." + f" Should be the same length as number of boundary_edges, {n_be}, " + f" saw a length of {len(h)}" + ) + except TypeError: + raise TypeError( + "h_bc must be a dictionary of numpy arrays indexed by frequency." + ) + except IndexError: + raise TypeError( + "h_bc must be a dictionary of numpy arrays indexed by frequency. Did not" + f" find key {freq}." + ) + except KeyError: + raise KeyError( + "h_bc must be a dictionary of numpy arrays indexed by frequency. Did not" + f" find key {freq}." + ) + self._h_bc = h_bc + self._M_bc = mesh.boundary_edge_vector_integral + + def getA(self, freq): + r""" + System matrix + + .. math:: + + \mathbf{A} = + \mathbf{C}^\top \mathbf{M}^{cc}_{\mu} \mathbf{C} + + 1\omega \mathbf{M}^e_\sigma + + """ + C = self.mesh.edge_curl + Mcc_mui = self.MccMui + Me_sigma = self.MeSigma + + return C.T.tocsr() @ Mcc_mui @ C + 1j * omega(freq) * Me_sigma + + def getRHS(self, freq): + """ + Right hand side constructed using Dirichlet boundary conditions + """ + M_bc = self._M_bc + if self._h_bc is None: + # left and right have the same 1D survey + src = self._sim_left.survey.get_sources_by_frequency(freq)[0] + f_left, f_right = self.boundary_fields() + h_bc = np.zeros(M_bc.shape[1], dtype=complex) + left, right, bot, top = self._b_inds + h_bc[top] = 1.0 + h_bc[left] = f_left[src, "h"][:, 0] + h_bc[right] = f_right[src, "h"][:, 0] + else: + h_bc = self._h_bc[freq] + return 1j * omega(freq) * (M_bc @ h_bc) + + def getADeriv_sigma(self, freq, u, v, adjoint=False): + return 1j * omega(freq) * self.MeSigmaDeriv(u, v, adjoint=adjoint) + + def getADeriv_mui(self, freq, u, v, adjoint=False): + C = self.mesh.edge_curl + if adjoint: + return self.MccMuiDeriv(C * u, C * v, adjoint) + return C.T * self.MccMuiDeriv(C * u, v, adjoint) + + def getADeriv(self, freq, u, v, adjoint=False): + return self.getADeriv_sigma(freq, u, v, adjoint) + self.getADeriv_mui( + freq, u, v, adjoint + ) + + def getRHSDeriv(self, freq, src, v, adjoint=False): + if self._h_bc is not None: + return Zero() + M_bc = self._M_bc + f_left, f_right = self.boundary_fields() + left, right, _, __ = self._b_inds + src_1d = self._sim_left.survey.get_sources_by_frequency(freq)[0] + + # derivatives from the Jv func of the 1D sim + if not adjoint: + h_bc_dm_v = np.zeros(M_bc.shape[1], dtype=complex) + h_bc_dm_v[left] = f_left.field_deriv_m("h", freq, src_1d, v, adjoint=False) + h_bc_dm_v[right] = f_right.field_deriv_m( + "h", freq, src_1d, v, adjoint=False + ) + + return 1j * omega(freq) * (M_bc @ h_bc_dm_v) + else: + v_dm = M_bc.T @ v + v_left, v_right = v_dm[left], v_dm[right] + df_dmT = f_left.field_deriv_m("h", freq, src_1d, v_left, adjoint=True) + df_dmT += f_right.field_deriv_m("h", freq, src_1d, v_right, adjoint=True) + + return 1j * omega(freq) * df_dmT + + def boundary_fields(self, model=None): + "Returns the 1D field objects at the boundaries" + if getattr(self, "_boundary_fields", None) is None: + if model is None: + model = self.model + sim = self._sim_left + if self.muiMap is None: + try: + sim.mui = self._P_l @ self.mui + except Exception: + sim.mui = self.mui + if self.sigmaMap is None: + try: + sim.sigma = self._P_l @ self.sigma + except Exception: + sim.sigma = self.sigma + f_left = sim.fields(model) + + sim = self._sim_right + if self.muiMap is None: + try: + sim.mui = self._P_r @ self.mui + except Exception: + sim.mui = self.mui + if self.sigmaMap is None: + try: + sim.sigma = self._P_r @ self.sigma + except Exception: + sim.sigma = self.sigma + f_right = sim.fields(model) + + self._boundary_fields = (f_left, f_right) + return self._boundary_fields + + @property + def _delete_on_model_update(self): + items = super()._delete_on_model_update + items.append("_boundary_fields") + return items + + +class Simulation2DMagneticField(BaseFDEMSimulation): + """ + A + """ + + _solutionType = "hSolution" + _formulation = "HJ" + fieldsPair = Fields2DMagneticField + + def __init__(self, mesh, e_bc=None, **kwargs): + if mesh.dim != 2: + raise ValueError( + f"The mesh must be a 2D mesh. The provided mesh has dimension {mesh.dim}" + ) + + super().__init__(mesh, **kwargs) + + for src in self.survey.source_list: + for rx in src.receiver_list: + if not ( + (rx.orientation == "yx" and isinstance(rx, Impedance)) + or (rx.orientation == "xy" and isinstance(rx, Admittance)) + or (rx.orientation == "zx" and isinstance(rx, Tipper)) + ): + raise TypeError( + "natural_source.Simulation2DMagneticField supports Impedance and" + " Admittance receivers for an yx orientation, and Tipper receivers" + " for a zx orientation. Please provide a survey with valid receivers." + ) + + if e_bc is None: + if isinstance(mesh, (TensorMesh, TreeMesh)): + b_e = mesh.boundary_edges + top = np.where(b_e[:, 1] == mesh.nodes_y[-1]) + bot = np.where(b_e[:, 1] == mesh.nodes_y[0]) + left = np.where(b_e[:, 0] == mesh.nodes_x[0]) + right = np.where(b_e[:, 0] == mesh.nodes_x[-1]) + + if isinstance(mesh, TensorMesh): + h_l = h_r = mesh.h[1] + is_b = np.zeros(mesh.shape_cells, dtype=bool) + is_b[0, :] = True + P_l = maps.Projection(mesh.n_cells, is_b.reshape(-1, order="F")) + is_b[0, :] = False + is_b[-1, :] = True + P_r = maps.Projection(mesh.n_cells, is_b.reshape(-1, order="F")) + else: + h_l = _centers_to_widths(b_e[left][:, 1] - mesh.nodes_y[0]) + h_r = _centers_to_widths(b_e[right][:, 1] - mesh.nodes_y[0]) + b_l, b_r, _, __ = mesh.cell_boundary_indices + P_l = maps.Projection(mesh.n_cells, b_l) + P_r = maps.Projection(mesh.n_cells, b_r) + + self._b_inds = (left, right, bot, top) + self._P_l = P_l + self._P_r = P_r + + map_l_kwargs = {} + map_r_kwargs = {} + if self.rhoMap is not None: + map_l_kwargs["rhoMap"] = P_l * self.rhoMap + map_r_kwargs["rhoMap"] = P_r * self.rhoMap + if self.muMap is not None: + map_l_kwargs["muMap"] = P_l * self.muMap + map_r_kwargs["muMap"] = P_r * self.muMap + + # create a survey with 1 source per frequency (no receivers) + frequencies = self.survey.frequencies + survey = Survey([Planewave([], freq) for freq in frequencies]) + self._sim_left = Simulation1DMagneticField( + TensorMesh((h_l,), (mesh.nodes_y[0],)), + survey=survey, + solver=self.solver, + **map_l_kwargs, + ) + self._sim_right = Simulation1DMagneticField( + TensorMesh((h_r,), (mesh.nodes_y[0],)), + survey=survey, + solver=self.solver, + **map_r_kwargs, + ) + else: + raise NotImplementedError( + f"Unable to infer 1D mesh from {type(mesh)}. You must supply custom" + " boundary conditions for the electric field." + ) + self._e_bc = None + else: + n_be = mesh.boundary_edges.shape[0] + for freq in self.survey.frequencies: + try: + e = e_bc[freq] + if len(e) != n_be: + raise ValueError( + f"Boundary condition item for frequency {freq} is incorrect length." + f" Should be the same length as number of boundary_edges, {n_be}, " + f" saw a length of {len(e)}" + ) + except TypeError: + raise TypeError( + "e_bc must be a dictionary of numpy arrays indexed by frequency." + ) + except IndexError: + raise TypeError( + "e_bc must be a dictionary of numpy arrays indexed by frequency." + ) + except KeyError: + raise KeyError( + "e_bc must be a dictionary of numpy arrays indexed by frequency. Did not" + f" find key {freq}." + ) + self._e_bc = e_bc + self._M_bc = mesh.boundary_edge_vector_integral + + def getA(self, freq): + r""" + System matrix + + .. math:: + + \mathbf{A} = + \mathbf{C}^\top \mathbf{M}^{cc}_{\rho} \mathbf{C} + + 1\omega \mathbf{M}^e_\mu + """ + C = self.mesh.edge_curl + Mcc_rho = self.MccRho + Me_mu = self.MeMu + + return C.T.tocsr() @ Mcc_rho @ C + 1j * omega(freq) * Me_mu + + def getRHS(self, freq): + """ + Right hand side constructed using Dirichlet boundary conditions + """ + M_bc = self._M_bc + if self._e_bc is None: + # left and right have the same 1D survey + src = self._sim_left.survey.get_sources_by_frequency(freq)[0] + f_left, f_right = self.boundary_fields() + e_bc = np.zeros(M_bc.shape[1], dtype=complex) + left, right, bot, top = self._b_inds + e_bc[top] = 1.0 + e_bc[left] = f_left[src, "e"][:, 0] + e_bc[right] = f_right[src, "e"][:, 0] + else: + e_bc = self._e_bc[freq] + return -M_bc @ e_bc + + def getADeriv_rho(self, freq, u, v, adjoint=False): + C = self.mesh.edge_curl + if adjoint: + return self.MccRhoDeriv(C * u, C * v, adjoint) + return C.T * self.MccRhoDeriv(C * u, v, adjoint) + + def getADeriv_mu(self, freq, u, v, adjoint=False): + return 1j * omega(freq) * self.MeMuDeriv(u, v, adjoint=adjoint) + + def getADeriv(self, freq, u, v, adjoint=False): + return self.getADeriv_rho(freq, u, v, adjoint) + self.getADeriv_mu( + freq, u, v, adjoint + ) + + def getRHSDeriv(self, freq, src, v, adjoint=False): + if self._e_bc is not None: + return Zero() + M_bc = self._M_bc + f_left, f_right = self.boundary_fields() + left, right, _, __ = self._b_inds + src_1d = self._sim_left.survey.get_sources_by_frequency(freq)[0] + + # derivatives from the Jv func of the 1D sim + if not adjoint: + e_bc_dm_v = np.zeros(M_bc.shape[1], dtype=complex) + e_bc_dm_v[left] = f_left.field_deriv_m("e", freq, src_1d, v, adjoint=False) + e_bc_dm_v[right] = f_right.field_deriv_m( + "e", freq, src_1d, v, adjoint=False + ) + return -(M_bc @ e_bc_dm_v) + else: + v_dm = -(M_bc.T @ v) + v_left, v_right = v_dm[left], v_dm[right] + df_dmT = f_left.field_deriv_m("e", freq, src_1d, v_left, adjoint=True) + df_dmT += f_right.field_deriv_m("e", freq, src_1d, v_right, adjoint=True) + return df_dmT + + def boundary_fields(self, model=None): + "Returns the 1D field objects at the boundaries" + if getattr(self, "_boundary_fields", None) is None: + if model is None: + model = self.model + sim = self._sim_left + if self.muMap is None: + try: + sim.mu = self._P_l @ self.mu + except Exception: + sim.mu = self.mu + if self.rhoMap is None: + try: + sim.rho = self._P_l @ self.rho + except Exception: + sim.rho = self.rho + f_left = sim.fields(model) + + sim = self._sim_right + if self.muMap is None: + try: + sim.mu = self._P_r @ self.mu + except Exception: + sim.mu = self.mu + if self.rhoMap is None: + try: + sim.rho = self._P_r @ self.rho + except Exception: + sim.rho = self.rho + f_right = sim.fields(model) + + self._boundary_fields = (f_left, f_right) + return self._boundary_fields + + @property + def _delete_on_model_update(self): + items = super()._delete_on_model_update + items.append("_boundary_fields") + return items + + +################################### +# 3D problems +################################### + + +class Simulation3DPrimarySecondary(Simulation3DElectricField): + r""" + A NSEM problem solving a e formulation and a primary/secondary fields decomposition. + + By eliminating the magnetic flux density using + + .. math :: + + \mathbf{b} = \frac{1}{i \omega} \left(-\mathbf{C} \mathbf{e} \right) + + + we can write Maxwell's equations as a second order system in + :math:`\mathbf{e}` only: + + .. math :: + + \left[ + \mathbf{C}^{\top} \mathbf{M_{\mu^{-1}}^f} \mathbf{C} + + i \omega \mathbf{M_{\sigma}^e} + \right] + \mathbf{e}_{s} + = i \omega \mathbf{M_{\sigma_{p}}^e} \mathbf{e}_{p} + + which we solve for :math:`\mathbf{e_s}`. + The total field :math:`\mathbf{e} = \mathbf{e_p} + \mathbf{e_s}`. + + The primary field is estimated from a background model (commonly as a 1D model). + """ + + def __init__(self, mesh, survey=None, sigmaPrimary=None, **kwargs): + super().__init__(mesh=mesh, survey=survey, **kwargs) + self.sigmaPrimary = sigmaPrimary + + # fieldsPair = Fields3DPrimarySecondary + + @property + def sigmaPrimary(self): + """ + A background model, use for the calculation of the primary fields. + + """ + return self._sigmaPrimary + + @sigmaPrimary.setter + def sigmaPrimary(self, val): + # Note: TODO add logic for val, make sure it is the correct size. + self._sigmaPrimary = val diff --git a/simpeg/electromagnetics/natural_source/simulation_1d.py b/simpeg/electromagnetics/natural_source/simulation_1d.py index 56325e8945..0e8609db09 100644 --- a/simpeg/electromagnetics/natural_source/simulation_1d.py +++ b/simpeg/electromagnetics/natural_source/simulation_1d.py @@ -1,3 +1,5 @@ +"""Recursive 1D simulation class.""" + import numpy as np from scipy.constants import mu_0 @@ -5,6 +7,7 @@ from ... import props from ...utils import validate_type from ..frequency_domain.survey import Survey +from .sources import Planewave from .receivers import Impedance @@ -58,6 +61,7 @@ def __init__( **kwargs, ): super().__init__(survey=survey, **kwargs) + self.fix_Jmatrix = fix_Jmatrix self.sigma = sigma self.rho = rho @@ -80,14 +84,33 @@ def survey(self): @survey.setter def survey(self, value): + """Define the survey.""" if value is not None: value = validate_type("survey", value, Survey, cast=False) for src in value.source_list: + if not isinstance(src, Planewave): + raise NotImplementedError( + ( + "Simulation1DRecursive defines sources using the " + f"Planewave class, got {type(src)} instead." + ) + ) for rx in src.receiver_list: if not isinstance(rx, Impedance): raise NotImplementedError( - f"{type(self).__name__} does not support {type(rx).__name__} receivers, only implemented for 'Impedance'." + ( + "Simulation1DRecursive only supports the Impedance " + f"receiver class, got {type(rx)} instead." + ) + ) + if (rx.orientation != "xy") and (rx.orientation != "yx"): + raise NotImplementedError( + ( + "Simulation1DRecursive only allows 'xy' or 'yx' for the " + f"orientation property of Impedance receivers, got {rx.orientation}." + ) ) + self._survey = value @property @@ -151,20 +174,20 @@ def _get_recursive_impedances_deriv(self, frequencies, thicknesses, sigmas): Parameters ---------- frequencies : (n_freq, ) np.ndarray - Frequencies in Hz + Frequencies in Hz. thicknesses : (n_layer-1, ) np.ndarray - Layer thicknesses in meters, starting from the bottom + Layer thicknesses in meters, starting from the bottom. sigmas : (n_layer, ) np.ndarray - Layer conductivities in S/m, starting from the bottom + Layer conductivities in S/m, starting from the bottom. Returns ------- Z : (n_freq, ) np.ndarray - Complex impedance at surface + Complex impedance at surface. Z_dsigma : (n_freq, n_layer) np.ndarray - Derivative of complex impedances at surface with respect to sigma + Derivative of complex impedances at surface with respect to sigma. Z_dsigma : (n_freq, n_layer-1) np.ndarray - Derivative of complex impedances at surface with respect to thicknesses + Derivative of complex impedances at surface with respect to thicknesses. """ frequencies = np.asarray(frequencies) thicknesses = np.asarray(thicknesses)[::-1] @@ -220,12 +243,7 @@ def fields(self, m): return None def dpred(self, m, f=None): - """ - Computes the data for a given 1D model. - - :param np.array m: inversion model (nP,) - :return np.array f: data (nD,) - """ + # Inherited self.model = m # Compute complex impedances for each frequency= @@ -238,17 +256,33 @@ def dpred(self, m, f=None): for src in self.survey.source_list: i_freq = np.searchsorted(self.survey.frequencies, src.frequency) for rx in src.receiver_list: + + if rx.orientation == "xy": + pm = 1 + elif rx.orientation == "yx": + pm = -1 + else: + msg = ( + f"Invalid receiver orientation '{rx.orientation}' " + f"for receiver '{rx}'. " + "Only 'xy' and 'yx' orientations are supported for " + f"the {type(self).__name__} class." + ) + raise ValueError(msg) + if rx.component == "real": - d.append(np.real(Z[i_freq])) + d.append(pm * np.real(Z[i_freq])) elif rx.component == "imag": - d.append(np.imag(Z[i_freq])) + d.append(pm * np.imag(Z[i_freq])) elif rx.component == "apparent_resistivity": d.append( np.abs(Z[i_freq]) ** 2 / (2 * np.pi * src.frequency * mu_0) ) elif rx.component == "phase": d.append( - (180.0 / np.pi) * np.arctan2(Z[i_freq].imag, Z[i_freq].real) + pm + * (180.0 / np.pi) + * np.arctan2(Z[i_freq].imag, Z[i_freq].real) ) return np.array(d) @@ -283,10 +317,24 @@ def getJ(self, m, f=None): i_freq = np.searchsorted(self.survey.frequencies, src.frequency) Js_row = Js[i_freq] for rx in src.receiver_list: + + if rx.orientation == "xy": + pm = 1 + elif rx.orientation == "yx": + pm = -1 + else: + msg = ( + f"Invalid receiver orientation '{rx.orientation}' " + f"for receiver '{rx}'. " + "Only 'xy' and 'yx' orientations are supported for " + f"the {type(self).__name__} class." + ) + raise ValueError(msg) + if rx.component == "real": - Jrows = np.real(Js_row) + Jrows = pm * np.real(Js_row) elif rx.component == "imag": - Jrows = np.imag(Js_row) + Jrows = pm * np.imag(Js_row) elif rx.component == "apparent_resistivity": Jrows = (np.pi * src.frequency * mu_0) ** -1 * ( np.real(Z[i_freq]) * np.real(Js_row) @@ -299,7 +347,7 @@ def getJ(self, m, f=None): bot = real**2 + imag**2 d_real_dm = np.real(Js_row) d_imag_dm = np.imag(Js_row) - Jrows = C * (-imag / bot * d_real_dm + real / bot * d_imag_dm) + Jrows = pm * C * (-imag / bot * d_real_dm + real / bot * d_imag_dm) end = start + rx.nD J[start:end] = Jrows start = end diff --git a/simpeg/electromagnetics/natural_source/sources.py b/simpeg/electromagnetics/natural_source/sources.py index 83aeed5742..17b08f7c85 100644 --- a/simpeg/electromagnetics/natural_source/sources.py +++ b/simpeg/electromagnetics/natural_source/sources.py @@ -3,16 +3,19 @@ from ... import maps from ..frequency_domain.sources import BaseFDEMSrc from ..utils import omega -from .utils.source_utils import homo1DModelSource +from .utils.source_utils import ( + primary_e_1d_solution, + project_1d_fields_to_mesh_edges, +) import discretize from discretize.utils import volume_average - ################# # Sources # ################# +# Rename to BasePlanewave class Planewave(BaseFDEMSrc): """ Source class for the 1D and pseudo-3D problems. @@ -30,7 +33,7 @@ class Planewave(BaseFDEMSrc): # Need to implement such that it works for all dims. -# Rename to be more descriptive +# Rename to be more descriptive (I suggest PlanewavePrimarySecondary) class PlanewaveXYPrimary(Planewave): """ NSEM planewave source for both polarizations (x and y) @@ -71,12 +74,13 @@ def _get_sigmas(self, simulation): mesh3d.h[-1], ] mesh1d = discretize.TensorMesh(hs, x0=x0) - if len(self._sigma_primary) == mesh3d.nC: + n_sigma = np.size(self._sigma_primary) + if n_sigma == mesh3d.nC: # volume average down to 1D mesh self._sigma1d = np.exp( volume_average(mesh3d, mesh1d, np.log(self._sigma_primary)) ) - elif len(self._sigma_primary) == mesh1d.nC: + elif n_sigma == mesh1d.nC: self._sigma1d = self._sigma_primary else: self._sigma1d = np.ones(mesh1d.nC) * self._sigma_primary @@ -106,9 +110,14 @@ def ePrimary(self, simulation): """ if self._ePrimary is None: sigma_1d, _ = self._get_sigmas(simulation) - self._ePrimary = homo1DModelSource( - simulation.mesh, self.frequency, sigma_1d - ) + e_1d = primary_e_1d_solution(simulation.mesh, sigma_1d, self.frequency) + e_1d = project_1d_fields_to_mesh_edges(simulation.mesh, e_1d) + + # To output X and Y polarization for 1D mesh + if simulation.mesh.dim == 1: + e_1d = np.c_[e_1d, -e_1d] + + self._ePrimary = e_1d return self._ePrimary def bPrimary(self, simulation): diff --git a/simpeg/electromagnetics/natural_source/utils/__init__.py b/simpeg/electromagnetics/natural_source/utils/__init__.py index 285ec2731b..df6a30e37e 100644 --- a/simpeg/electromagnetics/natural_source/utils/__init__.py +++ b/simpeg/electromagnetics/natural_source/utils/__init__.py @@ -1,4 +1,4 @@ -""" module simpeg.EM.NSEM.Utils +"""module simpeg.EM.NSEM.Utils Collection of utilities that are usefull for the NSEM problem @@ -7,6 +7,11 @@ """ from .solutions_1d import get1DEfields # Add the names of the functions +from .source_utils import ( + primary_e_1d_solution, + primary_h_1d_solution, + project_1d_fields_to_mesh_edges, +) from .analytic_1d import getEHfields, getImpedance from .data_utils import ( appResPhs, diff --git a/simpeg/electromagnetics/natural_source/utils/plot_utils.py b/simpeg/electromagnetics/natural_source/utils/plot_utils.py index c608940fec..5ba591866f 100644 --- a/simpeg/electromagnetics/natural_source/utils/plot_utils.py +++ b/simpeg/electromagnetics/natural_source/utils/plot_utils.py @@ -5,7 +5,6 @@ from ...utils import omega from ....utils import validate_type, validate_list_of_types - # Define the default component dictionaries DEFAULT_COMP_DICT = { "xx": {"color": "green", "label": "Imp_xx", "marker": "_", "ls": "None"}, diff --git a/simpeg/electromagnetics/natural_source/utils/source_utils.py b/simpeg/electromagnetics/natural_source/utils/source_utils.py index 822c04d2c5..e2fab2def3 100644 --- a/simpeg/electromagnetics/natural_source/utils/source_utils.py +++ b/simpeg/electromagnetics/natural_source/utils/source_utils.py @@ -1,185 +1,389 @@ +""" +Utility functions for NSEM sources. +""" + import numpy as np -import discretize +from scipy.constants import mu_0 +import scipy.sparse as sp +from discretize import TensorMesh -from ....utils import mkvc -from .solutions_1d import get1DEfields +from ...utils import omega +from ....utils import get_default_solver +from .analytic_1d import getEHfields -def homo1DModelSource(mesh, freq, sigma_1d): - """ - Function that calculates and return background fields +def primary_e_1d_solution( + mesh, + sigma_1d, + freq, + top_bc="dirichlet", + bot_bc="robin", + skin_depth_factor=3.0, +): + r"""Compute 1D electric field solution on nodes. + + Parameters + ---------- + mesh : discretize.base.BaseTensorMesh + A 1d, 2d or 3d tensor mesh or tree mesh. + sigma_1d : array + 1D conductivity model defined along the vertical discretization. + Conductivities are defined from the bottom cell upwards. + freq : float + Operating frequency in Hz. + top_bc : string {"dirichlet", "neumann"} + Use "dirichlet" for a solution where the electric field is equal + to 1 at the top of the mesh. Use "neumann" to implement a boundary + condition such that the magnetic field is equal to 1 at the top of + the mesh. + bot_bc : string {"dirichlet", "robin"} + Assumes only a downgoing wave at the bottom boundary. Use "dirichlet" + to set the value directly from the semi-analytic propagator matrix + solution. Use "robin" to set the boundary condition discretely. + skin_depth_factor : float + Number of additional skin depths added to the bottom of the 1D mesh + where the discrete solution is solved. + + Returns + ------- + numpy.ndarray (n_edges,) + Total electric field solution on the nodes of the 1D vertical + discretization. + + Notes + ----- + For the 1D electric field solution, Maxwell's equations take the form: + + .. math:: + \begin{align} + &\frac{\partial e_x}{\partial z} + i\omega b_y = 0 \\ + &\frac{\partial (\mu^{-1}b_y}{\partial z} + \sigma e_x = 0 + \end{align} + + We take the inner product of Faraday's law with a test function $\phi$, + and the inner product of Ampere's law with a test function $\psi$. + + .. math:: + \begin{align} + &\langle \phi , \partial_z e_x \rangle + + i\omega \langle \phi , b_y \rangle = 0 \\ + &\langle \psi , \partial_z (\mu^{-1}b_y) \rangle + + \langle \psi, \sigma e \rangle = 0 + \end{align} - :param discretize.base.BaseMesh mesh: Holds information on the discretization - :param float freq: The frequency to solve at - :param numpy.ndarray sigma_1d: Background model of conductivity to base the calculations on, 1d model. - :rtype: numpy.ndarray - :return: eBG_bp, E fields for the background model at both polarizations with shape (mesh.nE, 2). + We multiply Ampere's law by :math:`i\omega` and integrate by parts. Using + Faraday's law to express the surface integral in terms of the electric field + we obtain: + .. math:: + - i\omega \langle \partial_z \psi , \mu^{-1}b_y \rangle + - \int_{\partial \Omega }\psi \mu^{-1} \partial_z \, e_x \, da + + i\omega \langle \psi, \sigma e_x \rangle = 0 + + In discrete form, we obtain the following equations: + + .. math:: + \begin{align} + & \boldsymbol{\phi}^T \mathbf{M_f G_n e} + = - i\omega \phi^T \mathbf{M_f b} \\ + &-i \omega \boldsymbol{\psi}^T \mathbf{G_n^T M_{\frac{1}{\mu}} b} + + i \omega \boldsymbol{\psi}^T \mathbf{M_\sigma e} + - \boldsymbol{\psi}^T (\mathbf{B \, e + q}) = 0 + \end{align} + + Combining these equations, we obtain the following linear system for + computing the electric fields on mesh nodes: + + .. math:: + \big [ \mathbf{G_n^T M_{\frac{1}{\mu}} G_n} + + i \omega \mathbf{M_\sigma - B }\big ] \mathbf{e} + = \mathbf{q} + + where matrix :math:`\mathbf{B}` and vector :math:`\mathbf{q}` are used to + impose boundary conditions. """ + # Extract vertical discretization + hz = mesh.h[-1] - # Get a 1d solution for a halfspace background - if mesh.dim == 1: - mesh1d = mesh + if len(hz) != len(sigma_1d): + raise ValueError( + "Number of cells in vertical direction must match length of " + f"'sigma_1d'. Here hz has length {len(hz)} and sigma_1d has " + f"length {len(sigma_1d)}" + ) + + # Generate extended 1D mesh and conductivity model to solve 1D problem + skin_depth = np.sqrt(2 / (omega(freq) * mu_0 * sigma_1d[0])) + n_pad = int(np.ceil(skin_depth_factor * skin_depth / hz[0])) + + hz_ext = np.pad(hz, (n_pad, 0), mode="edge") + mesh_ext = TensorMesh([hz_ext], origin=[mesh.origin[-1] - hz[0] * n_pad]) + sigma_1d_ext = np.pad(sigma_1d, (n_pad, 0), mode="edge") + + # Generate the system matrix + G = mesh_ext.nodal_gradient + M_e_mui = mesh_ext.get_edge_inner_product(mu_0, invert_model=True) + M_f_sigma = mesh_ext.get_face_inner_product(sigma_1d_ext) + + w = 2 * np.pi * freq + A = G.T @ M_e_mui @ G + 1j * w * M_f_sigma + + fixed_nodes = np.zeros(mesh_ext.n_nodes, dtype=bool) + e_fixed = [] + q = np.zeros(mesh_ext.n_nodes, dtype=np.complex128) + + # Bottom BC + if bot_bc == "dirichlet": + e_d, e_u, h_d, h_u = getEHfields(mesh_ext, sigma_1d_ext, freq, mesh.nodes_x) + e_tot = e_d + e_u + e_tot /= e_tot[-1] + fixed_nodes[0] = True + e_fixed.append(e_tot[0]) + elif bot_bc == "robin": + k_bot = np.sqrt(-1.0j * w * mu_0 * sigma_1d_ext[0]) + A[0, 0] += 1j * k_bot / mu_0 else: - mesh1d = discretize.TensorMesh([mesh.h[-1]], [mesh.x0[-1]]) + msg = ( + f"Invalid 'bot_bc' equal to '{bot_bc}'. " + "It must be one of {'dirichlet', 'robin'}." + ) + raise ValueError(msg) - # Note: Everything is using e^iwt - e0_1d = get1DEfields(mesh1d, sigma_1d, freq) - if mesh.dim == 1: - eBG_px = mkvc(e0_1d, 2) - eBG_py = -mkvc( - e0_1d, 2 - ) # added a minus to make the results in the correct quadrents. - elif mesh.dim == 2: - ex_px = np.zeros(mesh.vnEx, dtype=complex) - ey_px = np.zeros((mesh.nEy, 1), dtype=complex) - for i in np.arange(mesh.vnEx[0]): - ex_px[i, :] = -e0_1d - eBG_px = np.vstack((mkvc(ex_px, 2), ey_px)) - # Setup y (north) polarization (_py) - ex_py = np.zeros((mesh.nEx, 1), dtype="complex128") - ey_py = np.zeros(mesh.vnEy, dtype="complex128") - # Assign the source to ey_py - for i in np.arange(mesh.vnEy[0]): - ey_py[i, :] = e0_1d - # ey_py[1:-1, 1:-1, 1:-1] = 0 - eBG_py = np.vstack((ex_py, mkvc(ey_py, 2))) - elif mesh.dim == 3: - # us the z component of ex_grid as lookup for solution - edges_u, inv_edges = np.unique(mesh.gridEx[:, -1], return_inverse=True) - map_to_edge_u = np.where(np.isclose(mesh1d.gridN, edges_u[:, None], atol=0.0))[ - 1 - ] - ex_px = -e0_1d[map_to_edge_u][inv_edges] - ey_px = np.zeros(mesh.nEy, dtype=complex) - ez_px = np.zeros(mesh.nEz, dtype=complex) - eBG_px = np.r_[ex_px, ey_px, ez_px][:, None] - - edges_u, inv_edges = np.unique(mesh.gridEy[:, -1], return_inverse=True) - map_to_edge_u = np.where(np.isclose(mesh1d.gridN, edges_u[:, None], atol=0.0))[ - 1 - ] - ex_py = np.zeros(mesh.nEx, dtype=complex) - ey_py = e0_1d[map_to_edge_u][inv_edges] - ez_py = np.zeros(mesh.nEz, dtype=complex) - eBG_py = np.r_[ex_py, ey_py, ez_py][:, None] - - # Return the electric fields - eBG_bp = np.hstack((eBG_px, eBG_py)) - return eBG_bp - - -def analytic1DModelSource(mesh, freq, sigma_1d): + # Top BC + if top_bc == "dirichlet": + fixed_nodes[-1] = True + e_fixed.append(1.0) + elif top_bc == "neumann": + q[-1] = -1j * w + else: + msg = ( + f"Invalid 'top_bc' equal to '{top_bc}'. " + "It must be one of {'dirichlet', 'neumann'}." + ) + raise ValueError(msg) + + P_fixed = sp.eye(mesh_ext.n_nodes, format="csc")[:, fixed_nodes] + P_free = sp.eye(mesh_ext.n_nodes, format="csc")[:, ~fixed_nodes] + q_free = P_free.T @ (q - A @ (P_fixed @ e_fixed)) + A_free = P_free.T @ A @ P_free + + Ainv = get_default_solver()(A_free) + e_1d = P_free @ (Ainv @ q_free) + P_fixed @ e_fixed + + if n_pad != 0: + e_1d = e_1d[n_pad:] + return e_1d + + +def primary_h_1d_solution( + mesh, + sigma_1d, + freq, + top_bc="dirichlet", + bot_bc="robin", + skin_depth_factor=3.0, +): + r"""Compute 1D magnetic field solution on nodes. + + Parameters + ---------- + mesh : discretize.base.BaseTensorMesh + A 1d, 2d or 3d tensor mesh or tree mesh. + sigma_1d : array + 1D conductivity model defined along the vertical discretization. + Conductivities are defined from the bottom cell upwards. + freq : float + Operating frequency in Hz. + top_bc : string {"dirichlet", "neumann"} + Use "dirichlet" for a solution where the magnetic field is equal + to 1 at the top of the mesh. Use "neumann" to implement a boundary + condition such that the electric field is equal to 1 at the top of + the mesh. + bot_bc : string {"dirichlet", "robin"} + Assumes only a downgoing wave at the bottom boundary. Use "dirichlet" + to set the value directly from the semi-analytic propagator matrix + solution. Use "robin" to set the boundary condition discretely. + skin_depth_factor : float + Number of additional skin depths added to the bottom of the 1D mesh + where the discrete solution is solved. + + Returns + ------- + numpy.ndarray (n_edges,) + Total magnetic field solution on the nodes of the 1D vertical + discretization. + + Notes + ----- + For the 1D magnetic field solution, Maxwell's equations take the form: + + .. math:: + \begin{align} + &\frac{\partial (\rho j_y)}{\partial z} - i\omega \mu h_x = 0 \\ + &\frac{\partial h_x}{\partial z} - j_y = 0 + \end{align} + + We take the inner product of Faraday's law with a test function $\phi$, + and the inner product of Ampere's law with a test function $\psi$. + + .. math:: + \begin{align} + &\langle \phi , \partial_z (\rho j_y) \rangle + - i\omega \langle \phi , \mu h_x \rangle = 0 \\ + &\langle \psi , \partial_z h_x \rangle + - \langle \psi, j_y \rangle = 0 + \end{align} + + We integrate Ampere's law by parts, the use Faraday's law to represent the + surface integral in terms of the magnetic field: + + .. math:: + -\langle \partial_z \phi , \rho \, j_y \rangle + + \int_{\partial \Omega} \, \phi \rho \partial_z h_x \, da + - i\omega \langle \phi , \mu h_x \rangle = 0 + + In discrete form, we obtain the following equations: + + .. math:: + \begin{align} + & \mathbf{\phi^T G_n^T \, M_\rho \, j} + + i\omega \phi^T \mathbf{M_\mu \, h} + - \phi^T (\mathbf{B \, h + q}) = 0 \\ + & \mathbf{\psi^T M_f G_n \, h} = \mathbf{\psi^T M_f j} + \end{align} + + Combining these equations, we obtain the following linear system for + computing the electric fields on mesh nodes: + + .. math:: + \big [ \mathbf{G_n^T M_\rho G_n} + + i \omega\mathbf{M_\mu} + - \mathbf{B} \big ] \mathbf{h} + = \mathbf{q} + + where matrix :math:`\mathbf{B}` and vector :math:`\mathbf{q}` are used to + impose boundary conditions. """ - Function that calculates and return background fields + # Extract vertical discretization + hz = mesh.h[-1] + + if len(hz) != len(sigma_1d): + raise ValueError( + "Number of cells in vertical direction must match length of " + f"'sigma_1d'. Here hz has length {len(hz)} and sigma_1d has " + f"length {len(sigma_1d)}" + ) + + # Generate extended 1D mesh and resistivity model to solve 1D problem + skin_depth = np.sqrt(2 / (omega(freq) * mu_0 * sigma_1d[0])) + n_pad = int(np.ceil(skin_depth_factor * skin_depth / hz[0])) + + hz_ext = np.pad(hz, (n_pad, 0), mode="edge") + mesh_ext = TensorMesh([hz_ext], origin=[mesh.origin[-1] - hz[0] * n_pad]) + sigma_1d_ext = np.pad(sigma_1d, (n_pad, 0), mode="edge") + + # Generate the system matrix + G = mesh_ext.nodal_gradient + M_e_rho = mesh_ext.get_edge_inner_product(sigma_1d_ext, invert_model=True) + M_f_mu = mesh_ext.get_face_inner_product(mu_0) + + w = 2 * np.pi * freq + A = G.T @ M_e_rho @ G + 1j * w * M_f_mu + + fixed_nodes = np.zeros(mesh_ext.n_nodes, dtype=bool) + h_fixed = [] + q = np.zeros(mesh_ext.n_nodes, dtype=np.complex128) + + # Bottom BC + if bot_bc == "dirichlet": + e_d, e_u, h_d, h_u = getEHfields(mesh_ext, sigma_1d_ext, freq, mesh.nodes_x) + h_tot = h_d + h_u + h_tot /= h_tot[-1] + fixed_nodes[0] = True + h_fixed.append(h_tot[0]) + elif bot_bc == "robin": + k_bot = np.sqrt(-1.0j * w * mu_0 * sigma_1d_ext[0]) + A[0, 0] += 1j * k_bot / sigma_1d[0] + else: + msg = ( + f"Invalid 'bot_bc' equal to '{bot_bc}'. " + "It must be one of {'dirichlet', 'robin'}." + ) + raise ValueError(msg) - :param discretize.base.BaseMesh mesh: Holds information on the discretization - :param float freq: The frequency to solve at - :param numpy.ndarray sigma_1d: Background model of conductivity to base the calculations on, 1d model. - :rtype: numpy.ndarray - :return: eBG_bp, E fields for the background model at both polarizations with shape (mesh.nE, 2). + # Top BC + if top_bc == "dirichlet": + fixed_nodes[-1] = True + h_fixed.append(1.0) + elif top_bc == "neumann": + q[-1] = 1.0 + else: + msg = ( + f"Invalid 'top_bc' equal to '{top_bc}'. " + "It must be one of {'dirichlet', 'neumann'}." + ) + raise ValueError(msg) + + P_fixed = sp.eye(mesh_ext.n_nodes, format="csc")[:, fixed_nodes] + P_free = sp.eye(mesh_ext.n_nodes, format="csc")[:, ~fixed_nodes] + q_free = P_free.T @ (q - A @ (P_fixed @ h_fixed)) + A_free = P_free.T @ A @ P_free + + Ainv = get_default_solver()(A_free) + h_1d = P_free @ (Ainv @ q_free) + P_fixed @ h_fixed + + if n_pad != 0: + h_1d = h_1d[n_pad:] + return h_1d + +def project_1d_fields_to_mesh_edges(mesh, u_1d): + """Project 1D nodal field solution to edges of a mesh. + + Parameters + ---------- + mesh : discretize.base.BaseTensorMesh + A 1d, 2d or 3d tensor mesh or tree mesh. + u_1d : np.ndarray + 1D field solution along the vertical discretization of the input mesh. + + Returns + ------- + numpy.ndarray (n_edges, n_polarization) + Fields on the edges of the mesh for each polarization. """ - from simpeg.NSEM.Utils import getEHfields + if len(u_1d) != (expected := len(mesh.h[-1]) + 1): + msg = ( + f"Found invalid 'u_1d' with '{len(u_1d)}' elements. " + f"It must match the number of vertical edges in the mesh ({expected})." + ) + raise ValueError(msg) - # Get a 1d solution for a halfspace background - if mesh.dim == 1: - mesh1d = mesh - elif mesh.dim == 2: - mesh1d = discretize.TensorMesh([mesh.h[1]], np.array([mesh.x0[1]])) - elif mesh.dim == 3: - mesh1d = discretize.TensorMesh([mesh.h[2]], np.array([mesh.x0[2]])) - - # # Note: Everything is using e^iwt - Eu, Ed, _, _ = getEHfields(mesh1d, sigma_1d, freq, mesh.nodes_z) - # Make the fields into a dictionary of location and the fields - e0_1d = Eu + Ed - E1dFieldDict = dict(zip(mesh.nodes_z, e0_1d)) if mesh.dim == 1: - eBG_px = mkvc(e0_1d, 2) - eBG_py = -mkvc( - e0_1d, 2 - ) # added a minus to make the results in the correct quadrents. - elif mesh.dim == 2: - ex_px = np.zeros(mesh.vnEx, dtype=complex) - ey_px = np.zeros((mesh.nEy, 1), dtype=complex) - for i in np.arange(mesh.vnEx[0]): - ex_px[i, :] = -e0_1d - eBG_px = np.vstack((mkvc(ex_px, 2), ey_px)) - # Setup y (north) polarization (_py) - ex_py = np.zeros((mesh.nEx, 1), dtype="complex128") - ey_py = np.zeros(mesh.vnEy, dtype="complex128") - # Assign the source to ey_py - for i in np.arange(mesh.vnEy[0]): - ey_py[i, :] = e0_1d - # ey_py[1:-1, 1:-1, 1:-1] = 0 - eBG_py = np.vstack((ex_py, mkvc(ey_py, 2))) - elif mesh.dim == 3: - # Setup x (east) polarization (_x) - ex_px = -np.array([E1dFieldDict[i] for i in mesh.gridEx[:, 2]]).reshape(-1, 1) - ey_px = np.zeros((mesh.nEy, 1), dtype=complex) - ez_px = np.zeros((mesh.nEz, 1), dtype=complex) - # Construct the full fields - eBG_px = np.vstack((ex_px, ey_px, ez_px)) - # Setup y (north) polarization (_py) - ex_py = np.zeros((mesh.nEx, 1), dtype="complex128") - ey_py = np.array([E1dFieldDict[i] for i in mesh.gridEy[:, 2]]).reshape(-1, 1) - ez_py = np.zeros((mesh.nEz, 1), dtype="complex128") - # Construct the full fields - eBG_py = np.vstack((ex_py, mkvc(ey_py, 2), ez_py)) - - # Return the electric fields - eBG_bp = np.hstack((eBG_px, eBG_py)) - return eBG_bp - - -# def homo3DModelSource(mesh, model, freq): -# """ -# Function that estimates 1D analytic background fields from a 3D model. - -# :param Simpeg mesh object mesh: Holds information on the discretization -# :param float freq: The frequency to solve at -# :param np.array sigma_1d: Background model of conductivity to base the calculations on, 1d model. -# :rtype: numpy.ndarray (mesh.nE, 2) -# :return: eBG_bp, E fields for the background model at both polarizations. - -# """ - -# if mesh.dim < 3: -# raise IOError('Input mesh has to have 3 dimensions.') - - -# # Get the locations -# a = mesh.gridCC[:, 0:2].copy() -# unixy = np.unique(a.view(a.dtype.descr * a.shape[1])).view(float).reshape(-1, 2) -# uniz = np.unique(mesh.gridCC[:, 2]) -# # # Note: Everything is using e^iwt -# # Need to loop thourgh the xy locations, assess the model and calculate the fields at the phusdo cell centers. -# # Then interpolate the cc fields to the edges. - -# e0_1d = get1DEfields(mesh1d, sigma_1d, freq) - -# elif mesh.dim == 3: -# # Setup x (east) polarization (_x) -# ex_px = np.zeros(mesh.vnEx, dtype=complex) -# ey_px = np.zeros((mesh.nEy, 1), dtype=complex) -# ez_px = np.zeros((mesh.nEz, 1), dtype=complex) -# # Assign the source to ex_x -# for i in np.arange(mesh.vnEx[0]): -# for j in np.arange(mesh.vnEx[1]): -# ex_px[i, j, :] = -e0_1d -# eBG_px = np.vstack((mkvc(ex_px, 2), ey_px, ez_px)) -# # Setup y (north) polarization (_py) -# ex_py = np.zeros((mesh.nEx, 1), dtype='complex128') -# ey_py = np.zeros(mesh.vnEy, dtype='complex128') -# ez_py = np.zeros((mesh.nEz, 1), dtype='complex128') -# # Assign the source to ey_py -# for i in np.arange(mesh.vnEy[0]): -# for j in np.arange(mesh.vnEy[1]): -# ey_py[i, j, :] = e0_1d -# # ey_py[1:-1, 1:-1, 1:-1] = 0 -# eBG_py = np.vstack((ex_py, mkvc(ey_py, 2), ez_py)) - -# # Return the electric fields -# eBG_bp = np.hstack((eBG_px, eBG_py)) -# return eBG_bp + return u_1d + + # Vertical 1D discretization + hz = mesh.h[-1] + mesh_1d = TensorMesh([hz], origin=[mesh.origin[-1]]) + + # Field polarized along x-direction + u_x = ( + mesh_1d.get_interpolation_matrix(mesh.edges_x[:, -1], location_type="nodes") + @ u_1d + ) + + if mesh.dim == 2: + return np.r_[u_x, np.zeros(mesh.n_edges_y)] + + else: + + # Field polarized along y-direction + u_y = ( + mesh_1d.get_interpolation_matrix(mesh.edges_y[:, 2], location_type="nodes") + @ u_1d + ) + + u_x = np.r_[u_x, np.zeros(mesh.n_edges_y + mesh.n_edges_z)] + u_y = np.r_[np.zeros(mesh.n_edges_x), u_y, np.zeros(mesh.n_edges_z)] + + return np.c_[u_x, u_y] diff --git a/simpeg/electromagnetics/natural_source/utils/test_utils.py b/simpeg/electromagnetics/natural_source/utils/test_utils.py index 88f8131db9..e9a0a54cec 100644 --- a/simpeg/electromagnetics/natural_source/utils/test_utils.py +++ b/simpeg/electromagnetics/natural_source/utils/test_utils.py @@ -236,7 +236,7 @@ def setupSimpegNSEM_tests_location_assign_list( # discretize.TensorMesh.write_UBC(mesh,'Mesh-pre.msh', models={'Sigma-pre.dat': np.exp(model_true)}) # create background conductivity model sigma_back = 1e-2 - sigBG = np.zeros(mesh.nC) * sigma_back + sigBG = np.full(mesh.nC, fill_value=sigma_back) sigBG[~active] = 1e-8 # Set the mapping @@ -357,7 +357,7 @@ def setupSimpegNSEM_PrimarySecondary(inputSetup, freqs, comp="Imp", singleFreq=F # discretize.TensorMesh.write_UBC(mesh,'Mesh-pre.msh', models={'Sigma-pre.dat': np.exp(model_true)}) # create background conductivity model sigma_back = 1e-2 - sigBG = np.zeros(mesh.nC) * sigma_back + sigBG = np.full(mesh.nC, fill_value=sigma_back) sigBG[~active] = 1e-8 # Set the mapping diff --git a/simpeg/electromagnetics/static/resistivity/__init__.py b/simpeg/electromagnetics/static/resistivity/__init__.py index 990c6367a4..3b76626452 100644 --- a/simpeg/electromagnetics/static/resistivity/__init__.py +++ b/simpeg/electromagnetics/static/resistivity/__init__.py @@ -15,6 +15,7 @@ Simulation2DNodal Simulation3DCellCentered Simulation3DNodal + Simulation3DHierarchicalNodal Receivers ========= @@ -72,7 +73,11 @@ receivers.BaseRx """ -from .simulation import Simulation3DCellCentered, Simulation3DNodal +from .simulation import ( + Simulation3DCellCentered, + Simulation3DNodal, + Simulation3DHierarchicalNodal, +) from .simulation_2d import Simulation2DCellCentered, Simulation2DNodal from .simulation_1d import Simulation1DLayers from .survey import Survey diff --git a/simpeg/electromagnetics/static/resistivity/receivers.py b/simpeg/electromagnetics/static/resistivity/receivers.py index 3607a4049b..ffeffe5ef6 100644 --- a/simpeg/electromagnetics/static/resistivity/receivers.py +++ b/simpeg/electromagnetics/static/resistivity/receivers.py @@ -184,9 +184,7 @@ def eval(self, src, mesh, f): # noqa: A003 if self.data_type == "apparent_resistivity": try: - if mesh.dim == 2: - return v / self.geometric_factor[src][:, None] - return v / self.geometric_factor[src] + return v / self.geometric_factor[src][:, None] except KeyError: raise KeyError( "Receiver geometric factor has not been set, please execute " diff --git a/simpeg/electromagnetics/static/resistivity/simulation.py b/simpeg/electromagnetics/static/resistivity/simulation.py index 150b5641a6..0409bf9f95 100644 --- a/simpeg/electromagnetics/static/resistivity/simulation.py +++ b/simpeg/electromagnetics/static/resistivity/simulation.py @@ -1,3 +1,5 @@ +"""3D DC resistivity simulation classes.""" + import numpy as np import scipy.sparse as sp @@ -9,7 +11,7 @@ validate_active_indices, ) from ....data import Data -from ....base import BaseElectricalPDESimulation +from ....base import BaseElectricalPDESimulation, BaseHierarchicalElectricalSimulation from ....base.pde_simulation import _inner_mat_mul_op from .survey import Survey from .fields import Fields3DCellCentered, Fields3DNodal @@ -18,15 +20,34 @@ class BaseDCSimulation(BaseElectricalPDESimulation): - """ - Base DC Problem + r"""Base class for 3D DC resistivity simulation. + + This class is used to define properties and methods necessary for solving the + 3D direct current resistivity problem using mimetic finite volume. The PDE we are + solving is given by: + + .. math:: + \nabla \cdot \sigma \nabla \phi = - I \delta (r) + + where we are solving for the electric potential :math:`\phi` is the electric potential. + The electrical conductivity is given by :math:`\sigma`, and :math:`I \delta (r)` + represents current *I* injected at point *r*. + Child classes of ``BaseDCSimulation`` solve the above expression numerically + for various cases using mimetic finite volume. + + Parameters + ---------- + mesh : discretize.base.BaseMesh + The mesh. + survey : .resistivity.survey.Survey + The DC resistivity survey. """ _mini_survey = None Ainv = None - def __init__( + def __init__( # noqa D107 self, mesh, survey=None, @@ -64,7 +85,7 @@ def survey(self, value): @property def storeJ(self): - """Whether to store the sensitivity matrix + """Whether to store the sensitivity matrix. Returns ------- @@ -78,7 +99,7 @@ def storeJ(self, value): @property def surface_faces(self): - """Array defining which boundary faces to interpret as surfaces of Neumann boundary + """Return which boundary faces to interpret as surfaces of Neumann boundary. DC problems will always enforce a Neumann boundary on surface interfaces. The default (available on semi-structured grids) assumes the top interface @@ -86,7 +107,7 @@ def surface_faces(self): Returns ------- - None or (n_bf, ) numpy.ndarray of bool + None or (n_bf,) numpy.ndarray of bool """ return self._surface_faces @@ -98,6 +119,18 @@ def surface_faces(self, value): self._surface_faces = value def fields(self, m=None, calcJ=True): + """Compute and return the fields for the model provided. + + Parameters + ---------- + m : (n_param,) numpy.ndarray + The model. + + Returns + ------- + .resistivity.fields.FieldsDC + The DC fields object. + """ if m is not None: self.model = m @@ -113,6 +146,28 @@ def fields(self, m=None, calcJ=True): return f def getJ(self, m, f=None): + r"""Compute the sensitivity matrix for a given model. + + Where :math:`\mathbf{d}` are the data, :math:`\mathbf{m}` are the model parameters, + and the sensitivity matrix is defined as: + + .. math:: + \mathbf{J} = \dfrac{\partial \mathbf{d}}{\partial \mathbf{m}} + + this method computes and returns the sensitivity matrix. + + Parameters + ---------- + m : (n_param,) numpy.ndarray + The model parameters. + f : .resistivity.fields.FieldsDC, optional + Fields solved for all sources. + + Returns + ------- + (n_data, n_param) numpy.ndarray + The sensitivity matrix times. + """ self.model = m if getattr(self, "_Jmatrix", None) is None: if f is None: @@ -120,7 +175,8 @@ def getJ(self, m, f=None): self._Jmatrix = self._Jtvec(m, v=None, f=f).T return self._Jmatrix - def dpred(self, m=None, f=None): + def dpred(self, m=None, f=None): # noqa D102 + # Docstring inherited from parent class. if self._mini_survey is not None: # Temporarily set self.survey to self._mini_survey survey = self.survey @@ -135,8 +191,30 @@ def dpred(self, m=None, f=None): return self._mini_survey_data(data) def getJtJdiag(self, m, W=None, f=None): - """ - Return the diagonal of JtJ + r"""Return the diagonal of JtJ. + + Where :math:`\mathbf{d}` are the data, :math:`\mathbf{m}` are the model parameters, + and the sensitivity matrix is defined as: + + .. math:: + \mathbf{J} = \dfrac{\partial \mathbf{d}}{\partial \mathbf{m}} + + this method computes and returns the diagonal elements + of :math:`\mathbf{J^T J}`. + + Parameters + ---------- + m : (n_param,) numpy.ndarray + The model parameters. + W : (n_param,) numpy.ndarray, optional + Cell weights. + f : .resistivity.fields.FieldsDC, optional + Fields solved for all sources. + + Returns + ------- + (n_param,) numpy.ndarray + The diagonal of :math:`\mathbf{J^T J}`. """ if getattr(self, "_jtjdiag", None) is None: J = self.getJ(m, f=f) @@ -154,8 +232,34 @@ def getJtJdiag(self, m, W=None, f=None): return self._jtjdiag def Jvec(self, m, v, f=None): - """ - Compute sensitivity matrix (J) and vector (v) product. + r"""Compute the sensitivity matrix times a vector. + + Where :math:`\mathbf{d}` are the data, :math:`\mathbf{m}` are the model parameters, + and the sensitivity matrix is defined as: + + .. math:: + \mathbf{J} = \dfrac{\partial \mathbf{d}}{\partial \mathbf{m}} + + this method computes and returns the matrix-vector product: + + .. math:: + \mathbf{J v} + + for a given vector :math:`v`. + + Parameters + ---------- + m : (n_param,) numpy.ndarray + The model parameters. + v : (n_param,) numpy.ndarray + The vector. + f : .resistivity.fields.FieldsDC, optional + Fields solved for all sources. + + Returns + ------- + (n_data,) numpy.ndarray + The sensitivity matrix times a vector. """ if f is None: f = self.fields(m) @@ -187,10 +291,35 @@ def Jvec(self, m, v, f=None): return self._mini_survey_data(Jv) def Jtvec(self, m, v, f=None): - """ - Compute adjoint sensitivity matrix (J^T) and vector (v) product. - """ + r"""Compute the adjoint sensitivity matrix times a vector. + + Where :math:`\mathbf{d}` are the data, :math:`\mathbf{m}` are the model parameters, + and the sensitivity matrix is defined as: + + .. math:: + \mathbf{J} = \dfrac{\partial \mathbf{d}}{\partial \mathbf{m}} + + this method computes and returns the matrix-vector product: + + .. math:: + \mathbf{J^T v} + + for a given vector :math:`v`. + Parameters + ---------- + m : (n_param,) numpy.ndarray + The model parameters. + v : (n_data,) numpy.ndarray + The vector. + f : .resistivity.fields.FieldsDC, optional + Fields solved for all sources. + + Returns + ------- + (n_param,) numpy.ndarray + The adjoint sensitivity matrix times a vector. + """ if f is None: f = self.fields(m) @@ -203,11 +332,11 @@ def Jtvec(self, m, v, f=None): return self._Jtvec(m, v=v, f=f) def _Jtvec(self, m, v=None, f=None): - """ - Compute adjoint sensitivity matrix (J^T) and vector (v) product. - Full J matrix can be computed by inputing v=None - """ + """Compute adjoint sensitivity matrix (J^T) and vector (v) product. + This method does the actual computation of J-transpose times a vector. + Or when *v* = ``None``, it returns the full transpose of the sensitivity matrix. + """ if self._mini_survey is not None: survey = self._mini_survey else: @@ -263,12 +392,15 @@ def _Jtvec(self, m, v=None, f=None): return (self._mini_survey_data(Jtv.T)).T def getSourceTerm(self): - """ - Evaluates the sources, and puts them in matrix form - :rtype: tuple - :return: q (nC or nN, nSrc) - """ + r"""Return the discrete source term for all sources. + Returns + ------- + numpy.ndarray + The source terms for number of unique source locations. + (n_cells, n_sources) for cell centered formulations. + (n_nodes, n_sources) for nodal formulations. + """ if getattr(self, "_q", None) is None: if self._mini_survey is not None: Srcs = self._mini_survey.source_list @@ -290,10 +422,21 @@ def getSourceTerm(self): @property def _delete_on_model_update(self): + """List of model-dependent attributes to clean upon model update. + + Some of the simulation's attributes are model-dependent. This property specifies + the model-dependent attributes that must be cleared when the model is updated. + + Returns + ------- + list of str + List of the model-dependent attributes to clean upon model update. + """ toDelete = super()._delete_on_model_update return toDelete + ["_Jmatrix", "_gtgdiag"] def _mini_survey_data(self, d_mini): + """Get mini survey data.""" if self._mini_survey is not None: out = d_mini[self._invs[0]] # AM out[self._dipoles[0]] -= d_mini[self._invs[1]] # AN @@ -304,6 +447,7 @@ def _mini_survey_data(self, d_mini): return out def _mini_survey_dataT(self, v): + """Get transpose of mini survey data.""" if self._mini_survey is not None: out = np.zeros(self._mini_survey.nD) # Need to use ufunc.at because there could be repeated indices @@ -319,15 +463,104 @@ def _mini_survey_dataT(self, v): class Simulation3DCellCentered(BaseDCSimulation): - """ - 3D cell centered DC problem + r"""3D cell centered DC resistivity simulation class. + + Where :math:`\phi` is the electric potential, :math:`\rho` is the electrical resistivity, + and :math:`I \delta (r)` represents a grounded source which injects static current *I* at + location *r*, the 3D DC resistivity problem is define according to the following PDE: + + .. math:: + \nabla \cdot \frac{1}{\rho} \nabla \phi = - I \delta (r) + + The ``Simulation3DCellCentered`` class uses the mimetic finite volume approach to solve for + the discrete electric potentials at cell centers. See the *Notes* section for a + comprehensive description of the formulation. + + Notes + ----- + To derive the discrete solution, we start by considering Ampere's law and Faraday's law. + In the static regime, all time-derivative are zero. By also taking the divergence of + Ampere's law, we obtain: + + .. math:: + &\nabla \times \vec{e} = 0\\ + &\nabla \cdot \vec{j} = - \nabla \cdot \vec{j}_s + + where :math:`\vec{e}` is the electric field, :math:`\vec{j}` is the current density outside + the grounded source and and :math:`\vec{j}_s` is the source current density. The constitutive + relation between the electric field and current density is given by Ohm's law: + + .. math:: + \vec{e} = \rho \vec{j} + + where :math:`\rho` is the electrical resistivity. + + Faraday's law implies the electric field can be defined as the gradient of a scalar + potential :math:`\phi` as follows: + + .. math:: + \vec{e} = -\nabla \phi + + For a source representing current *I* injected at point *r*, the static form of Ampere's + law becomes: + + .. math:: + \nabla \cdot \vec{j} = - I \delta (r) + + For a vector test function :math:`\vec{u}` and a scalar test function :math:`\psi`, we + take the inner products with the three previous equations. Through vector calculus + identities and the divergence theorem, we obtain: + + .. math:: + & \int_\Omega \vec{u} \cdot \vec{e} \, dv + = \int_\Omega \vec{u} \cdot \rho \vec{j} \, dv \\ + & \int_\Omega \psi ( \nabla \cdot \vec{j} ) \, dv = + - I \int_\Omega \psi \, \delta (r) \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{e} \, dv = + \int_\Omega (\nabla \cdot \vec{u}) \phi \, dv + - \oint_{\partial \Omega} (\vec{u} \cdot \hat{n} ) \, \phi \, da + + where the surface integral defines the boundary conditions. + + The above expressions are discretized in space according to the finite volume method. + The discrete current densities :math:`\mathbf{j}` are defined on mesh faces, + and the discrete electric potential :math:`\boldsymbol{\phi}` are defined at cell centers. + This implies :math:`\mathbf{u}` and :math:`\mathbf{e}` must be defined on mesh faces, + and :math:`\boldsymbol{\psi}` must be defined at cell centers. We obtain the following + set of discrete inner-products: + + .. math:: + &\mathbf{u^T M_f \, e} = \mathbf{u^T M_{f\rho} \, j} \\ + &\boldsymbol{\psi^T} \mathbf{M_c D j} = \boldsymbol{\psi^T} \mathbf{q} \\ + &\mathbf{u^T M_f e} = \mathbf{u^T (D^T - B ) M_c} \boldsymbol{\phi} + + where + + * :math:`\mathbf{D}` is the divergence operator (faces to cell centers) + * :math:`\mathbf{q}` is an integrated source term + * :math:`\mathbf{B}` is a matrix that implements boundary conditions + * :math:`\mathbf{M_c}` is the cell inner-product matrix + * :math:`\mathbf{M_f}` is the face inner-product matrix + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities + projected to faces + + By combining the discrete equations to form a discrete solution in terms of the + discrete electric potential on mesh nodes, we obtain: + + .. math:: + \big [ \mathbf{M_c D M_{f\rho}^{-1} (D^T - B ) M_c} \big ] \boldsymbol{\phi} + = \mathbf{q} + + Note that :math:`\mathbf{D^T - B}` is effectively a gradient operator that has been + modified to implement the boundary conditions. + """ _solutionType = "phiSolution" _formulation = "HJ" # CC potentials means J is on faces fieldsPair = Fields3DCellCentered - def __init__(self, mesh, survey=None, bc_type="Robin", **kwargs): + def __init__(self, mesh, survey=None, bc_type="Robin", **kwargs): # noqa D107 super().__init__(mesh=mesh, survey=survey, **kwargs) self.bc_type = bc_type self.setBC() @@ -353,11 +586,32 @@ def bc_type(self, value): ) def getA(self, resistivity=None): - """ - Make the A matrix for the cell centered DC resistivity problem - A = D MfRhoI G - """ + r"""Return the system matrix. + + This method generates and returns the system matrix for the cell-centered DC + resistivity problem. The system matrix is given by: + + .. math:: + \mathbf{A} = \mathbf{M_c D M_{f\rho} (G - B) M_c} + + where + + * :math:`\mathbf{D}` is the divergence operator (faces to cell centers) + * :math:`\mathbf{B}` is a matrix that implements boundary conditions + * :math:`\mathbf{M_c}` is the cell inner-product matrix + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities + projected to faces + Parameters + ---------- + resistivity : (n_cells,) numpy.ndarray + Electrical resistivities defined at cell centers + + Returns + ------- + (n_cells, n_cells) sp.sparse.csr_matrix + The system matrix. + """ D = self.Div G = self.Grad if resistivity is None: @@ -379,6 +633,55 @@ def getA(self, resistivity=None): return A def getADeriv(self, u, v, adjoint=False): + r"""Get resistivity derivative operation for the system matrix times a vector. + + The system matrix is given by: + + .. math:: + \mathbf{A} = \mathbf{M_c D M_{f\rho} (G - B) M_c} + + where + + * :math:`\mathbf{D}` is the divergence operator (faces to cell centers) + * :math:`\mathbf{B}` is a matrix that implements boundary conditions + * :math:`\mathbf{M_c}` is the cell inner-product matrix + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities + projected to faces + + See the *Notes* section of the doc strings for :class:`Simulation3DCellCentered` + for a full description of the formulation. + + Where :math:`\mathbf{m}` are the set of model parameters defining the + electromagnetic properties :math:`\mathbf{v}` is a vector and + :math:`\boldsymbol{\phi}` is the discrete electric potential solution, this + method assumes the discrete solution is fixed and returns + + .. math:: + \frac{\partial (\mathbf{A} \, \boldsymbol{\phi})}{\partial \mathbf{m}} \, + \mathbf{v} + + Or the adjoint operation + + .. math:: + \frac{\partial (\mathbf{A} \, \boldsymbol{\phi})}{\partial \mathbf{m}}^T + \, \mathbf{v} + + Parameters + ---------- + u : (n_cells,) numpy.ndarray + The solution for the electric potentials. + v : numpy.ndarray + The vector. (n_param,) for the standard operation. (n_cells,) for the adjoint + operation. + adjoint : bool + Whether to perform the adjoint operation. + + Returns + ------- + numpy.ndarray + Derivative of system matrix times a vector. (n_cells,) for the standard operation. + (n_param,) for the adjoint operation. + """ if self.rhoMap is not None: D = self.Div G = self.Grad @@ -391,25 +694,35 @@ def getADeriv(self, u, v, adjoint=False): return Zero() def getRHS(self): - """ - RHS for the DC problem - q - """ + """Compute and return right-hand sides for all sources. + + This method computes and returns the right-hand sides used to solve the + discrete finite volume solution for all sources. + Returns + ------- + (n_cells, n_sources) numpy.ndarray + The right-hand sides. + """ RHS = self.getSourceTerm() return RHS def getRHSDeriv(self, source, v, adjoint=False): + """Get derivative of the right-hand side with respect to the model. + + For ``Simulation3DCellCentered``, the derivative of the right-hand side with respect + to the model is zero. + + Returns + ------- + simpeg.utils.Zero + The SimPEG zero operator. """ - Derivative of the right hand side with respect to the model - """ - # TODO: add qDeriv for RHS depending on m - # qDeriv = source.evalDeriv(self, adjoint=adjoint) - # return qDeriv return Zero() def setBC(self): + """Set the boundary conditions for the gradient operator.""" mesh = self.mesh V = sp.diags(mesh.cell_volumes) self.Div = V @ mesh.face_divergence @@ -464,7 +777,7 @@ def setBC(self): is_t[:, :, -1] = True is_t = is_t.reshape(-1, order="F")[is_b] not_top = np.ones(boundary_faces.shape[0], dtype=bool) - not_top[-len(is_t) :] = ~is_t + not_top[-len(is_t) :] = ~is_t # noqa E203 self.surface_faces = ~not_top else: raise NotImplementedError( @@ -481,15 +794,102 @@ def setBC(self): class Simulation3DNodal(BaseDCSimulation): - """ - 3D nodal DC problem + r"""3D nodal DC resistivity simulation class. + + Where :math:`\phi` is the electric potential, :math:`\sigma` is the electrical conductivity, + and :math:`I \delta (r)` represents a grounded source which injects static current *I* at + location *r*, the DC resistivity problem is given by: + + .. math:: + \nabla \cdot \sigma \nabla \phi = - I \delta (r) + + The ``Simulation3DNodal`` class uses the mimetic finite volume approach to solve for + the discrete electric potentials at mesh nodes. See the *Notes* section for a + comprehensive description of the formulation. + + Notes + ----- + To derive the discrete solution, we start by considering Ampere's law and Faraday's law. + In the static regime, all time-derivative are zero. By also taking the divergence of + Ampere's law, we obtain: + + .. math:: + &\nabla \times \vec{e} = 0\\ + &\nabla \cdot \vec{j} = - \nabla \cdot \vec{j}_s + + where :math:`\vec{e}` is the electric field, :math:`\vec{j}` is the current density outside + the grounded source and and :math:`\vec{j}_s` is the source current density. The constitutive + relation between the electric field and current density is given by Ohm's law: + + .. math:: + \vec{j} = \sigma \vec{e} + + where :math:`\sigma` is the electrical conductivity. + + Faraday's law implies the electric field can be defined as the gradient of a scalar + potential :math:`\phi` as follows: + + .. math:: + \vec{e} = -\nabla \phi + + For a source representing current *I* injected at point *r*, the static form of Ampere's + law becomes: + + .. math:: + \nabla \cdot \vec{j} = - I \delta (r) + + For a vector test function :math:`\vec{u}` and a scalar test function :math:`\psi`, we + take the inner products with the three previous equations. Through vector calculus + identities and the divergence theorem, we obtain: + + .. math:: + & \int_\Omega \vec{u} \cdot \vec{j} \, dv = + \int_\Omega \vec{u} \cdot \sigma \vec{e} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{e} \, dv = + - \int_\Omega \vec{u} \cdot \nabla \phi \, dv \\ + & -\int_\Omega \nabla \psi \cdot \vec{j} \, dv + +\oint_{\partial \Omega} \psi (\vec{j} \cdot \hat{n}) \, da = + -I \int_\Omega \psi \, \delta (r) dv + + where the surface integral defines the boundary conditions. + + The above expressions are discretized in space according to the finite volume method. + The discrete electric fields :math:`\mathbf{e}` are defined on mesh edges, + and the discrete electric potentials :math:`\boldsymbol{\phi}` are defined on nodes. + This implies :math:`\mathbf{j}` and :math:`\mathbf{u}` must be defined on mesh edges, + and :math:`\boldsymbol{\psi}` must be defined on nodes. We obtain the following + set of discrete inner-products: + + .. math:: + &\mathbf{u^T M_e \, j} = \mathbf{u^T M_{e\sigma} \, e} \\ + &\mathbf{u^T M_e \, e} = -\mathbf{u^T M_e G} \boldsymbol{\phi} \\ + &-\boldsymbol{\psi} \mathbf{(G^T - B) M_e \, j} = \boldsymbol{\psi} \mathbf{q} + + where + + * :math:`\mathbf{G}` is the nodal gradient operator + * :math:`\mathbf{q}` is an integrated source term + * :math:`\mathbf{B}` is a matrix that applies boundary conditions + * :math:`\mathbf{M_e}` is the edge inner-product matrix + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + + By combining the discrete equations to form a discrete solution in terms of the + discrete electric potential on mesh nodes, we obtain: + + .. math:: + \big [ \mathbf{(G^T - B) M_{e\sigma} G} \big ] \boldsymbol{\phi} = \mathbf{q} + + Note that :math:`\mathbf{G^T - B}` effectively acts as a divergence operator in which + boundary conditions have been applied. + """ _solutionType = "phiSolution" _formulation = "EB" # N potentials means B is on faces fieldsPair = Fields3DNodal - def __init__(self, mesh, survey=None, bc_type="Robin", **kwargs): + def __init__(self, mesh, survey=None, bc_type="Robin", **kwargs): # noqa 107 super().__init__(mesh=mesh, survey=survey, **kwargs) # Not sure why I need to do this # To evaluate mesh.aveE2CC, this is required.... @@ -502,7 +902,7 @@ def __init__(self, mesh, survey=None, bc_type="Robin", **kwargs): @property def bc_type(self): - """Type of boundary condition to use for simulation. + """Get type of boundary condition to use for simulation. Returns ------- @@ -521,9 +921,30 @@ def bc_type(self, value): ) def getA(self, resistivity=None): - """ - Make the A matrix for the cell centered DC resistivity problem - A = G.T MeSigma G + r"""Return the system matrix. + + This method generates and returns the system matrix for the nodal DC + resistivity problem. The system matrix is given by: + + .. math:: + \mathbf{A} = \mathbf{(G^T - B) M_{e\sigma} G} + + where + + * :math:`\mathbf{G}` is the nodal gradient operator + * :math:`\mathbf{B}` is a matrix that implements boundary conditions + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + + Parameters + ---------- + resistivity : (n_cells,) numpy.ndarray + Electrical resistivities defined at cell centers + + Returns + ------- + (n_nodes, n_nodes) sp.sparse.csr_matrix + The system matrix. """ if resistivity is None: MeSigma = self.MeSigma @@ -555,9 +976,53 @@ def getA(self, resistivity=None): return A def getADeriv(self, u, v, adjoint=False): - """ - Product of the derivative of our system matrix with respect to the - model and a vector + r"""Get conductivity derivative operation for the system matrix times a vector. + + The system matrix is given by: + + .. math:: + \mathbf{A} = \mathbf{(G^T - B) M_{e\sigma} G} + + where + + * :math:`\mathbf{G}` is the nodal gradient operator + * :math:`\mathbf{B}` is a matrix that implements boundary conditions + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + + See the *Notes* section of the doc strings for :class:`Simulation3DNodal` + for a full description of the formulation. + + Where :math:`\mathbf{m}` are the set of model parameters defining the + electromagnetic properties :math:`\mathbf{v}` is a vector and + :math:`\boldsymbol{\phi}` is the discrete electric potential solution, this + method assumes the discrete solution is fixed and returns + + .. math:: + \frac{\partial (\mathbf{A} \, \boldsymbol{\phi})}{\partial \mathbf{m}} \, + \mathbf{v} + + Or the adjoint operation + + .. math:: + \frac{\partial (\mathbf{A} \, \boldsymbol{\phi})}{\partial \mathbf{m}}^T + \, \mathbf{v} + + Parameters + ---------- + u : (n_nodes,) numpy.ndarray + The solution for the electric potentials. + v : numpy.ndarray + The vector. (n_param,) for the standard operation. (n_nodes,) for the adjoint + operation. + adjoint : bool + Whether to perform the adjoint operation. + + Returns + ------- + numpy.ndarray + Derivative of system matrix times a vector. (n_nodes,) for the standard operation. + (n_param,) for the adjoint operation. """ Grad = self.mesh.nodal_gradient if not adjoint: @@ -571,6 +1036,7 @@ def getADeriv(self, u, v, adjoint=False): return out def setBC(self): + """Set boundary conditions for the divergence operation.""" if self.bc_type == "Dirichlet": # do nothing raise ValueError( @@ -624,7 +1090,7 @@ def setBC(self): is_t[:, :, -1] = True is_t = is_t.reshape(-1, order="F")[is_b] not_top = np.ones(boundary_faces.shape[0], dtype=bool) - not_top[-len(is_t) :] = ~is_t + not_top[-len(is_t) :] = ~is_t # noqa E203 else: raise NotImplementedError( f"Unable to infer surface boundaries for {type(mesh)}, please " @@ -644,30 +1110,176 @@ def setBC(self): self._AvgBC = AvgN2Fb.T @ AvgCC2Fb def getRHS(self): - """ - RHS for the DC problem - q - """ + """Compute and return right-hand sides for all sources. + This method computes and returns the right-hand sides used to solve the + discrete finite volume solution for all sources. + + Returns + ------- + (n_nodes, n_sources) numpy.ndarray + The right-hand sides. + """ RHS = self.getSourceTerm() return RHS def getRHSDeriv(self, source, v, adjoint=False): + """Get derivative of the right-hand side with respect to the model. + + For ``Simulation3DNodal``, the derivative of the right-hand side with respect + to the model is zero. + + Returns + ------- + simpeg.utils.Zero + The SimPEG zero operator. """ - Derivative of the right hand side with respect to the model - """ - # TODO: add qDeriv for RHS depending on m - # qDeriv = source.evalDeriv(self, adjoint=adjoint) - # return qDeriv return Zero() @property def _clear_on_sigma_update(self): - """ - These matrices are deleted if there is an update to the conductivity - model + """Add items to be cleared upon updating the `sigma` property. + + Returns + ------- + list + All of the items to be cleared up updating the `sigma` property. """ return super()._clear_on_sigma_update + ["_MBC_sigma"] +class Simulation3DHierarchicalNodal( + BaseHierarchicalElectricalSimulation, Simulation3DNodal +): + r"""3D hierarchical nodal DC resistivity simulation class. + + Where :math:`\phi` is the electric potential, :math:`\sigma` is the electrical conductivity, + and :math:`I \delta (r)` represents a grounded source which injects static current *I* at + location *r*, the DC resistivity problem is given by: + + .. math:: + \nabla \cdot \sigma \nabla \phi = - I \delta (r) + + The ``Simulation3DHierarchicalNodal`` class uses the mimetic finite volume approach to + solve for the discrete electric potentials at mesh nodes. This simulation adopts the + hierarchical framework wherein: + + * Thick structures are parameterized as conductivities at cell centers. This property + and the corresponding mapping are set with `sigma` and `sigmaMap`. + * Sheet-like structures can be parameterized as conductances on mesh faces. This property + and the corresponding mapping are set with `face_conductance` and `face_conductance_map`. + * Wire-like structures can be parameterized as area-integrated conductivities on + mesh edges. This property and the corresponding mapping as set with + `edge_area_conductance` and `edge_area_conductance_map`. + + See the *Notes* section for a comprehensive description of the formulation. + + Notes + ----- + To derive the discrete solution, we start by considering Ampere's law and Faraday's law. + In the static regime, all time-derivative are zero. By also taking the divergence of + Ampere's law, we obtain: + + .. math:: + &\nabla \times \vec{e} = 0\\ + &\nabla \cdot \vec{j} = - \nabla \cdot \vec{j}_s + + where :math:`\vec{e}` is the electric field, :math:`\vec{j}` is the current density outside + the grounded source and and :math:`\vec{j}_s` is the source current density. The constitutive + relation between the electric field and current density is given by Ohm's law: + + .. math:: + \vec{j} = \sigma \vec{e} + + where :math:`\sigma` is the electrical conductivity. + + Faraday's law implies the electric field can be defined as the gradient of a scalar + potential :math:`\phi` as follows: + + .. math:: + \vec{e} = -\nabla \phi + + For a source representing current *I* injected at point *r*, the static form of Ampere's + law becomes: + + .. math:: + \nabla \cdot \vec{j} = - I \delta (r) + + For a vector test function :math:`\vec{u}` and a scalar test function :math:`\psi`, we + take the inner products with the three previous equations. Through vector calculus + identities and the divergence theorem, we obtain: + + .. math:: + & \int_\Omega \vec{u} \cdot \vec{j} \, dv = + \int_\Omega \vec{u} \cdot \sigma \vec{e} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{e} \, dv = + - \int_\Omega \vec{u} \cdot \nabla \phi \, dv \\ + & -\int_\Omega \nabla \psi \cdot \vec{j} \, dv + +\oint_{\partial \Omega} \psi (\vec{j} \cdot \hat{n}) \, da = + -I \int_\Omega \psi \, \delta (r) dv + + where the surface integral defines the boundary conditions. + + The hierarchical approach assumes the existence of infinitesimally thin plate-like + regions between adjacent mesh faces and infinitesimally thin wire-like regions + between adjacent mesh edges. We re-express the inner-product with Ohm's law as follows: + + .. math:: + \int_\Omega \vec{u} \cdot \vec{j} \, dv =& + \sum_{n}^{nc} \int \vec{u} \cdot \sigma_n \vec{e} \, dv \\ + &+ \sum_{n}^{nf} \int \vec{u} \cdot \tau_n \vec{e} \, da \\ + &+ \sum_{n}^{ne} \int \vec{u} \cdot \kappa_n \vec{e} \, d\ell + + where :math:`\sigma_n` is the conductivity in cell *n*, :math:`\tau_n` is the face + conductance on face *n*, and :math:`\kappa_n` is the area-integrated conductivity + on edge *n*. + + The above expressions are discretized in space according to the finite volume method. + The discrete electric fields :math:`\mathbf{e}` are defined on mesh edges, + and the discrete electric potentials :math:`\boldsymbol{\phi}` are defined on nodes. + This implies :math:`\mathbf{j}` and :math:`\mathbf{u}` must be defined on mesh edges, + and :math:`\boldsymbol{\psi}` must be defined on nodes. We obtain the following + set of discrete inner-products: + + .. math:: + &\mathbf{u^T M_e \, j} = \mathbf{u^T M_{e\Sigma} \, e} \\ + &\mathbf{u^T M_e \, e} = -\mathbf{u^T M_e G} \boldsymbol{\phi} \\ + &-\boldsymbol{\psi} \mathbf{(G^T - B) M_e \, j} = \boldsymbol{\psi} \mathbf{q} + + where: + + .. math:: + \mathbf{M_{e\Sigma}} = \mathbf{M_{e\sigma} + M_{e\tau} + M_{e\kappa}} + + and + + * :math:`\mathbf{G}` is the nodal gradient operator + * :math:`\mathbf{q}` is an integrated source term + * :math:`\mathbf{B}` is a matrix that applies boundary conditions + * :math:`\mathbf{M_e}` is the edge inner-product matrix + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{e\tau}}` is the inner-product matrix for conductances + projected to edges + * :math:`\mathbf{M_{e\kappa}}` is the inner-product matrix for area integrated + conductivities projected to edges + + By combining the discrete equations to form a discrete solution in terms of the + discrete electric potential on mesh nodes, we obtain: + + .. math:: + \big [ \mathbf{(G^T - B) M_{e\Sigma} G} \big ] \boldsymbol{\phi} = \mathbf{q} + + """ + + def getA(self, resistivity=None): # noqa D102 + # Docstring inherited from parent class. + if resistivity is not None: + raise NotImplementedError( + "The 'resistivity' argument is not supported by the hierarchical " + "simulation, because it would ignore the face and edge conductances." + ) + return super().getA() + + Simulation3DCellCentred = Simulation3DCellCentered # UK and US! diff --git a/simpeg/electromagnetics/static/resistivity/survey.py b/simpeg/electromagnetics/static/resistivity/survey.py index 0d607c86b6..2d540a167e 100644 --- a/simpeg/electromagnetics/static/resistivity/survey.py +++ b/simpeg/electromagnetics/static/resistivity/survey.py @@ -253,8 +253,11 @@ def drape_electrodes_on_topography( The mesh on which the discretized fields are computed active_cells : numpy.ndarray of int or bool Active topography cells - topo_cell_cutoff : {"top", "center"} + topo_cell_cutoff : {"top", "center"}, optional Define topography at tops of cells or cell centers. + shift_horizontal : bool, optional + When True, locations are shifted horizontally to lie vertically over cell + centers. When False, the original horizontal locations are preserved. topography : (n, dim) numpy.ndarray, default = ``None`` Surface topography @@ -270,9 +273,6 @@ def drape_electrodes_on_topography( The ``force`` argument is not used in this function. It will be removed in SimPEG v0.27.0. - shift_horizontal : bool - When True, locations are shifted horizontally to lie vertically over cell - centers. When False, the original horizontal locations are preserved. option : {"top", "center"} Define topography at tops of cells or cell centers. @@ -281,6 +281,9 @@ def drape_electrodes_on_topography( Argument ``option`` is deprecated in favor of ``topo_cell_cutoff`` and will be removed in SimPEG v0.27.0. + See also + -------- + :func:`simpeg.utils.shift_to_discrete_topography` """ if option is not None: msg = ( diff --git a/simpeg/electromagnetics/static/spectral_induced_polarization/__init__.py b/simpeg/electromagnetics/static/spectral_induced_polarization/__init__.py index 9eefe9606d..5780d81af1 100644 --- a/simpeg/electromagnetics/static/spectral_induced_polarization/__init__.py +++ b/simpeg/electromagnetics/static/spectral_induced_polarization/__init__.py @@ -71,6 +71,5 @@ from . import receivers as Rx from .run import run_inversion, spectral_ip_mappings - Simulation2DCellCentred = Simulation2DCellCentered Simulation3DCellCentred = Simulation2DCellCentered diff --git a/simpeg/electromagnetics/static/spectral_induced_polarization/receivers.py b/simpeg/electromagnetics/static/spectral_induced_polarization/receivers.py index 3fc73b0f86..911bffed39 100644 --- a/simpeg/electromagnetics/static/spectral_induced_polarization/receivers.py +++ b/simpeg/electromagnetics/static/spectral_induced_polarization/receivers.py @@ -136,7 +136,7 @@ def getTimeP(self, times_all): numpy.ndarray Time projection from time-steps to time channels """ - time_inds = np.in1d(times_all, self.times) + time_inds = np.isin(times_all, self.times) return time_inds def eval(self, src, mesh, f): # noqa: A003 diff --git a/simpeg/electromagnetics/static/utils/static_utils.py b/simpeg/electromagnetics/static/utils/static_utils.py index 43bb8e1b01..238d2263dc 100644 --- a/simpeg/electromagnetics/static/utils/static_utils.py +++ b/simpeg/electromagnetics/static/utils/static_utils.py @@ -31,7 +31,6 @@ from ....utils.plot_utils import plot_1d_layer_model # noqa: F401 - try: import plotly.graph_objects as grapho @@ -1298,8 +1297,8 @@ def generate_dcip_sources_line( Returns ------- - simpeg.electromagnetics.static.resistivity.Survey - A DC survey object. + list of simpeg.electromagnetics.static.resistivity.sources.BaseSrc + A list of DC resistivity sources. """ assert survey_type.lower() in [ "pole-pole", diff --git a/simpeg/electromagnetics/time_domain/__init__.py b/simpeg/electromagnetics/time_domain/__init__.py index 5891b847ce..f60add24d9 100644 --- a/simpeg/electromagnetics/time_domain/__init__.py +++ b/simpeg/electromagnetics/time_domain/__init__.py @@ -9,10 +9,11 @@ and functionality is used to solve: .. math:: - \begin{align} + + \begin{aligned} \nabla \times \vec{e} + \frac{\partial \vec{b}}{\partial t} &= -\frac{\partial \vec{s}_m}{\partial t} \\ \nabla \times \vec{h} - \vec{j} &= \vec{s}_e - \end{align} + \end{aligned} where the constitutive relations between fields and fluxes are given by: @@ -34,6 +35,8 @@ Simulation3DElectricField Simulation3DMagneticField Simulation3DCurrentDensity + Simulation3DHierarchicalMagneticFluxDensity + Simulation3DHierarchicalElectricField Receivers ========= @@ -113,6 +116,8 @@ Simulation3DElectricField, Simulation3DMagneticField, Simulation3DCurrentDensity, + Simulation3DHierarchicalElectricField, + Simulation3DHierarchicalMagneticFluxDensity, ) from .simulation_1d import Simulation1DLayered from .fields import ( diff --git a/simpeg/electromagnetics/time_domain/fields.py b/simpeg/electromagnetics/time_domain/fields.py index 8ad996ad79..281579acde 100644 --- a/simpeg/electromagnetics/time_domain/fields.py +++ b/simpeg/electromagnetics/time_domain/fields.py @@ -20,8 +20,8 @@ class FieldsTDEM(TimeFields): simulation : .time_domain.BaseTDEMSimulation The TDEM simulation object used to compute the discrete field solution. - Example - ------- + Examples + -------- We want to access the fields for a discrete solution with :math:`\mathbf{e}` discretized to edges and :math:`\mathbf{b}` discretized to faces. To extract the fields for all sources and all time steps: @@ -54,7 +54,7 @@ def _GLoc(self, fieldType): return self.aliasFields[fieldType][1] def _eDeriv(self, tInd, src, dun_dm_v, v, adjoint=False): - if adjoint is True: + if adjoint: return ( self._eDeriv_u(tInd, src, v, adjoint), self._eDeriv_m(tInd, src, v, adjoint), @@ -62,7 +62,7 @@ def _eDeriv(self, tInd, src, dun_dm_v, v, adjoint=False): return self._eDeriv_u(tInd, src, dun_dm_v) + self._eDeriv_m(tInd, src, v) def _bDeriv(self, tInd, src, dun_dm_v, v, adjoint=False): - if adjoint is True: + if adjoint: return ( self._bDeriv_u(tInd, src, v, adjoint), self._bDeriv_m(tInd, src, v, adjoint), @@ -70,16 +70,15 @@ def _bDeriv(self, tInd, src, dun_dm_v, v, adjoint=False): return self._bDeriv_u(tInd, src, dun_dm_v) + self._bDeriv_m(tInd, src, v) def _dbdtDeriv(self, tInd, src, dun_dm_v, v, adjoint=False): - if adjoint is True: + if adjoint: return ( self._dbdtDeriv_u(tInd, src, v, adjoint), - Zero(), - # self._dbdtDeriv_m(tInd, src, v, adjoint), + self._dbdtDeriv_m(tInd, src, v, adjoint), ) return self._dbdtDeriv_u(tInd, src, dun_dm_v) + self._dbdtDeriv_m(tInd, src, v) def _hDeriv(self, tInd, src, dun_dm_v, v, adjoint=False): - if adjoint is True: + if adjoint: return ( self._hDeriv_u(tInd, src, v, adjoint), self._hDeriv_m(tInd, src, v, adjoint), @@ -87,7 +86,7 @@ def _hDeriv(self, tInd, src, dun_dm_v, v, adjoint=False): return self._hDeriv_u(tInd, src, dun_dm_v) + self._hDeriv_m(tInd, src, v) def _dhdtDeriv(self, tInd, src, dun_dm_v, v, adjoint=False): - if adjoint is True: + if adjoint: return ( self._dhdtDeriv_u(tInd, src, v, adjoint), self._dhdtDeriv_m(tInd, src, v, adjoint), @@ -95,7 +94,7 @@ def _dhdtDeriv(self, tInd, src, dun_dm_v, v, adjoint=False): return self._dhdtDeriv_u(tInd, src, dun_dm_v) + self._dhdtDeriv_m(tInd, src, v) def _jDeriv(self, tInd, src, dun_dm_v, v, adjoint=False): - if adjoint is True: + if adjoint: return ( self._jDeriv_u(tInd, src, v, adjoint), self._jDeriv_m(tInd, src, v, adjoint), @@ -165,8 +164,8 @@ class Fields3DMagneticFluxDensity(FieldsTDEM): simulation : .time_domain.Simulation3DMagneticFluxDensity The TDEM simulation object associated with the fields. - Example - ------- + Examples + -------- The ``Fields3DMagneticFluxDensity`` object stores the total magnetic flux density solution on mesh faces. To extract the discrete electric fields and magnetic flux densities for all sources and time-steps: @@ -233,12 +232,12 @@ def _dbdt(self, bSolution, source_list, tInd): return dbdt def _dbdtDeriv_u(self, tInd, src, dun_dm_v, adjoint=False): - if adjoint is True: - return -self._eDeriv_u(tInd, src, self._edgeCurl.T @ dun_dm_v, adjoint) + if adjoint: + return -self._eDeriv_u(tInd, src, self._edgeCurl.T * dun_dm_v, adjoint) return -(self._edgeCurl * self._eDeriv_u(tInd, src, dun_dm_v)) def _dbdtDeriv_m(self, tInd, src, v, adjoint=False): - if adjoint is True: + if adjoint: return -(self._eDeriv_m(tInd, src, self._edgeCurl.T * v, adjoint)) return -( self._edgeCurl * self._eDeriv_m(tInd, src, v) @@ -252,8 +251,8 @@ def _e(self, bSolution, source_list, tInd): return e def _eDeriv_u(self, tInd, src, dun_dm_v, adjoint=False): - if adjoint is True: - return self._MfMui.T @ (self._edgeCurl @ (self._MeSigmaI.T @ dun_dm_v)) + if adjoint: + return self._MfMui.T * (self._edgeCurl * (self._MeSigmaI.T * dun_dm_v)) return self._MeSigmaI * (self._edgeCurl.T * (self._MfMui * dun_dm_v)) def _eDeriv_m(self, tInd, src, v, adjoint=False): @@ -262,7 +261,7 @@ def _eDeriv_m(self, tInd, src, v, adjoint=False): _, s_eDeriv = src.evalDeriv(self._times[tInd], self, adjoint=adjoint) - if adjoint is True: + if adjoint: return self._MeSigmaIDeriv( -s_e + self._edgeCurl.T * (self._MfMui * bSolution), v, adjoint ) - s_eDeriv(self._MeSigmaI.T * v) @@ -364,8 +363,8 @@ class Fields3DElectricField(FieldsTDEM): simulation : .time_domain.Simulation3DElectricField The TDEM simulation object associated with the fields. - Example - ------- + Examples + -------- The ``Fields3DElectricField`` object stores the total electric field solution on mesh edges. To extract the discrete electric fields and db/dt for all sources and time-steps: @@ -526,8 +525,8 @@ class Fields3DMagneticField(FieldsTDEM): simulation : .time_domain.Simulation3DMagneticField The TDEM simulation object associated with the fields. - Example - ------- + Examples + -------- The ``Fields3DMagneticField`` object stores the total magnetic field solution on mesh edges. To extract the discrete magnetic fields and current density for all sources and time-steps: @@ -697,7 +696,7 @@ def _eDeriv_u(self, tInd, src, dun_dm_v, adjoint=False): def _eDeriv_m(self, tInd, src, v, adjoint=False): j = mkvc(self[src, "j", tInd]) - if adjoint is True: + if adjoint: return self._MfRhoDeriv( j, self.simulation.MfI.T * v, adjoint ) + self._jDeriv_m(tInd, src, self._MfRho * v) @@ -736,8 +735,8 @@ class Fields3DCurrentDensity(FieldsTDEM): simulation : .time_domain.Simulation3DCurrentDensity The TDEM simulation object associated with the fields. - Example - ------- + Examples + -------- The ``Fields3DCurrentDensity`` object stores the total current density solution on mesh faces. To extract the discrete current densities and magnetic fields for all sources and time-steps: @@ -814,7 +813,7 @@ def _dhdtDeriv_u(self, tInd, src, dun_dm_v, adjoint=False): MfRho = self._MfRho MeMuI = self._MeMuI - if adjoint is True: + if adjoint: return -MfRho.T * (C * (MeMuI.T * dun_dm_v)) return -MeMuI * (C.T * (MfRho * dun_dm_v)) @@ -823,7 +822,7 @@ def _dhdtDeriv_m(self, tInd, src, v, adjoint=False): C = self._edgeCurl MeMuI = self._MeMuI - if adjoint is True: + if adjoint: return -self._MfRhoDeriv(jSolution, C * (MeMuI * v), adjoint) return -MeMuI * (C.T * (self._MfRhoDeriv(jSolution, v))) @@ -833,7 +832,7 @@ def _e(self, jSolution, source_list, tInd): ) def _eDeriv_u(self, tInd, src, dun_dm_v, adjoint=False): - if adjoint is True: + if adjoint: return self._MfRho.T * (self.simulation.MfI.T * dun_dm_v) return self.simulation.MfI * (self._MfRho * dun_dm_v) diff --git a/simpeg/electromagnetics/time_domain/simulation.py b/simpeg/electromagnetics/time_domain/simulation.py index 94ad7a4b4f..087334775d 100644 --- a/simpeg/electromagnetics/time_domain/simulation.py +++ b/simpeg/electromagnetics/time_domain/simulation.py @@ -1,8 +1,11 @@ +"""3D TDEM simulations.""" + import numpy as np import scipy.sparse as sp from ...simulation import BaseTimeSimulation from ...utils import mkvc, sdiag, speye, Zero, validate_type, validate_float +from ...base import BaseHierarchicalElectricalSimulation from ..base import BaseEMSimulation from .survey import Survey from .fields import ( @@ -23,10 +26,11 @@ class BaseTDEMSimulation(BaseTimeSimulation, BaseEMSimulation): displacement, and Maxwell's equations are expressed as: .. math:: - \begin{align} - \nabla \times \vec{e} + \frac{\partial \vec{b}}{\partial t} &= -\frac{\partial \vec{s}_m}{\partial t} \\ + \begin{aligned} + \nabla \times \vec{e} + \frac{\partial \vec{b}}{\partial t} + &= -\frac{\partial \vec{s}_m}{\partial t} \\ \nabla \times \vec{h} - \vec{j} &= \vec{s}_e - \end{align} + \end{aligned} where the constitutive relations between fields and fluxes are given by: @@ -49,11 +53,17 @@ class BaseTDEMSimulation(BaseTimeSimulation, BaseEMSimulation): The time-domain EM survey. dt_threshold : float Threshold used when determining the unique time-step lengths. + store_factors : bool, optional + Whether to store the factorization of the system matrix for each unique + time-step length, so they can be reused by `Jvec` and `Jtvec`. """ - def __init__(self, mesh, survey=None, dt_threshold=1e-8, **kwargs): + def __init__( + self, mesh, survey=None, dt_threshold=1e-8, store_factors=False, **kwargs + ): # noqa D107 super().__init__(mesh=mesh, survey=survey, **kwargs) self.dt_threshold = dt_threshold + self.store_factors = store_factors if self.muMap is not None: raise NotImplementedError( "Time domain EM simulations do not support magnetic permeability " @@ -97,7 +107,61 @@ def dt_threshold(self): @dt_threshold.setter def dt_threshold(self, value): - self._dt_threshold = validate_float("dt_threshold", value, min_val=0.0) + value = validate_float("dt_threshold", value, min_val=0.0) + self._dt_threshold = value + self._dt_precision = None if value == 0.0 else int(np.ceil(-np.log10(value))) + + @property + def store_factors(self): + """Whether the factorization for each unique time step is stored. + + If True, the factorizations of the system matrix (and its transpose) are kept + between calls to `fields`, `Jvec`, and `Jtvec`. This can significantly speed + up the sensitivity operations in an inversion, at the cost of increased + memory usage. The stored factors are released the next time `fields` is + called, or when this property is set to False. + + Returns + ------- + bool + """ + return self._store_factors + + @store_factors.setter + def store_factors(self, value): + value = validate_type("store_factors", value, bool) + if not value: + self._stored_factors = {} + self._store_factors = value + + def _get_stored_factor(self, tInd): + """Get the factorization of the system matrix at a time step. + + The factorization is created if it does not exist yet. The factorizations are + keyed by the time step length, and the transposed solves needed by `Jtvec` use + the `T` of the same factorization. If `store_factors` is False, only the most + recent factorization is kept (`fields`, `Jvec` and `Jtvec` release it when + they finish). + """ + dt = self.time_steps[tInd] + precision = self._dt_precision + key = dt if precision is None else float(np.around(dt, precision)) + + if not hasattr(self, "_stored_factors"): + self._stored_factors = {} + + Ainv = self._stored_factors.get(key, None) + if Ainv is None: + if not self.store_factors: + self._stored_factors = {} + A = self.getAdiag(tInd) + if self.verbose: + print("Factoring... (dt = {:e})".format(dt)) + Ainv = self.solver(A, **self.solver_opts) + if self.verbose: + print("Done") + self._stored_factors[key] = Ainv + return Ainv def fields(self, m): """Compute and return the fields for the model provided. @@ -112,7 +176,6 @@ def fields(self, m): .time_domain.fields.FieldsTDEM The TDEM fields object. """ - self.model = m f = self.fieldsPair(self) @@ -124,23 +187,10 @@ def fields(self, m): print("{}\nCalculating fields(m)\n{}".format("*" * 50, "*" * 50)) # timestep to solve forward - Ainv = None - for tInd, dt in enumerate(self.time_steps): - # keep factors if dt is the same as previous step b/c A will be the - # same - if Ainv is not None and ( - tInd > 0 and abs(dt - self.time_steps[tInd - 1]) > self.dt_threshold - ): - Ainv.clean() - Ainv = None - - if Ainv is None: - A = self.getAdiag(tInd) - if self.verbose: - print("Factoring... (dt = {:e})".format(dt)) - Ainv = self.solver(A, **self.solver_opts) - if self.verbose: - print("Done") + for tInd in range(self.nT): + # factors are reused if dt is the same as a previous step b/c A will be + # the same + Ainv = self._get_stored_factor(tInd) rhs = self.getRHS(tInd + 1) # this is on the nodes of the time mesh Asubdiag = self.getAsubdiag(tInd) @@ -162,7 +212,8 @@ def fields(self, m): print("{}\nDone calculating fields(m)\n{}".format("*" * 50, "*" * 50)) # clean factors and return - Ainv.clean() + if not self.store_factors: + self._stored_factors = {} return f def Jvec(self, m, v, f=None): @@ -195,7 +246,6 @@ def Jvec(self, m, v, f=None): (n_data,) numpy.ndarray The sensitivity matrix times a vector. """ - if f is None: f = self.fields(m) @@ -224,18 +274,10 @@ def Jvec(self, m, v, f=None): # store the field derivs we need to project to calc full deriv df_dm_v = self.Fields_Derivs(self) - Adiaginv = None - - for tInd, dt in zip(range(self.nT), self.time_steps): - # keep factors if dt is the same as previous step b/c A will be the - # same - if Adiaginv is not None and (tInd > 0 and dt != self.time_steps[tInd - 1]): - Adiaginv.clean() - Adiaginv = None - - if Adiaginv is None: - A = self.getAdiag(tInd) - Adiaginv = self.solver(A, **self.solver_opts) + for tInd in range(self.nT): + # factors are reused if dt is the same as a previous step b/c A will be + # the same + Adiaginv = self._get_stored_factor(tInd) Asubdiag = self.getAsubdiag(tInd) @@ -278,7 +320,8 @@ def Jvec(self, m, v, f=None): mkvc(df_dm_v[src, "%sDeriv" % rx.projField, :]), ) ) - Adiaginv.clean() + if not self.store_factors: + self._stored_factors = {} # del df_dm_v, dun_dm_v, Asubdiag # return mkvc(Jv) return np.hstack(Jv) @@ -313,7 +356,6 @@ def Jtvec(self, m, v, f=None): (n_param,) numpy.ndarray The adjoint sensitivity matrix times a vector. """ - if f is None: f = self.fields(m) @@ -374,24 +416,11 @@ def Jtvec(self, m, v, f=None): del PT_v # no longer need this - AdiagTinv = None - # Do the back-solve through time # if the previous timestep is the same: no need to refactor the matrix - # for tInd, dt in zip(range(self.nT), self.time_steps): - for tInd in reversed(range(self.nT)): # tInd = tIndP - 1 - if AdiagTinv is not None and ( - tInd <= self.nT and self.time_steps[tInd] != self.time_steps[tInd + 1] - ): - AdiagTinv.clean() - AdiagTinv = None - - # refactor if we need to - if AdiagTinv is None: # and tInd > -1: - Adiag = self.getAdiag(tInd) - AdiagTinv = self.solver(Adiag.T.tocsr(), **self.solver_opts) + AdiagTinv = self._get_stored_factor(tInd).T if tInd < self.nT - 1: Asubdiag = self.getAsubdiag(tInd + 1) @@ -436,8 +465,8 @@ def Jtvec(self, m, v, f=None): # Treat the initial condition # del df_duT_v, ATinv_df_duT_v, A, Asubdiag - if AdiagTinv is not None: - AdiagTinv.clean() + if not self.store_factors: + self._stored_factors = {} return mkvc(JTv).astype(float) @@ -465,11 +494,12 @@ def getSourceTerm(self, tInd): Returns ------- s_m : numpy.ndarray - The magnetic sources terms. (n_faces, n_sources) for EB-formulations. (n_edges, n_sources) for HJ-formulations. + The magnetic sources terms. (n_faces, n_sources) for EB-formulations. + (n_edges, n_sources) for HJ-formulations. s_e : numpy.ndarray - The electric sources terms. (n_edges, n_sources) for EB-formulations. (n_faces, n_sources) for HJ-formulations. + The electric sources terms. (n_edges, n_sources) for EB-formulations. + (n_faces, n_sources) for HJ-formulations. """ - Srcs = self.survey.source_list if self._formulation == "EB": @@ -487,14 +517,13 @@ def getSourceTerm(self, tInd): return s_m, s_e def getInitialFields(self): - """Returns the fields for all sources at the initial time. + """Return the fields for all sources at the initial time. Returns ------- (n_edges or n_faces, n_sources) numpy.ndarray The fields for all sources at the initial time. """ - Srcs = self.survey.source_list if self._fieldType in ["b", "j"]: @@ -513,7 +542,7 @@ def getInitialFields(self): return ifields def getInitialFieldsDeriv(self, src, v, adjoint=False, f=None): - r"""Derivative of the initial fields with respect to the model for a given source. + r"""Return derivative of initial fields with respect to the model for a given source. For a given source object `src`, let :math:`\mathbf{u_0}` represent the initial fields discretized to the mesh. Where :math:`\mathbf{m}` are the model parameters @@ -533,8 +562,8 @@ def getInitialFieldsDeriv(self, src, v, adjoint=False, f=None): A TDEM source. v : numpy.ndarray A vector of appropriate dimension. When `adjoint` is ``False``, `v` is a - (n_param,) numpy.ndarray. When `adjoint` is ``True``, `v` is a (n_edges or n_faces,) - numpy.ndarray. + (n_param,) numpy.ndarray. When `adjoint` is ``True``, `v` is a + (n_edges or n_faces,) numpy.ndarray. adjoint : bool Whether to perform the adjoint operation. f : .time_domain.fields.BaseTDEMFields, optional @@ -584,10 +613,10 @@ def Adcinv(self): .. math:: \mathbf{A_{dc}} \, \boldsymbol{\phi_0} = \mathbf{q_{dc}} - where :math:`\mathbf{A_{dc}}` is the system matrix, :math:`\boldsymbol{\phi_0}` represents the - discrete solution for the electric potential and :math:`\mathbf{q_{dc}}` is the discrete - right-hand side. Electric fields are computed by applying a discrete gradient operator - to the discrete electric potential solution. + where :math:`\mathbf{A_{dc}}` is the system matrix, :math:`\boldsymbol{\phi_0}` + represents the discrete solution for the electric potential and :math:`\mathbf{q_{dc}}` + is the discrete right-hand side. Electric fields are computed by applying a discrete + gradient operator to the discrete electric potential solution. Returns ------- @@ -625,7 +654,7 @@ def _delete_on_model_update(self): list of str List of the model-dependent attributes to clean upon model update. """ - items = super()._delete_on_model_update + items = super()._delete_on_model_update + ["_stored_factors"] if self.sigmaMap is not None: items = items + ["_Adcinv"] #: clear DC matrix factors on any model updates # if there is a sigmaMap @@ -664,7 +693,8 @@ class Simulation3DMagneticFluxDensity(BaseTDEMSimulation): electric displacement: .. math:: - &\nabla \times \vec{e} + \frac{\partial \vec{b}}{\partial t} = - \frac{\partial \vec{s}_m}{\partial t} \\ + &\nabla \times \vec{e} + \frac{\partial \vec{b}}{\partial t} = + - \frac{\partial \vec{s}_m}{\partial t} \\ &\nabla \times \vec{h} - \vec{j} = \vec{s}_e where :math:`\vec{s}_e` is an electric source term that defines a source current density, @@ -676,8 +706,8 @@ class Simulation3DMagneticFluxDensity(BaseTDEMSimulation): \vec{j} &= \sigma \vec{e} \\ \vec{h} &= \mu^{-1} \vec{b} - We then take the inner products of all previous expressions with a vector test function :math:`\vec{u}`. - Through vector calculus identities and the divergence theorem, we obtain: + We then take the inner products of all previous expressions with a vector test function + :math:`\vec{u}`. Through vector calculus identities and the divergence theorem, we obtain: .. math:: & \int_\Omega \vec{u} \cdot (\nabla \times \vec{e}) \, dv @@ -685,9 +715,12 @@ class Simulation3DMagneticFluxDensity(BaseTDEMSimulation): = - \int_\Omega \vec{u} \cdot \frac{\partial \vec{s}_m}{\partial t} \, dv \\ & \int_\Omega (\nabla \times \vec{u}) \cdot \vec{h} \, dv - \oint_{\partial \Omega} \vec{u} \cdot (\vec{h} \times \hat{n}) \, da - - \int_\Omega \vec{u} \cdot \vec{j} \, dv = \int_\Omega \vec{u} \cdot \vec{s}_e \, dv \\ - & \int_\Omega \vec{u} \cdot \vec{j} \, dv = \int_\Omega \vec{u} \cdot \sigma \vec{e} \, dv \\ - & \int_\Omega \vec{u} \cdot \vec{h} \, dv = \int_\Omega \vec{u} \cdot \mu^{-1} \vec{b} \, dv + - \int_\Omega \vec{u} \cdot \vec{j} \, dv = + \int_\Omega \vec{u} \cdot \vec{s}_e \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{j} \, dv = + \int_\Omega \vec{u} \cdot \sigma \vec{e} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{h} \, dv = + \int_\Omega \vec{u} \cdot \mu^{-1} \vec{b} \, dv Assuming natural boundary conditions, the surface integral is zero. @@ -709,13 +742,17 @@ class Simulation3DMagneticFluxDensity(BaseTDEMSimulation): where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic + and electric source terms, respectively * :math:`\mathbf{M_e}` is the edge inner-product matrix * :math:`\mathbf{M_f}` is the face inner-product matrix - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse permeabilities projected to faces + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces - By cancelling like-terms and combining the discrete expressions in terms of the magnetic flux density, we obtain: + By cancelling like-terms and combining the discrete expressions in terms of the + magnetic flux density, we obtain: .. math:: \mathbf{C M_{e\sigma}^{-1} C^T M_{f\frac{1}{\mu}} b} @@ -723,8 +760,9 @@ class Simulation3DMagneticFluxDensity(BaseTDEMSimulation): = \mathbf{C M_{e\sigma}^{-1}} \mathbf{s_e} - \frac{\partial \mathbf{s_m}}{\partial t} - Finally, we discretize in time according to backward Euler. The discrete magnetic flux density - on mesh faces at time :math:`t_k > t_0` is obtained by solving the following at each time-step: + Finally, we discretize in time according to backward Euler. The discrete magnetic flux + density on mesh faces at time :math:`t_k > t_0` is obtained by solving the following + at each time-step: .. math:: \mathbf{A}_k \mathbf{b}_k = \mathbf{q_k} - \mathbf{B}_k \mathbf{b}_{k-1} @@ -732,10 +770,12 @@ class Simulation3DMagneticFluxDensity(BaseTDEMSimulation): where :math:`\Delta t_k = t_k - t_{k-1}` and .. math:: - &\mathbf{A}_k = \mathbf{C M_{e\sigma}^{-1} C^T M_{f\frac{1}{\mu}}} + \frac{1}{\Delta t_k} \mathbf{I} \\ + &\mathbf{A}_k = \mathbf{C M_{e\sigma}^{-1} C^T M_{f\frac{1}{\mu}}} + + \frac{1}{\Delta t_k} \mathbf{I} \\ &\mathbf{B}_k = -\frac{1}{\Delta t_k} \mathbf{I}\\ &\mathbf{q}_k = \mathbf{C M_{e\sigma}^{-1}} \mathbf{s}_{\mathbf{e}, k} \; - - \; \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{m}, k} - \mathbf{s}_{\mathbf{m}, k-1} \big ] + - \; \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{m}, k} + - \mathbf{s}_{\mathbf{m}, k-1} \big ] Although the following system is never explicitly formed, we can represent the solution at all time-steps as: @@ -769,12 +809,13 @@ class Simulation3DMagneticFluxDensity(BaseTDEMSimulation): Fields_Derivs = FieldsDerivativesEB def getAdiag(self, tInd): - r"""Diagonal system matrix for the given time-step index. + r"""Return diagonal system matrix for the given time-step index. This method returns the diagonal system matrix for the time-step index provided: .. math:: - \mathbf{A}_k = \mathbf{C M_{e\sigma}^{-1} C^T M_{f\frac{1}{\mu}}} + \frac{1}{\Delta t_k} \mathbf{I} + \mathbf{A}_k = \mathbf{C M_{e\sigma}^{-1} C^T M_{f\frac{1}{\mu}}} + + \frac{1}{\Delta t_k} \mathbf{I} where @@ -782,7 +823,8 @@ def getAdiag(self, tInd): * :math:`\mathbf{I}` is the identity matrix * :math:`\mathbf{C}` is the discrete curl operator * :math:`\mathbf{M_{e \sigma}}` is the conductivity inner-product matrix on edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inverse permeability inner-product matrix on faces + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inverse permeability inner-product + matrix on faces See the *Notes* section of the doc strings for :class:`Simulation3DMagneticFluxDensity` for a full description of the formulation. @@ -803,21 +845,22 @@ def getAdiag(self, tInd): C = self.mesh.edge_curl MeSigmaI = self.MeSigmaI MfMui = self.MfMui - I = speye(self.mesh.n_faces) + I = speye(self.mesh.n_faces) # noqa E741 A = 1.0 / dt * I + (C * (MeSigmaI * (C.T.tocsr() * MfMui))) - if self._makeASymmetric is True: + if self._makeASymmetric: return MfMui.T.tocsr() * A return A def getAdiagDeriv(self, tInd, u, v, adjoint=False): - r"""Derivative operation for the diagonal system matrix times a vector. + r"""Return derivative operation for the diagonal system matrix times a vector. The diagonal system matrix for time-step index *k* is given by: .. math:: - \mathbf{A}_k = \mathbf{C M_{e\sigma}^{-1} C^T M_{f\frac{1}{\mu}}} + \frac{1}{\Delta t_k} \mathbf{I} + \mathbf{A}_k = \mathbf{C M_{e\sigma}^{-1} C^T M_{f\frac{1}{\mu}}} + + \frac{1}{\Delta t_k} \mathbf{I} where @@ -825,14 +868,15 @@ def getAdiagDeriv(self, tInd, u, v, adjoint=False): * :math:`\mathbf{I}` is the identity matrix * :math:`\mathbf{C}` is the discrete curl operator * :math:`\mathbf{M_{e \sigma}}` is the conductivity inner-product matrix on edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inverse permeability inner-product matrix on faces + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inverse permeability inner-product + matrix on faces See the *Notes* section of the doc strings for :class:`Simulation3DMagneticFluxDensity` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a vector - and :math:`\mathbf{b_k}` is the discrete solution for time-step *k*, this method assumes - the discrete solution is fixed and returns + Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a + vector and :math:`\mathbf{b_k}` is the discrete solution for time-step *k*, this + method assumes the discrete solution is fixed and returns .. math:: \frac{\partial (\mathbf{A_k \, b_k})}{\partial \mathbf{m}} \, \mathbf{v} @@ -849,7 +893,8 @@ def getAdiagDeriv(self, tInd, u, v, adjoint=False): u : (n_faces,) numpy.ndarray The solution for the fields for the current model; i.e. :math:`\mathbf{b_k}`. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -867,25 +912,26 @@ def getAdiagDeriv(self, tInd, u, v, adjoint=False): MfMui = self.MfMui if adjoint: - if self._makeASymmetric is True: + if self._makeASymmetric: v = MfMui * v return self.MeSigmaIDeriv(C.T * (MfMui * u), C.T * v, adjoint) ADeriv = C * (self.MeSigmaIDeriv(C.T * (MfMui * u), v, adjoint)) - if self._makeASymmetric is True: + if self._makeASymmetric: return MfMui.T * ADeriv return ADeriv def getAsubdiag(self, tInd): - r"""Sub-diagonal system matrix for the time-step index provided. + r"""Return sub-diagonal system matrix for the time-step index provided. This method returns the sub-diagonal system matrix for the time-step index provided: .. math:: \mathbf{B}_k = -\frac{1}{\Delta t_k} \mathbf{I} - where :math:`\Delta t_k` is the step length and :math:`\mathbf{I}` is the identity matrix. + where :math:`\Delta t_k` is the step length and :math:`\mathbf{I}` is the identity + matrix. See the *Notes* section of the doc strings for :class:`Simulation3DMagneticFluxDensity` for a full description of the formulation. @@ -900,43 +946,45 @@ def getAsubdiag(self, tInd): (n_faces, n_faces) sp.sparse.csr_matrix The sub-diagonal system matrix. """ - dt = self.time_steps[tInd] MfMui = self.MfMui Asubdiag = -1.0 / dt * sp.eye(self.mesh.n_faces) - if self._makeASymmetric is True: + if self._makeASymmetric: return MfMui.T * Asubdiag return Asubdiag def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): - r"""Derivative operation for the sub-diagonal system matrix times a vector. + r"""Return derivative operation for the sub-diagonal system matrix times a vector. The sub-diagonal system matrix for time-step index *k* is given by: .. math:: \mathbf{B}_k = -\frac{1}{\Delta t_k} \mathbf{I} - where :math:`\Delta t_k` is the step length and :math:`\mathbf{I}` is the identity matrix. + where :math:`\Delta t_k` is the step length and :math:`\mathbf{I}` is the identity + matrix. See the *Notes* section of the doc strings for :class:`Simulation3DMagneticFluxDensity` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a vector - and :math:`\mathbf{b_{k-1}}` is the discrete solution for the previous time-step, - this method assumes the discrete solution is fixed and returns + Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a + vector and :math:`\mathbf{b_{k-1}}` is the discrete solution for the previous + time-step, this method assumes the discrete solution is fixed and returns .. math:: - \frac{\partial (\mathbf{B_k \, b_{k-1}})}{\partial \mathbf{m}} \, \mathbf{v} = \mathbf{0} + \frac{\partial (\mathbf{B_k \, b_{k-1}})}{\partial \mathbf{m}} \, \mathbf{v} + = \mathbf{0} Or the adjoint operation .. math:: - \frac{\partial (\mathbf{B_k \, b_{k-1}})}{\partial \mathbf{m}}^T \, \mathbf{v} = \mathbf{0} + \frac{\partial (\mathbf{B_k \, b_{k-1}})}{\partial \mathbf{m}}^T \, \mathbf{v} + = \mathbf{0} - The derivative operation returns a vector of zeros because the sub-diagonal system matrix - does not depend on the model!!! + The derivative operation returns a vector of zeros because the sub-diagonal + system matrix does not depend on the model!!! Parameters ---------- @@ -946,7 +994,8 @@ def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): The solution for the fields for the current model for the previous time-step; i.e. :math:`\mathbf{b_{k-1}}`. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -959,21 +1008,24 @@ def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): return Zero() * v def getRHS(self, tInd): - r"""Right-hand sides for the given time index. + r"""Return right-hand sides for the given time index. This method returns the right-hand sides for the time index provided. The right-hand side for each source is constructed according to: .. math:: \mathbf{q}_k = \mathbf{C M_{e\sigma}^{-1}} \mathbf{s}_{\mathbf{e}, k} \; - - \; \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{m}, k} - \mathbf{s}_{\mathbf{m}, k-1} \big ] + - \; \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{m}, k} + - \mathbf{s}_{\mathbf{m}, k-1} \big ] where * :math:`\Delta t_k` is the step length * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DMagneticFluxDensity` for a full description of the formulation. @@ -995,31 +1047,34 @@ def getRHS(self, tInd): s_m, s_e = self.getSourceTerm(tInd) rhs = C * (MeSigmaI * s_e) + s_m - if self._makeASymmetric is True: + if self._makeASymmetric: return MfMui.T * rhs return rhs def getRHSDeriv(self, tInd, src, v, adjoint=False): - r"""Derivative of the right-hand side times a vector for a given source and time index. + r"""Return right-hand side derivative times a vector for a given source and time index. The right-hand side for a given source at time index *k* is constructed according to: .. math:: \mathbf{q}_k = \mathbf{C M_{e\sigma}^{-1}} \mathbf{s}_{\mathbf{e}, k} \; - - \; \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{m}, k} - \mathbf{s}_{\mathbf{m}, k-1} \big ] + - \; \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{m}, k} + - \mathbf{s}_{\mathbf{m}, k-1} \big ] where * :math:`\Delta t_k` is the step length * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges - See the *Notes* section of the doc strings for :class:`Simulation3DMagneticFluxDensity` + See the *Notes* section of the doc strings for :class:`Simulation3DMagneticFluxDensity` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` is a vector, - this method returns + Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` + is a vector, this method returns .. math:: \frac{\partial \mathbf{q_k}}{\partial \mathbf{m}} \, \mathbf{v} @@ -1036,17 +1091,17 @@ def getRHSDeriv(self, tInd, src, v, adjoint=False): src : .time_domain.sources.BaseTDEMSrc The TDEM source object. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. Returns ------- numpy.ndarray - Derivative of the right-hand sides times a vector. (n_faces,) for the standard operation. - (n_param,) for the adjoint operation. + Derivative of the right-hand sides times a vector. (n_faces,) for the + standard operation. (n_param,) for the adjoint operation. """ - C = self.mesh.edge_curl MeSigmaI = self.MeSigmaI @@ -1072,7 +1127,7 @@ def getRHSDeriv(self, tInd, src, v, adjoint=False): RHSDeriv = C * MeSigmaIDeriv_v + C * MeSigmaI * s_eDeriv(v) + s_mDeriv(v) - if self._makeASymmetric is True: + if self._makeASymmetric: return self.MfMui.T * RHSDeriv return RHSDeriv @@ -1101,7 +1156,8 @@ class Simulation3DElectricField(BaseTDEMSimulation): electric displacement: .. math:: - &\nabla \times \vec{e} + \frac{\partial \vec{b}}{\partial t} = - \frac{\partial \vec{s}_m}{\partial t} \\ + &\nabla \times \vec{e} + \frac{\partial \vec{b}}{\partial t} = + - \frac{\partial \vec{s}_m}{\partial t} \\ &\nabla \times \vec{h} - \vec{j} = \vec{s}_e where :math:`\vec{s}_e` is an electric source term that defines a source current density, @@ -1113,8 +1169,9 @@ class Simulation3DElectricField(BaseTDEMSimulation): \vec{j} &= \sigma \vec{e} \\ \vec{h} &= \mu^{-1} \vec{b} - We then take the inner products of all previous expressions with a vector test function :math:`\vec{u}`. - Through vector calculus identities and the divergence theorem, we obtain: + We then take the inner products of all previous expressions with a vector test + function :math:`\vec{u}`. Through vector calculus identities and the divergence theorem, + we obtain: .. math:: & \int_\Omega \vec{u} \cdot (\nabla \times \vec{e}) \, dv @@ -1122,9 +1179,12 @@ class Simulation3DElectricField(BaseTDEMSimulation): = - \int_\Omega \vec{u} \cdot \frac{\partial \vec{s}_m}{\partial t} \, dv \\ & \int_\Omega (\nabla \times \vec{u}) \cdot \vec{h} \, dv - \oint_{\partial \Omega} \vec{u} \cdot (\vec{h} \times \hat{n}) \, da - - \int_\Omega \vec{u} \cdot \vec{j} \, dv = \int_\Omega \vec{u} \cdot \vec{s}_e \, dv \\ - & \int_\Omega \vec{u} \cdot \vec{j} \, dv = \int_\Omega \vec{u} \cdot \sigma \vec{e} \, dv \\ - & \int_\Omega \vec{u} \cdot \vec{h} \, dv = \int_\Omega \vec{u} \cdot \mu^{-1} \vec{b} \, dv + - \int_\Omega \vec{u} \cdot \vec{j} \, dv = + \int_\Omega \vec{u} \cdot \vec{s}_e \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{j} \, dv = + \int_\Omega \vec{u} \cdot \sigma \vec{e} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{h} \, dv = + \int_\Omega \vec{u} \cdot \mu^{-1} \vec{b} \, dv Assuming natural boundary conditions, the surface integral is zero. @@ -1146,21 +1206,27 @@ class Simulation3DElectricField(BaseTDEMSimulation): where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively * :math:`\mathbf{M_e}` is the edge inner-product matrix * :math:`\mathbf{M_f}` is the face inner-product matrix - * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities projected to edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse permeabilities projected to faces + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for conductivities + projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces - By cancelling like-terms and combining the discrete expressions in terms of the electric field, we obtain: + By cancelling like-terms and combining the discrete expressions in terms of the + electric field, we obtain: .. math:: - \mathbf{C^T M_{f\frac{1}{\mu}} C e} + \mathbf{M_{e\sigma}}\frac{\partial \mathbf{e}}{\partial t} + \mathbf{C^T M_{f\frac{1}{\mu}} C e} + + \mathbf{M_{e\sigma}}\frac{\partial \mathbf{e}}{\partial t} = \mathbf{C^T M_{f\frac{1}{\mu}}} \frac{\partial \mathbf{s_m}}{\partial t} - \frac{\partial \mathbf{s_e}}{\partial t} Finally, we discretize in time according to backward Euler. The discrete electric fields - on mesh edges at time :math:`t_k > t_0` is obtained by solving the following at each time-step: + on mesh edges at time :math:`t_k > t_0` is obtained by solving the following at each + time-step: .. math:: \mathbf{A}_k \mathbf{b}_k = \mathbf{q}_k - \mathbf{B}_k \mathbf{b}_{k-1} @@ -1168,11 +1234,13 @@ class Simulation3DElectricField(BaseTDEMSimulation): where :math:`\Delta t_k = t_k - t_{k-1}` and .. math:: - &\mathbf{A}_k = \mathbf{C^T M_{f\frac{1}{\mu}} C} + \frac{1}{\Delta t_k} \mathbf{M_{e\sigma}} \\ + &\mathbf{A}_k = \mathbf{C^T M_{f\frac{1}{\mu}} C} + + \frac{1}{\Delta t_k} \mathbf{M_{e\sigma}} \\ &\mathbf{B}_k = -\frac{1}{\Delta t_k} \mathbf{M_{e\sigma}} \\ &\mathbf{q}_k = \frac{1}{\Delta t_k} \mathbf{C^T M_{f\frac{1}{\mu}}} \big [ \mathbf{s}_{\mathbf{m}, k} - \mathbf{s}_{\mathbf{m}, k-1} \big ] - -\frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{e}, k} - \mathbf{s}_{\mathbf{e}, k-1} \big ] + -\frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{e}, k} + - \mathbf{s}_{\mathbf{e}, k-1} \big ] Although the following system is never explicitly formed, we can represent the solution at all time-steps as: @@ -1206,7 +1274,7 @@ class Simulation3DElectricField(BaseTDEMSimulation): Fields_Derivs = FieldsDerivativesEB # @profile - def Jtvec(self, m, v, f=None): + def Jtvec(self, m, v, f=None): # noqa D102 # Doctring inherited from parent class. if f is None: f = self.fields(m) @@ -1270,24 +1338,11 @@ def Jtvec(self, m, v, f=None): # no longer need this del PT_v - AdiagTinv = None - # Do the back-solve through time # if the previous timestep is the same: no need to refactor the matrix - # for tInd, dt in zip(range(self.nT), self.time_steps): - for tInd in reversed(range(self.nT)): # tInd = tIndP - 1 - if AdiagTinv is not None and ( - tInd <= self.nT and self.time_steps[tInd] != self.time_steps[tInd + 1] - ): - AdiagTinv.clean() - AdiagTinv = None - - # refactor if we need to - if AdiagTinv is None: # and tInd > -1: - Adiag = self.getAdiag(tInd) - AdiagTinv = self.solver(Adiag.T, **self.solver_opts) + AdiagTinv = self._get_stored_factor(tInd).T if tInd < self.nT - 1: Asubdiag = self.getAsubdiag(tInd + 1) @@ -1363,25 +1418,27 @@ def Jtvec(self, m, v, f=None): JTv = JTv + mkvc(-dAT_dm_v + dRHST_dm_v) # del df_duT_v, ATinv_df_duT_v, A, Asubdiag - if AdiagTinv is not None: - AdiagTinv.clean() + if not self.store_factors: + self._stored_factors = {} return mkvc(JTv).astype(float) def getAdiag(self, tInd): - r"""Diagonal system matrix for the time-step index provided. + r"""Return diagonal system matrix for the time-step index provided. This method returns the diagonal system matrix for the time-step index provided: .. math:: - \mathbf{A}_k = \mathbf{C^T M_{f\frac{1}{\mu}} C} + \frac{1}{\Delta t_k} \mathbf{M_{e\sigma}} + \mathbf{A}_k = \mathbf{C^T M_{f\frac{1}{\mu}} C} + + \frac{1}{\Delta t_k} \mathbf{M_{e\sigma}} where * :math:`\Delta t_k` is the step length * :math:`\mathbf{C}` is the discrete curl operator * :math:`\mathbf{M_{e \sigma}}` is the conductivity inner-product matrix on edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inverse permeability inner-product matrix on faces + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inverse permeability + inner-product matrix on faces See the *Notes* section of the doc strings for :class:`Simulation3DElectricField` for a full description of the formulation. @@ -1396,7 +1453,8 @@ def getAdiag(self, tInd): (n_edges, n_edges) sp.sparse.csr_matrix The diagonal system matrix. """ - assert tInd >= 0 and tInd < self.nT + if not 0 <= tInd < self.nT: + raise ValueError("Time step index must be within [0, nT]") dt = self.time_steps[tInd] C = self.mesh.edge_curl @@ -1406,26 +1464,28 @@ def getAdiag(self, tInd): return C.T.tocsr() * (MfMui * C) + 1.0 / dt * MeSigma def getAdiagDeriv(self, tInd, u, v, adjoint=False): - r"""Derivative operation for the diagonal system matrix times a vector. + r"""Return derivative operation for the diagonal system matrix times a vector. The diagonal system matrix for time-step index *k* is given by: .. math:: - \mathbf{A}_k = \mathbf{C^T M_{f\frac{1}{\mu}} C} + \frac{1}{\Delta t_k} \mathbf{M_{e\sigma}} + \mathbf{A}_k = \mathbf{C^T M_{f\frac{1}{\mu}} C} + + \frac{1}{\Delta t_k} \mathbf{M_{e\sigma}} where * :math:`\Delta t_k` is the step length * :math:`\mathbf{C}` is the discrete curl operator * :math:`\mathbf{M_{e \sigma}}` is the conductivity inner-product matrix on edges - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inverse permeability inner-product matrix on faces + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inverse permeability inner-product + matrix on faces See the *Notes* section of the doc strings for :class:`Simulation3DElectricField` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a vector - and :math:`\mathbf{e_k}` is the discrete solution for time-step *k*, this method assumes - the discrete solution is fixed and returns + Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a + vector and :math:`\mathbf{e_k}` is the discrete solution for time-step *k*, this + method assumes the discrete solution is fixed and returns .. math:: \frac{\partial (\mathbf{A_k \, e_k})}{\partial \mathbf{m}} \, \mathbf{v} @@ -1443,7 +1503,8 @@ def getAdiagDeriv(self, tInd, u, v, adjoint=False): The solution for the fields for the current model for the specified time-step; i.e. :math:`\mathbf{e_k}`. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint + operation. adjoint : bool Whether to perform the adjoint operation. @@ -1453,18 +1514,15 @@ def getAdiagDeriv(self, tInd, u, v, adjoint=False): Derivative of system matrix times a vector. (n_edges,) for the standard operation. (n_param,) for the adjoint operation. """ - assert tInd >= 0 and tInd < self.nT + if not 0 <= tInd < self.nT: + raise ValueError("Time step index must be within [0, nT]") dt = self.time_steps[tInd] - # MeSigmaDeriv = self.MeSigmaDeriv(u) - - if adjoint: - return 1.0 / dt * self.MeSigmaDeriv(u, v, adjoint) return 1.0 / dt * self.MeSigmaDeriv(u, v, adjoint) def getAsubdiag(self, tInd): - r"""Sub-diagonal system matrix for the time-step index provided. + r"""Return sub-diagonal system matrix for the time-step index provided. This method returns the sub-diagonal system matrix for the time-step index provided: @@ -1487,14 +1545,15 @@ def getAsubdiag(self, tInd): (n_edges, n_edges) sp.sparse.csr_matrix The sub-diagonal system matrix. """ - assert tInd >= 0 and tInd < self.nT + if not 0 <= tInd < self.nT: + raise ValueError("Time step index must be within [0, nT]") dt = self.time_steps[tInd] return -1.0 / dt * self.MeSigma def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): - r"""Derivative operation for the sub-diagonal system matrix times a vector. + r"""Return derivative operation for the sub-diagonal system matrix times a vector. The sub-diagonal system matrix for time-step index *k* is given by: @@ -1507,9 +1566,9 @@ def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): See the *Notes* section of the doc strings for :class:`Simulation3DElectricField` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a vector - and :math:`\mathbf{e_{k-1}}` is the discrete solution for the previous time-step, - this method assumes the discrete solution is fixed and returns + Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is + a vector and :math:`\mathbf{e_{k-1}}` is the discrete solution for the previous + time-step, this method assumes the discrete solution is fixed and returns .. math:: \frac{\partial (\mathbf{B_k \, e_{k-1}})}{\partial \mathbf{m}} \, \mathbf{v} @@ -1527,7 +1586,8 @@ def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): The solution for the fields for the current model for the previous time-step; i.e. :math:`\mathbf{e_{k-1}}`. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_edges,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -1537,22 +1597,23 @@ def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): Derivative of system matrix times a vector. (n_edges,) for the standard operation. (n_param,) for the adjoint operation. """ - dt = self.time_steps[tInd] + if not 0 <= tInd < self.nT: + raise ValueError("Time step index must be within [0, nT]") - if adjoint: - return -1.0 / dt * self.MeSigmaDeriv(u, v, adjoint) + dt = self.time_steps[tInd] return -1.0 / dt * self.MeSigmaDeriv(u, v, adjoint) def getRHS(self, tInd): - r"""Right-hand sides for the given time index. + r"""Return right-hand sides for the given time index. This method returns the right-hand sides for the time index provided. The right-hand side for each source is constructed according to: .. math:: \mathbf{q}_k = - -\frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{e}, k} - \mathbf{s}_{\mathbf{e}, k-1} \big ] + -\frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{e}, k} + - \mathbf{s}_{\mathbf{e}, k-1} \big ] - \frac{1}{\Delta t_k} \mathbf{C^T M_{f\frac{1}{\mu}}} \big [ \mathbf{s}_{\mathbf{m}, k} - \mathbf{s}_{\mathbf{m}, k-1} \big ] @@ -1560,8 +1621,10 @@ def getRHS(self, tInd): * :math:`\Delta t_k` is the step length * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrices for inverse permeabilities projected to faces + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic + and electric source terms, respectively + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrices for + inverse permeabilities projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DElectricField` for a full description of the formulation. @@ -1587,28 +1650,31 @@ def getRHS(self, tInd): return -1.0 / dt * (s_e - s_en1) + self.mesh.edge_curl.T * self.MfMui * s_m def getRHSDeriv(self, tInd, src, v, adjoint=False): - r"""Derivative of the right-hand side times a vector for a given source and time index. + r"""Return right-hand side derivative times a vector for a given source and time index. The right-hand side for a given source at time index *k* is constructed according to: .. math:: \mathbf{q}_k = - -\frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{e}, k} - \mathbf{s}_{\mathbf{e}, k-1} \big ] + -\frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{e}, k} + - \mathbf{s}_{\mathbf{e}, k-1} \big ] - \frac{1}{\Delta t_k} \mathbf{C^T M_{f\frac{1}{\mu}} } \big [ \mathbf{s}_{\mathbf{m}, k} - \mathbf{s}_{\mathbf{m}, k-1} \big ] - where + * :math:`\Delta t_k` is the step length * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrices for inverse permeabilities projected to faces + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrices for inverse + permeabilities projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DElectricField` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` is a vector, - this method returns + Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` + is a vector, this method returns .. math:: \frac{\partial \mathbf{q_k}}{\partial \mathbf{m}} \, \mathbf{v} @@ -1625,21 +1691,23 @@ def getRHSDeriv(self, tInd, src, v, adjoint=False): src : .time_domain.sources.BaseTDEMSrc The TDEM source object. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_edges,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. Returns ------- numpy.ndarray - Derivative of the right-hand sides times a vector. (n_edges,) for the standard operation. + Derivative of the right-hand sides times a vector. (n_edges,) for the + standard operation. (n_param,) for the adjoint operation. """ # right now, we are assuming that s_e, s_m do not depend on the model. return Zero() def getAdc(self): - r"""The system matrix for the DC resistivity problem. + r"""Return the system matrix for the DC resistivity problem. The solution to the DC resistivity problem is necessary at the initial time for galvanic sources whose currents are non-zero at the initial time. @@ -1648,19 +1716,21 @@ def getAdc(self): .. math:: \mathbf{A_{dc}}\,\boldsymbol{\phi_0} = \mathbf{q_{dc}} - where :math:`\mathbf{A_{dc}}` is the DC resistivity system matrix, :math:`\boldsymbol{\phi_0}` - is the discrete solution for the electric potentials at the initial time, and :math:`\mathbf{q_{dc}}` + where :math:`\mathbf{A_{dc}}` is the DC resistivity system matrix, + :math:`\boldsymbol{\phi_0}` is the discrete solution for the electric potentials + at the initial time, and :math:`\mathbf{q_{dc}}` is the galvanic source term. This method returns the system matrix for the nodal formulation, i.e.: .. math:: \mathbf{A_{dc}} = \mathbf{G^T \, M_{e\sigma} \, G} - where :math:`\mathbf{G}` is the nodal gradient operator with imposed boundary conditions, - and :math:`\mathbf{M_{e\sigma}}` is the inner product matrix for conductivities projected to edges. + where :math:`\mathbf{G}` is the nodal gradient operator with imposed boundary + conditions, and :math:`\mathbf{M_{e\sigma}}` is the inner product matrix for + conductivities projected to edges. - The electric fields at the initial time :math:`\mathbf{e_0}` are obtained by applying the - nodal gradient operator. I.e.: + The electric fields at the initial time :math:`\mathbf{e_0}` are obtained by + applying the nodal gradient operator. I.e.: .. math:: \mathbf{e_0} = \mathbf{G} \, \boldsymbol{\phi_0} @@ -1681,39 +1751,45 @@ def getAdc(self): return Adc def getAdcDeriv(self, u, v, adjoint=False): - r"""Derivative operation for the DC resistivity system matrix times a vector. + r"""Return derivative operation for the DC resistivity system matrix times a vector. The discrete solution to the 3D DC resistivity problem is expressed as: .. math:: \mathbf{A_{dc}}\boldsymbol{\phi_0} = \mathbf{q_{dc}} - where :math:`\mathbf{A_{dc}}` is the DC resistivity system matrix, :math:`\boldsymbol{\phi_0}` - is the discrete solution for the electric potentials at the initial time, and :math:`\mathbf{q_{dc}}` + where :math:`\mathbf{A_{dc}}` is the DC resistivity system matrix, + :math:`\boldsymbol{\phi_0}` is the discrete solution for the electric potentials + at the initial time, and :math:`\mathbf{q_{dc}}` is the galvanic source term. For a vector :math:`\mathbf{v}`, this method assumes the discrete solution is fixed and returns .. math:: - \frac{\partial (\mathbf{A_{dc}}\boldsymbol{\phi_0})}{\partial \mathbf{m}} \, \mathbf{v} + \frac{\partial (\mathbf{A_{dc}}\boldsymbol{\phi_0})}{\partial \mathbf{m}} + \, \mathbf{v} Or the adjoint operation .. math:: - \frac{\partial (\mathbf{A_{dc}}\boldsymbol{\phi_0})}{\partial \mathbf{m}}^T \, \mathbf{v} + \frac{\partial (\mathbf{A_{dc}}\boldsymbol{\phi_0})}{\partial \mathbf{m}}^T + \, \mathbf{v} Parameters ---------- u : (n_nodes,) numpy.ndarray - The solution for the fields for the current model; i.e. electric potentials at nodes. + The solution for the fields for the current model; i.e. electric potentials + at nodes. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_nodes,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_nodes,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. Returns ------- numpy.ndarray - Derivative of the DC resistivity system matrix times a vector. (n_nodes,) for the standard operation. + Derivative of the DC resistivity system matrix times a vector. + (n_nodes,) for the standard operation. (n_param,) for the adjoint operation. """ Grad = self.mesh.nodal_gradient @@ -1755,7 +1831,8 @@ class Simulation3DMagneticField(BaseTDEMSimulation): electric displacement: .. math:: - &\nabla \times \vec{e} + \frac{\partial \vec{b}}{\partial t} = - \frac{\partial \vec{s}_m}{\partial t} \\ + &\nabla \times \vec{e} + \frac{\partial \vec{b}}{\partial t} = + - \frac{\partial \vec{s}_m}{\partial t} \\ &\nabla \times \vec{h} - \vec{j} = \vec{s}_e where :math:`\vec{s}_e` is an electric source term that defines a source current density, @@ -1767,18 +1844,22 @@ class Simulation3DMagneticField(BaseTDEMSimulation): \vec{e} &= \rho \vec{e} \\ \vec{b} &= \mu \vec{h} - We then take the inner products of all previous expressions with a vector test function :math:`\vec{u}`. - Through vector calculus identities and the divergence theorem, we obtain: + We then take the inner products of all previous expressions with a vector test + function :math:`\vec{u}`. Through vector calculus identities and the divergence theorem, + we obtain: .. math:: & \int_\Omega (\nabla \times \vec{u}) \cdot \vec{e} \; dv - \oint_{\partial \Omega} \vec{u} \cdot (\vec{e} \times \hat{n} ) \, da + \int_\Omega \vec{u} \cdot \frac{\partial \vec{b}}{\partial t} \, dv = - \int_\Omega \vec{u} \cdot \frac{\partial \vec{s}_m}{\partial t} \, dv \\ - & \int_\Omega \vec{u} \cdot (\nabla \times \vec{h} ) \, dv - \int_\Omega \vec{u} \cdot \vec{j} \, dv + & \int_\Omega \vec{u} \cdot (\nabla \times \vec{h} ) \, dv + - \int_\Omega \vec{u} \cdot \vec{j} \, dv = \int_\Omega \vec{u} \cdot \vec{s}_e \, dv\\ - & \int_\Omega \vec{u} \cdot \vec{e} \, dv = \int_\Omega \vec{u} \cdot \rho \vec{j} \, dv \\ - & \int_\Omega \vec{u} \cdot \vec{b} \, dv = \int_\Omega \vec{u} \cdot \mu \vec{h} \, dv + & \int_\Omega \vec{u} \cdot \vec{e} \, dv = + \int_\Omega \vec{u} \cdot \rho \vec{j} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{b} \, dv = + \int_\Omega \vec{u} \cdot \mu \vec{h} \, dv Assuming natural boundary conditions, the surface integral is zero. @@ -1791,7 +1872,8 @@ class Simulation3DMagneticField(BaseTDEMSimulation): set of discrete inner-products: .. math:: - &\mathbf{u_e^T C^T M_f \, e } + \mathbf{u_e^T M_e} \frac{\partial \mathbf{b}}{\partial t} + &\mathbf{u_e^T C^T M_f \, e } + + \mathbf{u_e^T M_e} \frac{\partial \mathbf{b}}{\partial t} = - \mathbf{u_e^T} \, \frac{\partial \mathbf{s_m}}{\partial t} \\ &\mathbf{u_f^T C \, h} - \mathbf{u_f^T j} = \mathbf{u_f^T s_e} \\ &\mathbf{u_f^T M_f e} = \mathbf{u_f^T M_{f\rho} \, j} \\ @@ -1800,20 +1882,26 @@ class Simulation3DMagneticField(BaseTDEMSimulation): where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric + source terms, respectively * :math:`\mathbf{M_e}` is the edge inner-product matrix * :math:`\mathbf{M_f}` is the face inner-product matrix - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected to faces + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected + to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected + to faces - Cancelling like-terms and combining the discrete expressions in terms of the magnetic field, we obtain: + Cancelling like-terms and combining the discrete expressions in terms of the magnetic + field, we obtain: .. math:: - \mathbf{C^T M_{f\rho} C \, h} + \mathbf{M_{e\mu}} \frac{\partial \mathbf{h}}{\partial t} + \mathbf{C^T M_{f\rho} C \, h} + + \mathbf{M_{e\mu}} \frac{\partial \mathbf{h}}{\partial t} = \mathbf{C^T M_{f\rho} s_e} - \frac{\partial \mathbf{s_m}}{\partial t} Finally, we discretize in time according to backward Euler. The discrete magnetic field - on mesh edges at time :math:`t_k > t_0` is obtained by solving the following at each time-step: + on mesh edges at time :math:`t_k > t_0` is obtained by solving the following at + each time-step: .. math:: \mathbf{A}_k \mathbf{h}_k = \mathbf{q}_k - \mathbf{B}_k \mathbf{h}_{k-1} @@ -1824,7 +1912,8 @@ class Simulation3DMagneticField(BaseTDEMSimulation): &\mathbf{A}_k = \mathbf{C^T M_{f\rho} C} + \frac{1}{\Delta t_k} \mathbf{M_{e\mu}} \\ &\mathbf{B}_k = -\frac{1}{\Delta t_k} \mathbf{M_{e\mu}}\\ &\mathbf{q}_k = \mathbf{C^T M_{f\rho} s}_{\mathbf{e},k} \; - - \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{m},k} + \mathbf{s}_{\mathbf{m},k-1} \big ] + - \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{m},k} + + \mathbf{s}_{\mathbf{m},k-1} \big ] Although the following system is never explicitly formed, we can represent the solution at all time-steps as: @@ -1849,7 +1938,6 @@ class Simulation3DMagneticField(BaseTDEMSimulation): where the magnetic fields at the initial time :math:`\mathbf{h_0}` are computed analytically or numerically depending on whether the source carries non-zero current at the initial time. - """ _fieldType = "h" @@ -1858,7 +1946,7 @@ class Simulation3DMagneticField(BaseTDEMSimulation): Fields_Derivs = FieldsDerivativesHJ def getAdiag(self, tInd): - r"""Diagonal system matrix for the given time-step index. + r"""Return diagonal system matrix for the given time-step index. This method returns the diagonal system matrix for the time-step index provided: @@ -1885,7 +1973,8 @@ def getAdiag(self, tInd): (n_edges, n_edges) sp.sparse.csr_matrix The diagonal system matrix. """ - assert tInd >= 0 and tInd < self.nT + if not 0 <= tInd < self.nT: + raise ValueError("Time step index must be within [0, nT]") dt = self.time_steps[tInd] C = self.mesh.edge_curl @@ -1895,7 +1984,7 @@ def getAdiag(self, tInd): return C.T * (MfRho * C) + 1.0 / dt * MeMu def getAdiagDeriv(self, tInd, u, v, adjoint=False): - r"""Derivative operation for the diagonal system matrix times a vector. + r"""Return derivative operation for the diagonal system matrix times a vector. The diagonal system matrix for time-step index *k* is given by: @@ -1912,9 +2001,9 @@ def getAdiagDeriv(self, tInd, u, v, adjoint=False): See the *Notes* section of the doc strings for :class:`Simulation3DMagneticField` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a vector - and :math:`\mathbf{h_k}` is the discrete solution for time-step *k*, this method assumes - the discrete solution is fixed and returns + Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a + vector and :math:`\mathbf{h_k}` is the discrete solution for time-step *k*, this + method assumes the discrete solution is fixed and returns .. math:: \frac{\partial (\mathbf{A_k \, h_k})}{\partial \mathbf{m}} \, \mathbf{v} @@ -1931,7 +2020,8 @@ def getAdiagDeriv(self, tInd, u, v, adjoint=False): u : (n_edges,) numpy.ndarray The solution for the fields for the current model; i.e. :math:`\mathbf{h_k}`. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_edges,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -1951,7 +2041,7 @@ def getAdiagDeriv(self, tInd, u, v, adjoint=False): return C.T * self.MfRhoDeriv(C * u, v, adjoint) def getAsubdiag(self, tInd): - r"""Sub-diagonal system matrix for the time-step index provided. + r"""Return sub-diagonal system matrix for the time-step index provided. This method returns the sub-diagonal system matrix for the time-step index provided: @@ -1981,7 +2071,7 @@ def getAsubdiag(self, tInd): return -1.0 / dt * self.MeMu def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): - r"""Derivative operation for the sub-diagonal system matrix times a vector. + r"""Return derivative operation for the sub-diagonal system matrix times a vector. The sub-diagonal system matrix for time-step index *k* is given by: @@ -1994,9 +2084,9 @@ def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): See the *Notes* section of the doc strings for :class:`Simulation3DMagneticField` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a vector - and :math:`\mathbf{h_{k-1}}` is the discrete solution for the previous time-step, - this method assumes the discrete solution is fixed and returns + Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` + is a vector and :math:`\mathbf{h_{k-1}}` is the discrete solution for the previous + time-step, this method assumes the discrete solution is fixed and returns .. math:: \frac{\partial (\mathbf{B_k \, h_{k-1}})}{\partial \mathbf{m}} \, \mathbf{v} @@ -2014,7 +2104,8 @@ def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): The solution for the fields for the current model for the previous time-step; i.e. :math:`\mathbf{h_{k-1}}`. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_edges,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -2027,21 +2118,24 @@ def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): return Zero() def getRHS(self, tInd): - r"""Right-hand sides for the given time index. + r"""Return right-hand sides for the given time index. This method returns the right-hand sides for the time index provided. The right-hand side for each source is constructed according to: .. math:: \mathbf{q}_k = \mathbf{C^T M_{f\rho} s}_{\mathbf{e},k} \; - - \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{m},k} + \mathbf{s}_{\mathbf{m},k-1} \big ] + - \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{m},k} + + \mathbf{s}_{\mathbf{m},k-1} \big ] where * :math:`\Delta t_k` is the step length * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resisitivites projected to faces + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic + and electric source terms, respectively + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resisitivites + projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DMagneticField` for a full description of the formulation. @@ -2063,26 +2157,29 @@ def getRHS(self, tInd): return C.T * (MfRho * s_e) + s_m def getRHSDeriv(self, tInd, src, v, adjoint=False): - r"""Derivative of the right-hand side times a vector for a given source and time index. + r"""Return right-hand side derivative times a vector for a given source and time index. The right-hand side for a given source at time index *k* is constructed according to: .. math:: \mathbf{q}_k = \mathbf{C^T M_{f\rho} s}_{\mathbf{e},k} \; - - \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{m},k} + \mathbf{s}_{\mathbf{m},k-1} \big ] + - \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{m},k} + + \mathbf{s}_{\mathbf{m},k-1} \big ] where * :math:`\Delta t_k` is the step length * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resisitivites projected to faces + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resisitivites + projected to faces See the *Notes* section of the doc strings for :class:`Simulation3DMagneticField` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` is a vector, - this method returns + Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` + is a vector, this method returns .. math:: \frac{\partial \mathbf{q_k}}{\partial \mathbf{m}} \, \mathbf{v} @@ -2099,27 +2196,29 @@ def getRHSDeriv(self, tInd, src, v, adjoint=False): src : .time_domain.sources.BaseTDEMSrc The TDEM source object. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_edges,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_edges,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. Returns ------- numpy.ndarray - Derivative of the right-hand sides times a vector. (n_edges,) for the standard operation. + Derivative of the right-hand sides times a vector. (n_edges,) for the + standard operation. (n_param,) for the adjoint operation. """ C = self.mesh.edge_curl s_m, s_e = src.eval(self, self.times[tInd]) - if adjoint is True: + if adjoint: return self.MfRhoDeriv(s_e, C * v, adjoint) # assumes no source derivs return C.T * self.MfRhoDeriv(s_e, v, adjoint) # I DON'T THINK THIS IS CURRENTLY USED BY THE H-FORMULATION. def getAdc(self): - r"""The system matrix for the DC resistivity problem. + r"""Return the system matrix for the DC resistivity problem. The solution to the DC resistivity problem is necessary at the initial time for galvanic sources whose currents are non-zero at the initial time. @@ -2128,16 +2227,18 @@ def getAdc(self): .. math:: \mathbf{A_{dc}}\,\boldsymbol{\phi_0} = \mathbf{q_{dc}} - where :math:`\mathbf{A_{dc}}` is the DC resistivity system matrix, :math:`\boldsymbol{\phi_0}` - is the discrete solution for the electric potentials at the initial time, and :math:`\mathbf{q_{dc}}` + where :math:`\mathbf{A_{dc}}` is the DC resistivity system matrix, + :math:`\boldsymbol{\phi_0}` is the discrete solution for the electric potentials + at the initial time, and :math:`\mathbf{q_{dc}}` is the galvanic source term. This method returns the system matrix for the cell-centered formulation, i.e.: .. math:: \mathbf{D \, M_{f\rho}^{-1} \, G} - where :math:`\mathbf{D}` is the face divergence operator, :math:`\mathbf{G}` is the cell gradient - operator with imposed boundary conditions, and :math:`\mathbf{M_{f\rho}}` is the inner product + where :math:`\mathbf{D}` is the face divergence operator, :math:`\mathbf{G}` is + the cell gradient operator with imposed boundary conditions, and + :math:`\mathbf{M_{f\rho}}` is the inner product matrix for resistivities projected to faces. See the *Notes* section of the doc strings for @@ -2155,40 +2256,45 @@ def getAdc(self): return D * MfRhoI * G def getAdcDeriv(self, u, v, adjoint=False): - r"""Derivative operation for the DC resistivity system matrix times a vector. + r"""Return derivative operation for the DC resistivity system matrix times a vector. The discrete solution to the 3D DC resistivity problem is expressed as: .. math:: \mathbf{A_{dc}}\boldsymbol{\phi_0} = \mathbf{q_{dc}} - where :math:`\mathbf{A_{dc}}` is the DC resistivity system matrix, :math:`\boldsymbol{\phi_0}` - is the discrete solution for the electric potentials at the initial time, and :math:`\mathbf{q_{dc}}` + where :math:`\mathbf{A_{dc}}` is the DC resistivity system matrix, + :math:`\boldsymbol{\phi_0}` is the discrete solution for the electric potentials + at the initial time, and :math:`\mathbf{q_{dc}}` is the galvanic source term. For a vector :math:`\mathbf{v}`, this method assumes the discrete solution is fixed and returns .. math:: - \frac{\partial (\mathbf{A_{dc}}\boldsymbol{\phi_0})}{\partial \mathbf{m}} \, \mathbf{v} + \frac{\partial (\mathbf{A_{dc}}\boldsymbol{\phi_0})}{\partial \mathbf{m}} \, + \mathbf{v} Or the adjoint operation .. math:: - \frac{\partial (\mathbf{A_{dc}}\boldsymbol{\phi_0})}{\partial \mathbf{m}}^T \, \mathbf{v} + \frac{\partial (\mathbf{A_{dc}}\boldsymbol{\phi_0})}{\partial \mathbf{m}}^T \, + \mathbf{v} Parameters ---------- u : (n_cells,) numpy.ndarray - The solution for the fields for the current model; i.e. electric potentials at cell centers. + The solution for the fields for the current model; i.e. electric potentials at + cell centers. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_cells,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_cells,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. Returns ------- numpy.ndarray - Derivative of the DC resistivity system matrix times a vector. (n_cells,) for the standard operation. - (n_param,) for the adjoint operation. + Derivative of the DC resistivity system matrix times a vector. (n_cells,) + for the standard operation. (n_param,) for the adjoint operation. """ D = sdiag(self.mesh.cell_volumes) * self.mesh.face_divergence G = D.T @@ -2226,7 +2332,8 @@ class Simulation3DCurrentDensity(BaseTDEMSimulation): electric displacement: .. math:: - &\nabla \times \vec{e} + \frac{\partial \vec{b}}{\partial t} = - \frac{\partial \vec{s}_m}{\partial t} \\ + &\nabla \times \vec{e} + \frac{\partial \vec{b}}{\partial t} = + - \frac{\partial \vec{s}_m}{\partial t} \\ &\nabla \times \vec{h} - \vec{j} = \vec{s}_e where :math:`\vec{s}_e` is an electric source term that defines a source current density, @@ -2238,18 +2345,21 @@ class Simulation3DCurrentDensity(BaseTDEMSimulation): \vec{e} &= \rho \vec{e} \\ \vec{b} &= \mu \vec{h} - We then take the inner products of all previous expressions with a vector test function :math:`\vec{u}`. - Through vector calculus identities and the divergence theorem, we obtain: + We then take the inner products of all previous expressions with a vector test function + :math:`\vec{u}`. Through vector calculus identities and the divergence theorem, we obtain: .. math:: & \int_\Omega (\nabla \times \vec{u}) \cdot \vec{e} \; dv - \oint_{\partial \Omega} \vec{u} \cdot (\vec{e} \times \hat{n} ) \, da + \int_\Omega \vec{u} \cdot \frac{\partial \vec{b}}{\partial t} \, dv = - \int_\Omega \vec{u} \cdot \frac{\partial \vec{s}_m}{\partial t} \, dv \\ - & \int_\Omega \vec{u} \cdot (\nabla \times \vec{h} ) \, dv - \int_\Omega \vec{u} \cdot \vec{j} \, dv + & \int_\Omega \vec{u} \cdot (\nabla \times \vec{h} ) \, dv + - \int_\Omega \vec{u} \cdot \vec{j} \, dv = \int_\Omega \vec{u} \cdot \vec{s}_e \, dv\\ - & \int_\Omega \vec{u} \cdot \vec{e} \, dv = \int_\Omega \vec{u} \cdot \rho \vec{j} \, dv \\ - & \int_\Omega \vec{u} \cdot \vec{b} \, dv = \int_\Omega \vec{u} \cdot \mu \vec{h} \, dv + & \int_\Omega \vec{u} \cdot \vec{e} \, dv = + \int_\Omega \vec{u} \cdot \rho \vec{j} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{b} \, dv = + \int_\Omega \vec{u} \cdot \mu \vec{h} \, dv Assuming natural boundary conditions, the surface integral is zero. @@ -2262,7 +2372,8 @@ class Simulation3DCurrentDensity(BaseTDEMSimulation): set of discrete inner-products: .. math:: - &\mathbf{u_e^T C^T M_f \, e } + \mathbf{u_e^T M_e} \frac{\partial \mathbf{b}}{\partial t} + &\mathbf{u_e^T C^T M_f \, e } + \mathbf{u_e^T M_e} + \frac{\partial \mathbf{b}}{\partial t} = - \mathbf{u_e^T} \, \frac{\partial \mathbf{s_m}}{\partial t} \\ &\mathbf{u_f^T C \, h} - \mathbf{u_f^T j} = \mathbf{u_f^T s_e} \\ &\mathbf{u_f^T M_f e} = \mathbf{u_f^T M_{f\rho} \, j} \\ @@ -2271,13 +2382,17 @@ class Simulation3DCurrentDensity(BaseTDEMSimulation): where * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic + and electric source terms, respectively * :math:`\mathbf{M_e}` is the edge inner-product matrix * :math:`\mathbf{M_f}` is the face inner-product matrix - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges - * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities projected to faces + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities + projected to edges + * :math:`\mathbf{M_{f\rho}}` is the inner-product matrix for resistivities + projected to faces - Cancelling like-terms and combining the discrete expressions in terms of the current density, we obtain: + Cancelling like-terms and combining the discrete expressions in terms of the current + density, we obtain: .. math:: \mathbf{C M_{e\mu}^{-1} C^T M_{f\rho} \, j} + @@ -2286,7 +2401,8 @@ class Simulation3DCurrentDensity(BaseTDEMSimulation): - \mathbf{C M_{e\mu}^{-1}} \frac{\partial \mathbf{s_m}}{\partial t} Finally, we discretize in time according to backward Euler. The discrete current density - on mesh edges at time :math:`t_k > t_0` is obtained by solving the following at each time-step: + on mesh edges at time :math:`t_k > t_0` is obtained by solving the following at + each time-step: .. math:: \mathbf{A}_k \mathbf{j}_k = \mathbf{q}_k - \mathbf{B}_k \mathbf{j}_{k-1} @@ -2294,10 +2410,13 @@ class Simulation3DCurrentDensity(BaseTDEMSimulation): where :math:`\Delta t_k = t_k - t_{k-1}` and .. math:: - &\mathbf{A}_k = \mathbf{C M_{e\mu}^{-1} C^T M_{f\rho}} + \frac{1}{\Delta t_k} \mathbf{I} \\ + &\mathbf{A}_k = \mathbf{C M_{e\mu}^{-1} C^T M_{f\rho}} + + \frac{1}{\Delta t_k} \mathbf{I} \\ &\mathbf{B}_k = - \frac{1}{\Delta t_k} \mathbf{I}\\ - &\mathbf{q}_k = - \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{e},k} + \mathbf{s}_{\mathbf{e},k-1} \big ] \; - - \; \frac{1}{\Delta t_k} \mathbf{C M_{e\mu}^{-1}} \big [ \mathbf{s}_{\mathbf{m},k} + \mathbf{s}_{\mathbf{m},k-1} \big ] + &\mathbf{q}_k = - \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{e},k} + + \mathbf{s}_{\mathbf{e},k-1} \big ] \; + - \; \frac{1}{\Delta t_k} \mathbf{C M_{e\mu}^{-1}} + \big [ \mathbf{s}_{\mathbf{m},k} + \mathbf{s}_{\mathbf{m},k-1} \big ] Although the following system is never explicitly formed, we can represent the solution at all time-steps as: @@ -2330,12 +2449,13 @@ class Simulation3DCurrentDensity(BaseTDEMSimulation): Fields_Derivs = FieldsDerivativesHJ def getAdiag(self, tInd): - r"""Diagonal system matrix for the given time-step index. + r"""Return diagonal system matrix for the given time-step index. This method returns the diagonal system matrix for the time-step index provided: .. math:: - \mathbf{A}_k = \mathbf{C M_{e\mu}^{-1} C^T M_{f\rho}} + \frac{1}{\Delta t_k} \mathbf{I} + \mathbf{A}_k = \mathbf{C M_{e\mu}^{-1} C^T M_{f\rho}} + + \frac{1}{\Delta t_k} \mathbf{I} where @@ -2358,7 +2478,8 @@ def getAdiag(self, tInd): (n_faces, n_faces) sp.sparse.csr_matrix The diagonal system matrix. """ - assert tInd >= 0 and tInd < self.nT + if not 0 <= tInd < self.nT: + raise ValueError("Time step index must be within [0, nT]") dt = self.time_steps[tInd] C = self.mesh.edge_curl @@ -2374,12 +2495,13 @@ def getAdiag(self, tInd): return A def getAdiagDeriv(self, tInd, u, v, adjoint=False): - r"""Derivative operation for the diagonal system matrix times a vector. + r"""Return derivative operation for the diagonal system matrix times a vector. The diagonal system matrix for time-step index *k* is given by: .. math:: - \mathbf{A}_k = \mathbf{C M_{e\mu}^{-1} C^T M_{f\rho}} + \frac{1}{\Delta t_k} \mathbf{I} + \mathbf{A}_k = \mathbf{C M_{e\mu}^{-1} C^T M_{f\rho}} + + \frac{1}{\Delta t_k} \mathbf{I} where @@ -2392,9 +2514,9 @@ def getAdiagDeriv(self, tInd, u, v, adjoint=False): See the *Notes* section of the doc strings for :class:`Simulation3DCurrentDensity` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a vector - and :math:`\mathbf{j_k}` is the discrete solution for time-step *k*, this method assumes - the discrete solution is fixed and returns + Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a + vector and :math:`\mathbf{j_k}` is the discrete solution for time-step *k*, this + method assumes the discrete solution is fixed and returns .. math:: \frac{\partial (\mathbf{A_k \, j_k})}{\partial \mathbf{m}} \, \mathbf{v} @@ -2411,7 +2533,8 @@ def getAdiagDeriv(self, tInd, u, v, adjoint=False): u : (n_faces,) numpy.ndarray The solution for the fields for the current model; i.e. :math:`\mathbf{j_k}`. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -2438,7 +2561,7 @@ def getAdiagDeriv(self, tInd, u, v, adjoint=False): return ADeriv def getAsubdiag(self, tInd): - r"""Sub-diagonal system matrix for the time-step index provided. + r"""Return sub-diagonal system matrix for the time-step index provided. This method returns the sub-diagonal system matrix for the time-step index provided: @@ -2471,7 +2594,7 @@ def getAsubdiag(self, tInd): return -1.0 / dt * eye def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): - r"""Derivative operation for the sub-diagonal system matrix times a vector. + r"""Return derivative operation for the sub-diagonal system matrix times a vector. The sub-diagonal system matrix for time-step index *k* is given by: @@ -2484,9 +2607,9 @@ def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): See the *Notes* section of the doc strings for :class:`Simulation3DCurrentDensity` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a vector - and :math:`\mathbf{j_{k-1}}` is the discrete solution for the previous time-step, - this method assumes the discrete solution is fixed and returns + Where :math:`\mathbf{m}` are the set of model parameters, :math:`\mathbf{v}` is a + vector and :math:`\mathbf{j_{k-1}}` is the discrete solution for the previous + time-step, this method assumes the discrete solution is fixed and returns .. math:: \frac{\partial (\mathbf{B_k \, j_{k-1}})}{\partial \mathbf{m}} \, \mathbf{v} @@ -2504,7 +2627,8 @@ def getAsubdiagDeriv(self, tInd, u, v, adjoint=False): The solution for the fields for the current model for the previous time-step; i.e. :math:`\mathbf{j_{k-1}}`. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. @@ -2523,15 +2647,19 @@ def getRHS(self, tInd): The right-hand side for each source is constructed according to: .. math:: - \mathbf{q}_k = - \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{e},k} + \mathbf{s}_{\mathbf{e},k-1} \big ] \; - - \; \frac{1}{\Delta t_k} \mathbf{C M_{e\mu}^{-1}} \big [ \mathbf{s}_{\mathbf{m},k} + \mathbf{s}_{\mathbf{m},k-1} \big ] + \mathbf{q}_k = - \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{e},k} + + \mathbf{s}_{\mathbf{e},k-1} \big ] \; + - \; \frac{1}{\Delta t_k} \mathbf{C M_{e\mu}^{-1}} + \big [ \mathbf{s}_{\mathbf{m},k} + \mathbf{s}_{\mathbf{m},k-1} \big ] where * :math:`\Delta t_k` is the step length * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DCurrentDensity` for a full description of the formulation. @@ -2561,25 +2689,30 @@ def getRHS(self, tInd): return rhs def getRHSDeriv(self, tInd, src, v, adjoint=False): - r"""Derivative of the right-hand side times a vector for a given source and time index. + r"""Return derivative of right-hand side times a vector for a source and time index. The right-hand side for a given source at time index *k* is constructed according to: .. math:: - \mathbf{q}_k = - \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{e},k} + \mathbf{s}_{\mathbf{e},k-1} \big ] \; - - \; \frac{1}{\Delta t_k} \mathbf{C M_{e\mu}^{-1}} \big [ \mathbf{s}_{\mathbf{m},k} + \mathbf{s}_{\mathbf{m},k-1} \big ] + \mathbf{q}_k = - \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{e},k} + + \mathbf{s}_{\mathbf{e},k-1} \big ] \; + - \; \frac{1}{\Delta t_k} \mathbf{C M_{e\mu}^{-1}} + \big [ \mathbf{s}_{\mathbf{m},k} + \mathbf{s}_{\mathbf{m},k-1} \big ] where * :math:`\Delta t_k` is the step length * :math:`\mathbf{C}` is the discrete curl operator - * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and electric source terms, respectively - * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities projected to edges + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic + and electric source terms, respectively + * :math:`\mathbf{M_{e\mu}}` is the inner-product matrix for permeabilities + projected to edges See the *Notes* section of the doc strings for :class:`Simulation3DCurrentDensity` for a full description of the formulation. - Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` is a vector, + Where :math:`\mathbf{m}` are the set of model parameters and :math:`\mathbf{v}` + is a vector, this method returns .. math:: @@ -2597,20 +2730,22 @@ def getRHSDeriv(self, tInd, src, v, adjoint=False): src : .time_domain.sources.BaseTDEMSrc The TDEM source object. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_faces,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_faces,) for the + adjoint operation. adjoint : bool Whether to perform the adjoint operation. Returns ------- numpy.ndarray - Derivative of the right-hand sides times a vector. (n_faces,) for the standard operation. + Derivative of the right-hand sides times a vector. (n_faces,) for the + standard operation. (n_param,) for the adjoint operation. """ return Zero() # assumes no derivs on sources def getAdc(self): - r"""The system matrix for the DC resistivity problem. + r"""Return the system matrix for the DC resistivity problem. The solution to the DC resistivity problem is necessary at the initial time for galvanic sources whose currents are non-zero at the initial time. @@ -2619,24 +2754,26 @@ def getAdc(self): .. math:: \mathbf{A_{dc}}\,\boldsymbol{\phi_0} = \mathbf{q_{dc}} - where :math:`\mathbf{A_{dc}}` is the DC resistivity system matrix, :math:`\boldsymbol{\phi_0}` - is the discrete solution for the electric potentials at the initial time, and :math:`\mathbf{q_{dc}}` + where :math:`\mathbf{A_{dc}}` is the DC resistivity system matrix, + :math:`\boldsymbol{\phi_0}` is the discrete solution for the electric potentials at + the initial time, and :math:`\mathbf{q_{dc}}` is the galvanic source term. This method returns the system matrix for the cell-centered formulation, i.e.: .. math:: \mathbf{D \, M_{f\rho}^{-1} \, G} - where :math:`\mathbf{D}` is the face divergence operator, :math:`\mathbf{G}` is the cell gradient - operator with imposed boundary conditions, and :math:`\mathbf{M_{f\rho}}` is the inner product - matrix for resistivities projected to faces. + where :math:`\mathbf{D}` is the face divergence operator, :math:`\mathbf{G}` is the + cell gradient operator with imposed boundary conditions, and :math:`\mathbf{M_{f\rho}}` + is the inner product matrix for resistivities projected to faces. The current density at the initial time :math:`\mathbf{j_0}` are obtained by applying: .. math:: \mathbf{j_0} = \mathbf{M_{f\rho}^{-1} \, G} \, \boldsymbol{\phi_0} - See the *Notes* section of the doc strings for :class:`.resistivity.Simulation3DCellCentered` + See the *Notes* section of the doc strings for + :class:`.resistivity.Simulation3DCellCentered` for a full description of the cell centered DC resistivity formulation. Returns @@ -2650,40 +2787,45 @@ def getAdc(self): return D * MfRhoI * G def getAdcDeriv(self, u, v, adjoint=False): - r"""Derivative operation for the DC resistivity system matrix times a vector. + r"""Return derivative operation for DC resistivity system matrix times a vector. The discrete solution to the 3D DC resistivity problem is expressed as: .. math:: \mathbf{A_{dc}}\boldsymbol{\phi_0} = \mathbf{q_{dc}} - where :math:`\mathbf{A_{dc}}` is the DC resistivity system matrix, :math:`\boldsymbol{\phi_0}` - is the discrete solution for the electric potentials at the initial time, and :math:`\mathbf{q_{dc}}` - is the galvanic source term. For a vector :math:`\mathbf{v}`, this method assumes - the discrete solution is fixed and returns + where :math:`\mathbf{A_{dc}}` is the DC resistivity system matrix, + :math:`\boldsymbol{\phi_0}` is the discrete solution for the electric potentials at + the initial time, and :math:`\mathbf{q_{dc}}` is the galvanic source term. For a + vector :math:`\mathbf{v}`, this method assumes the discrete solution is fixed + and returns .. math:: - \frac{\partial (\mathbf{A_{dc}}\boldsymbol{\phi_0})}{\partial \mathbf{m}} \, \mathbf{v} + \frac{\partial (\mathbf{A_{dc}}\boldsymbol{\phi_0})}{\partial \mathbf{m}} \, + \mathbf{v} Or the adjoint operation .. math:: - \frac{\partial (\mathbf{A_{dc}}\boldsymbol{\phi_0})}{\partial \mathbf{m}}^T \, \mathbf{v} + \frac{\partial (\mathbf{A_{dc}}\boldsymbol{\phi_0})}{\partial \mathbf{m}}^T \, + \mathbf{v} Parameters ---------- u : (n_cells,) numpy.ndarray - The solution for the fields for the current model; i.e. electric potentials at cell centers. + The solution for the fields for the current model; i.e. electric potentials at + cell centers. v : numpy.ndarray - The vector. (n_param,) for the standard operation. (n_cells,) for the adjoint operation. + The vector. (n_param,) for the standard operation. (n_cells,) for the adjoint + operation. adjoint : bool Whether to perform the adjoint operation. Returns ------- numpy.ndarray - Derivative of the DC resistivity system matrix times a vector. (n_cells,) for the standard operation. - (n_param,) for the adjoint operation. + Derivative of the DC resistivity system matrix times a vector. (n_cells,) + for the standard operation. (n_param,) for the adjoint operation. """ D = sdiag(self.mesh.cell_volumes) * self.mesh.face_divergence G = D.T @@ -2693,3 +2835,351 @@ def getAdcDeriv(self, u, v, adjoint=False): # self.MfRhoIDeriv(G * u, D.T * v, adjoint=True) return self.MfRhoIDeriv(G * u, G * v, adjoint=True) return D * self.MfRhoIDeriv(G * u, v) + + +############################################################################### +# Hierarchical # +############################################################################### +class Simulation3DHierarchicalElectricField( + BaseHierarchicalElectricalSimulation, Simulation3DElectricField +): + r"""3D hierarchical TDEM simulation in terms of the electric field. + + This simulation solves for the electric field at each time-step. + In this formulation, the electric fields are defined on mesh edges and the + magnetic flux density is defined on mesh faces; i.e. it is an EB formulation. + This simulation adopts the hierarchical framework wherein: + + * Thick structures are parameterized as conductivities at cell centers. This property + and the corresponding mapping are set with `sigma` and `sigmaMap`. + * Sheet-like structures can be parameterized as conductances on mesh faces. This property + and the corresponding mapping are set with `face_conductance` and `face_conductance_map`. + * Wire-like structures can be parameterized as area-integrated conductivities on + mesh edges. This property and the corresponding mapping as set with + `edge_area_conductance` and `edge_area_conductance_map`. + + See the *Notes* section for a comprehensive description of the formulation. + + Notes + ----- + Here, we start with the quasi-static approximation for Maxwell's equations by neglecting + electric displacement: + + .. math:: + &\nabla \times \vec{e} + \frac{\partial \vec{b}}{\partial t} = + - \frac{\partial \vec{s}_m}{\partial t} \\ + &\nabla \times \vec{h} - \vec{j} = \vec{s}_e + + where :math:`\vec{s}_e` is an electric source term that defines a source current density, + and :math:`\vec{s}_m` magnetic source term that defines a source magnetic flux density. + We define the constitutive relations for the electrical conductivity :math:`\sigma` + and magnetic permeability :math:`\mu` as: + + .. math:: + \vec{j} &= \sigma \vec{e} \\ + \vec{h} &= \mu^{-1} \vec{b} + + We then take the inner products of all previous expressions with a vector test function + :math:`\vec{u}`. Through vector calculus identities and the divergence theorem, we obtain: + + .. math:: + & \int_\Omega \vec{u} \cdot (\nabla \times \vec{e}) \, dv + + \int_\Omega \vec{u} \cdot \frac{\partial \vec{b}}{\partial t} \, dv + = - \int_\Omega \vec{u} \cdot \frac{\partial \vec{s}_m}{\partial t} \, dv \\ + & \int_\Omega (\nabla \times \vec{u}) \cdot \vec{h} \, dv + - \oint_{\partial \Omega} \vec{u} \cdot (\vec{h} \times \hat{n}) \, da + - \int_\Omega \vec{u} \cdot \vec{j} \, dv = + \int_\Omega \vec{u} \cdot \vec{s}_e \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{j} \, dv = + \int_\Omega \vec{u} \cdot \sigma \vec{e} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{h} \, dv = + \int_\Omega \vec{u} \cdot \mu^{-1} \vec{b} \, dv + + Assuming natural boundary conditions, the surface integral is zero. + + The hierarchical approach assumes the existence of infinitesimally thin plate-like + regions between adjacent mesh faces and infinitesimally thin wire-like regions + between adjacent mesh edges. We re-express the inner-product with Ohm's law as follows: + + .. math:: + \int_\Omega \vec{u} \cdot \vec{j} \, dv =& + \sum_{n}^{nc} \int \vec{u} \cdot \sigma_n \vec{e} \, dv \\ + &+ \sum_{n}^{nf} \int \vec{u} \cdot \tau_n \vec{e} \, da \\ + &+ \sum_{n}^{ne} \int \vec{u} \cdot \kappa_n \vec{e} \, d\ell + + where :math:`\sigma_n` is the conductivity in cell *n*, :math:`\tau_n` is the face + conductance on face *n*, and :math:`\kappa_n` is the area-integrated conductivity + on edge *n*. + + The above expressions are discretized in space according to the finite volume method. + The discrete electric fields :math:`\mathbf{e}` are defined on mesh edges, + and the discrete magnetic flux densities :math:`\mathbf{b}` are defined on mesh faces. + This implies :math:`\mathbf{j}` must be defined on mesh edges and :math:`\mathbf{h}` must + be defined on mesh faces. Where :math:`\mathbf{u_e}` and :math:`\mathbf{u_f}` represent + test functions discretized to edges and faces, respectively, we obtain the following + set of discrete inner-products: + + .. math:: + &\mathbf{u_f^T C e} + \mathbf{u_f^T } \, \frac{\partial \mathbf{b}}{\partial t} + = - \mathbf{u_f^T } \, \frac{\partial \mathbf{s_m}}{\partial t} \\ + &\mathbf{u_e^T C^T M_f h} - \mathbf{u_e^T M_e j} = \mathbf{u_e^T s_e} \\ + &\mathbf{u_e^T M_e j} = \mathbf{u_e^T M_{e\Sigma} e} \\ + &\mathbf{u_f^T M_f h} = \mathbf{u_f^T M_{f \frac{1}{\mu}} b} + + where: + + .. math:: + \mathbf{M_{e\Sigma}} = \mathbf{M_{e\sigma} + M_{e\tau} + M_{e\kappa}} + + and + + * :math:`\mathbf{C}` is the discrete curl operator + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively + * :math:`\mathbf{M_e}` is the edge inner-product matrix + * :math:`\mathbf{M_f}` is the face inner-product matrix + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for electrical conductivities + projected to edges + * :math:`\mathbf{M_{e\tau}}` is the inner-product matrix for conductances + projected to edges + * :math:`\mathbf{M_{e\kappa}}` is the inner-product matrix for area integrated + conductivities projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces + + By cancelling like-terms and combining the discrete expressions in terms of the electric + field, we obtain: + + .. math:: + \mathbf{C^T M_{f\frac{1}{\mu}} C e} + + \mathbf{M_{e\Sigma}}\frac{\partial \mathbf{e}}{\partial t} + = \mathbf{C^T M_{f\frac{1}{\mu}}} \frac{\partial \mathbf{s_m}}{\partial t} + - \frac{\partial \mathbf{s_e}}{\partial t} + + Finally, we discretize in time according to backward Euler. The discrete electric fields + on mesh edges at time :math:`t_k > t_0` is obtained by solving the following at each + time-step: + + .. math:: + \mathbf{A}_k \mathbf{b}_k = \mathbf{q}_k - \mathbf{B}_k \mathbf{b}_{k-1} + + where :math:`\Delta t_k = t_k - t_{k-1}` and + + .. math:: + &\mathbf{A}_k = \mathbf{C^T M_{f\frac{1}{\mu}} C} + \frac{1}{\Delta t_k} + \mathbf{M_{e\Sigma}} \\ + &\mathbf{B}_k = -\frac{1}{\Delta t_k} \mathbf{M_{e\Sigma}} \\ + &\mathbf{q}_k = \frac{1}{\Delta t_k} \mathbf{C^T M_{f\frac{1}{\mu}}} + \big [ \mathbf{s}_{\mathbf{m}, k} - \mathbf{s}_{\mathbf{m}, k-1} \big ] + -\frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{e}, k} + - \mathbf{s}_{\mathbf{e}, k-1}\big ] + + Although the following system is never explicitly formed, we can represent + the solution at all time-steps as: + + .. math:: + \begin{bmatrix} + \mathbf{A_1} & & & & \\ + \mathbf{B_2} & \mathbf{A_2} & & & \\ + & & \ddots & & \\ + & & & \mathbf{B_n} & \mathbf{A_n} + \end{bmatrix} + \begin{bmatrix} + \mathbf{e_1} \\ \mathbf{e_2} \\ \vdots \\ \mathbf{e_n} + \end{bmatrix} = + \begin{bmatrix} + \mathbf{q_1} \\ \mathbf{q_2} \\ \vdots \\ \mathbf{q_n} + \end{bmatrix} - + \begin{bmatrix} + \mathbf{B_1 e_0} \\ \mathbf{0} \\ \vdots \\ \mathbf{0} + \end{bmatrix} + + where the electric fields at the initial time :math:`\mathbf{e_0}` + are computed analytically or numerically depending on whether the + source is galvanic and carries non-zero current at the initial time. + + """ + + @property + def _delete_on_model_update(self): + """List of model-dependent attributes to clean upon model update. + + Some of the TDEM simulation's attributes are model-dependent. This property specifies + the model-dependent attributes that must be cleared when the model is updated. + + Returns + ------- + list of str + List of the model-dependent attributes to clean upon model update. + """ + items = super()._delete_on_model_update + if ( + (self.sigmaMap is not None) + | (self.face_conductance_map is not None) + | (self.edge_area_conductance_map is not None) + ): + items = items + ["_Adcinv"] # clear DC matrix factors on any model updates + + return items + + +class Simulation3DHierarchicalMagneticFluxDensity( + BaseHierarchicalElectricalSimulation, Simulation3DMagneticFluxDensity +): + r"""3D hierarchical TDEM simulation in terms of the magnetic flux density. + + This simulation solves for the magnetic flux density at each time-step. + In this formulation, the electric fields are defined on mesh edges and the + magnetic flux density is defined on mesh faces; i.e. it is an EB formulation. + + This simulation adopts the hierarchical framework wherein: + + * Thick structures are parameterized as conductivities at cell centers. This property + and the corresponding mapping are set with `sigma` and `sigmaMap`. + * Sheet-like structures can be parameterized as conductances on mesh faces. This property + and the corresponding mapping are set with `face_conductance` and `face_conductance_map`. + * Wire-like structures can be parameterized as area-integrated conductivities on + mesh edges. This property and the corresponding mapping as set with + `edge_area_conductance` and `edge_area_conductance_map`. + + See the *Notes* section for a comprehensive description of the formulation. + + Notes + ----- + Here, we start with the quasi-static approximation for Maxwell's equations by neglecting + electric displacement: + + .. math:: + &\nabla \times \vec{e} + \frac{\partial \vec{b}}{\partial t} = + - \frac{\partial \vec{s}_m}{\partial t} \\ + &\nabla \times \vec{h} - \vec{j} = \vec{s}_e + + where :math:`\vec{s}_e` is an electric source term that defines a source current density, + and :math:`\vec{s}_m` magnetic source term that defines a source magnetic flux density. + We define the constitutive relations for the electrical conductivity :math:`\sigma` + and magnetic permeability :math:`\mu` as: + + .. math:: + \vec{j} &= \sigma \vec{e} \\ + \vec{h} &= \mu^{-1} \vec{b} + + We then take the inner products of all previous expressions with a vector test function + :math:`\vec{u}`. Through vector calculus identities and the divergence theorem, we obtain: + + .. math:: + & \int_\Omega \vec{u} \cdot (\nabla \times \vec{e}) \, dv + + \int_\Omega \vec{u} \cdot \frac{\partial \vec{b}}{\partial t} \, dv + = - \int_\Omega \vec{u} \cdot \frac{\partial \vec{s}_m}{\partial t} \, dv \\ + & \int_\Omega (\nabla \times \vec{u}) \cdot \vec{h} \, dv + - \oint_{\partial \Omega} \vec{u} \cdot (\vec{h} \times \hat{n}) \, da + - \int_\Omega \vec{u} \cdot \vec{j} \, dv = + \int_\Omega \vec{u} \cdot \vec{s}_e \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{j} \, dv = + \int_\Omega \vec{u} \cdot \sigma \vec{e} \, dv \\ + & \int_\Omega \vec{u} \cdot \vec{h} \, dv = + \int_\Omega \vec{u} \cdot \mu^{-1} \vec{b} \, dv + + Assuming natural boundary conditions, the surface integral is zero. + + The hierarchical approach assumes the existence of infinitesimally thin plate-like + regions between adjacent mesh faces and infinitesimally thin wire-like regions + between adjacent mesh edges. We re-express the inner-product with Ohm's law as follows: + + .. math:: + \int_\Omega \vec{u} \cdot \vec{j} \, dv =& + \sum_{n}^{nc} \int \vec{u} \cdot \sigma_n \vec{e} \, dv \\ + &+ \sum_{n}^{nf} \int \vec{u} \cdot \tau_n \vec{e} \, da \\ + &+ \sum_{n}^{ne} \int \vec{u} \cdot \kappa_n \vec{e} \, d\ell + + where :math:`\sigma_n` is the conductivity in cell *n*, :math:`\tau_n` is the face + conductance on face *n*, and :math:`\kappa_n` is the area-integrated conductivity + on edge *n*. + + The above expressions are discretized in space according to the finite volume method. + The discrete electric fields :math:`\mathbf{e}` are defined on mesh edges, + and the discrete magnetic flux densities :math:`\mathbf{b}` are defined on mesh faces. + This implies :math:`\mathbf{j}` must be defined on mesh edges and :math:`\mathbf{h}` must + be defined on mesh faces. Where :math:`\mathbf{u_e}` and :math:`\mathbf{u_f}` represent + test functions discretized to edges and faces, respectively, we obtain the following + set of discrete inner-products: + + .. math:: + &\mathbf{u_f^T C e} + \mathbf{u_f^T } \, \frac{\partial \mathbf{b}}{\partial t} + = - \mathbf{u_f^T } \, \frac{\partial \mathbf{s_m}}{\partial t} \\ + &\mathbf{u_e^T C^T M_f h} - \mathbf{u_e^T M_e j} = \mathbf{u_e^T s_e} \\ + &\mathbf{u_e^T M_e j} = \mathbf{u_e^T M_{e\Sigma} e} \\ + &\mathbf{u_f^T M_f h} = \mathbf{u_f^T M_{f \frac{1}{\mu}} b} + + where: + + .. math:: + \mathbf{M_{e\Sigma}} = \mathbf{M_{e\sigma} + M_{e\tau} + M_{e\kappa}} + + and + + * :math:`\mathbf{C}` is the discrete curl operator + * :math:`\mathbf{s_m}` and :math:`\mathbf{s_e}` are the integrated magnetic and + electric source terms, respectively + * :math:`\mathbf{M_e}` is the edge inner-product matrix + * :math:`\mathbf{M_f}` is the face inner-product matrix + * :math:`\mathbf{M_{e\sigma}}` is the inner-product matrix for electrical conductivities + projected to edges + * :math:`\mathbf{M_{e\tau}}` is the inner-product matrix for conductances + projected to edges + * :math:`\mathbf{M_{e\kappa}}` is the inner-product matrix for area integrated + conductivities projected to edges + * :math:`\mathbf{M_{f\frac{1}{\mu}}}` is the inner-product matrix for inverse + permeabilities projected to faces + + By cancelling like-terms and combining the discrete expressions in terms of the + magnetic flux density, we obtain: + + .. math:: + \mathbf{C M_{e\sigma}^{-1} C^T M_{f\frac{1}{\mu}} b} + + \frac{\partial \mathbf{b}}{\partial t} + = \mathbf{C M_{e\Sigma}^{-1}} \mathbf{s_e} + - \frac{\partial \mathbf{s_m}}{\partial t} + + Finally, we discretize in time according to backward Euler. The discrete magnetic + flux density on mesh faces at time :math:`t_k > t_0` is obtained by solving the + following at each time-step: + + .. math:: + \mathbf{A}_k \mathbf{b}_k = \mathbf{q_k} - \mathbf{B}_k \mathbf{b}_{k-1} + + where :math:`\Delta t_k = t_k - t_{k-1}` and + + .. math:: + &\mathbf{A}_k = \mathbf{C M_{e\Sigma}^{-1} C^T M_{f\frac{1}{\mu}}} + + \frac{1}{\Delta t_k} \mathbf{I} \\ + &\mathbf{B}_k = -\frac{1}{\Delta t_k} \mathbf{I}\\ + &\mathbf{q}_k = \mathbf{C M_{e\Sigma}^{-1}} \mathbf{s}_{\mathbf{e}, k} \; + - \; \frac{1}{\Delta t_k} \big [ \mathbf{s}_{\mathbf{m}, k} + - \mathbf{s}_{\mathbf{m}, k-1} \big ] + + Although the following system is never explicitly formed, we can represent + the solution at all time-steps as: + + .. math:: + \begin{bmatrix} + \mathbf{A_1} & & & & \\ + \mathbf{B_2} & \mathbf{A_2} & & & \\ + & & \ddots & & \\ + & & & \mathbf{B_n} & \mathbf{A_n} + \end{bmatrix} + \begin{bmatrix} + \mathbf{b_1} \\ \mathbf{b_2} \\ \vdots \\ \mathbf{b_n} + \end{bmatrix} = + \begin{bmatrix} + \mathbf{q_1} \\ \mathbf{q_2} \\ \vdots \\ \mathbf{q_n} + \end{bmatrix} - + \begin{bmatrix} + \mathbf{B_1 b_0} \\ \mathbf{0} \\ \vdots \\ \mathbf{0} + \end{bmatrix} + + where the magnetic flux densities at the initial time :math:`\mathbf{b_0}` + are computed analytically or numerically depending on whether the source + carries non-zero current at the initial time. + """ + + pass diff --git a/simpeg/electromagnetics/utils/__init__.py b/simpeg/electromagnetics/utils/__init__.py index ab1970bcbe..72b254a5ae 100644 --- a/simpeg/electromagnetics/utils/__init__.py +++ b/simpeg/electromagnetics/utils/__init__.py @@ -16,7 +16,6 @@ getStraightLineCurrentIntegral segmented_line_current_source_term line_through_faces - getSourceTermLineCurrentPolygon Waveform Utilities ================== diff --git a/simpeg/electromagnetics/utils/current_utils.py b/simpeg/electromagnetics/utils/current_utils.py index 698c7a45b2..e99b714210 100644 --- a/simpeg/electromagnetics/utils/current_utils.py +++ b/simpeg/electromagnetics/utils/current_utils.py @@ -383,6 +383,10 @@ def line_through_faces( ---------- mesh : discretize.TreeMesh The OctTreeMesh (3D) for the system. + locations : (n, 3) numpy.ndarray + The locations of the nodes of the wire path. The current flows from + ``locations[0]`` towards ``locations[-1]``. Locations are moved to the + closest cell centers. normalize_by_area : bool, default: ``True`` If ``True``, normalize by face area check_divergence : bool, default: ``True`` @@ -402,11 +406,11 @@ def not_aligned_error(i): raise NotImplementedError( "With the current implementation, the line between points " "must align with the axes of the mesh. The points " - f"{locations[i, :]} and {locations[i+1, :]} do not." + f"{locations[i, :]} and {locations[i + 1, :]} do not." ) # pre-processing step: find closest cell centers - cell_centers = discretize.utils.closest_points_index(mesh, locations, "CC") + cell_centers = mesh.closest_points_index(locations, "CC") locations = mesh.gridCC[cell_centers, :] # next step: find segments between lines @@ -415,7 +419,7 @@ def not_aligned_error(i): if len(dimension) > 1: not_aligned_error(i) dimension = dimension[0] - direction = np.sign(locations[i, dimension] - locations[i + 1, dimension]) + direction = np.sign(locations[i + 1, dimension] - locations[i, dimension]) if dimension == 0: grid_loc = "x" @@ -430,12 +434,8 @@ def not_aligned_error(i): current_inds = slice(start, start + mesh.n_faces_z) # interpolate to closest face - loca = discretize.utils.closest_points_index( - mesh, locations[i, :], f"F{grid_loc}" - ) - locb = discretize.utils.closest_points_index( - mesh, locations[i + 1, :], f"F{grid_loc}" - ) + loca = mesh.closest_points_index(locations[i, :], f"F{grid_loc}") + locb = mesh.closest_points_index(locations[i + 1, :], f"F{grid_loc}") if len(loca) > 1 or len(locb) > 1: raise Exception( diff --git a/simpeg/electromagnetics/utils/testing_utils.py b/simpeg/electromagnetics/utils/testing_utils.py index 86444a8979..2bd70c248b 100644 --- a/simpeg/electromagnetics/utils/testing_utils.py +++ b/simpeg/electromagnetics/utils/testing_utils.py @@ -125,7 +125,122 @@ def getFDEMProblem(fdemType, comp, SrcList, freq, useMu=False, verbose=False): else: raise NotImplementedError() - # prb.solver_opts = dict(check_accuracy=True) + + return prb + + +def get_FDEM_hierarchical_problem( + fdemType, comp, SrcList, freq, useMu=False, verbose=False +): + cs = 10.0 + ncx, ncy, ncz = 0, 0, 0 + npad = 8 + hx = [(cs, npad, -1.3), (cs, ncx), (cs, npad, 1.3)] + hy = [(cs, npad, -1.3), (cs, ncy), (cs, npad, 1.3)] + hz = [(cs, npad, -1.3), (cs, ncz), (cs, npad, 1.3)] + mesh = TensorMesh([hx, hy, hz], ["C", "C", "C"]) + + if useMu is True: + wire_map = maps.Wires( + ("log_sigma", mesh.nC), + ("log_tau", mesh.nF), + ("log_kappa", mesh.nE), + ("mu", mesh.nC), + ) + else: + wire_map = maps.Wires( + ("log_sigma", mesh.nC), ("log_tau", mesh.nF), ("log_kappa", mesh.nE) + ) + + sigma_map = maps.ExpMap(nP=mesh.nC) * wire_map.log_sigma + tau_map = maps.ExpMap(nP=mesh.nF) * wire_map.log_tau + kappa_map = maps.ExpMap(nP=mesh.nE) * wire_map.log_kappa + if useMu: + mu_map = maps.IdentityMap(nP=mesh.nC) * wire_map.mu + else: + mu_map = None + + x = ( + np.array( + [np.linspace(-5.0 * cs, -2.0 * cs, 3), np.linspace(5.0 * cs, 2.0 * cs, 3)] + ) + + cs / 4.0 + ) # don't sample right by the source, slightly off alignment from either staggered grid + XYZ = utils.ndgrid(x, x, np.linspace(-2.0 * cs, 2.0 * cs, 5)) + Rx0 = getattr(fdem.Rx, "Point" + comp[0]) + if comp[-1] == "r": + real_or_imag = "real" + elif comp[-1] == "i": + real_or_imag = "imag" + rx0 = Rx0(XYZ, comp[1], real_or_imag) + + Src = [] + + for SrcType in SrcList: + if SrcType == "MagDipole": + Src.append( + fdem.Src.MagDipole([rx0], frequency=freq, location=np.r_[0.0, 0.0, 0.0]) + ) + elif SrcType == "MagDipole_Bfield": + Src.append( + fdem.Src.MagDipole_Bfield( + [rx0], frequency=freq, location=np.r_[0.0, 0.0, 0.0] + ) + ) + elif SrcType == "CircularLoop": + Src.append( + fdem.Src.CircularLoop( + [rx0], frequency=freq, location=np.r_[0.0, 0.0, 0.0] + ) + ) + elif SrcType == "LineCurrent": + Src.append( + fdem.Src.LineCurrent( + [rx0], + frequency=freq, + location=np.array([[0.0, 0.0, 0.0], [20.0, 0.0, 0.0]]), + ) + ) + elif SrcType == "RawVec": + S_m = np.zeros(mesh.nF) + S_e = np.zeros(mesh.nE) + S_m[ + mesh.closest_points_index([0.0, 0.0, 0.0], "Fz") + np.sum(mesh.vnF[:1]) + ] = 1e-3 + S_e[ + mesh.closest_points_index([0.0, 0.0, 0.0], "Ez") + np.sum(mesh.vnE[:1]) + ] = 1e-3 + Src.append( + fdem.Src.RawVec([rx0], freq, S_m, mesh.get_edge_inner_product() * S_e) + ) + + if verbose: + print(" Fetching {0!s} problem".format((fdemType))) + + if fdemType == "e": + survey = fdem.Survey(Src) + prb = fdem.Simulation3DHierarchicalElectricField( + mesh, + survey=survey, + sigmaMap=sigma_map, + face_conductance_map=tau_map, + edge_area_conductance_map=kappa_map, + muMap=mu_map, + ) + + elif fdemType == "b": + survey = fdem.Survey(Src) + prb = fdem.Simulation3DHierarchicalMagneticFluxDensity( + mesh, + survey=survey, + sigmaMap=sigma_map, + face_conductance_map=tau_map, + edge_area_conductance_map=kappa_map, + muMap=mu_map, + ) + + else: + raise NotImplementedError("NO SIMULATION FOR H OR J FORMULATION") return prb @@ -139,11 +254,20 @@ def crossCheckTest( useMu=False, TOL=1e-5, verbose=False, + sigma_only=True, ): + rng = np.random.default_rng(45) + def l2norm(r): return np.sqrt(r.dot(r)) - prb1 = getFDEMProblem(fdemType1, comp, SrcList, freq, useMu, verbose) + if sigma_only: + prb1 = getFDEMProblem(fdemType1, comp, SrcList, freq, useMu, verbose) + else: + prb1 = get_FDEM_hierarchical_problem( + fdemType1, comp, SrcList, freq, useMu, verbose + ) + mesh = prb1.mesh print( "Cross Checking Forward: {0!s}, {1!s} formulations - {2!s}".format( @@ -152,23 +276,38 @@ def l2norm(r): ) logsig = np.log(np.ones(mesh.nC) * CONDUCTIVITY) + logtau = np.log(np.ones(mesh.nF) * CONDUCTIVITY * np.min(mesh.h[0])) + logkappa = np.log(np.ones(mesh.nE) * CONDUCTIVITY * np.min(mesh.h[0]) ** 2) mu = np.ones(mesh.nC) * MU if addrandoms is True: - logsig += np.random.randn(mesh.nC) * np.log(CONDUCTIVITY) * 1e-1 - mu += np.random.randn(mesh.nC) * MU * 1e-1 + logsig += rng.standard_normal(mesh.nC) * np.log(CONDUCTIVITY) * 1e-1 + logtau += rng.standard_normal(mesh.nF) * np.log(CONDUCTIVITY) * 1e-1 + logkappa += rng.standard_normal(mesh.nE) * np.log(CONDUCTIVITY) * 1e-1 + mu += rng.standard_normal(mesh.nC) * MU * 1e-1 - if useMu is True: - m = np.r_[logsig, mu] + if sigma_only: + if useMu: + m = np.r_[logsig, mu] + else: + m = logsig else: - m = logsig + if useMu: + m = np.r_[logsig, logtau, logkappa, mu] + else: + m = np.r_[logsig, logtau, logkappa] d1 = prb1.dpred(m) if verbose: print(" Problem 1 solved") - prb2 = getFDEMProblem(fdemType2, comp, SrcList, freq, useMu, verbose) + if sigma_only: + prb2 = getFDEMProblem(fdemType2, comp, SrcList, freq, useMu, verbose) + else: + prb2 = get_FDEM_hierarchical_problem( + fdemType2, comp, SrcList, freq, useMu, verbose + ) d2 = prb2.dpred(m) diff --git a/simpeg/electromagnetics/viscous_remanent_magnetization/receivers.py b/simpeg/electromagnetics/viscous_remanent_magnetization/receivers.py index cc1c730704..f9a888b7e2 100644 --- a/simpeg/electromagnetics/viscous_remanent_magnetization/receivers.py +++ b/simpeg/electromagnetics/viscous_remanent_magnetization/receivers.py @@ -6,7 +6,6 @@ validate_ndarray_with_shape, ) - ######################################### # POINT RECEIVER CLASS FOR VRM ######################################### diff --git a/simpeg/electromagnetics/viscous_remanent_magnetization/survey.py b/simpeg/electromagnetics/viscous_remanent_magnetization/survey.py index 0f65d97d27..627484bd7a 100644 --- a/simpeg/electromagnetics/viscous_remanent_magnetization/survey.py +++ b/simpeg/electromagnetics/viscous_remanent_magnetization/survey.py @@ -5,7 +5,6 @@ from .sources import BaseSrcVRM from ...utils import validate_list_of_types, validate_ndarray_with_shape - ############################################ # BASE VRM SURVEY CLASS ############################################ diff --git a/simpeg/electromagnetics/viscous_remanent_magnetization/waveforms.py b/simpeg/electromagnetics/viscous_remanent_magnetization/waveforms.py index ba6e6641b7..e76da9051f 100644 --- a/simpeg/electromagnetics/viscous_remanent_magnetization/waveforms.py +++ b/simpeg/electromagnetics/viscous_remanent_magnetization/waveforms.py @@ -122,10 +122,10 @@ def getLogUniformDecay(self, fieldType, times, chi0, dchi, tau1, tau2): t0 = self.t0 times = np.kron(np.ones((nC, 1)), times) - chi0 = np.kron(np.reshape(chi0, newshape=(nC, 1)), np.ones((1, nT))) - dchi = np.kron(np.reshape(dchi, newshape=(nC, 1)), np.ones((1, nT))) - tau1 = np.kron(np.reshape(tau1, newshape=(nC, 1)), np.ones((1, nT))) - tau2 = np.kron(np.reshape(tau2, newshape=(nC, 1)), np.ones((1, nT))) + chi0 = np.kron(np.reshape(chi0, shape=(nC, 1)), np.ones((1, nT))) + dchi = np.kron(np.reshape(dchi, shape=(nC, 1)), np.ones((1, nT))) + tau1 = np.kron(np.reshape(tau1, shape=(nC, 1)), np.ones((1, nT))) + tau2 = np.kron(np.reshape(tau2, shape=(nC, 1)), np.ones((1, nT))) if fieldType == "h": eta = 0.5 * (1 - np.sign(times - t0)) * chi0 + 0.5 * ( @@ -276,10 +276,10 @@ def getLogUniformDecay(self, fieldType, times, chi0, dchi, tau1, tau2): delt = self.delt times = np.kron(np.ones((nC, 1)), times) - chi0 = np.kron(np.reshape(chi0, newshape=(nC, 1)), np.ones((1, nT))) - dchi = np.kron(np.reshape(dchi, newshape=(nC, 1)), np.ones((1, nT))) - tau1 = np.kron(np.reshape(tau1, newshape=(nC, 1)), np.ones((1, nT))) - tau2 = np.kron(np.reshape(tau2, newshape=(nC, 1)), np.ones((1, nT))) + chi0 = np.kron(np.reshape(chi0, shape=(nC, 1)), np.ones((1, nT))) + dchi = np.kron(np.reshape(dchi, shape=(nC, 1)), np.ones((1, nT))) + tau1 = np.kron(np.reshape(tau1, shape=(nC, 1)), np.ones((1, nT))) + tau2 = np.kron(np.reshape(tau2, shape=(nC, 1)), np.ones((1, nT))) if fieldType == "h": eta = (np.sign(times - t0 + delt) - np.sign(times - t0)) * ( diff --git a/simpeg/flow/richards/empirical.py b/simpeg/flow/richards/empirical.py index 97f6e5b640..8ddeabde9f 100644 --- a/simpeg/flow/richards/empirical.py +++ b/simpeg/flow/richards/empirical.py @@ -249,8 +249,8 @@ def _get_params(self): def __call__(self, u): Ks, A, gamma = self._get_params() P_p, P_n = _get_projections(u) # Compute the positive/negative domains - f_p = P_p * np.ones(len(u)) * Ks # ensures scalar Ks works - f_n = P_n * Ks * A / (A + abs(u) ** gamma) + f_p = P_p @ np.full_like(u, fill_value=Ks) + f_n = P_n @ (Ks * A / (A + abs(u) ** gamma)) return f_p + f_n def derivU(self, u): @@ -533,8 +533,8 @@ def __call__(self, u): P_p, P_n = _get_projections(u) # Compute the positive/negative domains theta_e = 1.0 / ((1.0 + abs(alpha * u) ** n) ** m) - f_p = P_p * np.ones(len(u)) * Ks # ensures scalar Ks works - f_n = P_n * Ks * theta_e**I * ((1.0 - (1.0 - theta_e ** (1.0 / m)) ** m) ** 2) + f_p = P_p @ np.full_like(u, fill_value=Ks) + f_n = P_n @ (Ks * theta_e**I * ((1.0 - (1.0 - theta_e ** (1.0 / m)) ** m) ** 2)) return f_p + f_n def derivM(self, u): diff --git a/simpeg/flow/richards/simulation.py b/simpeg/flow/richards/simulation.py index 29e5b10a53..97c2e58282 100644 --- a/simpeg/flow/richards/simulation.py +++ b/simpeg/flow/richards/simulation.py @@ -377,6 +377,13 @@ def Jfull(self, m=None, f=None): z = np.zeros((self.mesh.nC, B.shape[1])) du_dm = np.vstack((z, AinvB)) J = self.survey.deriv(self, f, du_dm_v=du_dm) # not multiplied by v + + # Patch: cast J into an ndarray if it's a np.matrix. + # We should update the survey and receivers to make use of sparray instead of + # spmatrix. + if isinstance(J, np.matrix): + J = np.asarray(J) + return J @utils.timeIt diff --git a/simpeg/maps/__init__.py b/simpeg/maps/__init__.py index e912ef6bef..741a38bda9 100644 --- a/simpeg/maps/__init__.py +++ b/simpeg/maps/__init__.py @@ -6,10 +6,16 @@ SphericalSystem, SumMap, TileMap, + TileMapNested, Wires, ) from ._clustering import PolynomialPetroClusterMap -from ._injection import Mesh2Mesh, InjectActiveCells +from ._injection import ( + Mesh2Mesh, + InjectActiveCells, + InjectActiveFaces, + InjectActiveEdges, +) from ._property_maps import ( ChiMap, ComplexMap, diff --git a/simpeg/maps/_base.py b/simpeg/maps/_base.py index cb186ed54f..25052cbb3e 100644 --- a/simpeg/maps/_base.py +++ b/simpeg/maps/_base.py @@ -7,8 +7,9 @@ import numpy as np import scipy.sparse as sp from scipy.sparse import csr_matrix as csr + from discretize.tests import check_derivative -from discretize.utils import Zero, Identity, mkvc, speye, sdiag +from discretize.utils import Zero, Identity, mkvc, volume_average, speye, sdiag import uuid from ..utils import ( @@ -354,6 +355,55 @@ def is_linear(self): return True +def _shapes_compatible(shape_a, shape_b): + r"""Check whether two mapping shapes agree, treating ``'*'`` as a wildcard.""" + return all( + x == "*" or y == "*" or x == y for x, y in zip(shape_a, shape_b, strict=True) + ) + + +def _resolve_combo_shape(maps): + r"""Infer the overall shape of a chain of mappings. + + ``maps`` must be ordered the same way they are stored on a + :class:`ComboMap`: from the mapping applied last to the mapping + applied first. A mapping with shape (``*``, ``*``) can act on a + vector of any length, so when a concrete dimension is known on one + side of such a mapping (because a neighboring mapping fixes it), + that dimension is propagated through it. + + Returns + ------- + (2) tuple of int or ``*`` + The resolved (output, input) shape of the combined mapping. + """ + n = len(maps) + # junctions[0] is the output size of the combination; junctions[n] is + # the input size (nP); junctions[i] in between is the size flowing + # between maps[i] (applied earlier) and maps[i - 1] (applied later). + junctions = [None] * (n + 1) + junctions[0] = maps[0].shape[0] + junctions[n] = maps[-1].shape[1] + for i in range(1, n): + out_dim = maps[i - 1].shape[1] + in_dim = maps[i].shape[0] + junctions[i] = out_dim if out_dim != "*" else in_dim + + def is_free(m): + return m.shape == ("*", "*") + + # propagate known dimensions through free maps toward the output... + for i in range(n - 1, -1, -1): + if is_free(maps[i]) and junctions[i] == "*" and junctions[i + 1] != "*": + junctions[i] = junctions[i + 1] + # ...and toward the input. + for i in range(n): + if is_free(maps[i]) and junctions[i + 1] == "*" and junctions[i] != "*": + junctions[i + 1] = junctions[i] + + return (junctions[0], junctions[n]) + + class ComboMap(IdentityMap): r"""Combination mapping constructed by joining a set of other mappings. @@ -414,37 +464,51 @@ class ComboMap(IdentityMap): def __init__(self, maps, **kwargs): super().__init__(mesh=None, **kwargs) + self.maps = maps - self.maps = [] - for ii, m in enumerate(maps): - assert isinstance(m, IdentityMap), "Unrecognized data type, " - "inherit from an IdentityMap or ComboMap!" - - if ( - ii > 0 - and not (self.shape[1] == "*" or m.shape[0] == "*") - and not self.shape[1] == m.shape[0] - ): - prev = self.maps[-1] + @property + def maps(self): + r"""The mappings being combined. - raise ValueError( - "Dimension mismatch in map[{0!s}] ({1!s}, {2!s}) " - "and map[{3!s}] ({4!s}, {5!s}).".format( - prev.__class__.__name__, - prev.shape[0], - prev.shape[1], - m.__class__.__name__, - m.shape[0], - m.shape[1], + Returns + ------- + tuple of simpeg.maps.IdentityMap + The mappings, ordered from last applied to first applied. This + is a ``tuple`` (rather than a ``list``) so it cannot be mutated + in a way that would make the cached :py:attr:`shape` stale; + assign a new value to ``maps`` instead. + """ + return self._maps + + @maps.setter + def maps(self, value): + value = validate_list_of_types("maps", value, IdentityMap, min_n=1) + + resolved = [] + for ii, m in enumerate(value): + if ii > 0: + prev_shape = _resolve_combo_shape(resolved) + if ( + not (prev_shape[1] == "*" or m.shape[0] == "*") + and not prev_shape[1] == m.shape[0] + ): + prev = resolved[-1] + raise ValueError( + "Dimension mismatch in map[{0!s}] ({1!s}, {2!s}) " + "and map[{3!s}] ({4!s}, {5!s}).".format( + prev.__class__.__name__, + prev.shape[0], + prev.shape[1], + m.__class__.__name__, + m.shape[0], + m.shape[1], + ) ) - ) - if np.any([isinstance(m, SumMap), isinstance(m, IdentityMap)]): - self.maps += [m] - elif isinstance(m, ComboMap): - self.maps += m.maps - else: - raise ValueError("Map[{0!s}] not supported", m.__class__.__name__) + resolved.append(m) + + self._maps = tuple(resolved) + self._shape = _resolve_combo_shape(self._maps) @property def shape(self): @@ -453,14 +517,18 @@ def shape(self): For a list of SimPEG mappings [:math:`\mathbf{f}_n,...,\mathbf{f}_1`] that have been joined to create a ``ComboMap``, this method returns the dimensions of the combination mapping. Recall that the ordering - of the list of mappings is from last to first. + of the list of mappings is from last to first. This is computed once + when the mapping's ``maps`` are set and reused afterward. Returns ------- (2) tuple of int - Dimensions of the mapping operator. + Dimensions of the mapping operator. If a dimension cannot be + resolved from the chain of mappings (e.g. every mapping in + the chain has shape (``*``, ``*``)), ``*`` is returned for + that dimension instead. """ - return (self.maps[0].shape[0], self.maps[-1].shape[1]) + return self._shape @property def nP(self): @@ -468,10 +536,10 @@ def nP(self): Returns ------- - int + int or ``*`` Number of parameters that the mapping acts on. """ - return self.maps[-1].nP + return self.shape[1] def _transform(self, m): for map_i in reversed(self.maps): @@ -761,37 +829,50 @@ class SumMap(ComboMap): """ def __init__(self, maps, **kwargs): - maps = validate_list_of_types("maps", maps, IdentityMap) - # skip ComboMap's init super(ComboMap, self).__init__(mesh=None, **kwargs) + self.maps = maps - self.maps = [] - for ii, m in enumerate(maps): - if not isinstance(m, IdentityMap): - raise TypeError( - "Unrecognized data type {}, inherit from an " - "IdentityMap!".format(type(m)) - ) + @property + def maps(self): + r"""The mappings being summed. - if ( - ii > 0 - and not (self.shape == "*" or m.shape == "*") - and not self.shape == m.shape - ): - raise ValueError( - "Dimension mismatch in map[{0!s}] ({1!s}, {2!s}) " - "and map[{3!s}] ({4!s}, {5!s}).".format( - self.maps[0].__class__.__name__, - self.maps[0].shape[0], - self.maps[0].shape[1], - m.__class__.__name__, - m.shape[0], - m.shape[1], + Returns + ------- + tuple of simpeg.maps.IdentityMap + The mappings being summed together. This is a ``tuple`` + (rather than a ``list``) so it cannot be mutated in a way + that would make the cached :py:attr:`shape` stale; assign a + new value to ``maps`` instead. + """ + return self._maps + + @maps.setter + def maps(self, value): + value = tuple(validate_list_of_types("maps", value, IdentityMap, min_n=1)) + + shape0, shape1 = value[0].shape + for ii, m in enumerate(value): + if ii > 0: + if not _shapes_compatible((shape0, shape1), m.shape): + raise ValueError( + "Dimension mismatch in map[{0!s}] ({1!s}, {2!s}) " + "and map[{3!s}] ({4!s}, {5!s}).".format( + value[0].__class__.__name__, + value[0].shape[0], + value[0].shape[1], + m.__class__.__name__, + m.shape[0], + m.shape[1], + ) ) - ) + if shape0 == "*": + shape0 = m.shape[0] + if shape1 == "*": + shape1 = m.shape[1] - self.maps += [m] + self._maps = value + self._shape = (shape0, shape1) @property def shape(self): @@ -800,9 +881,12 @@ def shape(self): Returns ------- tuple - The dimensions of the mapping. A tuple of the form (``int``,``int``) + The dimensions of the mapping. A tuple of the form (``int``,``int``). + If none of the summed mappings fix a given dimension, ``*`` is + returned for that dimension instead. This is computed once when + the mapping's ``maps`` are set and reused afterward. """ - return (self.maps[0].shape[0], self.maps[0].shape[1]) + return self._shape @property def nP(self): @@ -810,10 +894,10 @@ def nP(self): Returns ------- - int + int or ``*`` Number of parameters that the mapping acts on. """ - return self.maps[-1].shape[1] + return self.shape[1] def _transform(self, m): for ii, map_i in enumerate(self.maps): @@ -925,10 +1009,11 @@ def __init__(self, mesh=None, nP=None, **kwargs): self.model = None def sphericalDeriv(self, model): - if ( - getattr(self, "_sphericalDeriv", None) is None - or getattr(self, "model", None) is None - or not all(self.model == model) + if getattr(self, "model", None) is None: + self.model = model + + if getattr(self, "_sphericalDeriv", None) is None or not all( + self.model == model ): self.model = model @@ -1229,24 +1314,165 @@ def __init__( local_mesh, tol=1e-8, components=1, - enforce_active=True, **kwargs, ): + super().__init__(mesh=None, **kwargs) + self._global_mesh = validate_type( + "global_mesh", global_mesh, discretize.TreeMesh, cast=False + ) + self._local_mesh = validate_type( + "local_mesh", local_mesh, discretize.TreeMesh, cast=False + ) + + self._global_active = validate_active_indices( + "global_active", global_active, self.global_mesh.n_cells + ) + + self._tol = validate_float("tol", tol, min_val=0.0, inclusive_min=False) + self._components = validate_integer("components", components, min_val=1) + + # trigger creation of P + self.P + + @property + def global_mesh(self): + """Global TreeMesh defining the entire domain. + + Returns + ------- + discretize.TreeMesh """ - Parameters - ---------- - global_mesh : discretize.TreeMesh - Global TreeMesh defining the entire domain. - global_active : numpy.ndarray of bool or int - Defines the active cells in the global mesh. - local_mesh : discretize.TreeMesh - Local TreeMesh for the simulation. - tol : float, optional - Tolerance to avoid zero division - components : int, optional - Number of components in the model. E.g. a vector model in 3D would have 3 - components. + return self._global_mesh + + @property + def local_mesh(self): + """Local TreeMesh defining the local domain. + + Returns + ------- + discretize.TreeMesh + """ + return self._local_mesh + + @property + def global_active(self): + """Defines the active cells in the global mesh. + + Returns + ------- + (global_mesh.n_cells) numpy.ndarray of bool """ + return self._global_active + + @property + def local_active(self): + """ + This is the local_active of the global_active used in the global problem. + + Returns + ------- + (local_mesh.n_cells) numpy.ndarray of bool + """ + return self._local_active + + @property + def tol(self): + """Tolerance to avoid zero division. + + Returns + ------- + float + """ + return self._tol + + @property + def components(self): + """Number of components in the model. + + Returns + ------- + int + """ + return self._components + + @property + def P(self): + """ + Set the projection matrix with partial volumes + """ + if getattr(self, "_P", None) is None: + # Volume-averaging operator mapping the global mesh onto the local + # mesh. This weights by the true partial overlap volume of each + # pair of cells, so it is correct regardless of which mesh is finer + # in a given region (the center-assignment approach used previously + # broke down wherever the local mesh was finer than the global one). + vol_avg = volume_average(self.global_mesh, self.local_mesh) + + # keep only the active cells of the global model + P = vol_avg[:, self.global_active] + + # local cells that receive a contribution from active global cells + self._local_active = mkvc(np.asarray(P.sum(axis=1)).ravel() > self.tol) + + P = P[self.local_active, :] + + self._P = sp.block_diag([P for _ in range(self.components)]) + + return self._P + + def _transform(self, m): + return self.P * m + + @property + def shape(self): + """ + Shape of the matrix operation (number of indices x nP) + """ + return self.P.shape + + def deriv(self, m, v=None): + """ + :param numpy.ndarray m: model + :rtype: scipy.sparse.csr_matrix + :return: derivative of transformed model + """ + if v is not None: + return self.P * v + return self.P + + +class TileMapNested(IdentityMap): + """ + Mapping for tiled inversion. + + Uses volume averaging to map a model defined on a global mesh to the + local mesh. Every cell in the local mesh must also be in the global mesh. + + Parameters + ---------- + global_mesh : discretize.TreeMesh + Global TreeMesh defining the entire domain. + global_active : numpy.ndarray of bool or int + Defines the active cells in the global mesh. + local_mesh : discretize.TreeMesh + Local TreeMesh for the simulation. + tol : float, optional + Tolerance to avoid zero division + components : int, optional + Number of components in the model. E.g. a vector model in 3D would have 3 + components. + """ + + def __init__( + self, + global_mesh, + global_active, + local_mesh, + tol=1e-8, + components=1, + enforce_active=True, + **kwargs, + ): super().__init__(mesh=None, **kwargs) self._global_mesh = validate_type( "global_mesh", global_mesh, discretize.TreeMesh, cast=False diff --git a/simpeg/maps/_injection.py b/simpeg/maps/_injection.py index 68c02c2e61..a55c66abfa 100644 --- a/simpeg/maps/_injection.py +++ b/simpeg/maps/_injection.py @@ -1,6 +1,4 @@ -""" -Injection and interpolation map classes. -""" +"""Injection and interpolation map classes.""" import discretize import numpy as np @@ -18,11 +16,9 @@ class Mesh2Mesh(IdentityMap): - """ - Takes a model on one mesh are translates it to another mesh. - """ + """Takes a model on one mesh are translates it to another mesh.""" - def __init__(self, meshes, active_cells=None, **kwargs): + def __init__(self, meshes, active_cells=None, **kwargs): # noqa D107 # Sanity checks for the meshes parameter try: mesh, mesh2 = meshes @@ -50,11 +46,22 @@ def __init__(self, meshes, active_cells=None, **kwargs): # reset to not accepted None for mesh @IdentityMap.mesh.setter def mesh(self, value): + """Return the mesh are mapping to. + + Parameters + ---------- + discretize.base.BaseMesh + The mesh where you want to define the new model. The mesh you are mapping to. + + Returns + ------- + discretize.base.BaseMesh + """ self._mesh = validate_type("mesh", value, discretize.base.BaseMesh, cast=False) @property def mesh2(self): - """The source mesh used for the mapping. + """The mesh you want to map from. Returns ------- @@ -94,6 +101,16 @@ def active_cells(self, value): @property def P(self): + """Return the mapping operator. + + Mapping from one mesh to another is a linear operation. + This property returns the linear operator. + + Returns + ------- + (n_cells_1, n_cells_2) numpy.ndarray + The linear operator that maps from mesh 1 to mesh 2. + """ if getattr(self, "_P", None) is None: self._P = self.mesh2.get_interpolation_matrix( ( @@ -122,6 +139,23 @@ def _transform(self, m): return self.P * m def deriv(self, m, v=None): + """Compute derivative of the mapping with respect to the model. + + Parameters + ---------- + m : (n_param,) numpy.ndarray + The model parameters + v : (n_param,) numpy.ndarray, optional + A vector. + + Returns + ------- + numpy.ndarray + When *v* is ``None``, a (n_cells, n_param) numpy.ndaray is returned which + represents the derivative of the mapping with respect to the model. When + *v* is a vector, an (n_cells,) numpy.ndarray representing the derivative of + the mapping times the vector is returned. + """ if v is not None: return self.P * v return self.P @@ -155,7 +189,7 @@ class InjectActiveCells(IdentityMap): The physical property value assigned to all inactive cells in the mesh """ - def __init__( + def __init__( # noqa D107 self, mesh, active_cells=None, @@ -244,7 +278,7 @@ def active_cells(self, value): @property def shape(self): - """Dimensions of the mapping + """Dimensions of the mapping. Returns ------- @@ -272,7 +306,9 @@ def _transform(self, m): return self.P * m + self.value_inactive def inverse(self, u): - r"""Recover the model parameters (active cells) from a set of physical + r"""Compute the inverse projection operation. + + Recover the model parameters (active cells) from a set of physical property values defined on the entire mesh. For a discrete set of model parameters :math:`\mathbf{m}` defined @@ -301,7 +337,7 @@ def inverse(self, u): return self.P.T * u def deriv(self, m, v=None): - r"""Derivative of the mapping with respect to the input parameters. + r"""Return derivative of the mapping with respect to the input parameters. For a discrete set of model parameters :math:`\mathbf{m}` defined on a set of active cells, the mapping :math:`\mathbf{u}(\mathbf{m})` @@ -340,3 +376,355 @@ def deriv(self, m, v=None): if v is not None: return self.P * v return self.P + + +class InjectActiveFaces(IdentityMap): + r"""Map active faces model to all faces of a mesh. + + The ``InjectActiveFaces`` class is used to define the mapping when + the model consists of diagnostic property values defined on a set of active + mesh faces; e.g. faces below topography, z-faces only. For a discrete set of + model parameters :math:`\mathbf{m}` defined on a set of active + faces, the mapping :math:`\mathbf{u}(\mathbf{m})` is defined as: + + .. math:: + \mathbf{u}(\mathbf{m}) = \mathbf{Pm} + \mathbf{d}\, m_\perp + + where :math:`\mathbf{P}` is a (*nF* , *nP*) projection matrix from + active faces to all mesh faces, and :math:`\mathbf{d}` is a + (*nF* , 1) matrix that projects the inactive faces value + :math:`m_\perp` to all mesh faces. + + Parameters + ---------- + mesh : discretize.BaseMesh + A discretize mesh + active_faces : numpy.ndarray + Active faces array. Can be a boolean ``numpy.ndarray`` of length *mesh.nF* + or a ``numpy.ndarray`` of ``int`` containing the indices of the active faces. + value_inactive : float or numpy.ndarray + The physical property value assigned to all inactive faces in the mesh + + """ + + def __init__( + self, mesh, active_faces=None, value_inactive=0.0, nF=None + ): # noqa D107 + self.mesh = mesh + self.nF = nF or mesh.nF + self._active_faces = validate_active_indices( + "active_faces", active_faces, self.nF + ) + self._nP = np.sum(self.active_faces) + self.P = sp.eye(self.nF, format="csr")[:, self.active_faces] + self.value_inactive = value_inactive + + @property + def value_inactive(self): + """Return physical property value assigned to all inactive faces. + + Returns + ------- + numpy.ndarray + """ + return self._value_inactive + + @value_inactive.setter + def value_inactive(self, value): + n_inactive = self.nF - self.nP + if isinstance(value, Number): + value = validate_float("value_inactive", value) + value = np.full(n_inactive, value) + value = validate_ndarray_with_shape( + "value_inactive", value, shape=(n_inactive,) + ) + + self._value_inactive = np.zeros(self.nF, dtype=float) + self._value_inactive[~self.active_faces] = value + + @property + def active_faces(self): + """Return indices of active mesh faces. + + Returns + ------- + numpy.ndarray of bool + """ + return self._active_faces + + @property + def shape(self): + """Dimensions of the mapping. + + Returns + ------- + tuple of int + Where *nP* is the number of active faces and *nF* is + number of faces in the mesh, **shape** returns a + tuple (*nF* , *nP*). + """ + return (self.nF, self.nP) + + @property + def nP(self): + """Number of parameters the model acts on. + + Returns + ------- + int + Number of parameters the model acts on; i.e. the number of active faces. + """ + return int(self.active_faces.sum()) + + def _transform(self, m): + if m.ndim > 1: + return self.P * m + self.value_inactive[:, None] + return self.P * m + self.value_inactive + + def inverse(self, u): + r"""Compute the inverse projection operation. + + Recover the model parameters (active faces) from a set of physical + property values defined on the entire mesh. + + For a discrete set of model parameters :math:`\mathbf{m}` defined + on a set of active faces, the mapping :math:`\mathbf{u}(\mathbf{m})` + is defined as: + + .. math:: + \mathbf{u}(\mathbf{m}) = \mathbf{Pm} + \mathbf{d} \,m_\perp + + where :math:`\mathbf{P}` is a (*nF* , *nP*) projection matrix from + active faces to all mesh faces, and :math:`\mathbf{d}` is a + (*nR* , 1) matrix that projects the inactive face value + :math:`m_\perp` to all mesh faces. + + The inverse mapping is given by: + + .. math:: + \mathbf{m}(\mathbf{u}) = \mathbf{P^T u} + + Parameters + ---------- + u : (mesh.nF) numpy.ndarray + A vector which contains physical property values for all + mesh faces. + """ + return self.P.T * u + + def deriv(self, m, v=None): + r"""Return derivative of the mapping with respect to the input parameters. + + For a discrete set of model parameters :math:`\mathbf{m}` defined + on a set of active faces, the mapping :math:`\mathbf{u}(\mathbf{m})` + is defined as: + + .. math:: + \mathbf{u}(\mathbf{m}) = \mathbf{Pm} + \mathbf{d} \, m_\perp + + where :math:`\mathbf{P}` is a (*nF* , *nP*) projection matrix from + active faces to all mesh faces, and :math:`\mathbf{d}` is a + (*nF* , 1) matrix that projects the inactive face value + :math:`m_\perp` to all inactive mesh faces. + + the **deriv** method returns the derivative of :math:`\mathbf{u}` with respect + to the model parameters; i.e.: + + .. math:: + \frac{\partial \mathbf{u}}{\partial \mathbf{m}} = \mathbf{P} + + Note that in this case, **deriv** simply returns a sparse projection matrix. + + Parameters + ---------- + m : (nP) numpy.ndarray + A vector representing a set of model parameters. + v : (nP) numpy.ndarray + If not ``None``, the method returns the derivative times the vector *v*. + + Returns + ------- + scipy.sparse.csr_matrix + Derivative of the mapping with respect to the model parameters. If the + input argument *v* is not ``None``, the method returns the derivative times + the vector *v*. + """ + if v is not None: + return self.P * v + return self.P + + +class InjectActiveEdges(IdentityMap): + r"""Map active edges model to all edges of a mesh. + + The ``InjectActiveEdges`` class is used to define the mapping when + the model consists of diagnostic property values defined on a set of active + mesh edges; e.g. edges below topography, z-edges only. For a discrete set of + model parameters :math:`\mathbf{m}` defined on a set of active + edges, the mapping :math:`\mathbf{u}(\mathbf{m})` is defined as: + + .. math:: + \mathbf{u}(\mathbf{m}) = \mathbf{Pm} + \mathbf{d}\, m_\perp + + where :math:`\mathbf{P}` is a (*nE* , *nP*) projection matrix from + active edges to all mesh edges, and :math:`\mathbf{d}` is a + (*nE* , 1) matrix that projects the inactive edges value + :math:`m_\perp` to all mesh edges. + + Parameters + ---------- + mesh : discretize.BaseMesh + A discretize mesh + active_edges : numpy.ndarray + Active edges array. Can be a boolean ``numpy.ndarray`` of length *mesh.nE* + or a ``numpy.ndarray`` of ``int`` containing the indices of the active edges. + value_inactive : float or numpy.ndarray + The physical property value assigned to all inactive edges in the mesh. + + """ + + def __init__( + self, mesh, active_edges=None, value_inactive=0.0, nE=None + ): # noqa D107 + self.mesh = mesh + self.nE = nE or mesh.nE + self._active_edges = validate_active_indices( + "active_edges", active_edges, self.nE + ) + self._nP = np.sum(self.active_edges) + self.P = sp.eye(self.nE, format="csr")[:, self.active_edges] + self.value_inactive = value_inactive + + @property + def value_inactive(self): + """Return physical property value defined for all inactive edges. + + Returns + ------- + numpy.ndarray + """ + return self._value_inactive + + @value_inactive.setter + def value_inactive(self, value): + n_inactive = self.nE - self.nP + if isinstance(value, Number): + value = validate_float("value_inactive", value) + value = np.full(n_inactive, value) + value = validate_ndarray_with_shape( + "value_inactive", value, shape=(n_inactive,) + ) + + self._value_inactive = np.zeros(self.nE, dtype=float) + self._value_inactive[~self.active_edges] = value + + @property + def active_edges(self): + """Return indices of the edges. + + Returns + ------- + numpy.ndarray of bool. + """ + return self._active_edges + + @property + def shape(self): + """Return dimensions of the mapping. + + Returns + ------- + tuple of int + Where *nP* is the number of active edges and *nE* is + number of edges in the mesh, **shape** returns a + tuple (*nE* , *nP*). + """ + return (self.nE, self.nP) + + @property + def nP(self): + """Number of parameters the model acts on. + + Returns + ------- + int + Number of parameters the model acts on; i.e. the number of active edges. + """ + return int(self.active_edges.sum()) + + def _transform(self, m): + if m.ndim > 1: + return self.P * m + self.value_inactive[:, None] + return self.P * m + self.value_inactive + + def inverse(self, u): + r"""Compute the inverse projection operation. + + Recover the model parameters (active edges) from a set of physical + property values defined on the entire mesh. + + For a discrete set of model parameters :math:`\mathbf{m}` defined + on a set of active edges, the mapping :math:`\mathbf{u}(\mathbf{m})` + is defined as: + + .. math:: + \mathbf{u}(\mathbf{m}) = \mathbf{Pm} + \mathbf{d} \,m_\perp + + where :math:`\mathbf{P}` is a (*nE* , *nP*) projection matrix from + active edges to all mesh edges, and :math:`\mathbf{d}` is a + (*nE* , 1) matrix that projects the inactive edge value + :math:`m_\perp` to all mesh edges. + + The inverse mapping is given by: + + .. math:: + \mathbf{m}(\mathbf{u}) = \mathbf{P^T u} + + Parameters + ---------- + u : (mesh.nE) numpy.ndarray + A vector which contains physical property values for all + mesh edges. + """ + return self.P.T * u + + def deriv(self, m, v=None): + r"""Return derivative of the mapping with respect to the input parameters. + + For a discrete set of model parameters :math:`\mathbf{m}` defined + on a set of active edges, the mapping :math:`\mathbf{u}(\mathbf{m})` + is defined as: + + .. math:: + \mathbf{u}(\mathbf{m}) = \mathbf{Pm} + \mathbf{d} \, m_\perp + + where :math:`\mathbf{P}` is a (*nE* , *nP*) projection matrix from + active edges to all mesh edges, and :math:`\mathbf{d}` is a + (*nF* , 1) matrix that projects the inactive edge value + :math:`m_\perp` to all mesh edges. + + the **deriv** method returns the derivative of :math:`\mathbf{u}` with respect + to the model parameters; i.e.: + + .. math:: + \frac{\partial \mathbf{u}}{\partial \mathbf{m}} = \mathbf{P} + + Note that in this case, **deriv** simply returns a sparse projection matrix. + + Parameters + ---------- + m : (nP) numpy.ndarray + A vector representing a set of model parameters. + v : (nP) numpy.ndarray + If not ``None``, the method returns the derivative times the vector *v*. + + Returns + ------- + scipy.sparse.csr_matrix + Derivative of the mapping with respect to the model parameters. If the + input argument *v* is not ``None``, the method returns the derivative times + the vector *v*. + """ + if v is not None: + return self.P * v + return self.P diff --git a/simpeg/maps/_parametric.py b/simpeg/maps/_parametric.py index 4837b7c6fd..e5663a1332 100644 --- a/simpeg/maps/_parametric.py +++ b/simpeg/maps/_parametric.py @@ -20,6 +20,7 @@ ) from ._base import IdentityMap from ..utils.code_utils import deprecate_property +from ._utils import columns_dot_vector class ParametricCircleMap(IdentityMap): @@ -242,9 +243,10 @@ def deriv(self, m, v=None): / (np.pi * (a**2 * (-r + np.sqrt((X - x) ** 2 + (Y - y) ** 2)) ** 2 + 1)) ) + columns = [g1, g2, g3, g4, g5] if v is not None: - return sp.csr_matrix(np.c_[g1, g2, g3, g4, g5]) * v - return sp.csr_matrix(np.c_[g1, g2, g3, g4, g5]) + return columns_dot_vector(columns, v) + return sp.csr_matrix(np.c_[*columns]) @property def is_linear(self): @@ -679,9 +681,10 @@ def deriv(self, m, v=None): g3 = sdiag(alpha * (sig2 - sig1) / (1.0 + (alpha * f) ** 2) / np.pi) * V + columns = [g1, g2, g3] if v is not None: - return sp.csr_matrix(np.c_[g1, g2, g3]) * v - return sp.csr_matrix(np.c_[g1, g2, g3]) + return columns_dot_vector(columns, v) + return sp.csr_matrix(np.c_[*columns]) @property def is_linear(self): @@ -1062,9 +1065,10 @@ def deriv(self, m, v=None): else: raise (Exception("Not Implemented for Y and Z, your turn :)")) + columns = [g1, g2, g3] if v is not None: - return sp.csr_matrix(np.c_[g1, g2, g3]) * v - return sp.csr_matrix(np.c_[g1, g2, g3]) + return columns_dot_vector(columns, v) + return sp.csr_matrix(np.c_[*columns]) @property def is_linear(self): @@ -1472,19 +1476,20 @@ def deriv(self, m, v=None): the vector *v*. """ mDict = self.mDict(m) - derivative = sp.csr_matrix( - np.vstack( - [ - self._deriv_val_background(mDict), - self._deriv_val_layer(mDict), - self._deriv_layer_center(mDict), - self._deriv_layer_thickness(mDict), - ] - ).T + # Define a generator with the columns of the derivative matrix. + # The generator allows to avoid storing all columns in memory. + columns = ( + method(mDict) + for method in ( + self._deriv_val_background, + self._deriv_val_layer, + self._deriv_layer_center, + self._deriv_layer_thickness, + ) ) if v is not None: - return derivative @ v - return derivative + return columns_dot_vector(columns, v) + return sp.csr_matrix(np.vstack(list(columns)).T) class ParametricBlock(BaseParametric): @@ -1828,16 +1833,14 @@ def deriv(self, m, v=None): input argument *v* is not ``None``, the method returns the derivative times the vector *v*. """ - derivative = sp.csr_matrix( - getattr(self, "_deriv{}D".format(self.mesh.dim))(self.mDict(m)) - ) + derivative = getattr(self, "_deriv{}D".format(self.mesh.dim))(self.mDict(m)) if v is not None: return derivative @ v - return derivative + return sp.csr_matrix(derivative) class ParametricEllipsoid(ParametricBlock): - r"""Mapping for a rectangular block within a wholespace. + r"""Mapping for an ellipsoid within a wholespace. This mapping is used when the cells lying below the Earth's surface can be parameterized by an ellipsoid within a homogeneous medium. @@ -2225,25 +2228,26 @@ def _deriv_casing_top(self, mDict): def deriv(self, m, v=None): mDict = self.mDict(m) - derivative = sp.csr_matrix( - np.vstack( - [ - self._deriv_val_background(mDict), - self._deriv_val_layer(mDict), - self._deriv_val_casing(mDict), - self._deriv_val_insideCasing(mDict), - self._deriv_layer_center(mDict), - self._deriv_layer_thickness(mDict), - self._deriv_casing_radius(mDict), - self._deriv_casing_thickness(mDict), - self._deriv_casing_bottom(mDict), - self._deriv_casing_top(mDict), - ] - ).T + # Define a generator with the columns of the derivative matrix. + # The generator allows to avoid storing all columns in memory. + columns = ( + method(mDict) + for method in ( + self._deriv_val_background, + self._deriv_val_layer, + self._deriv_val_casing, + self._deriv_val_insideCasing, + self._deriv_layer_center, + self._deriv_layer_thickness, + self._deriv_casing_radius, + self._deriv_casing_thickness, + self._deriv_casing_bottom, + self._deriv_casing_top, + ) ) if v is not None: - return derivative @ v - return derivative + return columns_dot_vector(columns, v) + return sp.csr_matrix(np.vstack(list(columns)).T) class ParametricBlockInLayer(ParametricLayer): @@ -2682,11 +2686,7 @@ def _transform(self, m): return self._transform3d(m) def deriv(self, m, v=None): - derivative = ( - sp.csr_matrix(self._deriv2d(m)) - if self.mesh.dim == 2 - else sp.csr_matrix(self._deriv3d(m)) - ) + derivative = self._deriv2d(m) if self.mesh.dim == 2 else (self._deriv3d(m)) if v is not None: return derivative @ v - return derivative + return sp.csr_matrix(derivative) diff --git a/simpeg/maps/_utils.py b/simpeg/maps/_utils.py new file mode 100644 index 0000000000..5d43cfd20f --- /dev/null +++ b/simpeg/maps/_utils.py @@ -0,0 +1,75 @@ +""" +Utility functions for maps. + +.. important:: + + Classes and functions within this file are not meant to be public, just to be used + internally by maps. +""" + +from collections.abc import Iterable +import numpy.typing as npt + + +def columns_dot_vector(columns: Iterable[npt.NDArray], vector: npt.NDArray): + """ + Compute the dot product between a collection of columns and a vector. + + Use this function to compute the dot product between a matrix represented by + a sequence of column vectors and a given vector. It can perform the dot product + computation without allocating the full matrix. + + .. hint: + + We can pass a list of pre-allocated arrays, or a ``Generator`` that will produce + each one of the arrays in-place when it gets iterated. + The ``Generator`` approach could allow us to reduce memory consumption by + allocating only one column array at a time. + + Parameters + ---------- + columns : iterable of (m,) or (m, p) array + A collection of the column vectors that form the matrix. They can either be + 1D arrays (a single column each) or 2D arrays (a column block of the matrix). + The collection should contain a total number of *matrix columns* equal to the + size of the expected ``result`` vector (``n``). + vector : (m,) array + Vector that will be used in the dot product. + + Returns + ------- + result : (n,) vector + Resulting vector. + """ + empty = True # flag used to check if the iterable is empty + index = 0 + result = 0 + for column in columns: + empty = False + match column.ndim: + case 1: + # Add the column times the index-th value of the vector to the result. + result += column * vector[index] + index += 1 + case 2: + # Add to result the dot product between the 2D column block and the + # corresponding slice of the vector. + new_index = index + column.shape[1] + result += column @ vector[index:new_index] + index = new_index + case _: + msg = f"Invalid column '{column}' with '{column.ndim}' dimensions." + raise ValueError(msg) + + if empty: + msg = "Invalid empty 'columns' argument. It must contain at last one element." + raise ValueError(msg) + + if index != vector.size: + msg = ( + f"The total number of columns ('{index}') passed through the `columns` " + f"is not equal to the size of the vector ('{vector.size}'). " + ) + raise ValueError(msg) + + return result diff --git a/simpeg/meta/multiprocessing.py b/simpeg/meta/multiprocessing.py index 05edf03469..73a6233a71 100644 --- a/simpeg/meta/multiprocessing.py +++ b/simpeg/meta/multiprocessing.py @@ -1,3 +1,7 @@ +import atexit +import threading +from enum import Enum, auto +from queue import Empty from multiprocessing import Process, Queue, cpu_count from simpeg.meta import MetaSimulation, SumMetaSimulation, RepeatedSimulation from simpeg.props import HasModel @@ -5,6 +9,26 @@ import numpy as np +class _Op(Enum): + """The set of operations a `_SimulationProcess` understands. + + Sent as the first element of each task tuple put on a process's + `task_queue`; members pickle by reference (name), so this only needs + to be importable from the same module path in both processes, which + it is since a spawned child re-imports this module. + """ + + SET_SIM = auto() + GET_ITEM = auto() + DEL_ITEM = auto() + STORE_MODEL = auto() + CREATE_FIELDS = auto() + DPRED = auto() + JVEC = auto() + JTVEC = auto() + JTJ_DIAG = auto() + + class SimpleFuture: """Represents an object stored on a seperate simulation process.""" @@ -17,7 +41,7 @@ def __init__(self, item_id, sim_process): # classes stash the simulation, so this requires serializing # the simulation (something we explicitly want to avoid in all cases). # def result(self): - # self.t_queue.put(("get_item", (self.item_id,))) + # self.t_queue.put((_Op.GET_ITEM, (self.item_id,))) # item = self.r_queue.get() # if isinstance(item, Exception): # raise item @@ -25,7 +49,7 @@ def __init__(self, item_id, sim_process): def __del__(self): if self.sim_process.is_alive(): - self.sim_process.task_queue.put(("del_item", (self.item_id,))) + self.sim_process.task_queue.put((_Op.DEL_ITEM, (self.item_id,))) class _SimulationProcess(Process): @@ -59,103 +83,125 @@ def run(self): break op, args = task try: - if op == "set_sim": + if op == _Op.SET_SIM: (sim,) = args sim_key = uuid.uuid4().hex _cached_items[sim_key] = sim r_queue.put(sim_key) - elif op == "get_item": + elif op == _Op.GET_ITEM: (key,) = args r_queue.put(_cached_items[key]) - elif op == "del_item": + elif op == _Op.DEL_ITEM: (key,) = args _cached_items.pop(key, None) - elif op == 0: - # store_model + elif op == _Op.STORE_MODEL: sim_key, m = args sim = _cached_items[sim_key] sim.model = m - elif op == 1: - # create fields + r_queue.put(None) + elif op == _Op.CREATE_FIELDS: (sim_key,) = args sim = _cached_items[sim_key] f_key = uuid.uuid4().hex + # Put the key immediately so the client isn't blocked + # waiting on this (possibly expensive) computation before + # it can move on to dispatching work to other processes. r_queue.put(f_key) - fields = sim.fields(sim.model) + try: + fields = sim.fields(sim.model) + except Exception as err: + # Store the error itself in place of the fields, so + # it surfaces the first time this key is actually + # used, instead of appearing as a stray item here. + fields = err _cached_items[f_key] = fields - elif op == 2: - # do dpred + elif op == _Op.DPRED: sim_key, f_key = args sim = _cached_items[sim_key] fields = _cached_items[f_key] + if isinstance(fields, Exception): + raise fields d_pred = sim.dpred(sim.model, fields) r_queue.put(d_pred) - elif op == 3: - # do jvec + elif op == _Op.JVEC: sim_key, v, f_key = args sim = _cached_items[sim_key] fields = _cached_items[f_key] + if isinstance(fields, Exception): + raise fields jvec = sim.Jvec(sim.model, v, fields) r_queue.put(jvec) - elif op == 4: - # do jtvec + elif op == _Op.JTVEC: sim_key, v, f_key = args sim = _cached_items[sim_key] fields = _cached_items[f_key] + if isinstance(fields, Exception): + raise fields jtvec = sim.Jtvec(sim.model, v, fields) r_queue.put(jtvec) - elif op == 5: - # do jtj_diag + elif op == _Op.JTJ_DIAG: sim_key, w, f_key = args sim = _cached_items[sim_key] fields = _cached_items[f_key] + if isinstance(fields, Exception): + raise fields jtj = sim.getJtJdiag(sim.model, w, fields) r_queue.put(jtj) except Exception as err: r_queue.put(err) + def _get_result(self): + item = self.result_queue.get() + if isinstance(item, Exception): + raise item + return item + def set_sim(self, sim): self._check_closed() - self.task_queue.put(("set_sim", (sim,))) - key = self.result_queue.get() + self.task_queue.put((_Op.SET_SIM, (sim,))) + key = self._get_result() future = SimpleFuture(key, self) self._my_sim = future return future - def store_model(self, m): + def start_store_model(self, m): self._check_closed() sim = self._my_sim - self.task_queue.put((0, (sim.item_id, m))) + self.task_queue.put((_Op.STORE_MODEL, (sim.item_id, m))) + + def store_model(self, m): + self.start_store_model(m) + self._get_result() def get_fields(self): self._check_closed() sim = self._my_sim - self.task_queue.put((1, (sim.item_id,))) - key = self.result_queue.get() + self.task_queue.put((_Op.CREATE_FIELDS, (sim.item_id,))) + key = self._get_result() future = SimpleFuture(key, self) return future def start_dpred(self, f_future): self._check_closed() sim = self._my_sim - self.task_queue.put((2, (sim.item_id, f_future.item_id))) + self.task_queue.put((_Op.DPRED, (sim.item_id, f_future.item_id))) def start_j_vec(self, v, f_future): self._check_closed() sim = self._my_sim - self.task_queue.put((3, (sim.item_id, v, f_future.item_id))) + self.task_queue.put((_Op.JVEC, (sim.item_id, v, f_future.item_id))) def start_jt_vec(self, v, f_future): self._check_closed() sim = self._my_sim - self.task_queue.put((4, (sim.item_id, v, f_future.item_id))) + self.task_queue.put((_Op.JTVEC, (sim.item_id, v, f_future.item_id))) def start_jtj_diag(self, w, f_future): self._check_closed() sim = self._my_sim self.task_queue.put( ( - 5, + _Op.JTJ_DIAG, ( sim.item_id, w, @@ -166,16 +212,102 @@ def start_jtj_diag(self, w, f_future): def result(self): self._check_closed() - return self.result_queue.get() + return self._get_result() def join(self, timeout=None): self._check_closed() self.task_queue.put(None) self.task_queue.close() - self.result_queue.close() self.task_queue.join_thread() + + # A result the caller never read (e.g. because an earlier + # collection loop raised before reaching this process) can block + # this process's result_queue feeder thread from flushing, which + # would otherwise deadlock the plain Process.join() below. Drain + # in the background while we wait so that can't happen. + stop_draining = threading.Event() + + def _drain(): + while not stop_draining.is_set(): + try: + self.result_queue.get(timeout=0.1) + except Empty: + continue + + drain_thread = threading.Thread(target=_drain, daemon=True) + drain_thread.start() + try: + super().join(timeout=timeout) + finally: + stop_draining.set() + drain_thread.join() + + self.result_queue.close() self.result_queue.join_thread() - super().join(timeout=timeout) + + +def _shutdown_processes(processes, timeout=5.0): + """Ask workers to exit via poison pill; terminate any that don't.""" + for p in processes: + if p.is_alive(): + try: + p.join(timeout=timeout) + except Exception: + pass # fall through to terminate() + for p in processes: + if p.is_alive(): + p.terminate() # pragma: no cover + + +def _spawn_chunk_processes(n_sim, n_processes, build_chunk): + """Split `n_sim` items into contiguous chunks, one worker process each. + + Shared by every `Multiprocessing*Simulation.__init__`: they differ only + in how a chunk's combined simulation is built, which is supplied here + via `build_chunk`. + + Parameters + ---------- + n_sim : int + Total number of individual simulations to distribute. + n_processes : int + Number of worker processes to aim for. Chunks are sized as evenly + as possible; if `n_processes > n_sim` the extra, zero-sized chunks + are simply skipped, so fewer processes than requested may result. + build_chunk : callable + Called with `(i_start, i_end)` for each contiguous chunk and must + return the combined simulation to send to that chunk's process. + + Returns + ------- + processes : list of _SimulationProcess + data_offsets : numpy.ndarray + """ + chunk_sizes = min(n_processes, n_sim) * [n_sim // n_processes] + for i in range(n_sim % n_processes): + chunk_sizes[i] += 1 + + i_start = 0 + chunk_nd = [] + processes = [] + try: + for chunk in chunk_sizes: + if chunk == 0: + continue + i_end = i_start + chunk + sim_chunk = build_chunk(i_start, i_end) + chunk_nd.append(sim_chunk.survey.nD) + p = _SimulationProcess() + processes.append(p) + p.start() + p.set_sim(sim_chunk) + i_start = i_end + except Exception: + _shutdown_processes(processes) + raise + + data_offsets = np.cumsum(np.r_[0, chunk_nd]) + return processes, data_offsets class MultiprocessingMetaSimulation(MetaSimulation): @@ -225,46 +357,51 @@ class MultiprocessingMetaSimulation(MetaSimulation): >>> mp.set_start_method("spawn") """ + # The type of simulation used to represent each process's chunk of the + # work. Subclasses whose combination semantics differ from plain + # concatenation (e.g. summing) must override this to match. + _chunk_sim_class = MetaSimulation + def __init__(self, simulations, mappings, n_processes=None): super().__init__(simulations, mappings) if n_processes is None: n_processes = cpu_count() - # split simulation,mappings up into chunks - # (Which are currently defined using MetaSimulations) - n_sim = len(simulations) - chunk_sizes = min(n_processes, n_sim) * [n_sim // n_processes] - for i in range(n_sim % n_processes): - chunk_sizes[i] += 1 - - i_start = 0 - chunk_nd = [] - processes = [] - for chunk in chunk_sizes: - if chunk == 0: - continue - i_end = i_start + chunk - sim_chunk = MetaSimulation( + def build_chunk(i_start, i_end): + return self._chunk_sim_class( self.simulations[i_start:i_end], self.mappings[i_start:i_end] ) - chunk_nd.append(sim_chunk.survey.nD) - p = _SimulationProcess() - processes.append(p) - p.start() - p.set_sim(sim_chunk) - i_start = i_end - self._sim_processes = processes - self._data_offsets = np.cumsum(np.r_[0, chunk_nd]) + self._sim_processes, self._data_offsets = _spawn_chunk_processes( + len(simulations), n_processes, build_chunk + ) + atexit.register(self._atexit_cleanup) + + def _atexit_cleanup(self): + # Best-effort fallback for interpreter shutdown when `.join()` was + # never called. Uses terminate() (immediate, no queue cooperation + # needed) rather than the graceful join() protocol, so this can't + # itself hang interpreter shutdown. This must never run as a + # side-effect of an error from a normal method call (dpred/Jvec/ + # etc.) -- only atexit triggers it. + for p in getattr(self, "_sim_processes", ()): + if p.is_alive(): + p.terminate() @MetaSimulation.model.setter def model(self, value): updated = HasModel.model.fset(self, value) # Only send the model to the internal simulations if it was updated. if updated: + # Dispatch to every process before waiting on any of them, so + # the workers validate the model in parallel; then check each + # result immediately so a failure surfaces from this assignment + # instead of being deferred to a later, unrelated op. + for p in self._sim_processes: + p.start_store_model(self._model) for p in self._sim_processes: - p.store_model(self._model) + p.result() def fields(self, m): """Create fields for every simulation. @@ -347,6 +484,8 @@ def join(self, timeout=None): for p in self._sim_processes: if p.is_alive(): p.join(timeout=timeout) + if not any(p.is_alive() for p in self._sim_processes): + atexit.unregister(self._atexit_cleanup) class MultiprocessingSumMetaSimulation( @@ -372,6 +511,8 @@ class MultiprocessingSumMetaSimulation( will be the minimum of this number and the number of simulations. """ + _chunk_sim_class = SumMetaSimulation + def dpred(self, m=None, f=None): if f is None: if m is None: @@ -453,28 +594,10 @@ def __init__(self, simulation, mappings, n_processes=None): if n_processes is None: n_processes = cpu_count() - # split mappings up into chunks - n_sim = len(mappings) - chunk_sizes = min(n_processes, n_sim) * [n_sim // n_processes] - for i in range(n_sim % n_processes): - chunk_sizes[i] += 1 - - processes = [] - i_start = 0 - chunk_nd = [] - for chunk in chunk_sizes: - if chunk == 0: - continue - i_end = i_start + chunk - sim_chunk = RepeatedSimulation( - self.simulation, self.mappings[i_start:i_end] - ) - chunk_nd.append(sim_chunk.survey.nD) - p = _SimulationProcess() - processes.append(p) - p.start() - p.set_sim(sim_chunk) - i_start = i_end + def build_chunk(i_start, i_end): + return RepeatedSimulation(self.simulation, self.mappings[i_start:i_end]) - self._data_offsets = np.cumsum(np.r_[0, chunk_nd]) - self._sim_processes = processes + self._sim_processes, self._data_offsets = _spawn_chunk_processes( + len(mappings), n_processes, build_chunk + ) + atexit.register(self._atexit_cleanup) diff --git a/simpeg/optimization.py b/simpeg/optimization.py index 5b1b2a207b..cb108016e5 100644 --- a/simpeg/optimization.py +++ b/simpeg/optimization.py @@ -72,7 +72,6 @@ """ -import warnings from collections.abc import Callable from typing import Any, Optional @@ -1051,18 +1050,9 @@ def __init__( cg_maxiter: int = 5, **kwargs, ): - - if (val := kwargs.pop("tolCG", None)) is not None: - self.tolCG = val # Deprecated cg_rtol - else: - self.cg_rtol = cg_rtol + self.cg_rtol = cg_rtol self.cg_atol = cg_atol - - if (val := kwargs.pop("maxIterCG", None)) is not None: - self.maxIterCG = val - else: - self.cg_maxiter = cg_maxiter - + self.cg_maxiter = cg_maxiter super().__init__(**kwargs) @property @@ -1125,10 +1115,10 @@ def cg_maxiter(self, value): self._cg_maxiter = validate_integer("cg_maxiter", value, min_val=1) maxIterCG = deprecate_property( - cg_maxiter, old_name="maxIterCG", removal_version="0.26.0", future_warn=True + cg_maxiter, old_name="maxIterCG", removal_version="0.26.0", error=True ) tolCG = deprecate_property( - cg_rtol, old_name="tolCG", removal_version="0.26.0", future_warn=True + cg_rtol, old_name="tolCG", removal_version="0.26.0", error=True ) @@ -1525,46 +1515,14 @@ def __init__( lower: None | float | npt.NDArray[np.float64] = -np.inf, upper: None | float | npt.NDArray[np.float64] = np.inf, cg_maxiter: int = 5, - cg_rtol: float = None, - cg_atol: float = None, + cg_rtol: float = 1e-3, + cg_atol: float = 0.0, step_active_set: bool = True, active_set_grad_scale: float | np.ndarray = 1e-2, **kwargs, ): - if (val := kwargs.pop("tolCG", None)) is not None: - # Deprecated path when tolCG is passed. - self.tolCG = val - cg_atol = val - cg_rtol = 0.0 - elif cg_rtol is None and cg_atol is None: - # Note these defaults match previous settings... - # but they're not good in general... - # Ideally they will change to cg_rtol=1E-3 and cg_atol=0.0 - warnings.warn( - "The defaults for ProjectedGNCG will change in SimPEG 0.26.0. If you want to maintain the " - "previous behavior, explicitly set 'cg_atol=1E-3' and 'cg_rtol=0.0'.", - FutureWarning, - stacklevel=2, - ) - cg_atol = 1e-3 - cg_rtol = 0.0 - # defaults for if someone passes just cg_rtol or just cg_atol (to be removed on deprecation removal) - # These will likely be the future defaults - elif cg_atol is None: - cg_atol = 0.0 - elif cg_rtol is None: - cg_rtol = 1e-3 - - if (val := kwargs.pop("stepActiveSet", None)) is not None: - self.stepActiveSet = val - else: - self.step_active_set = step_active_set - - if (val := kwargs.pop("stepOffBoundsFact", None)) is not None: - self.stepOffBoundsFact = val - else: - self.active_set_grad_scale = active_set_grad_scale - + self.step_active_set = step_active_set + self.active_set_grad_scale = active_set_grad_scale super().__init__( lower=lower, upper=upper, @@ -1722,14 +1680,14 @@ def findSearchDirection(self): step_active_set, old_name="stepActiveSet", removal_version="0.26.0", - future_warn=True, + error=True, ) stepOffBoundsFact = deprecate_property( active_set_grad_scale, old_name="stepOffBoundsFact", removal_version="0.26.0", - future_warn=True, + error=True, ) # This was the weird part from before... the default tolerance was used as an absolute tolerance... @@ -1737,5 +1695,5 @@ def findSearchDirection(self): InexactGaussNewton.cg_atol, old_name="tolCG", removal_version="0.26.0", - future_warn=True, + error=True, ) diff --git a/simpeg/potential_fields/base.py b/simpeg/potential_fields/base.py index c2f311de08..25ab8e30b2 100644 --- a/simpeg/potential_fields/base.py +++ b/simpeg/potential_fields/base.py @@ -1,5 +1,7 @@ import os +from functools import partial from multiprocessing.pool import Pool +from multiprocessing.sharedctypes import RawArray import discretize import numpy as np @@ -14,6 +16,32 @@ except ImportError: choclo = None +# Per-worker state for the multiprocessed kernel build. Only the shared buffer +# goes through the pool initializer: on spawn platforms a large initializer +# payload makes the parent start workers one at a time. The simulation instead +# travels with the task chunks (once per chunk). +_kernel_worker_state = {} + + +def _init_kernel_worker(shared_buffer, shape, dtype): + _kernel_worker_state["kernel"] = np.frombuffer(shared_buffer, dtype=dtype).reshape( + shape + ) + + +def _fill_kernel_rows(simulation, row_start, receiver_location, components): + """Compute one receiver's rows and write them straight into the shared kernel. + + Returns the number of rows written so the parent can check that the row + offsets it handed out were consistent. + """ + kernel = _kernel_worker_state["kernel"] + rows = simulation.evaluate_integral(receiver_location, components) + n_rows = rows.shape[0] + kernel[row_start : row_start + n_rows] = rows.astype(kernel.dtype, copy=False) + return n_rows + + ############################################################################### # # # Base Potential Fields Simulation # @@ -313,8 +341,8 @@ def linear_operator(self): else: kernel_shape = (self.survey.nD, n_cells) dtype = self.sensitivity_dtype - kernel = np.empty(kernel_shape, dtype=dtype) if self.n_processes == 1: + kernel = np.empty(kernel_shape, dtype=dtype) id0 = 0 for args in self.survey._location_component_iterator(): rows = self.evaluate_integral(*args) @@ -323,16 +351,33 @@ def linear_operator(self): kernel[id0:id1] = rows.astype(dtype, copy=False) id0 = id1 else: - # multiprocessed - with Pool(processes=self.n_processes) as pool: - id0 = 0 - for rows in pool.starmap( - self.evaluate_integral, self.survey._location_component_iterator() - ): - n_c = rows.shape[0] - id1 = id0 + n_c - kernel[id0:id1] = rows.astype(dtype, copy=False) - id0 = id1 + # multiprocessed: the workers write their rows directly into one + # shared buffer, instead of pickling rows back to be concatenated. + n_bytes = int(np.prod(kernel_shape)) * np.dtype(dtype).itemsize + shared_buffer = RawArray("b", n_bytes) + tasks = [] + id0 = 0 + for location, components in self.survey._location_component_iterator(): + tasks.append((id0, location, components)) + id0 += len(components) + with Pool( + processes=self.n_processes, + initializer=_init_kernel_worker, + initargs=(shared_buffer, kernel_shape, dtype), + ) as pool: + n_rows_written = pool.starmap(partial(_fill_kernel_rows, self), tasks) + # Let the workers exit on their own: Pool.__exit__ would + # otherwise terminate() them mid-shutdown. + pool.close() + pool.join() + expected = [len(components) for _, _, components in tasks] + if n_rows_written != expected: + raise RuntimeError( + "evaluate_integral returned a different number of rows than " + "components; the shared kernel would be corrupt." + ) + # A view onto the shared buffer: no copy, and it keeps the buffer alive. + kernel = np.frombuffer(shared_buffer, dtype=dtype).reshape(kernel_shape) # if self.store_sensitivities != "forward_only": # kernel = np.vstack(kernel) diff --git a/simpeg/potential_fields/gravity/simulation.py b/simpeg/potential_fields/gravity/simulation.py index 11ca94da03..b40f11dcf4 100644 --- a/simpeg/potential_fields/gravity/simulation.py +++ b/simpeg/potential_fields/gravity/simulation.py @@ -16,7 +16,6 @@ from ._numba import choclo, NUMBA_FUNCTIONS_3D, NUMBA_FUNCTIONS_2D - if choclo is not None: from numba import jit @@ -693,7 +692,7 @@ def _gtg_diagonal_without_building_g(self, weights): Compute the diagonal of ``G.T @ G`` without building the ``G`` matrix. Parameters - ----------- + ---------- weights : (nD,) array Array with data weights. It should be the diagonal of the ``W`` matrix, squared. @@ -907,7 +906,7 @@ def _gtg_diagonal_without_building_g(self, weights): Compute the diagonal of ``G.T @ G`` without building the ``G`` matrix. Parameters - ----------- + ---------- weights : (nD,) array Array with data weights. It should be the diagonal of the ``W`` matrix, squared. diff --git a/simpeg/potential_fields/magnetics/simulation.py b/simpeg/potential_fields/magnetics/simulation.py index 9f3cb44c36..b3e6525cfc 100644 --- a/simpeg/potential_fields/magnetics/simulation.py +++ b/simpeg/potential_fields/magnetics/simulation.py @@ -1147,7 +1147,7 @@ def _gtg_diagonal_without_building_g(self, weights): Compute the diagonal of ``G.T @ G`` without building the ``G`` matrix. Parameters - ----------- + ---------- weights : (nD,) array Array with data weights. It should be the diagonal of the ``W`` matrix, squared. @@ -1567,7 +1567,7 @@ def _gtg_diagonal_without_building_g(self, weights): Compute the diagonal of ``G.T @ G`` without building the ``G`` matrix. Parameters - ----------- + ---------- weights : (nD,) array Array with data weights. It should be the diagonal of the ``W`` matrix, squared. diff --git a/simpeg/regularization/cross_gradient.py b/simpeg/regularization/cross_gradient.py index 708d2e0928..0827d1ca91 100644 --- a/simpeg/regularization/cross_gradient.py +++ b/simpeg/regularization/cross_gradient.py @@ -4,7 +4,6 @@ from .base import BaseSimilarityMeasure from ..utils import validate_type, coterminal, sdiag - ############################################################################### # # # Cross-Gradient # @@ -245,12 +244,14 @@ def calculate_cross_gradient(self, model, normalized=False, rtol=1e-6): grad_m1 = self._calculate_gradient(m1, normalized=normalized, rtol=rtol) grad_m2 = self._calculate_gradient(m2, normalized=normalized, rtol=rtol) - # for each model cell, compute the cross product of the gradient vectors. - cross_prod = np.cross(grad_m1, grad_m2) - if self.regularization_mesh.dim == 3: - cross_prod = np.linalg.norm(cross_prod, axis=-1) - - return cross_prod + if self.regularization_mesh.dim == 2: + result = np.abs(_cross_product_2d(grad_m1, grad_m2)) + elif self.regularization_mesh.dim == 3: + cross_prod = np.cross(grad_m1, grad_m2) + result = np.linalg.norm(cross_prod, axis=-1) + else: + raise ValueError() + return result def _model_gradients(self, models): """ @@ -473,3 +474,64 @@ def units(self, units: tuple[str] | None): units = ("metric", "metric") self._units = units + + +def _cross_product_2d(a, b): + """ + Compute the cross product between two 2D vectors. + + Parameters + ---------- + a : (2,) or (n, 2) array + First vector(s) to use in the cross product. + b : (2,) or (n, 2) array + Second vector(s) to use in the cross product. + + Returns + ------- + c : 1D array + Array containing the third coordinate(s) of the cross product vector between + ``a`` and ``b``. + + Notes + ----- + This function was added after Numpy dropped support for 2D vectors in + :func:`numpy.cross`. + + Examples + -------- + >>> a = np.array([1., 2.]) + >>> b = np.array([3., 4.]) + >>> _cross_product_2d(a, b) + array([-2.]) + + >>> a = np.array([[1., 2.], [5., 6.]]) + >>> b = np.array([[3., 4.], [4., 3.]]) + >>> _cross_product_2d(a, b) + array([-2., -9.]) + + >>> a = np.array([1., 2.]) + >>> b = np.array([[3., 4.], [4., 3.]]) + >>> _cross_product_2d(a, b) + array([-2., -5.]) + + """ + for name, array in {"a": a, "b": b}.items(): + if array.ndim not in (1, 2): + msg = ( + f"Invalid array '{name}' with '{array.ndim}' dimensions. " + "They must be 1D or 2D arrays." + ) + raise ValueError(msg) + + n_elements = array.size if array.ndim == 1 else array.shape[1] + if n_elements != 2: + msg = ( + f"Invalid array '{name}' containing vectors with '{n_elements}' " + "elements. It must contain 2D vectors." + ) + raise ValueError(msg) + + a, b = np.atleast_2d(a), np.atleast_2d(b) + cross_product = a[:, 0] * b[:, 1] - a[:, 1] * b[:, 0] + return cross_product diff --git a/simpeg/regularization/jtv.py b/simpeg/regularization/jtv.py index 0014071a30..304d32fd97 100644 --- a/simpeg/regularization/jtv.py +++ b/simpeg/regularization/jtv.py @@ -3,7 +3,6 @@ from .base import BaseSimilarityMeasure - ############################################################################### # # # Joint Total Variation # diff --git a/simpeg/utils/code_utils.py b/simpeg/utils/code_utils.py index c4d268e947..ff571da83f 100644 --- a/simpeg/utils/code_utils.py +++ b/simpeg/utils/code_utils.py @@ -63,15 +63,11 @@ def requiresVar(f): survey.pair(myProblem) - """.format( - f.__name__ - ) + """.format(f.__name__) else: extra = """ To use *{0!s}* method, SimPEG requires that the {1!s} be specified. - """.format( - f.__name__, var - ) + """.format(f.__name__, var) @wraps(f) def requiresVarWrapper(self, *args, **kwargs): diff --git a/simpeg/utils/io_utils/io_utils_electromagnetics.py b/simpeg/utils/io_utils/io_utils_electromagnetics.py index e0306a17ef..cec69984ac 100644 --- a/simpeg/utils/io_utils/io_utils_electromagnetics.py +++ b/simpeg/utils/io_utils/io_utils_electromagnetics.py @@ -3,7 +3,6 @@ import warnings from ..code_utils import validate_string, validate_type - ######################################################################################## # DIRECT CURRENT RESISTIVITY AND INDUCED POLARIZATION ######################################################################################## diff --git a/simpeg/utils/io_utils/io_utils_general.py b/simpeg/utils/io_utils/io_utils_general.py index 2fddb56243..e0bf17647e 100644 --- a/simpeg/utils/io_utils/io_utils_general.py +++ b/simpeg/utils/io_utils/io_utils_general.py @@ -145,9 +145,12 @@ def rename_path(downloadpath): # download files urllist = url if isinstance(url, list) else [url] for u, f in zip(urllist, downloadpath): - print("Downloading {}".format(u)) + if verbose: + print(f"Downloading {u}") urlretrieve(u, f) - print(" saved to: " + f) + if verbose: + print(f" saved to: {f}") - print("Download completed!") + if verbose: + print("Download completed!") return downloadpath if isinstance(url, list) else downloadpath[0] diff --git a/simpeg/utils/mesh_utils.py b/simpeg/utils/mesh_utils.py index 42a85bde14..be9d14e819 100644 --- a/simpeg/utils/mesh_utils.py +++ b/simpeg/utils/mesh_utils.py @@ -136,7 +136,7 @@ def get_discrete_topography(mesh, active_cells, topo_cell_cutoff="top"): A tensor or tree mesh. active_cells : numpy.ndarray of bool or int Active cells index; i.e. indices of cells below surface - topo_cell_cutoff : {"top", "center"} + topo_cell_cutoff : {"top", "center"}, optional String to specify the cutoff for ground cells and the locations of the discrete topography. For "top", ground cells lie entirely below the surface topography and the discrete topography is defined on the @@ -196,7 +196,11 @@ def get_discrete_topography(mesh, active_cells, topo_cell_cutoff="top"): dz = 0.0 return np.c_[mesh.cell_centers[inds, :-1], mesh.cell_centers[inds, -1] + dz] else: - raise NotImplementedError(f"{type(mesh)} mesh is not supported.") + msg = ( + f"Invalid mesh of type '{type(mesh).__name__}'. " + "`get_discrete_topography` only supports TensorMesh and TreeMesh." + ) + raise TypeError(msg) def shift_to_discrete_topography( @@ -217,15 +221,16 @@ def shift_to_discrete_topography( pts : (n, dim) numpy.ndarray The original set of points being shifted relative to the discretize surface topography. - active_cells : numpy.ndarray of int or bool, optional + active_cells : numpy.ndarray of int or bool Index array for all cells lying below the surface topography. - topo_cell_cutoff : {"top", "center"} + topo_cell_cutoff : {"top", "center"}, optional String to specify the cutoff for ground cells and the locations of the discrete topography. For "top", ground cells lie entirely below the surface topography and the discrete topography is defined on the top faces of surface cells. For "center", only the cell centers must lie below the surface topography and the discrete topography is defined at the centers of surface cells. - The topography is defined using the 'topo' input parameter. + The topography is defined using the ``active_cells`` parameter: the topography + is obtained as the topmost surface of active cells. heights : float or (n,) numpy.ndarray, optional Height(s) relative to the true surface topography. Used to preserve flight heights or borehole depths. @@ -237,11 +242,17 @@ def shift_to_discrete_topography( ------- (n, dim) numpy.ndarray The set of points shifted relative to the discretize surface topography. + + See also + -------- + :func:`simpeg.utils.get_discrete_topography` """ if mesh._meshType != "TENSOR" and mesh._meshType != "TREE": - raise NotImplementedError( - "shift_to_discrete_topography only supported for TensorMesh and TreeMesh'." + msg = ( + f"Invalid mesh of type '{type(mesh).__name__}'. " + "`shift_to_discrete_topography` only supports TensorMesh and TreeMesh." ) + raise TypeError(msg) if not isinstance(heights, (int, float)) and len(pts) != len(heights): raise ValueError( diff --git a/simpeg/utils/model_builder.py b/simpeg/utils/model_builder.py index 0e31cfdc99..d67780345e 100644 --- a/simpeg/utils/model_builder.py +++ b/simpeg/utils/model_builder.py @@ -34,7 +34,11 @@ def add_block(cell_centers, model, p0, p1, prop_value): if isinstance(cell_centers, BaseMesh): cell_centers = cell_centers.cell_centers - ind = get_indices_block(p0, p1, cell_centers) + # Hide BreakingChangeWarning coming from get_indices_block + with warnings.catch_warnings(): + warnings.simplefilter(action="ignore", category=BreakingChangeWarning) + ind = get_indices_block(p0, p1, cell_centers) + new_model = model.copy() new_model[ind] = prop_value return new_model @@ -185,7 +189,11 @@ def create_block_in_wholespace( pass sigma = np.zeros(cell_centers.shape[0]) + background_value - ind = get_indices_block(p0, p1, cell_centers) + + # Hide BreakingChangeWarning coming from get_indices_block + with warnings.catch_warnings(): + warnings.simplefilter(action="ignore", category=BreakingChangeWarning) + ind = get_indices_block(p0, p1, cell_centers) sigma[ind] = block_value @@ -358,7 +366,10 @@ def create_2_layer_model(cell_centers, depth, top_value=1.0, bottom_value=0.0): # The depth is always defined on the last one. p1[len(p1) - 1] -= depth - ind = get_indices_block(p0, p1, cell_centers) + # Hide BreakingChangeWarning coming from get_indices_block + with warnings.catch_warnings(): + warnings.simplefilter(action="ignore", category=BreakingChangeWarning) + ind = get_indices_block(p0, p1, cell_centers) sigma[ind] = top_value diff --git a/simpeg/utils/model_utils.py b/simpeg/utils/model_utils.py index dc48a0e17c..cde0527733 100644 --- a/simpeg/utils/model_utils.py +++ b/simpeg/utils/model_utils.py @@ -1,5 +1,5 @@ import warnings -from typing import Literal, Optional +from typing import Literal import discretize import numpy as np @@ -226,11 +226,11 @@ def _distance_weighting_numba( def distance_weighting( mesh: discretize.base.BaseMesh, reference_locs: np.ndarray, - active_cells: Optional[np.ndarray] = None, - exponent: Optional[float] = 2.0, - threshold: Optional[float] = None, + active_cells: np.ndarray | None = None, + exponent: float = 2.0, + threshold: float | None = None, engine: Literal["numba", "scipy"] = "numba", - cdist_opts: Optional[dict] = None, + cdist_opts: dict | None = None, ): r""" Construct diagonal elements of a distance weighting matrix @@ -254,7 +254,7 @@ def distance_weighting( active_cells : (mesh.n_cells) numpy.ndarray of bool, optional Index vector for the active cells on the mesh. If ``None``, every cell will be assumed to be active. - exponent : float or None, optional + exponent : float, optional Exponent parameter for distance weighting. The exponent should match the natural decay power of the potential field. For example, for gravity acceleration, set it to 2; for magnetic @@ -262,7 +262,7 @@ def distance_weighting( threshold : float or None, optional Threshold parameters used in the distance weighting. If ``None``, it will be set to half of the smallest cell width. - engine: str, 'numba' or 'scipy' + engine: str, 'numba' or 'scipy', optional Pick between a ``scipy.spatial.distance.cdist`` computation (memory intensive) or `for` loop implementation, parallelized with numba if available. Default to ``"numba"``. diff --git a/simpeg/utils/solver_utils.py b/simpeg/utils/solver_utils.py index 70af2dae68..b7a93adaeb 100644 --- a/simpeg/utils/solver_utils.py +++ b/simpeg/utils/solver_utils.py @@ -12,8 +12,6 @@ ) from pymatsolver.solvers import Base from .code_utils import deprecate_function -import warnings -from typing import Type __all__ = [ "Solver", @@ -44,34 +42,18 @@ _DEFAULT_SOLVER = SolverLU -def get_default_solver(warn=False) -> Type[Base]: +def get_default_solver() -> type[Base]: """Return the default solver used by simpeg. - Parameters - ---------- - warn : bool, optional - - .. deprecated:: 0.25.0 - - Argument ``warn`` is deprecated and will be removed in - SimPEG v0.26.0. - Returns ------- solver The default solver class used by simpeg's simulations. """ - if warn: - warnings.warn( - "The `warn` argument has been deprecated and will be " - "removed in SimPEG v0.26.0.", - FutureWarning, - stacklevel=2, - ) return _DEFAULT_SOLVER -def set_default_solver(solver_class: Type[Base]): +def set_default_solver(solver_class: type[Base]): """Set the default solver used by simpeg. Parameters diff --git a/tests/base/regularizations/test_cross_gradient.py b/tests/base/regularizations/test_cross_gradient.py index 65f21ea4b7..dc5438544e 100644 --- a/tests/base/regularizations/test_cross_gradient.py +++ b/tests/base/regularizations/test_cross_gradient.py @@ -1,3 +1,5 @@ +import re +import pytest import unittest import numpy as np @@ -8,6 +10,8 @@ regularization, ) +from simpeg.regularization.cross_gradient import _cross_product_2d + class CrossGradientTensor2D(unittest.TestCase): def setUp(self): @@ -310,5 +314,97 @@ def test_deriv2_no_arg(self): np.testing.assert_allclose(Wv, W @ v) +class TestCrossProduct2D: + """ + Test the ``_cross_product_2d`` private function. + + .. important:: + + This function was added after Numpy dropped support for 2D vectors in the + :func:`numpy.cross` function. + """ + + def test_single_vectors(self): + a = np.array([1.0, 2.0]) + b = np.array([3.0, 4.0]) + result = _cross_product_2d(a, b) + + a = np.array([1.0, 2.0, 0.0]) + b = np.array([3.0, 4.0, 0.0]) + _, _, expected = np.cross(a, b) + + assert result.ndim == 1 + np.testing.assert_allclose(result, expected) + + @pytest.mark.parametrize("a_x_b", [True, False], ids=["a x b", "b x a"]) + def test_single_and_multiple_vectors(self, a_x_b): + a = np.array([1.0, 2.0]) + b = np.array([[3.0, 4.0], [5.0, 6.0]]) + result = _cross_product_2d(a, b) if a_x_b else _cross_product_2d(b, a) + + a = np.array([1.0, 2.0, 0.0]) + b = np.array([[3.0, 4.0, 0.0], [5.0, 6.0, 0.0]]) + cross = np.cross(a, b) if a_x_b else np.cross(b, a) + expected = cross[:, -1] + + assert result.ndim == 1 + np.testing.assert_allclose(result, expected) + + def test_multiple_vectors(self): + a = np.array([[1.0, 2.0], [8.0, 9.0]]) + b = np.array([[3.0, 4.0], [5.0, 6.0]]) + result = _cross_product_2d(a, b) + + a = np.array([[1.0, 2.0, 0.0], [8.0, 9.0, 0.0]]) + b = np.array([[3.0, 4.0, 0.0], [5.0, 6.0, 0.0]]) + expected = np.cross(a, b)[:, -1] + + assert result.ndim == 1 + np.testing.assert_allclose(result, expected) + + @pytest.mark.parametrize("a_x_b", [True, False], ids=["a x b", "b x a"]) + @pytest.mark.parametrize( + "a", + [ + np.array([1.0]), + np.array([1.0, 2.0, 3.0]), + np.array([[1.0]]), + np.array([[1.0], [2.0]]), + np.array([[1.0, 2.0, 3.0]]), + np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), + ], + ) + def test_invalid_elements(self, a, a_x_b): + b = np.array([1.0, 2.0]) + msg = re.escape( + f"Invalid array '{'a' if a_x_b else 'b'}' containing vectors with" + ) + if a_x_b: + with pytest.raises(ValueError, match=msg): + _cross_product_2d(a, b) + else: + with pytest.raises(ValueError, match=msg): + _cross_product_2d(b, a) + + @pytest.mark.parametrize("a_x_b", [True, False], ids=["a x b", "b x a"]) + @pytest.mark.parametrize( + "a", + [np.array(1.0), np.arange(6).reshape(3, 2, 1)], + ) + def test_invalid_dimensions(self, a, a_x_b): + b = np.array([1.0, 2.0]) + msg = ( + re.escape(f"Invalid array '{'a' if a_x_b else 'b'}' with '") + + "[0-9]+" + + re.escape("' dimensions") + ) + if a_x_b: + with pytest.raises(ValueError, match=msg): + _cross_product_2d(a, b) + else: + with pytest.raises(ValueError, match=msg): + _cross_product_2d(b, a) + + if __name__ == "__main__": unittest.main() diff --git a/tests/base/regularizations/test_regularization.py b/tests/base/regularizations/test_regularization.py index cf0c0a33d5..1abb00d074 100644 --- a/tests/base/regularizations/test_regularization.py +++ b/tests/base/regularizations/test_regularization.py @@ -17,7 +17,6 @@ ) from simpeg.objective_function import ComboObjectiveFunction - TOL = 1e-7 testReg = True testRegMesh = True diff --git a/tests/base/test_base_pde_sim.py b/tests/base/test_base_pde_sim.py index e9406d1339..75be93630f 100644 --- a/tests/base/test_base_pde_sim.py +++ b/tests/base/test_base_pde_sim.py @@ -1,7 +1,14 @@ -import re +"""Test for base PDE simulations.""" +import re import pymatsolver -from simpeg.base import with_property_mass_matrices, BasePDESimulation +from simpeg.base import ( + with_property_mass_matrices, + with_surface_property_mass_matrices, + with_line_property_mass_matrices, + BasePDESimulation, + BaseHierarchicalElectricalSimulation, +) from simpeg import props, maps from simpeg.utils import PerformanceWarning import unittest @@ -19,33 +26,63 @@ # define a very simple class... @with_property_mass_matrices("sigma") @with_property_mass_matrices("mu") +@with_surface_property_mass_matrices("face_conductance") +@with_line_property_mass_matrices("edge_area_conductance") class SimpleSim(BasePDESimulation): - sigma, sigmaMap, sigmaDeriv = props.Invertible("Electrical conductivity (S/m)") + """Base class for simple simulation.""" + sigma, sigmaMap, sigmaDeriv = props.Invertible("Electrical conductivity (S/m)") + rho, rhoMap, rhoDeriv = props.Invertible("Electrical conductivity (S/m)") + props.Reciprocal(sigma, rho) mu, muMap, muDeriv = props.Invertible("Magnetic Permeability") + face_conductance, face_conductance_map, face_conductance_deriv = props.Invertible( + "Face conductivity, conductance (S)" + ) + edge_area_conductance, edge_area_conductance_map, edge_area_conductance_deriv = ( + props.Invertible("Edge conductivity, conductivity times area (Sm)") + ) - def __init__( - self, mesh, survey=None, sigma=None, sigmaMap=None, mu=mu_0, muMap=None + def __init__( # noqa D107 + self, + mesh, + survey=None, + sigma=None, + sigmaMap=None, + mu=mu_0, + muMap=None, + face_conductance=None, + face_conductance_map=None, + edge_area_conductance=None, + edge_area_conductance_map=None, ): super().__init__(mesh=mesh, survey=survey) self.sigma = sigma self.mu = mu + self.face_conductance = face_conductance + self.edge_area_conductance = edge_area_conductance self.sigmaMap = sigmaMap self.muMap = muMap + self.face_conductance_map = face_conductance_map + self.edge_area_conductance_map = edge_area_conductance_map @property def _delete_on_model_update(self): - """ - matrices to be deleted if the model for conductivity/resistivity is updated - """ + """Matrices deleted upon conductivity/resistivity model update.""" toDelete = super()._delete_on_model_update if self.sigmaMap is not None or self.rhoMap is not None: toDelete = toDelete + self._clear_on_sigma_update + if self.face_conductance_map is not None: + toDelete = toDelete + self._clear_on_face_conductance_update + if self.edge_area_conductance_map is not None: + toDelete = toDelete + self._clear_on_edge_area_conductance_update return toDelete class TestSim(unittest.TestCase): + """Test simulation.""" + def setUp(self): + """Set up functions.""" self.mesh = discretize.TensorMesh([5, 6, 7]) self.sim = SimpleSim(self.mesh, sigmaMap=maps.ExpMap()) @@ -69,6 +106,7 @@ def setUp(self): ] def test_zero_returns(self): + """Test zero returns.""" n_c = self.mesh.n_cells n_n = self.mesh.n_nodes n_f = self.mesh.n_faces @@ -112,6 +150,7 @@ def test_zero_returns(self): assert sim.MeSigmaIDeriv(u_e, Zero()).__class__ == Zero def test_simple_mass(self): + """Test simple mass matrix.""" sim = self.sim n_c = self.mesh.n_cells n_n = self.mesh.n_nodes @@ -144,6 +183,7 @@ def test_simple_mass(self): np.testing.assert_allclose(x_e, sim.MeI @ (sim.Me @ x_e)) def test_forward_expected_shapes(self): + """Test forward expected shapes.""" sim = self.sim sim.model = self.start_mod @@ -204,6 +244,7 @@ def test_forward_expected_shapes(self): ) def test_forward_anis_expected_shapes(self): + """Test forward anisotropy expected shapes.""" sim = self.sim sim.model = self.start_full_mod @@ -264,6 +305,7 @@ def test_forward_anis_expected_shapes(self): ) def test_adjoint_expected_shapes(self): + """Test adjoint expected shapes.""" sim = self.sim sim.model = self.start_mod @@ -326,6 +368,7 @@ def test_adjoint_expected_shapes(self): ) def test_adjoint_anis_expected_shapes(self): + """Test adjoint anisotropy expected shapes.""" sim = self.sim sim.model = self.start_full_mod @@ -388,6 +431,7 @@ def test_adjoint_anis_expected_shapes(self): ) def test_adjoint_opp(self): + """Test adjoint opp.""" sim = self.sim sim.model = self.start_mod @@ -447,6 +491,7 @@ def test_adjoint_opp(self): np.testing.assert_allclose(vJy, yJtv) def test_anis_adjoint_opp(self): + """Test anisotropy adjoint opp.""" sim = self.sim sim.model = self.start_full_mod @@ -485,6 +530,7 @@ def test_anis_adjoint_opp(self): np.testing.assert_allclose(vJy, yJtv) def test_Mcc_deriv(self): + """Test Mcc derive.""" u = np.random.randn(self.mesh.n_cells) sim = self.sim x0 = self.start_mod @@ -502,6 +548,7 @@ def Jvec(v): assert check_derivative(f, x0=x0, num=3, plotIt=False, random_seed=8672354) def test_Mn_deriv(self): + """Test Mn derive.""" u = np.random.randn(self.mesh.n_nodes) sim = self.sim x0 = self.start_mod @@ -519,6 +566,7 @@ def Jvec(v): assert check_derivative(f, x0=x0, num=3, plotIt=False, random_seed=523876) def test_Me_deriv(self): + """Test Me deriv.""" u = np.random.randn(self.mesh.n_edges) sim = self.sim x0 = self.start_mod @@ -536,6 +584,7 @@ def Jvec(v): assert check_derivative(f, x0=x0, num=3, plotIt=False, random_seed=9875163) def test_Me_diagonal_anisotropy_deriv(self): + """Test Me diagonal anisotropy derive.""" u = np.random.randn(self.mesh.n_edges) sim = self.sim x0 = self.start_diag_mod @@ -553,6 +602,7 @@ def Jvec(v): assert check_derivative(f, x0=x0, num=3, plotIt=False, random_seed=1658372) def test_Me_full_anisotropy_deriv(self): + """Test Me full anisotropy deriv.""" u = np.random.randn(self.mesh.n_edges) sim = self.sim_full_aniso x0 = self.start_full_mod @@ -570,6 +620,7 @@ def Jvec(v): assert check_derivative(f, x0=x0, num=3, plotIt=False, random_seed=9867234) def test_Mf_deriv(self): + """Test Mf deriv.""" u = np.random.randn(self.mesh.n_faces) sim = self.sim x0 = self.start_mod @@ -587,6 +638,7 @@ def Jvec(v): assert check_derivative(f, x0=x0, num=3, plotIt=False, random_seed=10523687) def test_Mf_diagonal_anisotropy_deriv(self): + """Test Mf diagonal anisotropy deriv.""" u = np.random.randn(self.mesh.n_faces) sim = self.sim x0 = self.start_diag_mod @@ -604,6 +656,7 @@ def Jvec(v): assert check_derivative(f, x0=x0, num=3, plotIt=False, random_seed=19876354) def test_Mf_full_anisotropy_deriv(self): + """Test Mf full anisotropy derive.""" u = np.random.randn(self.mesh.n_faces) sim = self.sim_full_aniso x0 = self.start_full_mod @@ -621,6 +674,7 @@ def Jvec(v): assert check_derivative(f, x0=x0, num=3, plotIt=False, random_seed=102309487) def test_MccI_deriv(self): + """Test MccI derive.""" u = np.random.randn(self.mesh.n_cells) sim = self.sim x0 = self.start_mod @@ -638,6 +692,7 @@ def Jvec(v): assert check_derivative(f, x0=x0, num=3, plotIt=False, random_seed=89726354) def test_MnI_deriv(self): + """Test MnI derive.""" u = np.random.randn(self.mesh.n_nodes) sim = self.sim x0 = self.start_mod @@ -655,6 +710,7 @@ def Jvec(v): assert check_derivative(f, x0=x0, num=3, plotIt=False, random_seed=12503698) def test_MeI_deriv(self): + """Test MeI deriv.""" u = np.random.randn(self.mesh.n_edges) sim = self.sim x0 = self.start_mod @@ -672,6 +728,7 @@ def Jvec(v): assert check_derivative(f, x0=x0, num=3, plotIt=False, random_seed=5674129834) def test_MfI_deriv(self): + """Test MfI derive.""" u = np.random.randn(self.mesh.n_faces) sim = self.sim x0 = self.start_mod @@ -689,6 +746,7 @@ def Jvec(v): assert check_derivative(f, x0=x0, num=3, plotIt=False, random_seed=532349) def test_Mcc_adjoint(self): + """Test Mcc adjoint.""" n_items = self.mesh.n_cells u = np.random.randn(n_items) sim = self.sim @@ -702,6 +760,7 @@ def test_Mcc_adjoint(self): np.testing.assert_allclose(yJv, vJty) def test_Mn_adjoint(self): + """Test Mn adjoint.""" n_items = self.mesh.n_nodes u = np.random.randn(n_items) sim = self.sim @@ -715,6 +774,7 @@ def test_Mn_adjoint(self): np.testing.assert_allclose(yJv, vJty) def test_Me_adjoint(self): + """Test Me adjoint.""" n_items = self.mesh.n_edges u = np.random.randn(n_items) sim = self.sim @@ -728,6 +788,7 @@ def test_Me_adjoint(self): np.testing.assert_allclose(yJv, vJty) def test_Mf_adjoint(self): + """Test Mf adjoint.""" n_items = self.mesh.n_faces u = np.random.randn(n_items) sim = self.sim @@ -741,6 +802,7 @@ def test_Mf_adjoint(self): np.testing.assert_allclose(yJv, vJty) def test_MccI_adjoint(self): + """Test MccI adoint.""" n_items = self.mesh.n_cells u = np.random.randn(n_items) sim = self.sim @@ -754,6 +816,7 @@ def test_MccI_adjoint(self): np.testing.assert_allclose(yJv, vJty) def test_MnI_adjoint(self): + """Test MnI adjoint.""" n_items = self.mesh.n_nodes u = np.random.randn(n_items) sim = self.sim @@ -767,6 +830,7 @@ def test_MnI_adjoint(self): np.testing.assert_allclose(yJv, vJty) def test_MeI_adjoint(self): + """Test MeI adjoint.""" n_items = self.mesh.n_edges u = np.random.randn(n_items) sim = self.sim @@ -780,6 +844,7 @@ def test_MeI_adjoint(self): np.testing.assert_allclose(yJv, vJty) def test_MfI_adjoint(self): + """Test MfI adjoint.""" n_items = self.mesh.n_faces u = np.random.randn(n_items) sim = self.sim @@ -793,7 +858,634 @@ def test_MfI_adjoint(self): np.testing.assert_allclose(yJv, vJty) +class TestSimSurfaceProperties(unittest.TestCase): + """Tests for surface properties.""" + + def setUp(self): + """Set up function.""" + self.mesh = discretize.TensorMesh([5, 6, 7]) + self.sim = SimpleSim(self.mesh, face_conductance_map=maps.ExpMap()) + self.start_mod = np.log(1e-2 * np.ones(self.mesh.n_faces)) + np.random.randn( + self.mesh.n_faces + ) + + def test_zero_returns(self): + """Test zero returns.""" + n_f = self.mesh.n_faces + n_e = self.mesh.n_edges + sim = self.sim + + v = np.random.rand(n_f) + u_f = np.random.rand(n_f) + u_e = np.random.rand(n_e) + + # Test zero return on u passed as Zero + assert sim._Mf_face_conductance_deriv(Zero(), v).__class__ == Zero + assert sim._Me_face_conductance_deriv(Zero(), v).__class__ == Zero + assert sim._MfI_face_conductance_deriv(Zero(), v).__class__ == Zero + assert sim._MeI_face_conductance_deriv(Zero(), v).__class__ == Zero + + # Test zero return on v as Zero + assert sim._Mf_face_conductance_deriv(u_f, Zero()).__class__ == Zero + assert sim._Me_face_conductance_deriv(u_e, Zero()).__class__ == Zero + assert sim._MfI_face_conductance_deriv(u_f, Zero()).__class__ == Zero + assert sim._MeI_face_conductance_deriv(u_e, Zero()).__class__ == Zero + + def test_forward_expected_shapes(self): + """Test forward expected shapes.""" + sim = self.sim + sim.model = self.start_mod + + n_f = self.mesh.n_faces + # n_c = self.mesh.n_cells + # if U.shape (n_f, ) + u = np.random.rand(n_f) + v = np.random.randn(n_f) + u2 = np.random.rand(n_f, 2) + v2 = np.random.randn(n_f, 4) + + # These cases should all return an array of shape (n_f, ) + # if V.shape (n_c, ) + out = sim._Mf_face_conductance_deriv(u, v) + assert out.shape == (n_f,) + out = sim._Mf_face_conductance_deriv(u, v[:, None]) + assert out.shape == (n_f,) + out = sim._Mf_face_conductance_deriv(u[:, None], v) + assert out.shape == (n_f,) + out = sim._Mf_face_conductance_deriv(u[:, None], v[:, None]) + assert out.shape == (n_f,) + + # now check passing multiple V's + out = sim._Mf_face_conductance_deriv(u, v2) + assert out.shape == (n_f, 4) + out = sim._Mf_face_conductance_deriv(u[:, None], v2) + assert out.shape == (n_f, 4) + + # also ensure it properly broadcasted the operation.... + out_2 = np.empty_like(out) + for i in range(v2.shape[1]): + out_2[:, i] = sim._Mf_face_conductance_deriv(u[:, None], v2[:, i]) + np.testing.assert_equal(out, out_2) + + # now check for multiple source polarizations + out = sim._Mf_face_conductance_deriv(u2, v) + assert out.shape == (n_f, 2) + out = sim._Mf_face_conductance_deriv(u2, v[:, None]) + assert out.shape == (n_f, 2) + + # and with multiple RHS + out = sim._Mf_face_conductance_deriv(u2, v2) + assert out.shape == (n_f, v2.shape[1], 2) + + # and test broadcasting here... + out_2 = np.empty_like(out) + for i in range(v2.shape[1]): + out_2[:, i, :] = sim._Mf_face_conductance_deriv(u2, v2[:, i]) + np.testing.assert_equal(out, out_2) + + # test None as v + UM = sim._Mf_face_conductance_deriv(u) + np.testing.assert_allclose(UM @ v, sim._Mf_face_conductance_deriv(u, v)) + + UM = sim._Mf_face_conductance_deriv(u2) + np.testing.assert_allclose( + UM @ v, sim._Mf_face_conductance_deriv(u2, v).reshape(-1, order="F") + ) + + def test_adjoint_expected_shapes(self): + """Test adjoint expected shapes.""" + sim = self.sim + sim.model = self.start_mod + + n_f = self.mesh.n_faces + + u = np.random.rand(n_f) + v = np.random.randn(n_f) + v2 = np.random.randn(n_f, 4) + u2 = np.random.rand(n_f, 2) + v2_2 = np.random.randn(n_f, 2) + v3 = np.random.rand(n_f, 4, 2) + + # These cases should all return an array of shape (n_c, ) + # if V.shape (n_f, ) + out = sim._Mf_face_conductance_deriv(u, v, adjoint=True) + assert out.shape == (n_f,) + out = sim._Mf_face_conductance_deriv(u, v[:, None], adjoint=True) + assert out.shape == (n_f,) + out = sim._Mf_face_conductance_deriv(u[:, None], v, adjoint=True) + assert out.shape == (n_f,) + out = sim._Mf_face_conductance_deriv(u[:, None], v[:, None], adjoint=True) + assert out.shape == (n_f,) + + # now check passing multiple V's + out = sim._Mf_face_conductance_deriv(u, v2, adjoint=True) + assert out.shape == (n_f, 4) + out = sim._Mf_face_conductance_deriv(u[:, None], v2, adjoint=True) + assert out.shape == (n_f, 4) + + # also ensure it properly broadcasted the operation.... + out_2 = np.empty_like(out) + for i in range(v2.shape[1]): + out_2[:, i] = sim._Mf_face_conductance_deriv(u, v2[:, i], adjoint=True) + np.testing.assert_equal(out, out_2) + + # now check for multiple source polarizations + out = sim._Mf_face_conductance_deriv(u2, v2_2, adjoint=True) + assert out.shape == (n_f,) + out = sim._Mf_face_conductance_deriv(u2, v2_2, adjoint=True) + assert out.shape == (n_f,) + + # and with multiple RHS + out = sim._Mf_face_conductance_deriv(u2, v3, adjoint=True) + assert out.shape == (n_f, v3.shape[1]) + + # and test broadcasting here... + out_2 = np.empty_like(out) + for i in range(v2.shape[1]): + out_2[:, i] = sim._Mf_face_conductance_deriv(u2, v3[:, i, :], adjoint=True) + np.testing.assert_equal(out, out_2) + + # test None as v + UMT = sim._Mf_face_conductance_deriv(u, adjoint=True) + np.testing.assert_allclose( + UMT @ v, sim._Mf_face_conductance_deriv(u, v, adjoint=True) + ) + + UMT = sim._Mf_face_conductance_deriv(u2, adjoint=True) + np.testing.assert_allclose( + UMT @ v2_2.reshape(-1, order="F"), + sim._Mf_face_conductance_deriv(u2, v2_2, adjoint=True), + ) + + def test_adjoint_opp_shapes(self): + """Test adjoint opp shapes.""" + sim = self.sim + sim.model = self.start_mod + + n_f = self.mesh.n_faces + + u = np.random.rand(n_f) + u2 = np.random.rand(n_f, 2) + + y = np.random.rand(n_f) + y2 = np.random.rand(n_f, 4) + + v = np.random.randn(n_f) + v2 = np.random.randn(n_f, 4) + v2_2 = np.random.randn(n_f, 2) + v3 = np.random.rand(n_f, 4, 2) + + # u1, y1 -> v1 + vJy = v @ sim._Mf_face_conductance_deriv(u, y) + yJtv = y @ sim._Mf_face_conductance_deriv(u, v, adjoint=True) + np.testing.assert_allclose(vJy, yJtv) + + # u1, y2 -> v2 + vJy = np.sum(v2 * sim._Mf_face_conductance_deriv(u, y2)) + yJtv = np.sum(y2 * sim._Mf_face_conductance_deriv(u, v2, adjoint=True)) + np.testing.assert_allclose(vJy, yJtv) + + # u2, y1 -> v2_2 + vJy = np.sum(v2_2 * sim._Mf_face_conductance_deriv(u2, y)) + yJtv = np.sum(y * sim._Mf_face_conductance_deriv(u2, v2_2, adjoint=True)) + np.testing.assert_allclose(vJy, yJtv) + + # u2, y2 -> v3 + vJy = np.sum(v3 * sim._Mf_face_conductance_deriv(u2, y2)) + yJtv = np.sum(y2 * sim._Mf_face_conductance_deriv(u2, v3, adjoint=True)) + np.testing.assert_allclose(vJy, yJtv) + + # Also test Inverse opp, just to be sure... + # u1, y1 -> v1 + vJy = v @ sim._MfI_face_conductance_deriv(u, y) + yJtv = y @ sim._MfI_face_conductance_deriv(u, v, adjoint=True) + np.testing.assert_allclose(vJy, yJtv) + + # u1, y2 -> v2 + vJy = np.sum(v2 * sim._MfI_face_conductance_deriv(u, y2)) + yJtv = np.sum(y2 * sim._MfI_face_conductance_deriv(u, v2, adjoint=True)) + np.testing.assert_allclose(vJy, yJtv) + + # u2, y1 -> v2_2 + vJy = np.sum(v2_2 * sim._MfI_face_conductance_deriv(u2, y)) + yJtv = np.sum(y * sim._MfI_face_conductance_deriv(u2, v2_2, adjoint=True)) + np.testing.assert_allclose(vJy, yJtv) + + # u2, y2 -> v3 + vJy = np.sum(v3 * sim._MfI_face_conductance_deriv(u2, y2)) + yJtv = np.sum(y2 * sim._MfI_face_conductance_deriv(u2, v3, adjoint=True)) + np.testing.assert_allclose(vJy, yJtv) + + def test_Me_deriv(self): + """Test Me derive.""" + u = np.random.randn(self.mesh.n_edges) + sim = self.sim + x0 = self.start_mod + + def f(x): + sim.model = x + d = sim._Me_face_conductance @ u + + def Jvec(v): + sim.model = x0 + return sim._Me_face_conductance_deriv(u, v) + + return d, Jvec + + assert check_derivative(f, x0=x0, num=3, random_seed=12312, plotIt=False) + + def test_Mf_deriv(self): + """Test Mf deriv.""" + u = np.random.randn(self.mesh.n_faces) + sim = self.sim + x0 = self.start_mod + + def f(x): + sim.model = x + d = sim._Mf_face_conductance @ u + + def Jvec(v): + sim.model = x0 + return sim._Mf_face_conductance_deriv(u, v) + + return d, Jvec + + assert check_derivative(f, x0=x0, num=3, random_seed=542353, plotIt=False) + + def test_MeI_deriv(self): + """Test MeI derive.""" + u = np.random.randn(self.mesh.n_edges) + sim = self.sim + x0 = self.start_mod + + def f(x): + sim.model = x + d = sim._MeI_face_conductance @ u + + def Jvec(v): + sim.model = x0 + return sim._MeI_face_conductance_deriv(u, v) + + return d, Jvec + + assert check_derivative(f, x0=x0, num=3, random_seed=47594, plotIt=False) + + def test_MfI_deriv(self): + """Test MfI deriv.""" + u = np.random.randn(self.mesh.n_faces) + sim = self.sim + x0 = self.start_mod + + def f(x): + sim.model = x + d = sim._MfI_face_conductance @ u + + def Jvec(v): + sim.model = x0 + return sim._MfI_face_conductance_deriv(u, v) + + return d, Jvec + + assert check_derivative(f, x0=x0, num=3, random_seed=2950, plotIt=False) + + def test_Me_adjoint(self): + """Test Me adjoint.""" + n_items = self.mesh.n_edges + u = np.random.randn(n_items) + sim = self.sim + sim.model = self.start_mod + + v = np.random.randn(self.mesh.n_faces) + y = np.random.randn(n_items) + + yJv = y @ sim._Me_face_conductance_deriv(u, v) + vJty = v @ sim._Me_face_conductance_deriv(u, y, adjoint=True) + np.testing.assert_allclose(yJv, vJty) + + def test_Mf_adjoint(self): + """Test Mf adjoint.""" + n_items = self.mesh.n_faces + u = np.random.randn(n_items) + sim = self.sim + sim.model = self.start_mod + + v = np.random.randn(self.mesh.n_faces) + y = np.random.randn(n_items) + + yJv = y @ sim._Mf_face_conductance_deriv(u, v) + vJty = v @ sim._Mf_face_conductance_deriv(u, y, adjoint=True) + np.testing.assert_allclose(yJv, vJty) + + def test_MeI_adjoint(self): + """Test MeI adjoint.""" + n_items = self.mesh.n_edges + u = np.random.randn(n_items) + sim = self.sim + sim.model = self.start_mod + + v = np.random.randn(self.mesh.n_faces) + y = np.random.randn(n_items) + + yJv = y @ sim._MeI_face_conductance_deriv(u, v) + vJty = v @ sim._MeI_face_conductance_deriv(u, y, adjoint=True) + np.testing.assert_allclose(yJv, vJty) + + def test_MfI_adjoint(self): + """Test MfI adjoint.""" + n_items = self.mesh.n_faces + u = np.random.randn(n_items) + sim = self.sim + sim.model = self.start_mod + + v = np.random.randn(self.mesh.n_faces) + y = np.random.randn(n_items) + + yJv = y @ sim._MfI_face_conductance_deriv(u, v) + vJty = v @ sim._MfI_face_conductance_deriv(u, y, adjoint=True) + np.testing.assert_allclose(yJv, vJty) + + +class TestSimEdgeProperties(unittest.TestCase): + """Tests for edge properties.""" + + def setUp(self): + """Set up function.""" + self.mesh = discretize.TensorMesh([5, 6, 7]) + self.sim = SimpleSim(self.mesh, edge_area_conductance_map=maps.ExpMap()) + self.start_mod = np.log(1e-2 * np.ones(self.mesh.n_edges)) + np.random.randn( + self.mesh.n_edges + ) + + def test_zero_returns(self): + """Test zero returns.""" + n_e = self.mesh.n_edges + sim = self.sim + + v = np.random.rand(n_e) + u_e = np.random.rand(n_e) + + # Test zero return on u passed as Zero + assert sim._Me_edge_area_conductance_deriv(Zero(), v).__class__ == Zero + assert sim._MeI_edge_area_conductance_deriv(Zero(), v).__class__ == Zero + + # Test zero return on v as Zero + assert sim._Me_edge_area_conductance_deriv(u_e, Zero()).__class__ == Zero + assert sim._MeI_edge_area_conductance_deriv(u_e, Zero()).__class__ == Zero + + def test_forward_expected_shapes(self): + """Test forward expected shapes.""" + sim = self.sim + sim.model = self.start_mod + + n_e = self.mesh.n_edges + # n_c = self.mesh.n_cells + # if U.shape (n_f, ) + u = np.random.rand(n_e) + v = np.random.randn(n_e) + u2 = np.random.rand(n_e, 2) + v2 = np.random.randn(n_e, 4) + + # These cases should all return an array of shape (n_f, ) + # if V.shape (n_c, ) + out = sim._Me_edge_area_conductance_deriv(u, v) + assert out.shape == (n_e,) + out = sim._Me_edge_area_conductance_deriv(u, v[:, None]) + assert out.shape == (n_e,) + out = sim._Me_edge_area_conductance_deriv(u[:, None], v) + assert out.shape == (n_e,) + out = sim._Me_edge_area_conductance_deriv(u[:, None], v[:, None]) + assert out.shape == (n_e,) + + # now check passing multiple V's + out = sim._Me_edge_area_conductance_deriv(u, v2) + assert out.shape == (n_e, 4) + out = sim._Me_edge_area_conductance_deriv(u[:, None], v2) + assert out.shape == (n_e, 4) + + # also ensure it properly broadcasted the operation.... + out_2 = np.empty_like(out) + for i in range(v2.shape[1]): + out_2[:, i] = sim._Me_edge_area_conductance_deriv(u[:, None], v2[:, i]) + np.testing.assert_equal(out, out_2) + + # now check for multiple source polarizations + out = sim._Me_edge_area_conductance_deriv(u2, v) + assert out.shape == (n_e, 2) + out = sim._Me_edge_area_conductance_deriv(u2, v[:, None]) + assert out.shape == (n_e, 2) + + # and with multiple RHS + out = sim._Me_edge_area_conductance_deriv(u2, v2) + assert out.shape == (n_e, v2.shape[1], 2) + + # and test broadcasting here... + out_2 = np.empty_like(out) + for i in range(v2.shape[1]): + out_2[:, i, :] = sim._Me_edge_area_conductance_deriv(u2, v2[:, i]) + np.testing.assert_equal(out, out_2) + + # test None as v + UM = sim._Me_edge_area_conductance_deriv(u) + np.testing.assert_allclose(UM @ v, sim._Me_edge_area_conductance_deriv(u, v)) + + UM = sim._Me_edge_area_conductance_deriv(u2) + np.testing.assert_allclose( + UM @ v, sim._Me_edge_area_conductance_deriv(u2, v).reshape(-1, order="F") + ) + + def test_adjoint_expected_shapes(self): + """Test adjoint expected shapes.""" + sim = self.sim + sim.model = self.start_mod + + n_e = self.mesh.n_edges + + u = np.random.rand(n_e) + v = np.random.randn(n_e) + v2 = np.random.randn(n_e, 4) + u2 = np.random.rand(n_e, 2) + v2_2 = np.random.randn(n_e, 2) + v3 = np.random.rand(n_e, 4, 2) + + # These cases should all return an array of shape (n_c, ) + # if V.shape (n_f, ) + out = sim._Me_edge_area_conductance_deriv(u, v, adjoint=True) + assert out.shape == (n_e,) + out = sim._Me_edge_area_conductance_deriv(u, v[:, None], adjoint=True) + assert out.shape == (n_e,) + out = sim._Me_edge_area_conductance_deriv(u[:, None], v, adjoint=True) + assert out.shape == (n_e,) + out = sim._Me_edge_area_conductance_deriv(u[:, None], v[:, None], adjoint=True) + assert out.shape == (n_e,) + + # now check passing multiple V's + out = sim._Me_edge_area_conductance_deriv(u, v2, adjoint=True) + assert out.shape == (n_e, 4) + out = sim._Me_edge_area_conductance_deriv(u[:, None], v2, adjoint=True) + assert out.shape == (n_e, 4) + + # also ensure it properly broadcasted the operation.... + out_2 = np.empty_like(out) + for i in range(v2.shape[1]): + out_2[:, i] = sim._Me_edge_area_conductance_deriv(u, v2[:, i], adjoint=True) + np.testing.assert_equal(out, out_2) + + # now check for multiple source polarizations + out = sim._Me_edge_area_conductance_deriv(u2, v2_2, adjoint=True) + assert out.shape == (n_e,) + out = sim._Me_edge_area_conductance_deriv(u2, v2_2, adjoint=True) + assert out.shape == (n_e,) + + # and with multiple RHS + out = sim._Me_edge_area_conductance_deriv(u2, v3, adjoint=True) + assert out.shape == (n_e, v3.shape[1]) + + # and test broadcasting here... + out_2 = np.empty_like(out) + for i in range(v2.shape[1]): + out_2[:, i] = sim._Me_edge_area_conductance_deriv( + u2, v3[:, i, :], adjoint=True + ) + np.testing.assert_equal(out, out_2) + + # test None as v + UMT = sim._Me_edge_area_conductance_deriv(u, adjoint=True) + np.testing.assert_allclose( + UMT @ v, sim._Me_edge_area_conductance_deriv(u, v, adjoint=True) + ) + + UMT = sim._Me_edge_area_conductance_deriv(u2, adjoint=True) + np.testing.assert_allclose( + UMT @ v2_2.reshape(-1, order="F"), + sim._Me_edge_area_conductance_deriv(u2, v2_2, adjoint=True), + ) + + def test_adjoint_opp_shapes(self): + """Test adjoint opp shapes.""" + sim = self.sim + sim.model = self.start_mod + + n_e = self.mesh.n_edges + + u = np.random.rand(n_e) + u2 = np.random.rand(n_e, 2) + + y = np.random.rand(n_e) + y2 = np.random.rand(n_e, 4) + + v = np.random.randn(n_e) + v2 = np.random.randn(n_e, 4) + v2_2 = np.random.randn(n_e, 2) + v3 = np.random.rand(n_e, 4, 2) + + # u1, y1 -> v1 + vJy = v @ sim._Me_edge_area_conductance_deriv(u, y) + yJtv = y @ sim._Me_edge_area_conductance_deriv(u, v, adjoint=True) + np.testing.assert_allclose(vJy, yJtv) + + # u1, y2 -> v2 + vJy = np.sum(v2 * sim._Me_edge_area_conductance_deriv(u, y2)) + yJtv = np.sum(y2 * sim._Me_edge_area_conductance_deriv(u, v2, adjoint=True)) + np.testing.assert_allclose(vJy, yJtv) + + # u2, y1 -> v2_2 + vJy = np.sum(v2_2 * sim._Me_edge_area_conductance_deriv(u2, y)) + yJtv = np.sum(y * sim._Me_edge_area_conductance_deriv(u2, v2_2, adjoint=True)) + np.testing.assert_allclose(vJy, yJtv) + + # u2, y2 -> v3 + vJy = np.sum(v3 * sim._Me_edge_area_conductance_deriv(u2, y2)) + yJtv = np.sum(y2 * sim._Me_edge_area_conductance_deriv(u2, v3, adjoint=True)) + np.testing.assert_allclose(vJy, yJtv) + + # Also test Inverse opp, just to be sure... + # u1, y1 -> v1 + vJy = v @ sim._MeI_edge_area_conductance_deriv(u, y) + yJtv = y @ sim._MeI_edge_area_conductance_deriv(u, v, adjoint=True) + np.testing.assert_allclose(vJy, yJtv) + + # u1, y2 -> v2 + vJy = np.sum(v2 * sim._MeI_edge_area_conductance_deriv(u, y2)) + yJtv = np.sum(y2 * sim._MeI_edge_area_conductance_deriv(u, v2, adjoint=True)) + np.testing.assert_allclose(vJy, yJtv) + + # u2, y1 -> v2_2 + vJy = np.sum(v2_2 * sim._MeI_edge_area_conductance_deriv(u2, y)) + yJtv = np.sum(y * sim._MeI_edge_area_conductance_deriv(u2, v2_2, adjoint=True)) + np.testing.assert_allclose(vJy, yJtv) + + # u2, y2 -> v3 + vJy = np.sum(v3 * sim._MeI_edge_area_conductance_deriv(u2, y2)) + yJtv = np.sum(y2 * sim._MeI_edge_area_conductance_deriv(u2, v3, adjoint=True)) + np.testing.assert_allclose(vJy, yJtv) + + def test_Me_deriv(self): + """Test Me deriv.""" + u = np.random.randn(self.mesh.n_edges) + sim = self.sim + x0 = self.start_mod + + def f(x): + sim.model = x + d = sim._Me_edge_area_conductance @ u + + def Jvec(v): + sim.model = x0 + return sim._Me_edge_area_conductance_deriv(u, v) + + return d, Jvec + + assert check_derivative(f, x0=x0, num=3, random_seed=3284, plotIt=False) + + def test_MeI_deriv(self): + """Test MeI derive.""" + u = np.random.randn(self.mesh.n_edges) + sim = self.sim + x0 = self.start_mod + + def f(x): + sim.model = x + d = sim._MeI_edge_area_conductance @ u + + def Jvec(v): + sim.model = x0 + return sim._MeI_edge_area_conductance_deriv(u, v) + + return d, Jvec + + assert check_derivative(f, x0=x0, num=3, random_seed=4372, plotIt=False) + + def test_Me_adjoint(self): + """Test Me adjoint.""" + n_items = self.mesh.n_edges + u = np.random.randn(n_items) + sim = self.sim + sim.model = self.start_mod + + v = np.random.randn(self.mesh.n_edges) + y = np.random.randn(n_items) + + yJv = y @ sim._Me_edge_area_conductance_deriv(u, v) + vJty = v @ sim._Me_edge_area_conductance_deriv(u, y, adjoint=True) + np.testing.assert_allclose(yJv, vJty) + + def test_MeI_adjoint(self): + """Test MeI adjoint.""" + n_items = self.mesh.n_edges + u = np.random.randn(n_items) + sim = self.sim + sim.model = self.start_mod + + v = np.random.randn(self.mesh.n_edges) + y = np.random.randn(n_items) + + yJv = y @ sim._MeI_edge_area_conductance_deriv(u, v) + vJty = v @ sim._MeI_edge_area_conductance_deriv(u, y, adjoint=True) + np.testing.assert_allclose(yJv, vJty) + + def test_bad_derivative_stash(): + """Test bad derivative stash.""" mesh = discretize.TensorMesh([5, 6, 7]) sim = SimpleSim(mesh, sigmaMap=maps.ExpMap()) sim.model = np.random.rand(mesh.n_cells) @@ -815,6 +1507,7 @@ def test_bad_derivative_stash(): def test_solver_defaults(caplog, info_logging): + """Test solver defaults.""" mesh = discretize.TensorMesh([2, 2, 2]) sim = BasePDESimulation(mesh) # Check that logging.info was created @@ -825,9 +1518,7 @@ def test_solver_defaults(caplog, info_logging): @pytest.mark.parametrize("solver_class", [pymatsolver.SolverLU, pymatsolver.Solver]) def test_performance_warning_on_solver(solver_class): - """ - Test PerformanceWarning when setting an inefficient solver. - """ + """Test PerformanceWarning when setting an inefficient solver.""" mesh = discretize.TensorMesh([2, 2, 2]) regex = re.escape( f"The 'pymatsolver.{solver_class.__name__}' solver might lead to high " @@ -838,6 +1529,7 @@ def test_performance_warning_on_solver(solver_class): def test_bad_solver(): + """Test bad solver.""" mesh = discretize.TensorMesh([2, 2, 2]) msg = re.escape("BasePDESimulation.solver must be a class") with pytest.raises(TypeError, match=msg): @@ -849,11 +1541,29 @@ def test_bad_solver(): def test_mesh_required(): + """Test mesh required.""" with pytest.raises(TypeError): BasePDESimulation() def test_bad_mesh(): + """Test bad mesh.""" with pytest.raises(TypeError): # should error on anything besides a discretize.base.BaseMesh BasePDESimulation(np.array([1, 2, 3])) + + +def test_unstructured_mesh(): + """Test unstructured mesh in hierarchical simulations.""" + rng = np.random.default_rng(42) + mesh = discretize.SimplexMesh(rng.standard_normal(size=(4, 3)), np.c_[0, 1, 2, 3]) + sim = BaseHierarchicalElectricalSimulation( + mesh=mesh, + survey=None, + sigma=np.ones(mesh.n_cells), + face_conductance=np.ones(mesh.n_faces), + edge_area_conductance=np.ones(mesh.n_edges), + ) + with pytest.raises(NotImplementedError): + # should error on anything besides a discretize.base.BaseRegularMesh + sim.MeSigmaI diff --git a/tests/base/test_directives.py b/tests/base/test_directives.py index 387f74d6c3..f6059fb2a0 100644 --- a/tests/base/test_directives.py +++ b/tests/base/test_directives.py @@ -841,13 +841,10 @@ def test_time_iter_no_opt(self): time_name = directive._time_file_name.name assert directive._time_iter_file_name.name == time_name + "_###" - def test_deprecated_fileName(self): + def test_removed_fileName(self): directive = DummySaveEveryIteration(name="dummy") - - with pytest.warns(FutureWarning, match=r"'fileName' has been deprecated .*"): - f_name = directive.fileName - - assert f_name == "dummy" + with pytest.raises(AttributeError, match=r"'fileName' has been removed.*"): + directive.fileName class TestSaveModelEveryIteration: @@ -1167,11 +1164,11 @@ def test_end_iter(self, tmp_path, on_disk): files = list(directory.iterdir()) assert len(files) == len(directive.outDict) - def test_deprecated(self): - with pytest.warns(FutureWarning, match=".*saveOnDisk has been deprecated.*"): - directive = directives.SaveOutputDictEveryIteration(saveOnDisk=True) - - assert directive.on_disk + def test_removed(self): + with pytest.raises( + NotImplementedError, match=".*saveOnDisk has been removed.*" + ): + directives.SaveOutputDictEveryIteration(saveOnDisk=True) @pytest.mark.parametrize("on_disk", [True, False], ids=["on_disk", "not_on_disk"]) def test_file_abs_path_optional(self, on_disk): diff --git a/tests/base/test_directives_deprecations.py b/tests/base/test_directives_removals.py similarity index 57% rename from tests/base/test_directives_deprecations.py rename to tests/base/test_directives_removals.py index 0c930b6b1d..266cdbc372 100644 --- a/tests/base/test_directives_deprecations.py +++ b/tests/base/test_directives_removals.py @@ -5,14 +5,14 @@ import pytest import importlib -REGEX = r"The `simpeg\.directives\.[a-z_]+` submodule has been deprecated, " +REGEX = r"No module named 'simpeg\.directives\.[a-z_]+'" DEPRECATED_SUBMODULES = ("directives", "pgi_directives", "sim_directives") @pytest.mark.parametrize("submodule", DEPRECATED_SUBMODULES) -def test_deprecations(submodule): +def test_removals(submodule): """ - Test FutureWarning when trying to import the deprecated modules. + Test if error is raised when trying to import the removed modules. """ - with pytest.warns(FutureWarning, match=REGEX): + with pytest.raises(ModuleNotFoundError, match=REGEX): importlib.import_module(f"simpeg.directives.{submodule}") diff --git a/tests/base/test_maps.py b/tests/base/test_maps.py index 564a1b24df..9850b78a02 100644 --- a/tests/base/test_maps.py +++ b/tests/base/test_maps.py @@ -1,3 +1,5 @@ +"""Tests for mapping objects.""" + from copy import deepcopy import numpy as np import unittest @@ -6,7 +8,7 @@ import scipy.sparse as sp from simpeg import maps, models, utils -from discretize.utils import mesh_builder_xyz, refine_tree_xyz, active_from_xyz +from discretize.utils import mesh_builder_xyz, active_from_xyz import inspect from simpeg.maps._parametric import ( @@ -34,6 +36,8 @@ "ActiveCells", "EffectiveSusceptibilityMap", "InjectActiveCells", + "InjectActiveFaces", + "InjectActiveEdges", "LogMap", "LinearMap", "ReciprocalMap", @@ -62,6 +66,8 @@ "ActiveCells", "EffectiveSusceptibilityMap", "InjectActiveCells", + "InjectActiveFaces", + "InjectActiveEdges", "LogMap", "LinearMap", "ReciprocalMap", @@ -88,6 +94,7 @@ def test_IdentityMap_init(): + """Test for IdentityMap.""" m = maps.IdentityMap() assert m.nP == "*" @@ -108,8 +115,108 @@ def test_IdentityMap_init(): maps.IdentityMap(nP="x") +def test_combomap_shape_propagation(): + # A map created without a fixed nP has shape ('*', '*') and should + # pick up a concrete dimension from a neighboring mapping. + free_map = maps.ExpMap() + fixed_map = maps.Projection(1, np.zeros(5, dtype=int)) + + combo = maps.ComboMap([free_map, fixed_map]) + assert combo.shape == (5, 1) + assert combo.nP == 1 + + # propagation should cascade through several free maps chained together + combo = maps.ComboMap([maps.ExpMap(), maps.ExpMap(), fixed_map]) + assert combo.shape == (5, 1) + + # a chain made entirely of free maps stays unresolved + combo = maps.ComboMap([maps.ExpMap(), maps.ExpMap()]) + assert combo.shape == ("*", "*") + assert combo.nP == "*" + + # nesting an already-resolved ComboMap inside another should not lose + # the resolved dimension + inner = maps.ComboMap([maps.ExpMap(), fixed_map]) + outer = maps.ComboMap([maps.ExpMap(), inner]) + assert outer.shape == (5, 1) + + # genuine mismatches between fixed dimensions must still raise, even + # when a free map sits between them + with pytest.raises(ValueError): + maps.ComboMap( + [maps.Projection(3, np.zeros(2, dtype=int)), maps.ExpMap(), fixed_map] + ) + + +def test_combomap_shape_is_cached(): + fixed_map = maps.Projection(1, np.zeros(5, dtype=int)) + combo = maps.ComboMap([maps.ExpMap(), fixed_map]) + assert combo.shape == (5, 1) + + # reassigning .maps must recompute (and re-cache) the shape + combo.maps = [maps.IdentityMap(nP=3)] + assert combo.shape == (3, 3) + + # .maps is a tuple, so it can't be mutated in place in a way that + # would make the cached shape stale; reassignment is required instead + assert isinstance(combo.maps, tuple) + with pytest.raises(AttributeError): + combo.maps.append(maps.ExpMap()) + + # mutating the original list passed in does not affect the stored maps + original = [maps.ExpMap(), fixed_map] + combo = maps.ComboMap(original) + original.append(maps.IdentityMap(nP=99)) + assert combo.shape == (5, 1) + assert len(combo.maps) == 2 + + +def test_combomap_maps_validation(): + with pytest.raises(ValueError): + maps.ComboMap([]) + + with pytest.raises(TypeError): + maps.ComboMap([maps.ExpMap(), "not a map"]) + + with pytest.raises(ValueError): + maps.ComboMap([maps.IdentityMap(nP=3), maps.IdentityMap(nP=5)]) + + # a single mapping (not wrapped in a list) is also accepted + combo = maps.ComboMap(maps.ExpMap(nP=4)) + assert combo.shape == (4, 4) + + +def test_summap_shape_propagation(): + summap = maps.SumMap([maps.ExpMap(), maps.IdentityMap(nP=7)]) + assert summap.shape == (7, 7) + assert summap.nP == 7 + + summap = maps.SumMap([maps.ExpMap(), maps.ExpMap()]) + assert summap.shape == ("*", "*") + assert summap.nP == "*" + + # .maps is an immutable tuple, decoupled from the list passed in + assert isinstance(summap.maps, tuple) + original = [maps.ExpMap(), maps.IdentityMap(nP=7)] + summap = maps.SumMap(original) + original.append(maps.IdentityMap(nP=99)) + assert summap.shape == (7, 7) + assert len(summap.maps) == 2 + + +def test_summap_maps_validation(): + with pytest.raises(ValueError): + maps.SumMap([]) + + with pytest.raises(ValueError): + maps.SumMap([maps.IdentityMap(nP=3), maps.IdentityMap(nP=5)]) + + class MapTests(unittest.TestCase): + """Tests for mappings.""" + def setUp(self): + """Set up function.""" maps2test2D = [M for M in dir(maps) if M not in MAPS_TO_EXCLUDE_2D] maps2test3D = [M for M in dir(maps) if M not in MAPS_TO_EXCLUDE_3D] @@ -138,22 +245,27 @@ def setUp(self): self.meshCyl = discretize.CylindricalMesh([10.0, 1.0, 10.0], x0="00C") def test_transforms2D(self): + """Test transform for 2D.""" for M in self.maps2test2D: self.assertTrue(M(self.mesh2).test(random_seed=42)) def test_transforms2Dvec(self): + """Test transform for 2D vector.""" for M in self.maps2test2D: self.assertTrue(M(self.mesh2).test(random_seed=42)) def test_transforms3D(self): + """Test transfom 3D.""" for M in self.maps2test3D: self.assertTrue(M(self.mesh3).test(random_seed=42)) def test_transforms3Dvec(self): + """Test transform for 3D vector.""" for M in self.maps2test3D: self.assertTrue(M(self.mesh3).test(random_seed=42)) def test_invtransforms2D(self): + """Test for inverse transform in 2D.""" for M in self.maps2test2D: print("Testing Inverse {0}".format(str(M.__name__))) mapping = M(self.mesh2) @@ -172,6 +284,7 @@ def test_invtransforms2D(self): pass def test_invtransforms3D(self): + """Test for inverse transform in 3D.""" for M in self.maps2test3D: print("Testing Inverse {0}".format(str(M.__name__))) @@ -192,11 +305,13 @@ def test_invtransforms3D(self): pass def test_ParametricCasingAndLayer(self): + """Test parametric casing with layer.""" mapping = maps.ParametricCasingAndLayer(self.meshCyl) m = np.r_[-2.0, 1.0, 6.0, 2.0, -0.1, 0.2, 0.5, 0.2, -0.2, 0.2] self.assertTrue(mapping.test(m=m, random_seed=42)) def test_ParametricBlock2D(self): + """Test parametric 2D block map.""" mesh = discretize.TensorMesh([np.ones(30), np.ones(20)], x0=np.array([-15, -5])) mapping = maps.ParametricBlock(mesh) # val_background,val_block, block_x0, block_dx, block_y0, block_dy @@ -204,7 +319,7 @@ def test_ParametricBlock2D(self): self.assertTrue(mapping.test(m=m, random_seed=42)) def test_transforms_logMap_reciprocalMap(self): - + """Test transform log-map reciprocal map.""" mapping = maps.LogMap(self.mesh2) self.assertTrue(mapping.test(random_seed=42)) mapping = maps.LogMap(self.mesh3) @@ -216,18 +331,22 @@ def test_transforms_logMap_reciprocalMap(self): self.assertTrue(mapping.test(random_seed=42)) def test_EffectiveSusceptibilityMap(self): + """Test effective susceptibility map.""" mapping = maps.EffectiveSusceptibilityMap(50000.0, mesh=self.mesh3) self.assertTrue(mapping.test(random_seed=42)) def test_Mesh2MeshMap(self): + """Test mesh to mesh map for scalar.""" mapping = maps.Mesh2Mesh([self.mesh22, self.mesh2]) self.assertTrue(mapping.test(random_seed=42)) def test_Mesh2MeshMapVec(self): + """Test Mesh2Mesh mapping for vector.""" mapping = maps.Mesh2Mesh([self.mesh22, self.mesh2]) self.assertTrue(mapping.test(random_seed=42)) def test_mapMultiplication(self): + """Test map multiplication.""" M = discretize.TensorMesh([2, 3]) expMap = maps.ExpMap(M) vertMap = maps.SurjectVertical1D(M) @@ -259,6 +378,7 @@ def test_mapMultiplication(self): self.assertRaises(ValueError, lambda: combo * np.ones((100, 5))) def test_activeCells(self): + """Test active cells.""" M = discretize.TensorMesh([2, 4], "0C") for actMap in [ maps.InjectActiveCells(M, M.cell_centers_y <= 0, 10, nC=M.shape_cells[1]), @@ -274,6 +394,7 @@ def test_activeCells(self): self.assertLess((mod.transformDeriv - combo.deriv(m)).toarray().sum(), TOL) def test_tripleMultiply(self): + """Test triple multiply mapping.""" M = discretize.TensorMesh([2, 4], "0C") expMap = maps.ExpMap(M) vertMap = maps.SurjectVertical1D(M) @@ -303,6 +424,7 @@ def test_tripleMultiply(self): self.assertRaises(ValueError, lambda: actMap * vertMap * expMap) def test_map2Dto3D_x(self): + """Test Surject2Dto3D x.""" M2 = discretize.TensorMesh([2, 4]) M3 = discretize.TensorMesh([3, 2, 4]) m = np.random.rand(int(M2.nC)) @@ -318,6 +440,7 @@ def test_map2Dto3D_x(self): ) def test_map2Dto3D_y(self): + """Test Surject2Dto3D.""" M2 = discretize.TensorMesh([3, 4]) M3 = discretize.TensorMesh([3, 2, 4]) m = np.random.rand(M2.nC) @@ -333,6 +456,7 @@ def test_map2Dto3D_y(self): ) def test_map2Dto3D_z(self): + """Test map 2D to 3D z.""" M2 = discretize.TensorMesh([3, 2]) M3 = discretize.TensorMesh([3, 2, 4]) m = np.random.rand(M2.nC) @@ -348,6 +472,7 @@ def test_map2Dto3D_z(self): ) def test_ParametricPolyMap(self): + """Test parametric poly map.""" M2 = discretize.TensorMesh([np.ones(10), np.ones(10)], "CN") mParamPoly = maps.ParametricPolyMap(M2, 2, logSigma=True, normal="Y") self.assertTrue( @@ -355,12 +480,14 @@ def test_ParametricPolyMap(self): ) def test_ParametricSplineMap(self): + """Test parametric spline map.""" M2 = discretize.TensorMesh([np.ones(10), np.ones(10)], "CN") x = M2.cell_centers_x mParamSpline = maps.ParametricSplineMap(M2, x, normal="Y", order=1) self.assertTrue(mParamSpline.test(random_seed=42)) def test_parametric_block(self): + """Test parametric block.""" M1 = discretize.TensorMesh([np.ones(10)], "C") block = maps.ParametricBlock(M1) self.assertTrue( @@ -402,6 +529,7 @@ def test_parametric_block(self): ) def test_parametric_ellipsoid(self): + """Test parametric ellipsoid.""" M2 = discretize.TensorMesh([np.ones(10), np.ones(20)], "CC") block = maps.ParametricEllipsoid(M2) self.assertTrue( @@ -434,6 +562,7 @@ def test_parametric_ellipsoid(self): ) def test_sum(self): + """Test sum mapping.""" M2 = discretize.TensorMesh([np.ones(10), np.ones(20)], "CC") block = maps.ParametricEllipsoid(M2) * maps.Projection( 7, np.r_[1, 2, 3, 4, 5, 6] @@ -459,6 +588,7 @@ def test_sum(self): self.assertTrue(summap1.test(m=m0, random_seed=42)) def test_surject_units(self): + """Test surjection units.""" M2 = discretize.TensorMesh([np.ones(10), np.ones(20)], "CC") unit1 = M2.gridCC[:, 0] < 0 unit2 = M2.gridCC[:, 0] >= 0 @@ -473,6 +603,7 @@ def test_surject_units(self): self.assertTrue(surject_units.test(m=m0, random_seed=42)) def test_Projection(self): + """Test projection.""" nP = 10 m = np.arange(nP) self.assertTrue(np.all(maps.Projection(nP, slice(5)) * m == m[:5])) @@ -495,9 +626,7 @@ def test_Projection(self): mapping.test(random_seed=42) def test_Tile(self): - """ - Test for TileMap - """ + """Test for TileMap.""" rxLocs = np.random.randn(3, 3) * 20 h = [5, 5, 5] padDist = np.ones((3, 2)) * 100 @@ -508,14 +637,11 @@ def test_Tile(self): local_mesh = mesh_builder_xyz( rxLocs, h, padding_distance=padDist, mesh_type="tree" ) - local_mesh = refine_tree_xyz( - local_mesh, - rxLocs[ii, :].reshape((1, -1)), - method="radial", - octree_levels=[1], + local_mesh.refine_points( + points=rxLocs[ii, :].reshape((1, -1)), + padding_cells_by_level=[1], finalize=True, ) - local_meshes.append(local_mesh) mesh = mesh_builder_xyz(rxLocs, h, padding_distance=padDist, mesh_type="tree") @@ -548,7 +674,40 @@ def test_Tile(self): self.assertTrue((local_mass - total_mass) / total_mass < 1e-8) + def test_Tile_finer_local(self): + """ + TileMap should volume-average correctly even when the local mesh is + finer than the global mesh in part of the domain. The center-assignment + approach used previously left holes (cells dropped from local_active) + and scaled the surviving cells by the global/local volume ratio. + """ + hx = np.ones(4) + global_mesh = discretize.TreeMesh([hx, hx], diagonal_balance=False) + global_mesh.refine(1, diagonal_balance=False) + local_mesh = discretize.TreeMesh([hx, hx], diagonal_balance=False) + local_mesh.refine(2, diagonal_balance=False) # finer than the global mesh + + active = np.ones(global_mesh.nC, dtype=bool) + tile_map = maps.TileMap(global_mesh, active, local_mesh) + + # no holes: every local cell overlapping the (fully active) global mesh + # must remain active + self.assertEqual(tile_map.local_active.sum(), local_mesh.nC) + + # a constant model must map to the same constant (no scaling blowup) + out = tile_map * np.ones(global_mesh.nC) + np.testing.assert_allclose(out, 1.0) + + # mass is conserved + model = np.random.randn(int(active.sum())) + total_mass = (model * global_mesh.cell_volumes[active]).sum() + local_mass = ( + (tile_map * model) * local_mesh.cell_volumes[tile_map.local_active] + ).sum() + self.assertAlmostEqual((local_mass - total_mass) / total_mass, 0.0, places=8) + def test_logit_errors(self): + """Test logit errors.""" nP = 10 scalar_lower = -2 scalar_upper = 2 @@ -576,7 +735,8 @@ def test_logit_errors(self): nP=10, lower_bound=scalar_lower, upper_bound=bad_vector_upper ) - # test that two upper and lower arrays will not broadcast when not specifying the number of parameters + # test that two upper and lower arrays will not broadcast when not specifying + # the number of parameters with pytest.raises( ValueError, match="Upper bound does not broadcast to the lower bound.*" ): @@ -595,6 +755,7 @@ def test_logit_errors(self): def test_logit_limits(): + """Test logit limits.""" logit_map = maps.LogisticSigmoidMap(lower_bound=-1, upper_bound=2) assert logit_map * np.r_[0] == np.r_[0.5] @@ -609,7 +770,10 @@ def test_logit_limits(): class TestWires(unittest.TestCase): + """Tests for Wires mapping.""" + def test_basic(self): + """Test basic wires mapping.""" mesh = discretize.TensorMesh([10, 10, 10]) wires = maps.Wires( @@ -629,12 +793,16 @@ def test_basic(self): class TestSCEMT(unittest.TestCase): + """Test spherical coordinates.""" + def test_sphericalInclusions(self): + """Test spherical inclusions.""" mesh = discretize.TensorMesh([4, 5, 3]) mapping = maps.SelfConsistentEffectiveMedium(mesh, sigma0=1e-1, sigma1=1.0) mapping.test(num=3, random_seed=42) def test_spheroidalInclusions(self): + """Test spheroidal inclusions.""" mesh = discretize.TensorMesh([4, 3, 2]) mapping = maps.SelfConsistentEffectiveMedium( mesh, sigma0=1e-1, sigma1=1.0, alpha0=0.8, alpha1=0.9, rel_tol=1e-8 @@ -656,6 +824,7 @@ def test_spheroidalInclusions(self): ], ) def test_LinearMap(A, b): + """Test LinearMap.""" map1 = maps.LinearMap(A, b) x = np.random.rand(map1.nP) y1 = A @ x @@ -679,6 +848,7 @@ def test_LinearMap(A, b): ], ) def test_LinearMapDerivs(A, b): + """Test LinearMapDerivs.""" mapping = maps.LinearMap(A, b) # check passing v=None m = np.random.rand(mapping.nP) @@ -690,6 +860,7 @@ def test_LinearMapDerivs(A, b): def test_LinearMap_errors(): + """Test LinearMap errors.""" # object with no matmul operator with pytest.raises(TypeError): maps.LinearMap("No Matmul") @@ -711,6 +882,7 @@ def __matmul__(self, other): def test_linearity(): + """Test linearity.""" mesh1 = discretize.TensorMesh([3]) mesh2 = discretize.TensorMesh([3, 4]) mesh3 = discretize.TensorMesh([3, 4, 5]) @@ -735,6 +907,14 @@ def test_linearity(): mesh3, mesh3.cell_centers[:, -1] < 0.75, ), + maps.InjectActiveFaces( + mesh3, + mesh3.faces[:, -1] < 0.75, + ), + maps.InjectActiveEdges( + mesh3, + mesh3.edges[:, -1] < 0.75, + ), maps.TileMap( mesh_tree, mesh_tree.cell_centers[:, -1] < 0.75, @@ -784,6 +964,7 @@ def active_cells(self, mesh): return active_cells def get_message_removed_error(self, old_name, new_name, version="v0.24.0"): + """Get message removed error.""" msg = ( f"'{old_name}' was removed in " f"SimPEG {version}, please use '{new_name}' instead." @@ -795,26 +976,20 @@ class TestParametricPolyMap(RemovedIndActive): """Test removed ``actInd`` in ParametricPolyMap.""" def test_error_argument(self, mesh, active_cells): - """ - Test if error is raised after passing ``actInd`` to the constructor. - """ + """Test if error is raised after passing ``actInd`` to the constructor.""" msg = "Unsupported keyword argument actInd" with pytest.raises(TypeError, match=msg): maps.ParametricPolyMap(mesh, 2, actInd=active_cells) def test_error_accessing_property(self, mesh, active_cells): - """ - Test error when trying to access the ``actInd`` property. - """ + """Test error when trying to access the ``actInd`` property.""" mapping = maps.ParametricPolyMap(mesh, 2, active_cells=active_cells) msg = "actInd has been removed, please use active_cells" with pytest.raises(NotImplementedError, match=msg): mapping.actInd def test_error_setter(self, mesh, active_cells): - """ - Test error when trying to set the ``actInd`` property. - """ + """Test error when trying to set the ``actInd`` property.""" mapping = maps.ParametricPolyMap(mesh, 2, active_cells=active_cells) msg = "actInd has been removed, please use active_cells" with pytest.raises(NotImplementedError, match=msg): @@ -826,29 +1001,24 @@ class TestMesh2Mesh(RemovedIndActive): @pytest.fixture def meshes(self, mesh): + """Test mesh.""" return [mesh, deepcopy(mesh)] def test_error_argument(self, meshes, active_cells): - """ - Test if error is raised after passing ``indActive`` to the constructor. - """ + """Test if error is raised after passing ``indActive`` to the constructor.""" msg = self.get_message_removed_error("indActive", "active_cells") with pytest.raises(TypeError, match=msg): maps.Mesh2Mesh(meshes, indActive=active_cells) def test_error_accessing_property(self, meshes, active_cells): - """ - Test error when trying to access the ``indActive`` property. - """ + """Test error when trying to access the ``indActive`` property.""" mapping = maps.Mesh2Mesh(meshes, active_cells=active_cells) msg = "indActive has been removed, please use active_cells" with pytest.raises(NotImplementedError, match=msg): mapping.indActive def test_warning_setter(self, meshes, active_cells): - """ - Test warning when trying to set the ``indActive`` property. - """ + """Test warning when trying to set the ``indActive`` property.""" mapping = maps.Mesh2Mesh(meshes, active_cells=active_cells) msg = "indActive has been removed, please use active_cells" with pytest.raises(NotImplementedError, match=msg): @@ -859,26 +1029,20 @@ class TestInjectActiveCells(RemovedIndActive): """Test removed ``indActive`` and ``valInactive`` in ``InjectActiveCells``.""" def test_indactive_error_argument(self, mesh, active_cells): - """ - Test if error is raised after passing ``indActive`` to the constructor. - """ + """Test if error is raised after passing ``indActive`` to the constructor.""" msg = self.get_message_removed_error("indActive", "active_cells") with pytest.raises(TypeError, match=msg): maps.InjectActiveCells(mesh, indActive=active_cells) def test_indactive_error_accessing_property(self, mesh, active_cells): - """ - Test error when trying to access the ``indActive`` property. - """ + """Test error when trying to access the ``indActive`` property.""" mapping = maps.InjectActiveCells(mesh, active_cells=active_cells) msg = "indActive has been removed, please use active_cells" with pytest.raises(NotImplementedError, match=msg): mapping.indActive def test_indactive_error_setter(self, mesh, active_cells): - """ - Test error when trying to set the ``indActive`` property. - """ + """Test error when trying to set the ``indActive`` property.""" mapping = maps.InjectActiveCells(mesh, active_cells=active_cells) msg = "indActive has been removed, please use active_cells" with pytest.raises(NotImplementedError, match=msg): @@ -886,9 +1050,7 @@ def test_indactive_error_setter(self, mesh, active_cells): @pytest.mark.parametrize("value_inactive", (3.14, np.array([1]))) def test_valinactive_error_argument(self, mesh, active_cells, value_inactive): - """ - Test if error is raised after passing ``valInactive`` to the constructor. - """ + """Test if error is raised after passing ``valInactive`` to the constructor.""" msg = self.get_message_removed_error("valInactive", "value_inactive") with pytest.raises(TypeError, match=msg): maps.InjectActiveCells( @@ -896,9 +1058,7 @@ def test_valinactive_error_argument(self, mesh, active_cells, value_inactive): ) def test_valinactive_error_accessing_property(self, mesh, active_cells): - """ - Test error when trying to access the ``valInactive`` property. - """ + """Test error when trying to access the ``valInactive`` property.""" mapping = maps.InjectActiveCells( mesh, active_cells=active_cells, value_inactive=3.14 ) @@ -907,9 +1067,7 @@ def test_valinactive_error_accessing_property(self, mesh, active_cells): mapping.valInactive def test_valinactive_error_setter(self, mesh, active_cells): - """ - Test error when trying to set the ``valInactive`` property. - """ + """Test error when trying to set the ``valInactive`` property.""" mapping = maps.InjectActiveCells( mesh, active_cells=active_cells, value_inactive=3.14 ) @@ -925,18 +1083,14 @@ class TestParametric(RemovedIndActive): @pytest.mark.parametrize("map_class", CLASSES) def test_indactive_error_argument(self, mesh, active_cells, map_class): - """ - Test if error is raised after passing ``indActive`` to the constructor. - """ + """Test if error is raised after passing ``indActive`` to the constructor.""" msg = self.get_message_removed_error("indActive", "active_cells") with pytest.raises(TypeError, match=msg): map_class(mesh, indActive=active_cells) @pytest.mark.parametrize("map_class", CLASSES) def test_indactive_error_accessing_property(self, mesh, active_cells, map_class): - """ - Test error when trying to access the ``indActive`` property. - """ + """Test error when trying to access the ``indActive`` property.""" mapping = map_class(mesh, active_cells=active_cells) msg = "indActive has been removed, please use active_cells" with pytest.raises(NotImplementedError, match=msg): @@ -944,9 +1098,7 @@ def test_indactive_error_accessing_property(self, mesh, active_cells, map_class) @pytest.mark.parametrize("map_class", CLASSES) def test_indactive_error_setter(self, mesh, active_cells, map_class): - """ - Test error when trying to set the ``indActive`` property. - """ + """Test error when trying to set the ``indActive`` property.""" mapping = map_class(mesh, active_cells=active_cells) msg = "indActive has been removed, please use active_cells" with pytest.raises(NotImplementedError, match=msg): @@ -957,7 +1109,6 @@ class TestParametricDeriv: """ Test the ``deriv`` method of parametric maps. - Test if ``map.deriv(m) @ v`` is equivalent to ``map.deriv(m, v=v)``. """ @@ -989,9 +1140,7 @@ def cyl_mesh(self): ], ) def test_deriv_mesh_3d(self, mesh_3d, map_class): - """ - Test maps on a 3d mesh. - """ + """Test maps on a 3d mesh.""" kwargs = {} if map_class is maps.ParametricPolyMap: kwargs["order"] = [1, 1] @@ -1004,9 +1153,7 @@ def test_deriv_mesh_3d(self, mesh_3d, map_class): np.testing.assert_allclose(derivative @ v, mapping.deriv(model, v=v)) def test_deriv_mesh_2d(self, mesh_2d): - """ - Test maps on a 2d mesh. - """ + """Test maps on a 2d mesh.""" mapping = maps.ParametricCircleMap(mesh_2d) model_size = mapping.shape[1] rng = np.random.default_rng(seed=48) @@ -1016,9 +1163,7 @@ def test_deriv_mesh_2d(self, mesh_2d): np.testing.assert_allclose(derivative @ v, mapping.deriv(model, v=v)) def test_deriv_cyl_mesh(self, cyl_mesh): - """ - Test maps on a cylindrical mesh. - """ + """Test maps on a cylindrical mesh.""" mapping = maps.ParametricCasingAndLayer(cyl_mesh) model_size = mapping.shape[1] rng = np.random.default_rng(seed=48) @@ -1029,9 +1174,7 @@ def test_deriv_cyl_mesh(self, cyl_mesh): def test_deriv_SelfConsistentEffectiveMedium(): - """ - Test deriv method of ``SelfConsistentEffectiveMedium``. - """ + """Test deriv method of ``SelfConsistentEffectiveMedium``.""" h = 10 mesh = discretize.TensorMesh([h, h, h], "CCN") mapping = maps.SelfConsistentEffectiveMedium(mesh, sigma0=1, sigma1=2) @@ -1044,16 +1187,16 @@ def test_deriv_SelfConsistentEffectiveMedium(): class TestComplexMapDerivative: - """ - Test deriv method of ComplexMap. - """ + """Test deriv method of ComplexMap.""" @pytest.fixture def mesh(self): + """Return mesh.""" return discretize.TensorMesh([4]) @pytest.fixture def active_cells(self, mesh): + """Return active cells.""" return mesh.cell_centers < 0.5 def test_deriv(self, mesh, active_cells): @@ -1089,9 +1232,7 @@ def test_deriv_with_vector(self, mesh, active_cells): np.testing.assert_allclose(expected, derivative) def test_deriv_within_combo(self, mesh, active_cells): - """ - Test the deriv method when being called within a ``ComboMap``. - """ + """Test the deriv method when being called within a ``ComboMap``.""" n_cells = mesh.n_cells n_active_cells = np.sum(active_cells) inject_map = maps.InjectActiveCells( @@ -1106,10 +1247,7 @@ def test_deriv_within_combo(self, mesh, active_cells): np.testing.assert_allclose(expected, derivative @ m) def test_deriv_within_combo_with_vector(self, mesh, active_cells): - """ - Test the deriv method when being called within a ``ComboMap`` and ``v`` as an - array. - """ + """Test the deriv method when called with ``ComboMap`` and array ``v``.""" n_cells = mesh.n_cells n_active_cells = np.sum(active_cells) inject_map = maps.InjectActiveCells( diff --git a/tests/base/test_maps_utils.py b/tests/base/test_maps_utils.py new file mode 100644 index 0000000000..26a48aeab4 --- /dev/null +++ b/tests/base/test_maps_utils.py @@ -0,0 +1,74 @@ +""" +Test private map utility functions. +""" + +import pytest +import numpy as np + +from simpeg.maps._utils import columns_dot_vector + + +class TestColumnsDotVector: + """Test the ``columns_dot_vector`` function.""" + + n_cols = 5 + n_rows = 3 + + @pytest.fixture + def vector(self): + """Sample vector for following tests.""" + rng = np.random.default_rng(seed=4141) + return rng.uniform(low=-1.0, high=1.0, size=self.n_cols) + + @pytest.fixture(params=["all-1d", "some-2d"]) + def columns(self, request): + """Sample columns for following tests.""" + rng = np.random.default_rng(seed=42) + match request.param: + case "all-1d": + columns = [ + rng.uniform(low=-1.0, high=1.0, size=self.n_rows) + for _ in range(self.n_cols) + ] + case "some-2d": + columns = [ + rng.uniform(low=-1.0, high=1.0, size=self.n_rows), + rng.uniform(low=-1.0, high=1.0, size=(self.n_rows, 3)), + rng.uniform(low=-1.0, high=1.0, size=self.n_rows), + ] + case _: + raise ValueError() + return columns + + def test_error_empty_columns(self, vector): + with pytest.raises(ValueError, match="Invalid empty 'columns' argument"): + columns_dot_vector([], vector) + + def test_error_invalid_dimension(self, vector): + columns = [ + np.array([1.0, 2.0, 3.0]), + np.array([[[1.0, 2.0, 4.0]]]), + ] + with pytest.raises(ValueError, match="dimensions"): + columns_dot_vector(columns, vector) + + def test_error_invalid_number_of_columns(self, vector): + # Create a list with only 2 columns + columns = [ + np.array([1.0, 2.0, 3.0]), + np.array([4.0, 5.0, 6.0]), + ] + with pytest.raises(ValueError, match="not equal to the size of the vector"): + columns_dot_vector(columns, vector) + + @pytest.mark.parametrize("columns_type", ["list", "generator"]) + def test_dot_product(self, columns, vector, columns_type): + """ + Compare the dot product against the expected result using the full matrix. + """ + true_matrix = np.c_[*columns] + if columns_type == "generator": + columns = (c for c in columns) + np.testing.assert_allclose( + columns_dot_vector(columns, vector), true_matrix @ vector + ) diff --git a/tests/base/test_optimizers.py b/tests/base/test_optimizers.py index f8c80bb3c8..f5d57850c1 100644 --- a/tests/base/test_optimizers.py +++ b/tests/base/test_optimizers.py @@ -246,17 +246,12 @@ def test_kwargs_only(self): ): optimization.InexactCG(1e-3) - def test_deprecated(self): - with pytest.warns(FutureWarning, match=".*tolCG has been deprecated.*"): - cg_pars = optimization.InexactCG(tolCG=1e-3) - assert cg_pars.cg_atol == 0.0 - assert cg_pars.cg_rtol == 1e-3 - - with pytest.warns(FutureWarning, match=".*maxIterCG has been deprecated.*"): - cg_pars = optimization.InexactCG(maxIterCG=3) - assert cg_pars.cg_atol == 0.0 - assert cg_pars.cg_rtol == 1e-1 - assert cg_pars.cg_maxiter == 3 + def test_removed(self): + """Test error after removed deprecated properties.""" + with pytest.raises(TypeError): + optimization.InexactCG(tolCG=1e-3) + with pytest.raises(TypeError): + optimization.InexactCG(maxIterCG=3) class TestProjectedGradient: @@ -289,48 +284,33 @@ def test_kwargs_only(self): optimization.ProjectedGradient(10) @pytest.mark.parametrize("on_init", [True, False], ids=["init", "attribute setter"]) - def test_deprecated_tolCG(self, on_init): - match = ".*tolCG has been deprecated.*cg_rtol.*" + def test_removed_tolCG(self, on_init): + match = ".*tolCG has been removed.*cg_rtol.*" if on_init: - with pytest.warns(FutureWarning, match=match): - opt = optimization.ProjectedGradient(tolCG=1e-3) + with pytest.raises(NotImplementedError, match=match): + optimization.ProjectedGradient(tolCG=1e-3) else: opt = optimization.ProjectedGradient() - with pytest.warns(FutureWarning, match=match): + with pytest.raises(NotImplementedError, match=match): opt.tolCG = 1e-3 - with pytest.warns(FutureWarning, match=match): - assert opt.tolCG == 1e-3 - assert opt.cg_atol == 0.0 - assert opt.cg_rtol == 1e-3 - - # test setting new changes old - opt.cg_rtol = 1e-4 - - with pytest.warns(FutureWarning, match=match): - assert opt.tolCG == 1e-4 + with pytest.raises(NotImplementedError, match=match): + opt.tolCG @pytest.mark.parametrize("on_init", [True, False], ids=["init", "attribute setter"]) - def test_deprecated_maxIterCG(self, on_init): + def test_removed_maxIterCG(self, on_init): - match = ".*maxIterCG has been deprecated.*" + match = ".*maxIterCG has been removed.*" if on_init: - with pytest.warns(FutureWarning, match=match): - opt = optimization.ProjectedGradient(maxIterCG=3) + with pytest.raises(NotImplementedError, match=match): + optimization.ProjectedGradient(maxIterCG=3) else: opt = optimization.ProjectedGradient() - with pytest.warns(FutureWarning, match=match): + with pytest.raises(NotImplementedError, match=match): opt.maxIterCG = 3 - with pytest.warns(FutureWarning, match=match): - assert opt.maxIterCG == 3 - - assert opt.cg_maxiter == 3 - - # test setting new changes old - opt.cg_maxiter = 8 - with pytest.warns(FutureWarning, match=match): - assert opt.maxIterCG == 8 + with pytest.raises(NotImplementedError, match=match): + opt.maxIterCG class TestInexactGaussNewton: @@ -357,48 +337,33 @@ def test_kwargs_only(self): optimization.InexactGaussNewton(10) @pytest.mark.parametrize("on_init", [True, False], ids=["init", "attribute setter"]) - def test_deprecated_tolCG(self, on_init): - match = ".*tolCG has been deprecated.*cg_rtol.*" + def test_removed_tolCG(self, on_init): + match = ".*tolCG has been removed.*cg_rtol.*" if on_init: - with pytest.warns(FutureWarning, match=match): - opt = optimization.InexactGaussNewton(tolCG=1e-3) + with pytest.raises(NotImplementedError, match=match): + optimization.InexactGaussNewton(tolCG=1e-3) else: opt = optimization.InexactGaussNewton() - with pytest.warns(FutureWarning, match=match): + with pytest.raises(NotImplementedError, match=match): opt.tolCG = 1e-3 - with pytest.warns(FutureWarning, match=match): - assert opt.tolCG == 1e-3 - assert opt.cg_atol == 0.0 - assert opt.cg_rtol == 1e-3 - - # test setting new changes old - opt.cg_rtol = 1e-4 - - with pytest.warns(FutureWarning, match=match): - assert opt.tolCG == 1e-4 + with pytest.raises(NotImplementedError, match=match): + opt.tolCG @pytest.mark.parametrize("on_init", [True, False], ids=["init", "attribute setter"]) - def test_deprecated_maxIterCG(self, on_init): + def test_removed_maxIterCG(self, on_init): - match = ".*maxIterCG has been deprecated.*" + match = ".*maxIterCG has been removed.*" if on_init: - with pytest.warns(FutureWarning, match=match): - opt = optimization.InexactGaussNewton(maxIterCG=3) + with pytest.raises(NotImplementedError, match=match): + optimization.InexactGaussNewton(maxIterCG=3) else: opt = optimization.InexactGaussNewton() - with pytest.warns(FutureWarning, match=match): + with pytest.raises(NotImplementedError, match=match): opt.maxIterCG = 3 - with pytest.warns(FutureWarning, match=match): - assert opt.maxIterCG == 3 - - assert opt.cg_maxiter == 3 - - # test setting new changes old - opt.cg_maxiter = 8 - with pytest.warns(FutureWarning, match=match): - assert opt.maxIterCG == 8 + with pytest.raises(NotImplementedError, match=match): + opt.maxIterCG class TestProjectedGNCG: @@ -415,14 +380,11 @@ def test_defaults(self, cg_tol_defaults): opt = optimization.ProjectedGNCG(cg_rtol=1e-4) assert opt.cg_atol == 0.0 assert opt.cg_rtol == 1e-4 - # test the old defaults + # test the new defaults else: - with pytest.warns( - FutureWarning, match="The defaults for ProjectedGNCG will change.*" - ): - opt = optimization.ProjectedGNCG() - assert opt.cg_rtol == 0.0 - assert opt.cg_atol == 1e-3 + opt = optimization.ProjectedGNCG() + assert opt.cg_rtol == 1e-3 + assert opt.cg_atol == 0.0 assert opt.cg_maxiter == 5 assert np.isneginf(opt.lower) assert np.isposinf(opt.upper) @@ -446,60 +408,27 @@ def test_kwargs_only(self): ): optimization.ProjectedGNCG(10) - @pytest.mark.parametrize("on_init", [True, False], ids=["init", "attribute setter"]) - def test_deprecated_tolCG(self, on_init): - if on_init: - with pytest.warns( - FutureWarning, match=".*tolCG has been deprecated.*cg_atol.*" - ): - opt = optimization.ProjectedGNCG(tolCG=1e-5) - else: - opt = optimization.ProjectedGNCG() - with pytest.warns( - FutureWarning, match=".*tolCG has been deprecated.*cg_atol.*" - ): - opt.tolCG = 1e-5 - - with pytest.warns(FutureWarning, match=".*tolCG has been deprecated.*"): - assert opt.tolCG == 1e-5 - - assert opt.cg_atol == 1e-5 - assert opt.cg_rtol == 0.0 - - # test setting new changes old - opt.cg_atol = 1e-4 - - with pytest.warns(FutureWarning, match=".*tolCG has been deprecated.*"): - assert opt.tolCG == 1e-4 - @pytest.mark.parametrize("on_init", [True, False], ids=["init", "attribute setter"]) @pytest.mark.parametrize( - ("old_name", "new_name", "val1", "val2"), + ("old_name", "new_name", "value"), [ - ("maxIterCG", "cg_maxiter", 3, 8), - ("stepActiveSet", "step_active_set", True, False), - ("stepOffBoundsFact", "active_set_grad_scale", 1.2, 1.4), + ("tolCG", "cg_atol", 1e-5), + ("maxIterCG", "cg_maxiter", 3), + ("stepActiveSet", "step_active_set", True), + ("stepOffBoundsFact", "active_set_grad_scale", 1.2), ], - ids=["maxIterCG", "stepActiveSet", "stepOffBoundsFact"], + ids=["tolCG", "maxIterCG", "stepActiveSet", "stepOffBoundsFact"], ) - def test_deprecated_maxIterCG(self, on_init, old_name, new_name, val1, val2): + def test_removed_properties(self, on_init, old_name, new_name, value): - match = f".*{old_name} has been deprecated.*" + match = f".*{old_name} has been removed.*{new_name}.*" if on_init: - with pytest.warns(FutureWarning, match=match): - opt = optimization.ProjectedGNCG(**{old_name: val1}) + with pytest.raises(NotImplementedError, match=match): + opt = optimization.ProjectedGNCG(**{old_name: value}) else: opt = optimization.ProjectedGNCG() - with pytest.warns(FutureWarning, match=match): - setattr(opt, old_name, val1) - opt.maxIterCG = 3 - - with pytest.warns(FutureWarning, match=match): - assert getattr(opt, old_name) == val1 - - assert getattr(opt, old_name) == val1 - - setattr(opt, new_name, val2) + with pytest.raises(NotImplementedError, match=match): + setattr(opt, old_name, value) - with pytest.warns(FutureWarning, match=match): - assert getattr(opt, old_name) == val2 + with pytest.raises(NotImplementedError, match=match): + getattr(opt, old_name) diff --git a/tests/base/test_utils.py b/tests/base/test_utils.py index 1fa7ad6d39..cba821b097 100644 --- a/tests/base/test_utils.py +++ b/tests/base/test_utils.py @@ -4,6 +4,7 @@ import scipy.sparse as sp import os import shutil +import urllib.request from simpeg.utils import ( sdiag, sub2ind, @@ -26,7 +27,6 @@ ) import discretize - TOL = 1e-8 np.random.seed(25) @@ -320,6 +320,38 @@ def test_downloads(self): shutil.rmtree(os.path.expanduser("./test_url")) +class TestDownloadVerbose: + """ + Tests for the verbose argument of the download function + """ + + URL = "https://example.com/simpeg/data.txt" + + @pytest.fixture + def mock_urlretrieve(self, monkeypatch): + def urlretrieve(url, filename): + with open(filename, "w") as fid: + fid.write("data") + + monkeypatch.setattr(urllib.request, "urlretrieve", urlretrieve) + + def test_silent(self, tmp_path, capsys, mock_urlretrieve): + download(self.URL, folder=str(tmp_path), verbose=False) + assert capsys.readouterr().out == "" + + def test_silent_on_existing_file(self, tmp_path, capsys, mock_urlretrieve): + download(self.URL, folder=str(tmp_path), overwrite=True, verbose=False) + download(self.URL, folder=str(tmp_path), overwrite=True, verbose=False) + assert capsys.readouterr().out == "" + + def test_verbose(self, tmp_path, capsys, mock_urlretrieve): + file_name = download(self.URL, folder=str(tmp_path), verbose=True) + output = capsys.readouterr().out + assert self.URL in output + assert file_name in output + assert "Download completed!" in output + + class TestCoterminalAngle: """ Tests for the coterminal function diff --git a/tests/dask/test_mag_MVI_Octree.py b/tests/dask/test_mag_MVI_Octree.py index 5516589dd5..97f9e9e946 100644 --- a/tests/dask/test_mag_MVI_Octree.py +++ b/tests/dask/test_mag_MVI_Octree.py @@ -12,7 +12,7 @@ ) -from discretize.utils import mesh_builder_xyz, refine_tree_xyz, active_from_xyz +from discretize.utils import mesh_builder_xyz, active_from_xyz import numpy as np from simpeg.potential_fields import magnetics as mag import shutil @@ -62,9 +62,7 @@ def setUp(self): mesh = mesh_builder_xyz( xyzLoc, h, padding_distance=padDist, depth_core=100, mesh_type="tree" ) - mesh = refine_tree_xyz( - mesh, topo, method="surface", octree_levels=[4, 4], finalize=True - ) + mesh.refine_surface(topo, padding_cells_by_level=[4, 4], finalize=True) self.mesh = mesh # Define an active cells from topo actv = active_from_xyz(mesh, topo) diff --git a/tests/dask/test_mag_inversion_linear_Octree.py b/tests/dask/test_mag_inversion_linear_Octree.py index e01da350cd..165b19a22a 100644 --- a/tests/dask/test_mag_inversion_linear_Octree.py +++ b/tests/dask/test_mag_inversion_linear_Octree.py @@ -73,14 +73,7 @@ def setUp(self): mesh_type="TREE", ) - self.mesh = mesh_utils.refine_tree_xyz( - self.mesh, - topo, - method="surface", - octree_levels=nCpad, - octree_levels_padding=nCpad, - finalize=True, - ) + self.mesh.refine_surface(topo, padding_cells_by_level=nCpad, finalize=True) # Define an active cells from topo actv = active_from_xyz(self.mesh, topo) diff --git a/tests/dask/test_mag_nonLinear_Amplitude.py b/tests/dask/test_mag_nonLinear_Amplitude.py index 8da94479b1..ca7325b276 100644 --- a/tests/dask/test_mag_nonLinear_Amplitude.py +++ b/tests/dask/test_mag_nonLinear_Amplitude.py @@ -14,7 +14,7 @@ from simpeg.potential_fields import magnetics from simpeg import utils from simpeg.utils import mkvc -from discretize.utils import mesh_builder_xyz, refine_tree_xyz, active_from_xyz +from discretize.utils import mesh_builder_xyz, active_from_xyz import unittest import shutil @@ -65,9 +65,7 @@ def setUp(self): mesh = mesh_builder_xyz( rxLoc, h, padding_distance=padDist, depth_core=100, mesh_type="tree" ) - mesh = refine_tree_xyz( - mesh, topo, method="surface", octree_levels=[4, 4], finalize=True - ) + mesh.refine_surface(topo, padding_cells_by_level=[4, 4], finalize=True) # Define an active cells from topo actv = active_from_xyz(mesh, topo) diff --git a/tests/em/em1d/test_EM1D_TD_multilayer_ip.py b/tests/em/em1d/test_EM1D_TD_multilayer_ip.py new file mode 100644 index 0000000000..d13ed5e65a --- /dev/null +++ b/tests/em/em1d/test_EM1D_TD_multilayer_ip.py @@ -0,0 +1,214 @@ +""" +Verification example for a multi-layer model with induced polarisation + +This example is based on the synthetic model in +Li et al (2019), A discussion of 2D induced polarization effects in airborne +electromagnetic and inversion with a robust 1D laterally constrained inversion +scheme, Geophysics, vol 84, no 2, doi 10.1190/geo2018-0102.1 + +""" + +import numpy as np +import unittest + +from simpeg import maps +import simpeg.electromagnetics.time_domain as tdem + +# Survey config (Lin et al 2019) +SURVEY_CONFIG = dict( + waveform=dict( + current=np.array((0.0, 1.0, 1.0, 0.0)), # [-] + time=np.array((-10.0e-3, -9.0e-3, 0.0, 5.0e-6)), # [s] + peak_current=100, # [A] + ), + ground=dict( + resistivities=np.array([5000.0, 500.0, 5000.0]), # [Ohm.m] + thicknesses=np.array([20.0, 50.0]), # [m] + eta=np.array([0.0, 350e-3, 0.0]), # [V/V] + tau=np.array([0.0, 1.0e-3, 0.0]), # [s] + c=np.array([0.0, 0.5, 0.0]), # - + ), + tx=dict( + nturns=16, # [-] + elevation=(elevation := 30), # [m] + area=(area := 300), # [m2] + center=(center := np.array((0, 0, elevation))), + radius=(radius := np.sqrt(area / np.pi)), + theta=(theta := np.linspace(0, 2 * np.pi, 200, endpoint=False)), + pts=( + pts := np.vstack( + (radius * np.cos(theta), radius * np.sin(theta), [0.0] * len(theta)) + ) + ), + location=pts.T + center, + ), + rx=dict( + location=center, + orientation="z", + gates=10 ** np.linspace(-2, -5, 31), # time channels [s] + ), +) + + +class EM1D_TD_IP_test(unittest.TestCase): + """Testing surveys consistency of IP in time-domain computations + + - models with/without IPs + - models without IP vs with IP and null chargeabilities + - models with homogeneous/heterogeneous chargeabilities + """ + + @classmethod + def setUpClass(cls): + """Configuring survey and simulations for all test methods""" + # Simpeg objects + cls.survey = dict( + waveform=( + waveform := tdem.sources.PiecewiseLinearWaveform( + times=SURVEY_CONFIG["waveform"]["time"], + currents=SURVEY_CONFIG["waveform"]["current"], + ) + ), + model_mapping=maps.IdentityMap( + nP=len(SURVEY_CONFIG["ground"]["thicknesses"]) + 1 + ), + receiver_list=( + receiver_list := [ + tdem.receivers.PointMagneticFluxTimeDerivative( + SURVEY_CONFIG["rx"]["location"], + SURVEY_CONFIG["rx"]["gates"], + orientation=SURVEY_CONFIG["rx"]["orientation"], + ) + ] + ), + source_list=( + source_list := [ + tdem.sources.LineCurrent( + receiver_list=receiver_list, + location=SURVEY_CONFIG["tx"]["location"], + waveform=waveform, + current=( + SURVEY_CONFIG["waveform"]["peak_current"] + * SURVEY_CONFIG["tx"]["nturns"] + ), + ) + ] + ), + survey=tdem.Survey(source_list), + ) + + # Pelton parameters for all simulations + eta_null = np.zeros(3) + tau_null = np.zeros(3) + c_null = np.zeros(3) + + eta_heter = SURVEY_CONFIG["ground"]["eta"] + tau_heter = SURVEY_CONFIG["ground"]["tau"] + c_heter = SURVEY_CONFIG["ground"]["c"] + + eta_single = SURVEY_CONFIG["ground"]["eta"][1] + tau_single = SURVEY_CONFIG["ground"]["tau"][1] + c_single = SURVEY_CONFIG["ground"]["c"][1] + + eta_hom = np.ones(3) * eta_single + tau_hom = np.ones(3) * tau_single + c_hom = np.ones(3) * c_single + + # When using IP, note that infinite frequency resistivity/conductivity + # is expected while Lin et al. (2019) rely on 0-frequency parameters + cls.resistivities_0 = SURVEY_CONFIG["ground"]["resistivities"] + cls.resistivities_inf_null = cls.resistivities_0 * (1 - eta_null) + cls.resistivities_inf_heter = cls.resistivities_0 * (1 - eta_heter) + cls.resistivities_inf_single = cls.resistivities_0 * (1 - eta_single) + cls.resistivities_inf_hom = cls.resistivities_0 * (1 - eta_hom) + + # Preparing all simulations + cls.simulation_no_ip = tdem.Simulation1DLayered( + survey=cls.survey["survey"], + thicknesses=SURVEY_CONFIG["ground"]["thicknesses"], + rhoMap=cls.survey["model_mapping"], + ) + cls.simulation_null_ip = tdem.Simulation1DLayered( + survey=cls.survey["survey"], + thicknesses=SURVEY_CONFIG["ground"]["thicknesses"], + rhoMap=cls.survey["model_mapping"], + eta=eta_null, + tau=tau_null, + c=c_null, + ) + cls.simulation_heter_ip = tdem.Simulation1DLayered( + survey=cls.survey["survey"], + thicknesses=SURVEY_CONFIG["ground"]["thicknesses"], + rhoMap=cls.survey["model_mapping"], + eta=eta_heter, + tau=tau_heter, + c=c_heter, + ) + cls.simulation_hom_ip = tdem.Simulation1DLayered( + survey=cls.survey["survey"], + thicknesses=SURVEY_CONFIG["ground"]["thicknesses"], + rhoMap=cls.survey["model_mapping"], + eta=eta_hom, + tau=tau_hom, + c=c_hom, + ) + cls.simulation_single_ip = tdem.Simulation1DLayered( + survey=cls.survey["survey"], + thicknesses=SURVEY_CONFIG["ground"]["thicknesses"], + rhoMap=cls.survey["model_mapping"], + eta=SURVEY_CONFIG["ground"]["eta"][1], + tau=SURVEY_CONFIG["ground"]["tau"][1], + c=SURVEY_CONFIG["ground"]["c"][1], + ) + + def test_null_ip(self): + """Consistency of model with null chargeability""" + dbdt_no_ip = np.abs(self.simulation_no_ip.dpred(self.resistivities_0)) + dbdt_null_ip = np.abs( + self.simulation_null_ip.dpred(self.resistivities_inf_null) + ) + self.assertTrue( + np.allclose(dbdt_no_ip, dbdt_null_ip), + "No IP and null chargeabilitiy should return same results", + ) + + def test_ip(self): + """Consistency of models with/without IP""" + dbdt_no_ip = np.abs(self.simulation_no_ip.dpred(self.resistivities_0)) + dbdt_hom_ip = np.abs(self.simulation_hom_ip.dpred(self.resistivities_inf_hom)) + self.assertFalse( + np.allclose(dbdt_no_ip, dbdt_hom_ip), + "Models with and without IP should not return same results", + ) + + def test_hom_ip(self): + """Consistency of models with single / multiple homogeneous chargeabilities""" + dbdt_single_ip = np.abs( + self.simulation_single_ip.dpred(self.resistivities_inf_single) + ) + dbdt_hom_ip = np.abs(self.simulation_hom_ip.dpred(self.resistivities_inf_hom)) + self.assertTrue( + np.allclose(dbdt_single_ip, dbdt_hom_ip), + "Models with single or homogeneous multiple parameters should" + " return same results", + ) + + def test_heter_ip(self): + """Consistency of models with hom/heter-ogeneous chargeabilities""" + dbdt_no_ip = np.abs(self.simulation_no_ip.dpred(self.resistivities_0)) + dbdt_hom_ip = np.abs(self.simulation_hom_ip.dpred(self.resistivities_inf_hom)) + dbdt_heter_ip = np.abs( + self.simulation_heter_ip.dpred(self.resistivities_inf_heter) + ) + self.assertFalse( + np.allclose(dbdt_no_ip, dbdt_heter_ip), + "No IP and heterogeneous chargeabilities results should not match", + ) + self.assertFalse( + np.allclose(dbdt_hom_ip, dbdt_heter_ip), + "Hom/heter-ogeneous chargeabilities results should not match", + ) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/em/em1d/test_bugfix_one_null_dchi.py b/tests/em/em1d/test_bugfix_one_null_dchi.py new file mode 100644 index 0000000000..75427fd242 --- /dev/null +++ b/tests/em/em1d/test_bugfix_one_null_dchi.py @@ -0,0 +1,178 @@ +""" +Test bugfix in EM1D simulation that ignored viscous remanent magnetization effect if at +least one dchi value is null. +""" + +import pytest +import numpy as np +import simpeg +import simpeg.electromagnetics.time_domain as tdem +from simpeg.electromagnetics.base_1d import BaseEM1DSimulation + + +def build_loop(center, radius, size=200): + """ + Build a horizontal circular loop around the center. + + Parameters + ---------- + center : tuple of float + The x, y, z location of the center of the loop. + radius : float + Loop's radius. + size : int, optional + Number of points that will form the loop. + + Returns + ------- + locations : (size, 3) array + Array with the x, y, z coordinates of the loop points. + """ + xc, yc, zc = center + theta = np.linspace(0, 2 * np.pi, size, endpoint=False) + x = xc + radius * np.cos(theta) + y = yc + radius * np.sin(theta) + z = zc + np.zeros_like(theta) + return np.vstack((x, y, z)).T + + +@pytest.fixture +def survey(): + # Define receiver + receiver_location = (0, 0, 30) + time_channels = 10 ** np.linspace(-2, -5, 31) # [s] + receiver = tdem.receivers.PointMagneticFluxTimeDerivative( + receiver_location, time_channels, orientation="z" + ) + + # Define source. + # Define source as a circular loop around the receiver. Use a piecewise linear + # waveform. + area = 300 # [m2] + radius = np.sqrt(area / np.pi) + peak_current = 100 # [A] + n_turns = 16 + waveform_times = [-10e-3, -9e-3, 0, 5e-6] # [s] + waveform_currents = [0, 1, 1, 0] + + waveform = tdem.sources.PiecewiseLinearWaveform( + times=waveform_times, currents=waveform_currents + ) + source = tdem.sources.LineCurrent( + receiver_list=[receiver], + location=build_loop(receiver_location, radius), + waveform=waveform, + current=peak_current * n_turns, + ) + + # Define survey + survey = tdem.Survey([source]) + return survey + + +class TestComplexMu: + """ + Test the :meth:`BaseEM1DSimulation.compute_complex_mu` method. + + Check if passing any null value in the ``dchi`` array generates + ``mu`` with non-null imaginary parts. Without the bugfix, a single null value in + ``dchi`` would ignore the viscous remanent magnetization, generating real ``mu``. + """ + + thicknesses = np.array([20.0, 50.0]) + resistivities = np.array([5000.0, 500.0, 5000.0]) # [Ohm.m] + frequencies = np.logspace(-1, -5, 11) + tau1 = np.full(shape=3, fill_value=1e-10) + tau2 = np.full(shape=3, fill_value=10.0) + + def compute_mu(self, dchi, survey): + """ + Use the :class:`BaseEM1DSimulation` to compute mu for a given ``dchi``. + """ + sim = BaseEM1DSimulation( + thicknesses=self.thicknesses, + survey=survey, + rho=self.resistivities, + dchi=dchi, + tau1=self.tau1, + tau2=self.tau2, + ) + return sim.compute_complex_mu(self.frequencies) + + def test_dchi_small_vs_null(self, survey): + dchi_zeros = np.array([0, 0, 0]) + dchi_almost_zeros = np.array([1e-15, 1e-15, 1e-15]) + np.testing.assert_allclose( + self.compute_mu(dchi_zeros, survey), + self.compute_mu(dchi_almost_zeros, survey), + ) + + def test_dchi_effect(self, survey): + dchi_zeros = np.array([0, 0, 0]) + dchi_non_zeros = np.array([3e-3, 2e-2, 1e-1]) + assert not np.allclose( + self.compute_mu(dchi_zeros, survey), + self.compute_mu(dchi_non_zeros, survey), + ) + + def test_dchi_at_least_one_null(self, survey): + dchi = np.array([3e-3, 2e-2, 1e-10]) + dchi_one_null = np.array([3e-3, 2e-2, 0]) + np.testing.assert_allclose( + self.compute_mu(dchi, survey), + self.compute_mu(dchi_one_null, survey), + ) + + +class TestViscousRemanentMagnetization: + """ + Test if the viscous remanent magnetization effect is present in the dB/dt data. + """ + + thicknesses = np.array([20.0, 50.0]) # [m] + model_map = simpeg.maps.IdentityMap(nP=len(thicknesses) + 1) + + resistivities = np.array([5000.0, 500.0, 5000.0]) # [Ohm.m] + tau1 = np.full(shape=3, fill_value=1e-10) + tau2 = np.full(shape=3, fill_value=10.0) + + def get_simulation(self, dchi, survey): + simulation = tdem.Simulation1DLayered( + survey=survey, + thicknesses=self.thicknesses, + rhoMap=self.model_map, + dchi=dchi, + tau1=self.tau1, + tau2=self.tau2, + ) + return simulation + + def dpred(self, dchi, survey): + return self.get_simulation(dchi, survey).dpred(self.resistivities) + + def test_dchi_small_vs_null(self, survey): + dchi_zeros = np.array([0, 0, 0]) + dchi_almost_zeros = np.array([1e-15, 1e-15, 1e-15]) + + dpred_zeros = self.dpred(dchi_zeros, survey) + dpred_almost_zeros = self.dpred(dchi_almost_zeros, survey) + np.testing.assert_allclose(dpred_zeros, dpred_almost_zeros) + + def test_dchi_effect(self, survey): + dchi_zeros = np.array([0, 0, 0]) + dchi_non_zeros = np.array([3e-3, 2e-2, 1e-1]) + + dpred_zeros = self.dpred(dchi_zeros, survey) + dpred_non_zeros = self.dpred(dchi_non_zeros, survey) + assert not np.allclose(dpred_zeros, dpred_non_zeros) + + def test_dchi_at_least_one_null(self, survey): + """ + Test if having one value of dchi equal to zero still predicts VRM effect. + """ + dchi = np.array([3e-3, 2e-2, 1e-10]) + dchi_one_null = np.array([3e-3, 2e-2, 0]) + + dpred = self.dpred(dchi, survey) + dpred_one_null = self.dpred(dchi_one_null, survey) + np.testing.assert_allclose(dpred, dpred_one_null) diff --git a/tests/em/em1d/test_bugfix_one_null_eta.py b/tests/em/em1d/test_bugfix_one_null_eta.py new file mode 100644 index 0000000000..0efbe9de85 --- /dev/null +++ b/tests/em/em1d/test_bugfix_one_null_eta.py @@ -0,0 +1,177 @@ +""" +Test bugfix in EM1D simulation that ignored IP effect if at least one eta value is null. +""" + +import pytest +import numpy as np +import simpeg +import simpeg.electromagnetics.time_domain as tdem +from simpeg.electromagnetics.base_1d import BaseEM1DSimulation + + +def build_loop(center, radius, size=200): + """ + Build a horizontal circular loop around the center. + + Parameters + ---------- + center : tuple of float + The x, y, z location of the center of the loop. + radius : float + Loop's radius. + size : int, optional + Number of points that will form the loop. + + Returns + ------- + locations : (size, 3) array + Array with the x, y, z coordinates of the loop points. + """ + xc, yc, zc = center + theta = np.linspace(0, 2 * np.pi, size, endpoint=False) + x = xc + radius * np.cos(theta) + y = yc + radius * np.sin(theta) + z = zc + np.zeros_like(theta) + return np.vstack((x, y, z)).T + + +@pytest.fixture +def survey(): + # Define receiver + receiver_location = (0, 0, 30) + time_channels = 10 ** np.linspace(-2, -5, 31) # [s] + receiver = tdem.receivers.PointMagneticFluxTimeDerivative( + receiver_location, time_channels, orientation="z" + ) + + # Define source. + # Define source as a circular loop around the receiver. Use a piecewise linear + # waveform. + area = 300 # [m2] + radius = np.sqrt(area / np.pi) + peak_current = 100 # [A] + n_turns = 16 + waveform_times = [-10e-3, -9e-3, 0, 5e-6] # [s] + waveform_currents = [0, 1, 1, 0] + + waveform = tdem.sources.PiecewiseLinearWaveform( + times=waveform_times, currents=waveform_currents + ) + source = tdem.sources.LineCurrent( + receiver_list=[receiver], + location=build_loop(receiver_location, radius), + waveform=waveform, + current=peak_current * n_turns, + ) + + # Define survey + survey = tdem.Survey([source]) + return survey + + +class TestComplexSigma: + """ + Test the :meth:`BaseEM1DSimulation.compute_complex_sigma` method. + + Check if passing any null chargeability value in the ``eta`` array generates + sigmas with non-null imaginary parts. Without the bugfix, a single null value in + ``eta`` would ignore the IP effect, generating real sigmas. + """ + + thicknesses = np.array([20.0, 50.0]) + c = np.array([0, 0.5, 0]) + tau = np.array([0, 1.0e-3, 0]) + resistivities = np.array([5000.0, 500.0, 5000.0]) # [Ohm.m] + frequencies = np.logspace(-1, -5, 11) + + def compute_sigmas(self, eta, survey): + """ + Use the :class:`BaseEM1DSimulation` to compute sigmas for a given ``eta``. + """ + sim = BaseEM1DSimulation( + thicknesses=self.thicknesses, + survey=survey, + rho=self.resistivities, + eta=eta, + tau=self.tau, + c=self.c, + ) + return sim.compute_complex_sigma(self.frequencies) + + def test_sigmas_no_ip(self, survey): + eta_zeros = np.array([0, 0, 0]) + eta_almost_zeros = np.array([1e-15, 1e-15, 1e-15]) + np.testing.assert_allclose( + self.compute_sigmas(eta_zeros, survey), + self.compute_sigmas(eta_almost_zeros, survey), + ) + + def test_sigmas_ip(self, survey): + eta_zeros = np.array([0, 0, 0]) + eta_non_zeros = np.array([3e-3, 2e-2, 1e-1]) + assert not np.allclose( + self.compute_sigmas(eta_zeros, survey), + self.compute_sigmas(eta_non_zeros, survey), + ) + + def test_sigmas_ip_one_null(self, survey): + eta = np.array([3e-3, 2e-2, 1e-10]) + eta_one_null = np.array([3e-3, 2e-2, 0]) + np.testing.assert_allclose( + self.compute_sigmas(eta, survey), + self.compute_sigmas(eta_one_null, survey), + ) + + +class TestIPEffect: + """ + Test if the IP effect is present in the dB/dt predicted data. + """ + + thicknesses = np.array([20.0, 50.0]) # [m] + model_map = simpeg.maps.IdentityMap(nP=len(thicknesses) + 1) + + resistivities = np.array([5000.0, 500.0, 5000.0]) # [Ohm.m] + tau = np.array([1e-10, 1.0e-3, 1e-10]) # [s] + c = np.array([1e-10, 0.5, 1e-10]) # - + + def get_simulation(self, eta, survey): + simulation = tdem.Simulation1DLayered( + survey=survey, + thicknesses=self.thicknesses, + rhoMap=self.model_map, + eta=eta, + tau=self.tau, + c=self.c, + ) + return simulation + + def dpred(self, eta, survey): + return self.get_simulation(eta, survey).dpred(self.resistivities) + + def test_no_ip_effect(self, survey): + eta_zeros = np.array([0, 0, 0]) + eta_almost_zeros = np.array([1e-15, 1e-15, 1e-15]) + + dpred_zeros = self.dpred(eta_zeros, survey) + dpred_almost_zeros = self.dpred(eta_almost_zeros, survey) + np.testing.assert_allclose(dpred_zeros, dpred_almost_zeros) + + def test_ip_effect_vs_no_ip(self, survey): + eta_zeros = np.array([0, 0, 0]) + eta_non_zeros = np.array([3e-3, 2e-2, 1e-1]) + + dpred_zeros = self.dpred(eta_zeros, survey) + dpred_non_zeros = self.dpred(eta_non_zeros, survey) + assert not np.allclose(dpred_zeros, dpred_non_zeros) + + def test_ip_effect_one_null(self, survey): + """ + Test if having one value of eta equal to zero still predicts IP effect. + """ + eta = np.array([3e-3, 2e-2, 1e-10]) + eta_one_null = np.array([3e-3, 2e-2, 0]) + + dpred = self.dpred(eta, survey) + dpred_one_null = self.dpred(eta_one_null, survey) + np.testing.assert_allclose(dpred, dpred_one_null) diff --git a/tests/em/fdem/forward/test_FDEM_analytic_edge_face_conductivities.py b/tests/em/fdem/forward/test_FDEM_analytic_edge_face_conductivities.py new file mode 100644 index 0000000000..8e3393400e --- /dev/null +++ b/tests/em/fdem/forward/test_FDEM_analytic_edge_face_conductivities.py @@ -0,0 +1,278 @@ +"""Analytic tests for hierarchical physical properties.""" + +import discretize +import numpy as np +import pytest +from scipy.constants import mu_0 +from simpeg import maps +from simpeg.utils import ndgrid +from simpeg.electromagnetics import frequency_domain as fdem + +ABS_TOL = 1e-13 +REL_TOL = 0.1 + + +@pytest.mark.parametrize("orientation", ["x", "z"]) +@pytest.mark.parametrize("rx_type", ["MagneticFluxDensity"]) +@pytest.mark.parametrize("formulation", ["MagneticFluxDensity", "ElectricField"]) +@pytest.mark.parametrize("mesh_type", ["CYL", "TREE"]) +def test_layer_conductance_to_analytic(mesh_type, formulation, rx_type, orientation): + """Validate 1D analytic solution for thin layer against layer as face conductances.""" + # Some static parameters + loop_radius = np.pi**-0.5 + receiver_location = np.c_[12.0, 0.0, 1.0] + source_location = np.r_[0.0, 0.0, 1.0] + frequencies = np.logspace(2, 3, 2) + + layer_depth = 40.0 + layer_thickness = 0.1 + layer_conductivity = 100 + background_conductivity = 2.5e-3 + + tau = layer_thickness * layer_conductivity + + # 1D LAYER MODEL + thicknesses = np.array([layer_depth - layer_thickness / 2, layer_thickness]) + n_layer = len(thicknesses) + 1 + + sigma_1d = background_conductivity * np.ones(n_layer) + sigma_1d[1] = layer_conductivity + + sigma_map_1d = maps.IdentityMap(nP=n_layer) + + # 3D LAYER MODEL + if mesh_type == "CYL": + hr = [(2.0, 120), (2.0, 25, 1.3)] + hz = [(2.0, 25, -1.3), (2.0, 200), (2.0, 25, 1.3)] + + mesh = discretize.CylindricalMesh([hr, 1, hz], x0="00C") + + ind = np.where(mesh.h[2] == np.min(mesh.h[2]))[0] + ind = ind[int(len(ind) / 2)] + + mesh.origin = mesh.origin - np.r_[0.0, 0.0, mesh.nodes_z[ind] - 24] + + elif mesh_type == "TREE": + dh = 2.5 # base cell width + dom_width = 8000.0 # domain width + nbc = 2 ** int( + np.round(np.log(dom_width / dh) / np.log(2.0)) + ) # num. base cells + + h = [(dh, nbc)] + mesh = discretize.TreeMesh([h, h, h], x0="CCC") + mesh.refine_points( + np.reshape(source_location, (1, 3)), + level=-1, + padding_cells_by_level=[8, 4, 4, 4], + finalize=False, + ) + x0s = np.vstack([ii * np.c_[-60, -60, -60] for ii in range(1, 5)]) + x1s = np.vstack([ii * np.c_[60, 60, 10] for ii in range(1, 5)]) + + mesh.refine_box(x0s, x1s, levels=[-2, -3, -4, -5], finalize=False) + mesh.finalize() + + sigma_3d = 1e-8 * np.ones(mesh.nC) + sigma_3d[mesh.cell_centers[:, -1] < 0.0] = background_conductivity + + tau_3d = np.zeros(mesh.nF) + tau_3d[np.isclose(mesh.faces[:, -1], -layer_depth)] = tau + tau_map = maps.IdentityMap(nP=mesh.n_faces) + + # DEFINE SURVEY + rx_list = [ + getattr(fdem.receivers, "Point{}Secondary".format(rx_type))( + receiver_location, component="real", orientation=orientation + ), + getattr(fdem.receivers, "Point{}Secondary".format(rx_type))( + receiver_location, component="imag", orientation=orientation + ), + ] + + # 1D SURVEY AND SIMULATION + src_1d = [ + fdem.sources.MagDipole( + rx_list, f, location=np.r_[0.0, 0.0, 1.0], orientation=orientation + ) + for f in frequencies + ] + survey_1d = fdem.Survey(src_1d) + + sim_1d = fdem.Simulation1DLayered( + survey=survey_1d, + thicknesses=thicknesses, + sigmaMap=sigma_map_1d, + ) + + # 3D SURVEY AND SIMULATION + if mesh_type == "CYL": + src_3d = [ + fdem.sources.CircularLoop( + rx_list, + f, + radius=loop_radius, + location=source_location, + ) + for f in frequencies + ] + else: + src_3d = [ + fdem.sources.MagDipole( + rx_list, + f, + location=source_location, + orientation=orientation, + ) + for f in frequencies + ] + + survey_3d = fdem.Survey(src_3d) + + # DEFINE THE SIMULATIONS + if formulation == "MagneticFluxDensity": + sim_3d = fdem.Simulation3DHierarchicalMagneticFluxDensity( + mesh=mesh, + survey=survey_3d, + sigma=sigma_3d, + face_conductance_map=tau_map, + ) + else: + sim_3d = fdem.Simulation3DHierarchicalElectricField( + mesh=mesh, + survey=survey_3d, + sigma=sigma_3d, + face_conductance_map=tau_map, + ) + + # COMPUTE SOLUTIONS + analytic_solution = mu_0 * sim_1d.dpred(sigma_1d) # ALWAYS RETURNS H-FIELD + numeric_solution = sim_3d.dpred(tau_3d) + + np.testing.assert_allclose( + numeric_solution, analytic_solution, atol=ABS_TOL, rtol=REL_TOL + ) + + +def test_edge_conductivity(): + """Cross check for a thin conductive wire.""" + # Some static parameters + location_a = np.r_[-40, 0, 0] + location_b = np.r_[40, 0, 0] + locations_rx = ndgrid(np.linspace(-10, 10, 4), 0, 8) + frequencies = np.logspace(2, 3, 2) + + wire_depth = 16.0 + wire_width = 1.0 + wire_length = 20.0 + wire_conductivity = 1e0 # Only 1 order of magnitude (linear regime + background_conductivity = 1e-1 + + kappa_value = wire_width**2 * wire_conductivity + + # Mesh + dh = 0.25 # base cell width + dom_width = 2000.0 # domain width + nbc = 2 ** int(np.round(np.log(dom_width / dh) / np.log(2.0))) # num. base cells + + h = [(dh, nbc)] + mesh = discretize.TreeMesh([h, h, h], x0="CCC") + + pts = ndgrid( + np.arange(-wire_length / 2, wire_length / 2 + 1e-6, dh), 0, -wire_depth + ) + mesh.refine_points( + pts, + level=-1, + padding_cells_by_level=[4, 4, 4, 4], + finalize=False, + ) + + pts = np.vstack([locations_rx, location_a, location_b]) + mesh.refine_points( + pts, + level=-2, + padding_cells_by_level=[4, 4, 4, 4], + finalize=False, + ) + x0s = np.vstack([ii * np.c_[-60, -60, -30] for ii in range(1, 4)]) + x1s = np.vstack([ii * np.c_[60, 60, 10] for ii in range(1, 4)]) + + mesh.refine_box(x0s, x1s, levels=[-5, -6, -7], finalize=False) + mesh.finalize() + print(mesh.n_cells) + + # Models + ccs = mesh.cell_centers + sigma_0 = 1e-8 * np.ones(mesh.n_cells) + sigma_0[ccs[:, -1] < 0.0] = background_conductivity + + sigma_voxel = sigma_0.copy() + inds_block = ( + (np.abs(ccs[:, 0]) <= wire_length / 2) + & (np.abs(ccs[:, 1]) <= wire_width / 2) + & (np.abs(ccs[:, 2] + wire_depth) <= wire_width / 2) + ) + sigma_voxel[inds_block] = wire_conductivity + print(sum(inds_block)) + + kappa = np.zeros(mesh.n_edges) + edges = mesh.edges + inds_kappa = ( + (np.abs(edges[:, 0]) <= wire_length / 2) + & (np.isclose(edges[:, 1], 0.0)) + & (np.isclose(edges[:, 2], -wire_depth)) + ) + kappa[inds_kappa] = kappa_value + print(sum(inds_kappa)) + + # DEFINE SURVEY + src_sigma = [] + src_kappa = [] + for freq in frequencies: + rx_sigma = [] + rx_kappa = [] + for comp in ["real", "imag"]: + rx_sigma.append( + fdem.receivers.PointElectricField( + locations=locations_rx, orientation="x", component=comp + ) + ) + rx_kappa.append( + fdem.receivers.PointElectricField( + locations=locations_rx, orientation="x", component=comp + ) + ) + + src_sigma.append( + fdem.sources.LineCurrent( + rx_sigma, frequency=freq, location=np.c_[location_a, location_b].T + ) + ) + src_kappa.append( + fdem.sources.LineCurrent( + rx_kappa, frequency=freq, location=np.c_[location_a, location_b].T + ) + ) + + survey_sigma = fdem.Survey(src_sigma) + survey_kappa = fdem.Survey(src_kappa) + + sim_sigma = fdem.simulation.Simulation3DElectricField( + mesh=mesh, survey=survey_sigma, sigmaMap=maps.IdentityMap(nP=mesh.n_cells) + ) + sim_kappa = fdem.simulation.Simulation3DHierarchicalElectricField( + mesh=mesh, + survey=survey_kappa, + sigma=sigma_0, + edge_area_conductance_map=maps.IdentityMap(nP=mesh.n_edges), + ) + + # COMPUTE SOLUTIONS + dpred_0 = sim_sigma.dpred(sigma_0) + true_solution = sim_sigma.dpred(sigma_voxel) - dpred_0 + approx_solution = sim_kappa.dpred(kappa) - dpred_0 + + np.testing.assert_allclose( + true_solution, approx_solution, atol=ABS_TOL, rtol=REL_TOL + ) diff --git a/tests/em/fdem/forward/test_FDEM_analytics.py b/tests/em/fdem/forward/test_FDEM_analytics.py index ebadf7a7ea..15f9b4ea2e 100644 --- a/tests/em/fdem/forward/test_FDEM_analytics.py +++ b/tests/em/fdem/forward/test_FDEM_analytics.py @@ -134,7 +134,7 @@ def test_CylindricalMeshEBDipoles(self, plotIt=plotIt): # set up source # test electric dipole src_loc = np.r_[0.0, 0.0, 0.0] - s_ind = utils.closest_points_index(mesh, src_loc, "Fz") + mesh.nFx + s_ind = mesh.closest_points_index(src_loc, "Fz") + mesh.nFx de = np.zeros(mesh.nF, dtype=complex) de[s_ind] = 1.0 / csz diff --git a/tests/em/fdem/forward/test_FDEM_casing.py b/tests/em/fdem/forward/test_FDEM_casing.py index 92d8b85153..074b685f55 100644 --- a/tests/em/fdem/forward/test_FDEM_casing.py +++ b/tests/em/fdem/forward/test_FDEM_casing.py @@ -4,7 +4,6 @@ import unittest from scipy.constants import mu_0 - n = 50 freq = 1.0 a = 5e-2 diff --git a/tests/em/fdem/forward/test_fields_multiple_sources.py b/tests/em/fdem/forward/test_fields_multiple_sources.py new file mode 100644 index 0000000000..7bb827e512 --- /dev/null +++ b/tests/em/fdem/forward/test_fields_multiple_sources.py @@ -0,0 +1,28 @@ +""" +Fields requested for several sources at once match the fields of each source. +""" + +import numpy as np +import discretize + +from simpeg.electromagnetics import frequency_domain as fdem +from simpeg.utils import get_default_solver + + +def test_e_formulation_b_for_several_sources(): + mesh = discretize.TensorMesh([np.full(8, 50.0)] * 3, "CCC") + # different frequencies, so each source's column has its own scaling + sources = [ + fdem.sources.MagDipole([], frequency=f, location=np.r_[0.0, 0.0, 10.0]) + for f in (1.0, 10.0, 100.0) + ] + sim = fdem.Simulation3DElectricField( + mesh, + survey=fdem.Survey(sources), + sigma=1e-2, + solver=get_default_solver(), + ) + f = sim.fields() + b_all = f[sources, "b"] + for i, src in enumerate(sources): + np.testing.assert_allclose(b_all[:, i], f[src, "b"][:, 0]) diff --git a/tests/em/fdem/forward/test_permittivity.py b/tests/em/fdem/forward/test_permittivity.py index aaaff90b74..bcee7fa958 100644 --- a/tests/em/fdem/forward/test_permittivity.py +++ b/tests/em/fdem/forward/test_permittivity.py @@ -7,7 +7,6 @@ import discretize from simpeg.electromagnetics import frequency_domain as fdem - # set up the mesh hx = 1 hz = 1 @@ -148,7 +147,7 @@ def test_mag_dipole(epsilon, frequency, simulation): def test_e_dipole(epsilon, frequency, simulation): sources = [ fdem.sources.LineCurrent( - [], frequency, location=np.array([[0, 0, 1], [0, 0, -1]]), current=1 / 2 + [], frequency, location=np.array([[0, 0, -1], [0, 0, 1]]), current=1 / 2 ) ] survey = fdem.Survey(sources) @@ -207,7 +206,7 @@ def test_cross_check_e_dipole(epsilon_r, frequency): # J-Formulation sources_j_target = [ fdem.sources.LineCurrent( - [], freq, location=np.array([[0, 0, 1], [0, 0, -1]]), current=1 / 2 + [], freq, location=np.array([[0, 0, -1], [0, 0, 1]]), current=1 / 2 ) for freq in frequencies ] @@ -223,7 +222,7 @@ def test_cross_check_e_dipole(epsilon_r, frequency): # H-formulation sources_h_target = [ fdem.sources.LineCurrent( - [], freq, location=np.array([[0, 0, 1], [0, 0, -1]]), current=1 / 2 + [], freq, location=np.array([[0, 0, -1], [0, 0, 1]]), current=1 / 2 ) for freq in frequencies ] diff --git a/tests/em/fdem/inverse/derivs/__init__.py b/tests/em/fdem/inverse/derivs/__init__.py deleted file mode 100644 index 01e17ee649..0000000000 --- a/tests/em/fdem/inverse/derivs/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -if __name__ == "__main__": - import glob - import unittest - - test_file_strings = glob.glob("test_*.py") - module_strings = [s[0 : len(s) - 3] for s in test_file_strings] - suites = [unittest.defaultTestLoader.loadTestsFromName(s) for s in module_strings] - testSuite = unittest.TestSuite(suites) - - unittest.TextTestRunner(verbosity=2).run(testSuite) diff --git a/tests/em/fdem/inverse/derivs/test_FDEM_derivs.py b/tests/em/fdem/inverse/derivs/test_FDEM_derivs_supplemental.py similarity index 100% rename from tests/em/fdem/inverse/derivs/test_FDEM_derivs.py rename to tests/em/fdem/inverse/derivs/test_FDEM_derivs_supplemental.py diff --git a/tests/em/fdem/inverse/derivs/test_FDEM_getJ.py b/tests/em/fdem/inverse/derivs/test_FDEM_getJ.py new file mode 100644 index 0000000000..5e67b00535 --- /dev/null +++ b/tests/em/fdem/inverse/derivs/test_FDEM_getJ.py @@ -0,0 +1,77 @@ +""" +Test the getJ method of the 3D FDEM simulations. +""" + +import pytest +import numpy as np +import discretize +from simpeg import maps +import simpeg.electromagnetics.frequency_domain as fdem + +SIMULATIONS = [ + fdem.Simulation3DElectricField, + fdem.Simulation3DMagneticFluxDensity, + fdem.Simulation3DCurrentDensity, + fdem.Simulation3DMagneticField, +] + +RECEIVERS = [ + fdem.receivers.PointElectricField, + fdem.receivers.PointMagneticFluxDensity, + fdem.receivers.PointMagneticField, + fdem.receivers.PointCurrentDensity, +] + + +def get_simulation(simulation_class, receiver_class): + """ + Build a small FDEM simulation with a magnetic dipole source. + + Parameters + ---------- + simulation_class : type + One of the 3D FDEM simulation classes. + receiver_class : type + One of the FDEM point receiver classes. + + Returns + ------- + simulation : BaseFDEMSimulation + """ + h = [(10.0, 4, -1.3), (10.0, 4), (10.0, 4, 1.3)] + mesh = discretize.TensorMesh([h, h, h], origin="CCC") + + # Don't place receivers right on top of the source + receiver_locations = np.array([[-15.0, 5.0, 5.0], [15.0, -5.0, -5.0]]) + receivers = [ + receiver_class(receiver_locations, orientation="z", component=component) + for component in ("real", "imag") + ] + source = fdem.sources.MagDipole( + receiver_list=receivers, frequency=100.0, location=np.array([0.0, 0.0, 0.0]) + ) + survey = fdem.Survey([source]) + return simulation_class(mesh=mesh, survey=survey, sigmaMap=maps.ExpMap(mesh)) + + +@pytest.mark.parametrize("receiver_class", RECEIVERS) +@pytest.mark.parametrize("simulation_class", SIMULATIONS) +def test_getJ_vs_Jvec_Jtvec(simulation_class, receiver_class): + """ + Test that the sensitivity matrix from getJ is consistent with Jvec and Jtvec. + """ + simulation = get_simulation(simulation_class, receiver_class) + rng = np.random.default_rng(seed=42) + # Use a conductive model (1 S/m) so the real and imaginary data have similar + # magnitudes and can be compared with a relative tolerance + model = np.zeros(simulation.mesh.n_cells) + v = rng.normal(size=model.size) + w = rng.normal(size=simulation.survey.nD) + + fields = simulation.fields(model) + jac = simulation.getJ(model, f=fields) + + np.testing.assert_allclose(jac @ v, simulation.Jvec(model, v, f=fields), rtol=1e-7) + np.testing.assert_allclose( + jac.T @ w, simulation.Jtvec(model, w, f=fields), rtol=1e-7 + ) diff --git a/tests/em/fdem/inverse/test_FDEM_adjoint.py b/tests/em/fdem/inverse/test_FDEM_adjoint.py new file mode 100644 index 0000000000..bfc67e6547 --- /dev/null +++ b/tests/em/fdem/inverse/test_FDEM_adjoint.py @@ -0,0 +1,71 @@ +"""Adjoint tests for FDEM problems.""" + +import numpy as np +from scipy.constants import mu_0 +from simpeg.electromagnetics.utils.testing_utils import ( + getFDEMProblem, + get_FDEM_hierarchical_problem, +) +import pytest + +testE = True +testB = True + +verbose = False + +TOL = 1e-6 +FLR = 1e-20 # "zero", so if residual below this --> pass regardless of order +CONDUCTIVITY = 1e1 +MU = mu_0 +freq = 1e-1 +addrandoms = True + + +@pytest.mark.parametrize("receiver_comp", ["r", "i"]) +@pytest.mark.parametrize("receiver_dir", ["x", "y", "z"]) +@pytest.mark.parametrize( + "receiver_type", + ["ElectricField", "MagneticFluxDensity", "CurrentDensity", "MagneticField"], +) +@pytest.mark.parametrize( + "src_type", + [ + "MagDipole", + "CircularLoop", + "MagDipole_Bfield", + "RawVec", + "LineCurrent", + ], +) +@pytest.mark.parametrize("sim_type", ["e", "b", "e_hier", "b_hier", "h", "j"]) +def test_adjoint(sim_type, src_type, receiver_type, receiver_dir, receiver_comp): + """Perform adjoint test for FDEM problems.""" + rng = np.random.default_rng(84) + rx_type = (receiver_type, receiver_dir, receiver_comp) + if "hier" in sim_type: + prb = get_FDEM_hierarchical_problem(sim_type[0], rx_type, [src_type], freq) + else: + prb = getFDEMProblem(sim_type, rx_type, [src_type], freq) + + m = np.log( + np.ones(prb.sigmaMap.nP) * CONDUCTIVITY + ) # works for sigma_only and sigma, tau, kappa + mu = np.ones(prb.mesh.nC) * MU + + if addrandoms is True: + m = m + rng.standard_normal(prb.sigmaMap.nP) * np.log(CONDUCTIVITY) * 1e-1 + mu = mu + rng.standard_normal(prb.mesh.nC) * MU * 1e-1 + + survey = prb.survey + # prb.PropMap.PropModel.mu = mu + # prb.PropMap.PropModel.mui = 1./mu + u = prb.fields(m) + + v = rng.uniform(size=survey.nD) + w = rng.uniform(size=prb.sigmaMap.nP) # works for sigma_only and sigma, tau, kappa + + vJw = v.dot(prb.Jvec(m, w, u)) + wJtv = w.dot(prb.Jtvec(m, v, u)) + + print(vJw, wJtv, vJw - wJtv, np.abs(vJw - wJtv) < FLR + TOL * np.abs(wJtv)) + np.testing.assert_allclose(vJw, wJtv, rtol=TOL, atol=FLR) diff --git a/tests/em/fdem/inverse/test_FDEM_derivs.py b/tests/em/fdem/inverse/test_FDEM_derivs.py new file mode 100644 index 0000000000..2ea69f4f8e --- /dev/null +++ b/tests/em/fdem/inverse/test_FDEM_derivs.py @@ -0,0 +1,51 @@ +"""Derivative tests for FDEM problems.""" + +import numpy as np +from scipy.constants import mu_0 +from discretize.tests import check_derivative +from simpeg.electromagnetics.utils.testing_utils import ( + getFDEMProblem, + get_FDEM_hierarchical_problem, +) +import pytest + +TOL = 1e-5 +FLR = 1e-20 # "zero", so if residual below this --> pass regardless of order +CONDUCTIVITY = 1e1 +MU = mu_0 +freq = 3.16 + + +# Previously this only tested "electric fields +@pytest.mark.parametrize("receiver_comp", ["r", "i"]) +@pytest.mark.parametrize("receiver_dir", ["x", "y", "z"]) +@pytest.mark.parametrize( + "receiver_type", + ["ElectricField", "MagneticFluxDensity", "CurrentDensity", "MagneticField"], +) +@pytest.mark.parametrize( + "src_type", + [ + "MagDipole", + "CircularLoop", + "MagDipole_Bfield", + "RawVec", + "LineCurrent", + ], +) +@pytest.mark.parametrize("sim_type", ["e", "b", "e_hier", "b_hier"]) +def test_deriv(sim_type, src_type, receiver_type, receiver_dir, receiver_comp): + """Perform derivative test.""" + rx_type = (receiver_type, receiver_dir, receiver_comp) + + if "hier" in sim_type: + prb = get_FDEM_hierarchical_problem(sim_type[0], rx_type, [src_type], freq) + else: + prb = getFDEMProblem(sim_type, rx_type, [src_type], freq) + + x0 = np.log(np.ones(prb.sigmaMap.nP) * CONDUCTIVITY) # should work + + def fun(x): + return prb.dpred(x), lambda x: prb.Jvec(x0, x) + + check_derivative(fun, x0, num=2, random_seed=66, plotIt=False, eps=FLR) diff --git a/tests/em/fdem/muinverse/test_muinverse.py b/tests/em/fdem/muinverse/test_muinverse.py index 9e45560342..4629977e12 100644 --- a/tests/em/fdem/muinverse/test_muinverse.py +++ b/tests/em/fdem/muinverse/test_muinverse.py @@ -74,7 +74,7 @@ def setupProblem( ) elif prbtype in ["MagneticField", "CurrentDensity"]: - ind = utils.closest_points_index(mesh, src_loc, "Fz") + mesh.vnF[0] + ind = mesh.closest_points_index(src_loc, "Fz") + mesh.vnF[0] vec = np.zeros(mesh.nF) vec[ind] = 1.0 diff --git a/tests/em/nsem/forward/test_1D_finite_volume.py b/tests/em/nsem/forward/test_1D_finite_volume.py index 07b8ecd8b5..17360afba6 100644 --- a/tests/em/nsem/forward/test_1D_finite_volume.py +++ b/tests/em/nsem/forward/test_1D_finite_volume.py @@ -4,7 +4,6 @@ from simpeg import maps import unittest - TOL_SIGMA = 0.2 # 20% (These are very loose tests) TOL_PHASE = 5 # 3 degrees diff --git a/tests/em/nsem/forward/test_1D_mu_array.py b/tests/em/nsem/forward/test_1D_mu_array.py new file mode 100644 index 0000000000..e2ab0cee56 --- /dev/null +++ b/tests/em/nsem/forward/test_1D_mu_array.py @@ -0,0 +1,37 @@ +""" +An array of permeabilities without a map gives the same fields as with a map. +""" + +import numpy as np +import discretize +from scipy.constants import mu_0 + +from simpeg import maps +from simpeg.electromagnetics import natural_source as nsem +from simpeg.utils import get_default_solver + + +def test_1d_electric_field_mu_array(): + mesh = discretize.TensorMesh([[(50.0, 10, -1.3), (50.0, 40), (50.0, 10, 1.3)]], "C") + sigma = np.where(mesh.cell_centers < 0, 1e-2, 1e-8) + mu = np.where(mesh.cell_centers < -500, 2 * mu_0, mu_0) + rx = nsem.receivers.Impedance([[0.0]], orientation="yx", component="app_res") + sources = [nsem.sources.Planewave([rx], f) for f in (1.0, 10.0)] + + fields = [] + for kwargs, model in ( + ({"mu": mu}, None), + ({"muMap": maps.IdentityMap(mesh)}, mu), + ): + sim = nsem.Simulation1DElectricField( + mesh, + survey=nsem.Survey(sources), + sigma=sigma, + solver=get_default_solver(), + **kwargs, + ) + fields.append(sim.fields(model)) + for src in sources: + h_array, h_map = fields[0][src, "h"], fields[1][src, "h"] + assert h_array.shape == (mesh.n_cells, 1) + np.testing.assert_allclose(h_array, h_map) diff --git a/tests/em/nsem/forward/test_AnalyticFunctionVsAppResPhs.py b/tests/em/nsem/forward/test_AnalyticFunctionVsAppResPhs.py index cab4338952..d9168d51fc 100644 --- a/tests/em/nsem/forward/test_AnalyticFunctionVsAppResPhs.py +++ b/tests/em/nsem/forward/test_AnalyticFunctionVsAppResPhs.py @@ -3,7 +3,6 @@ from simpeg import discretize import numpy as np - TOL = 1e-6 diff --git a/tests/em/nsem/forward/test_Problem3D_VsAnalyticSolution.py b/tests/em/nsem/forward/test_Problem3D_VsAnalyticSolution.py index 5300d49273..896ebeb981 100644 --- a/tests/em/nsem/forward/test_Problem3D_VsAnalyticSolution.py +++ b/tests/em/nsem/forward/test_Problem3D_VsAnalyticSolution.py @@ -4,7 +4,6 @@ import numpy as np from simpeg.electromagnetics import natural_source as nsem - TOLr = 1 TOLp = 2 FLR = 1e-20 # "zero", so if residual below this --> pass regardless of order diff --git a/tests/em/nsem/forward/test_Recursive1D_VsAnalyticHalfspace.py b/tests/em/nsem/forward/test_Recursive1D_VsAnalyticHalfspace.py index be624bb19f..4d9d9f5085 100644 --- a/tests/em/nsem/forward/test_Recursive1D_VsAnalyticHalfspace.py +++ b/tests/em/nsem/forward/test_Recursive1D_VsAnalyticHalfspace.py @@ -1,97 +1,148 @@ -import unittest -import warnings +"""Pytests for 1D recursive solution.""" from simpeg.electromagnetics import natural_source as nsem +from simpeg.electromagnetics.natural_source.sources import Planewave, PlanewaveXYPrimary +from simpeg.electromagnetics.natural_source.receivers import ( + Impedance, + Admittance, + Tipper, + ApparentConductivity, +) from simpeg import maps import numpy as np from scipy.constants import mu_0 - -ns_rx = nsem.receivers - import pytest -def create_survey(freq): +def create_survey(freq, orientation): + """Generate test survey.""" receivers_list = [ - nsem.receivers.Impedance([[]], component="real"), - nsem.receivers.Impedance([[]], component="imag"), - nsem.receivers.Impedance([[]], component="app_res"), - nsem.receivers.Impedance([[]], component="phase"), + Impedance([[]], component="real", orientation=orientation), + Impedance([[]], component="imag", orientation=orientation), + Impedance([[]], component="app_res", orientation=orientation), + Impedance([[]], component="phase", orientation=orientation), ] - source_list = [nsem.sources.Planewave(receivers_list, f) for f in freq] + source_list = [Planewave(receivers_list, f) for f in freq] return nsem.survey.Survey(source_list) -def true_solution(freq, sigma_half): - # -ve sign can be removed if convention changes +def true_solution(freq, sigma_half, orientation): + """Compute true solution.""" + if orientation == "yx": + pm = -1 + else: + pm = 1 + soln = np.r_[ - -np.sqrt(np.pi * freq * mu_0 / sigma_half), - -np.sqrt(np.pi * freq * mu_0 / sigma_half), + -pm * np.sqrt(np.pi * freq * mu_0 / sigma_half), + -pm * np.sqrt(np.pi * freq * mu_0 / sigma_half), 1 / sigma_half, - -135.0, + -pm * 135.0, ] - return soln -def compute_simulation(freq, sigma_half): +def compute_simulation(freq, sigma_half, orientation): + """Compute numerical solution.""" layer_thicknesses = np.array([100.0]) conductivity_model = sigma_half * np.ones(2) model_mapping = maps.IdentityMap() - survey = create_survey(np.array([freq])) + survey = create_survey(np.array([freq]), orientation=orientation) simulation = nsem.simulation_1d.Simulation1DRecursive( survey=survey, thicknesses=layer_thicknesses, sigmaMap=model_mapping ) dpred = simulation.dpred(conductivity_model) - danal = true_solution(freq, sigma_half) + danal = true_solution(freq, sigma_half, orientation) return dpred, danal -class TestRecursiveForward(unittest.TestCase): - def test_1(self): - np.testing.assert_allclose(*compute_simulation(0.1, 0.001)) +# --- Forward tests (parameterized) --- +@pytest.mark.parametrize( + "freq, sigma_half, orientation", + [ + (0.1, 0.001, "xy"), + (0.1, 1.0, "yx"), + (100.0, 0.001, "xy"), + (100.0, 1.0, "yx"), + ], +) +def test_recursive_forward(freq, sigma_half, orientation): + """Test recursive forward solution.""" + dpred, danal = compute_simulation(freq, sigma_half, orientation) + np.testing.assert_allclose(dpred, danal) - def test_2(self): - np.testing.assert_allclose(*compute_simulation(0.1, 1.0)) - def test_3(self): - np.testing.assert_allclose(*compute_simulation(100.0, 0.001)) +@pytest.mark.parametrize( + "src_class", + [PlanewaveXYPrimary, Planewave], +) +def test_incorrect_src_types(src_class): + """Test incorrect source types.""" + loc = np.zeros((1, 3)) + rx = Impedance(loc) + src = src_class([rx], frequency=10) + survey = nsem.Survey([src]) - def test_4(self): - np.testing.assert_allclose(*compute_simulation(100.0, 1.0)) + if not isinstance(src, Planewave): + with pytest.raises( + NotImplementedError, + match=( + "Simulation1DRecursive defines sources using the " + f"Planewave class, got {type(src)} instead." + ), + ): + nsem.Simulation1DRecursive(survey=survey) @pytest.mark.parametrize( "rx_class", - [ - ns_rx.Impedance, - ns_rx.Admittance, - ns_rx.Tipper, - ns_rx.ApparentConductivity, - ], + [Admittance, Tipper, ApparentConductivity], ) def test_incorrect_rx_types(rx_class): + """Test incorrect receiver types.""" loc = np.zeros((1, 3)) - rx = rx_class(loc) - source = nsem.sources.Planewave(rx, frequency=10) - survey = nsem.Survey(source) - # make sure that only these exact classes do not issue warnings. - if rx_class is ns_rx.Impedance: - with warnings.catch_warnings(): - warnings.simplefilter("error") - nsem.Simulation1DRecursive(survey=survey) - else: + rx = ( + rx_class(loc) + if rx_class is ApparentConductivity + else rx_class(loc, orientation="xy") + ) + source = Planewave([rx], frequency=10) + survey = nsem.Survey([source]) + + if not isinstance(source, Impedance): with pytest.raises( - NotImplementedError, match="Simulation1DRecursive does not support .*" + NotImplementedError, + match=( + "Simulation1DRecursive only supports the Impedance receiver class, " + f"got {type(rx)} instead." + ), ): nsem.Simulation1DRecursive(survey=survey) -if __name__ == "__main__": - unittest.main() +@pytest.mark.parametrize( + "rx_orientation", + ["xx", "xy", "yx", "yy"], +) +def test_incorrect_rx_orientations(rx_orientation): + """Test incorrect receiver orientations.""" + loc = np.zeros((1, 3)) + rx = Impedance(loc, orientation=rx_orientation) + source = Planewave([rx], frequency=10) + survey = nsem.Survey([source]) + + if (rx.orientation != "xy") and (rx.orientation != "yx"): + with pytest.raises( + NotImplementedError, + match=( + "Simulation1DRecursive only allows 'xy' or 'yx' for the " + f"orientation property of Impedance receivers, got {rx.orientation}." + ), + ): + nsem.Simulation1DRecursive(survey=survey) diff --git a/tests/em/nsem/forward/test_Simulation2D_tree_mesh.py b/tests/em/nsem/forward/test_Simulation2D_tree_mesh.py new file mode 100644 index 0000000000..a6dfddcfad --- /dev/null +++ b/tests/em/nsem/forward/test_Simulation2D_tree_mesh.py @@ -0,0 +1,63 @@ +""" +Tests for the 2D NSEM simulations on a TreeMesh. +""" + +import numpy as np +import pytest +import discretize + +from simpeg import maps +from simpeg.electromagnetics import natural_source as nsem +from simpeg.utils import get_default_solver + +SIGMA = 1e-2 +FREQUENCIES = [0.1, 1.0, 10.0] + + +def layered(z, depth=3000.0): + sigma = np.full(z.shape, 1e-8) + sigma[z < 0] = 1e-1 + sigma[z < -depth] = SIGMA + return sigma + + +@pytest.mark.parametrize("orientation", ["xy", "yx"]) +def test_2d_tree_mesh_matches_tensor_mesh(orientation): + """The 1D side columns of a 2D TreeMesh are rebuilt from the mesh bottom. + + With an origin below zero, the side column cell widths used to be rebuilt + from absolute positions, giving wrong boundary data on a TreeMesh. + """ + h = [np.full(16, 100.0), np.full(64, 100.0)] + origin = [-800.0, -4000.0] + tensor = discretize.TensorMesh(h, origin=origin) + tree = discretize.TreeMesh(h, origin=origin, diagonal_balance=True) + tree.refine(-1) + sim_class = { + "xy": nsem.simulation.Simulation2DElectricField, + "yx": nsem.simulation.Simulation2DMagneticField, + }[orientation] + locations = np.array([[-350.0, 0.0], [50.0, 0.0], [450.0, 0.0]]) + d = [] + for mesh in (tensor, tree): + survey = nsem.survey.Survey( + [ + nsem.sources.Planewave( + [ + nsem.receivers.Impedance( + locations, orientation=orientation, component="app_res" + ) + ], + f, + ) + for f in FREQUENCIES + ] + ) + sim = sim_class( + mesh, + survey=survey, + sigmaMap=maps.IdentityMap(mesh), + solver=get_default_solver(), + ) + d.append(sim.dpred(layered(mesh.cell_centers[:, 1]))) + np.testing.assert_allclose(d[1], d[0], rtol=1e-5) diff --git a/tests/em/nsem/forward/test_Simulation2D_vs_Analytic_pytest.py b/tests/em/nsem/forward/test_Simulation2D_vs_Analytic_pytest.py index 96833bf431..0805aa877f 100644 --- a/tests/em/nsem/forward/test_Simulation2D_vs_Analytic_pytest.py +++ b/tests/em/nsem/forward/test_Simulation2D_vs_Analytic_pytest.py @@ -7,7 +7,7 @@ from simpeg import maps REL_TOLERANCE = 0.05 -ABS_TOLERANCE = 1e-13 +ABS_TOLERANCE = 1e-7 @pytest.fixture @@ -74,6 +74,16 @@ def get_survey(locations, frequencies, survey_type, component, orientation): ) ] + if survey_type == "admittance": + rx_list = [ + nsem.receivers.Admittance( + locations_e=locations, + locations_h=locations, + orientation=orientation, + component=component, + ) + ] + # ZTEM data types (Tzx, Tzy) elif survey_type == "tipper": rx_list = [ @@ -107,6 +117,16 @@ def get_analytic_halfspace_solution(sigma, f, survey_type, component, orientatio else: return 45 + # Admittance data types (Yxy, Yyx) + elif survey_type == "admittance": + if component in ["real", "imag"]: + ampl = 0.5 * np.sqrt(sigma / (np.pi * f * mu_0)) + if orientation == "yx": + ampl *= -1 + if component == "imag": + ampl *= -1 + return ampl + # ZTEM data types (Tzx, Tzy) elif survey_type == "tipper": return 0.0 @@ -124,10 +144,12 @@ def get_analytic_halfspace_solution(sigma, f, survey_type, component, orientatio ("impedance", "app_res", "yx"), ("impedance", "phase", "xy"), ("impedance", "phase", "yx"), - # ("tipper", "real", "zx"), - # ("tipper", "real", "zy"), - # ("tipper", "imag", "zx"), - # ("tipper", "imag", "zy"), + ("admittance", "real", "xy"), + ("admittance", "real", "yx"), + ("admittance", "imag", "xy"), + ("admittance", "imag", "yx"), + ("tipper", "real", "zx"), + ("tipper", "imag", "zx"), ] @@ -138,11 +160,17 @@ def test_analytic_halfspace_solution( # Numerical solution survey = get_survey(locations, frequencies, survey_type, component, orientation) model_hs = get_model(mesh, "halfspace") # 1e-2 halfspace - if orientation in ["xy", "zx"]: + if (orientation == "xy" and survey_type == "impedance") or ( + orientation == "yx" and survey_type == "admittance" + ): sim = nsem.simulation.Simulation2DElectricField( mesh, survey=survey, sigmaMap=mapping ) - elif orientation in ["yx", "zy"]: + elif ( + (orientation == "yx" and survey_type == "impedance") + or (orientation == "xy" and survey_type == "admittance") + or (orientation == "zx" and survey_type == "tipper") + ): sim = nsem.simulation.Simulation2DMagneticField( mesh, survey=survey, sigmaMap=mapping ) @@ -162,9 +190,7 @@ def test_analytic_halfspace_solution( ) analytic_solution = np.repeat(analytic_solution, n_locations) - # # Error - err = np.abs( - (numeric_solution - analytic_solution) / (analytic_solution + ABS_TOLERANCE) + # Error + np.testing.assert_allclose( + analytic_solution, numeric_solution, rtol=REL_TOLERANCE, atol=ABS_TOLERANCE ) - - assert np.all(err < REL_TOLERANCE) diff --git a/tests/em/nsem/forward/test_Simulation3D_vs_Analytic_pytest.py b/tests/em/nsem/forward/test_Simulation3D_vs_Analytic_pytest.py index da1e3ec0e6..f0507b881f 100644 --- a/tests/em/nsem/forward/test_Simulation3D_vs_Analytic_pytest.py +++ b/tests/em/nsem/forward/test_Simulation3D_vs_Analytic_pytest.py @@ -7,30 +7,40 @@ from simpeg import maps REL_TOLERANCE = 0.05 -ABS_TOLERANCE = 1e-13 +ABS_TOLERANCE = 1e-9 +REL_TOLERANCE_2 = 0.1 +ABS_TOLERANCE_2 = 1e-7 @pytest.fixture def mesh(): - # Mesh for testing - return TensorMesh( + """Get test mesh.""" + mesh = TensorMesh( [ - [(200, 6, -1.5), (200.0, 4), (200, 6, 1.5)], - [(200, 6, -1.5), (200.0, 4), (200, 6, 1.5)], - [(200, 8, -1.5), (200.0, 8), (200, 8, 1.5)], + [(200, 10, -1.5), (200.0, 6), (200, 10, 1.5)], + [(200, 10, -1.5), (200.0, 6), (200, 10, 1.5)], + [(200, 10, -1.5), (200.0, 10), (200, 10, 1.5)], ], "CCC", ) + mesh.origin[-1] -= 200.0 + return mesh @pytest.fixture def mapping(mesh): + """Get test mapping.""" return maps.IdentityMap(mesh) def get_model(mesh, model_type): - # Model used for testing + """Get test model.""" model = 1e-8 * np.ones(mesh.nC) + + if mesh.dim == 1: + model[mesh.cell_centers < 0.0] = 1e-2 + return model + model[mesh.cell_centers[:, 2] < 0.0] = 1e-2 if model_type == "layer": @@ -42,13 +52,14 @@ def get_model(mesh, model_type): mesh.cell_centers, ) model[ind_block] = 1e-1 + # pass return model @pytest.fixture def locations(): - # Receiver locations + """Get test locations.""" elevation = 0.0 v = np.r_[-350.0, -150.0, 150.0, 350.0] # needs to be symmetric rx_x, rx_y = np.meshgrid(v, v) @@ -59,11 +70,12 @@ def locations(): @pytest.fixture def frequencies(): - # Frequencies being evaluated + """Get test frequencies.""" return [1e-1, 2e-1] -def get_survey(locations, frequencies, survey_type, component): +def get_survey(locations, frequencies, survey_type, component, base_type): + """Get test survey.""" source_list = [] for f in frequencies: @@ -108,14 +120,49 @@ def get_survey(locations, frequencies, survey_type, component): ] elif survey_type == "apparent_conductivity": - rx_list = [nsem.receivers.ApparentConductivity(locations)] + rx_list = [ + nsem.receivers.ApparentConductivity( + locations_h=locations, + locations_e=locations, + formula=component, + ) + ] + + elif survey_type == "det_horizontal": + rx_list = [ + nsem.receivers.HorizontalDeterminant( + locations_h=locations, + locations_base=locations, + base_type=base_type, + component=component, + ) + ] + + elif survey_type == "gram_amp": + rx_list = [ + nsem.receivers.RootGramDeterminant( + locations_h=locations, + locations_base=locations, + base_type=base_type, + ) + ] + + elif survey_type == "cross_amp": + rx_list = [ + nsem.receivers.CrossProductAmplitude( + locations_h=locations, + locations_base=locations, + base_type=base_type, + ) + ] source_list.append(nsem.sources.PlanewaveXYPrimary(rx_list, f)) return nsem.survey.Survey(source_list) -def get_analytic_halfspace_solution(sigma, f, survey_type, component): +def get_analytic_halfspace_solution(sigma, f, survey_type, component, base_type): + """Get analytic halfpsace solution.""" # MT data types (Zxx, Zxy, Zyx, Zyy) if survey_type == "impedance": if component in ["real", "imag"]: @@ -145,29 +192,65 @@ def get_analytic_halfspace_solution(sigma, f, survey_type, component): elif survey_type == "apparent_conductivity": return sigma + elif survey_type == "det_horizontal": + if base_type == "magnetic": + if component == "imag": + return np.r_[0.0] + else: + return np.r_[1.0] + elif base_type == "electric": + if component == "real": + return ( + 0.025 * sigma / (2 * np.pi * f * mu_0) + ) # np.r_[0.] <-- analytically + elif component == "imag": + return -sigma / (2 * np.pi * f * mu_0) + else: + return sigma / (2 * np.pi * f * mu_0) + + elif survey_type == "gram_amp": + if base_type == "magnetic": + return np.r_[1.0] + elif base_type == "electric": + return sigma / (2 * np.pi * f * mu_0) + + elif survey_type == "cross_amp": + if base_type == "magnetic": + return np.r_[1.0] + elif base_type == "electric": + return sigma / (2 * np.pi * f * mu_0) + # Validate impedances, tippers and admittances against analytic # solution for a halfspace. CASES_LIST_HALFSPACE = [ - ("impedance", "real"), - ("impedance", "imag"), - ("impedance", "app_res"), - ("impedance", "phase"), - ("tipper", "real"), - ("tipper", "imag"), - ("admittance", "real"), - ("admittance", "imag"), - ("apparent_conductivity", None), + ("impedance", "real", None), + ("impedance", "imag", None), + ("tipper", "real", None), + ("tipper", "imag", None), + ("admittance", "real", None), + ("admittance", "imag", None), + ("det_horizontal", "real", "magnetic"), + ("det_horizontal", "imag", "magnetic"), + ("det_horizontal", "amp", "magnetic"), + ("det_horizontal", "real", "electric"), + ("det_horizontal", "imag", "electric"), + ("det_horizontal", "amp", "electric"), + ("cross_amp", None, "electric"), + ("gram_amp", None, "electric"), + ("cross_amp", None, "magnetic"), + ("gram_amp", None, "magnetic"), ] -@pytest.mark.parametrize("survey_type, component", CASES_LIST_HALFSPACE) +@pytest.mark.parametrize("survey_type, component, base_type", CASES_LIST_HALFSPACE) def test_analytic_halfspace_solution( - survey_type, component, frequencies, locations, mesh, mapping + survey_type, component, base_type, frequencies, locations, mesh, mapping ): + """Analytic halfspace solution tests.""" # Numerical solution - survey = get_survey(locations, frequencies, survey_type, component) + survey = get_survey(locations, frequencies, survey_type, component, base_type) model_hs = get_model(mesh, "halfspace") # 1e-2 halfspace sim = nsem.simulation.Simulation3DPrimarySecondary( mesh, @@ -183,24 +266,89 @@ def test_analytic_halfspace_solution( n_locations = np.shape(locations)[0] analytic_solution = np.hstack( [ - get_analytic_halfspace_solution(sigma_hs, f, survey_type, component) + get_analytic_halfspace_solution( + sigma_hs, f, survey_type, component, base_type + ) for f in frequencies ] ) analytic_solution = np.repeat(analytic_solution, n_locations) - # # Error - err = np.abs( - (numeric_solution - analytic_solution) / (analytic_solution + ABS_TOLERANCE) + if ( + (survey_type == "det_horizontal") + & (component == "real") + & (base_type == "electric") + ): + np.testing.assert_array_less( + np.abs(numeric_solution), np.abs(analytic_solution) + ) + else: + np.testing.assert_allclose( + analytic_solution, numeric_solution, rtol=REL_TOLERANCE, atol=ABS_TOLERANCE + ) + + +CASES_LIST_CROSSCHECK = [ + ("gram_amp", "root_gram_determinant"), + ("cross_amp", "cross_product_amplitude"), + ("det_horizontal", "horizontal_determinant"), +] + + +# PRIMARY-SECONDARY DOESN'T SEEM TO WORK UNLESS THE PADDING IS EXTREME. +@pytest.mark.parametrize("survey_type, component", CASES_LIST_CROSSCHECK) +def test_apparent_conductivity_crosscheck( + survey_type, component, frequencies, locations, mesh, mapping +): + """Cross check test for apparent conductivity data.""" + # Numerical solution + survey_1 = get_survey( + locations, + frequencies, + "apparent_conductivity", + component, + None, + ) + survey_2 = get_survey(locations, frequencies, survey_type, "amp", "electric") + + model_block = get_model(mesh, "block") + model_hs = get_model(mesh, "halfspace") # 1e-2 halfspace + + sim_1 = nsem.simulation.Simulation3DPrimarySecondary( + mesh, + survey=survey_1, + sigmaPrimary=model_hs, + sigmaMap=mapping, + solver=get_default_solver(), + ) + sim_2 = nsem.simulation.Simulation3DPrimarySecondary( + mesh, + survey=survey_2, + sigmaPrimary=model_hs, + sigmaMap=mapping, + solver=get_default_solver(), ) - assert np.all(err < REL_TOLERANCE) + dpred_1 = sim_1.dpred(model_block) + + alpha = 2 * np.pi * np.kron(frequencies, np.ones(len(locations))) * mu_0 + dpred_2 = alpha * sim_2.dpred(model_block) + + np.testing.assert_allclose( + dpred_1, dpred_2, rtol=REL_TOLERANCE_2, atol=ABS_TOLERANCE_2 + ) def test_symmetry_for_appcon(frequencies, locations, mesh, mapping): """Test the app con is symmetric across the y-axis.""" # Numerical solution - survey = get_survey(locations, frequencies, "apparent_conductivity", None) + survey = get_survey( + locations, + frequencies, + "apparent_conductivity", + "cross_product_amplitude", + None, + ) model_hs = get_model(mesh, "halfspace") # 1e-2 halfspace model_block = get_model(mesh, "block") sim = nsem.simulation.Simulation3DPrimarySecondary( diff --git a/tests/em/nsem/forward/test_fields_1d_vs_propagator_pytest.py b/tests/em/nsem/forward/test_fields_1d_vs_propagator_pytest.py new file mode 100644 index 0000000000..da71011503 --- /dev/null +++ b/tests/em/nsem/forward/test_fields_1d_vs_propagator_pytest.py @@ -0,0 +1,135 @@ +""" +Test NSEM solutions against propagator solution. +""" + +import re +import pytest +from scipy.constants import mu_0 +import numpy as np +from discretize import TensorMesh +from simpeg.electromagnetics.natural_source.utils import ( + primary_e_1d_solution, + primary_h_1d_solution, + getEHfields, +) +from simpeg import maps + +REL_TOLERANCE = 0.05 +ABS_TOLERANCE = 1e-5 + + +@pytest.fixture +def mesh(): + """Mesh for testing.""" + hz = 5 + nc = 500 + npad = 30 + pf = 1.1 + mesh = TensorMesh([[(hz, npad, -pf), (hz, nc), (hz, npad)]], "N") + mesh.x0 = -np.r_[mesh.h[0][: npad + 1].sum()] - 2000 + return mesh + + +@pytest.fixture +def mapping(mesh): + """Return mapping.""" + return maps.IdentityMap(mesh) + + +def get_model(mesh, model_type): + """Model used for testing.""" + model = 1e-8 * np.ones(mesh.nC) + model[mesh.cell_centers < 0.0] = 1e-2 + + if model_type == "layer": + model[mesh.cell_centers < -1000.0] = 1e-1 + + return model + + +CASES_LIST_HALFSPACE = [ + ("e", "dirichlet", "dirichlet"), + ("e", "dirichlet", "robin"), + ("e", "neumann", "dirichlet"), + ("e", "neumann", "robin"), + ("h", "dirichlet", "dirichlet"), + ("h", "dirichlet", "robin"), + ("h", "neumann", "dirichlet"), + ("h", "neumann", "robin"), +] + + +@pytest.mark.parametrize("solution_type, top_bc, bot_bc", CASES_LIST_HALFSPACE) +def test_propagator_fv1d_crosscheck(solution_type, top_bc, bot_bc, mesh, mapping): + """Validate 1d fields against propagator solution.""" + sig_1d = get_model(mesh, "halfspace") + freq = 100.0 + + # Propagator solution on nodes + Ed, Eu, Hd, Hu = getEHfields( + mesh, sig_1d, freq, mesh.nodes, scaleUD=True, scaleValue=1 + ) + + if solution_type == "e": + u1 = primary_e_1d_solution(mesh, sig_1d, freq, top_bc, bot_bc, 500) + if top_bc == "dirichlet": + u0 = Ed + Eu + u0 /= u0[-1] + elif top_bc == "neumann": + u0 = Hd + Hu + u0 /= u0[-1] + u0 = mesh.average_node_to_cell @ u0 + + u1 = mesh.nodal_gradient @ u1 + u1 /= -1.0j * 2 * np.pi * freq * mu_0 + + elif solution_type == "h": + u1 = primary_h_1d_solution(mesh, sig_1d, freq, top_bc, bot_bc, 500) + if top_bc == "dirichlet": + u0 = Hd + Hu + u0 /= u0[-1] + elif top_bc == "neumann": + u0 = Ed + Eu + u0 /= u0[-1] + u0 = mesh.average_node_to_cell @ u0 + + u1 = mesh.nodal_gradient @ u1 + u1 /= sig_1d + + np.testing.assert_allclose( + np.real(u1), np.real(u0), rtol=REL_TOLERANCE, atol=ABS_TOLERANCE + ) + np.testing.assert_allclose( + np.imag(u1), np.imag(u0), rtol=REL_TOLERANCE, atol=ABS_TOLERANCE + ) + + +@pytest.mark.parametrize( + "primary_solution_func", (primary_e_1d_solution, primary_h_1d_solution) +) +class TestErrors: + """ + Test errors raised by ``primary_e_1d_solution`` and ``primary_h_1d_solution``. + """ + + def test_invalid_top_bc(self, mesh, primary_solution_func): + sig_1d = get_model(mesh, "halfspace") + top_bc = "invalid bc" + msg = re.escape(f"Invalid 'top_bc' equal to '{top_bc}'") + with pytest.raises(ValueError, match=msg): + primary_solution_func(mesh, sigma_1d=sig_1d, freq=100, top_bc=top_bc) + + def test_invalid_bottom_bc(self, mesh, primary_solution_func): + sig_1d = get_model(mesh, "halfspace") + bottom_bc = "invalid bc" + msg = re.escape(f"Invalid 'bot_bc' equal to '{bottom_bc}'") + with pytest.raises(ValueError, match=msg): + primary_solution_func(mesh, sigma_1d=sig_1d, freq=100, bot_bc=bottom_bc) + + def test_invalid_sigma_size(self, mesh, primary_solution_func): + invalid_sigma = np.ones(3) + msg = re.escape( + "Number of cells in vertical direction must match length of 'sigma_1d'." + ) + with pytest.raises(ValueError, match=msg): + primary_solution_func(mesh, sigma_1d=invalid_sigma, freq=100) diff --git a/tests/em/nsem/forward/test_scalar_rho.py b/tests/em/nsem/forward/test_scalar_rho.py new file mode 100644 index 0000000000..f4a92ff623 --- /dev/null +++ b/tests/em/nsem/forward/test_scalar_rho.py @@ -0,0 +1,39 @@ +""" +The magnetic field simulations accept a scalar resistivity (or conductivity). +""" + +import numpy as np +import pytest +import discretize + +from simpeg.electromagnetics import natural_source as nsem +from simpeg.utils import get_default_solver + + +@pytest.mark.parametrize("dim", [1, 2]) +@pytest.mark.parametrize("prop", ["rho", "sigma"]) +def test_scalar_matches_array(dim, prop): + if dim == 1: + mesh = discretize.TensorMesh([np.full(30, 100.0)], "N") + sim_class = nsem.Simulation1DMagneticField + rx = nsem.receivers.Impedance([[0.0]], orientation="xy", component="app_res") + elif dim == 2: + mesh = discretize.TensorMesh([np.full(10, 100.0), np.full(30, 100.0)], "CN") + sim_class = nsem.Simulation2DMagneticField + rx = nsem.receivers.Impedance( + np.array([[0.0, 0.0]]), orientation="yx", component="app_res" + ) + else: # pragma: nocover + raise ValueError() + value = 100.0 if prop == "rho" else 0.01 + sources = [nsem.sources.Planewave([rx], f) for f in (1.0, 10.0)] + d = [ + sim_class( + mesh, + survey=nsem.Survey(sources), + solver=get_default_solver(), + **{prop: v}, + ).dpred() + for v in (value, np.full(mesh.n_cells, value)) + ] + np.testing.assert_allclose(d[0], d[1]) diff --git a/tests/em/nsem/forward/test_sources_sigma_primary.py b/tests/em/nsem/forward/test_sources_sigma_primary.py new file mode 100644 index 0000000000..a7c886827d --- /dev/null +++ b/tests/em/nsem/forward/test_sources_sigma_primary.py @@ -0,0 +1,20 @@ +""" +Tests for the primary conductivity of the NSEM plane wave sources. +""" + +import numpy as np +import discretize + +from simpeg.electromagnetics import natural_source as nsem + + +def test_scalar_sigma_primary(): + h = [(100.0, 3, -1.5), (100.0, 6), (100.0, 3, 1.5)] + mesh = discretize.TensorMesh([h, h, h], "CCC") + survey = nsem.survey.Survey([nsem.sources.PlanewaveXYPrimary([], 1.0)]) + sim = nsem.simulation.Simulation3DPrimarySecondary( + mesh, survey=survey, sigma=1e-2, sigmaPrimary=1e-2 + ) + sigma_1d, sigma_p = survey.source_list[0]._get_sigmas(sim) + np.testing.assert_allclose(sigma_1d, 1e-2) + np.testing.assert_allclose(sigma_p, 1e-2) diff --git a/tests/em/nsem/inversion/test_NSEM_2D_jvecjtvecadj_pytest.py b/tests/em/nsem/inversion/test_NSEM_2D_jvecjtvecadj_pytest.py index e93aee6089..f9697bc075 100644 --- a/tests/em/nsem/inversion/test_NSEM_2D_jvecjtvecadj_pytest.py +++ b/tests/em/nsem/inversion/test_NSEM_2D_jvecjtvecadj_pytest.py @@ -8,7 +8,7 @@ from simpeg.utils import model_builder from simpeg.electromagnetics import natural_source as nsem -ADJ_RTOL = 1e-5 +ADJ_RTOL = 2e-5 @pytest.fixture @@ -34,13 +34,6 @@ def mapping(mesh, active_cells): ) -@pytest.fixture -def sigma_hs(mesh, active_cells): - sigma_hs = 1e-8 * np.ones(mesh.nC) - sigma_hs[active_cells] = 1e1 - return sigma_hs - - @pytest.fixture def locations(): # Receiver locations @@ -110,6 +103,9 @@ def get_survey(survey_type, orientation, components, locations, frequencies): ("impedance", "yx", ["app_res"]), ("impedance", "xy", ["phase"]), ("impedance", "yx", ["phase"]), + ("admittance", "xy", ["real", "imag"]), + ("admittance", "yx", ["real", "imag"]), + ("tipper", "zx", ["real", "imag"]), ] @@ -125,18 +121,23 @@ def get_setup_objects( mesh, active_cells, mapping, - sigma_hs, ): survey = get_survey( survey_type, orientation, components, locations, frequencies ) # Define the simulation - if orientation in ["xy", "zy"]: + if (orientation == "xy" and survey_type == "impedance") or ( + orientation == "yx" and survey_type == "admittance" + ): sim = nsem.simulation.Simulation2DElectricField( mesh, survey=survey, sigmaMap=mapping ) - elif orientation in ["yx", "zx"]: + elif ( + (orientation == "yx" and survey_type == "impedance") + or (orientation == "xy" and survey_type == "admittance") + or (orientation == "zx" and survey_type == "tipper") + ): sim = nsem.simulation.Simulation2DMagneticField( mesh, survey=survey, sigmaMap=mapping ) @@ -170,7 +171,6 @@ def test_misfit( mesh, active_cells, mapping, - sigma_hs, ): m0, dmis = self.get_setup_objects( survey_type, @@ -181,7 +181,6 @@ def test_misfit( mesh, active_cells, mapping, - sigma_hs, ) sim = dmis.simulation @@ -205,7 +204,6 @@ def test_adjoint( mesh, active_cells, mapping, - sigma_hs, ): m0, dmis = self.get_setup_objects( survey_type, @@ -216,7 +214,6 @@ def test_adjoint( mesh, active_cells, mapping, - sigma_hs, ) sim = dmis.simulation n_data = sim.survey.nD diff --git a/tests/em/nsem/inversion/test_NSEM_3D_jvecjtvecadj_pytest.py b/tests/em/nsem/inversion/test_NSEM_3D_jvecjtvecadj_pytest.py index 7462997f03..5e7163ed7c 100644 --- a/tests/em/nsem/inversion/test_NSEM_3D_jvecjtvecadj_pytest.py +++ b/tests/em/nsem/inversion/test_NSEM_3D_jvecjtvecadj_pytest.py @@ -1,18 +1,18 @@ +"""Derivative and adjoint tests for 3D simulations.""" + import pytest import numpy as np from discretize import TensorMesh, tests -from simpeg import ( - maps, - data_misfit, -) +from simpeg import maps, data_misfit from simpeg.utils import mkvc, model_builder, get_default_solver from simpeg.electromagnetics import natural_source as nsem -ADJ_RTOL = 1e-10 +ADJ_RTOL = 1e-8 @pytest.fixture def mesh(): + """Return test mesh.""" return TensorMesh( [ [(200, 6, -1.5), (200.0, 4), (200, 6, 1.5)], @@ -25,26 +25,21 @@ def mesh(): @pytest.fixture def active_cells(mesh): + """Return active cells.""" return mesh.cell_centers[:, 2] < 0.0 @pytest.fixture def mapping(mesh, active_cells): + """Return mapping.""" return maps.InjectActiveCells(mesh, active_cells, 1e-8) * maps.ExpMap( nP=np.sum(active_cells) ) -@pytest.fixture -def sigma_hs(mesh, active_cells): - sigma_hs = 1e-8 * np.ones(mesh.nC) - sigma_hs[active_cells] = 1e1 - return sigma_hs - - @pytest.fixture def locations(): - # Receiver locations + """Return receiver locations.""" elevation = 0.0 rx_x, rx_y = np.meshgrid(np.arange(-350, 350, 200), np.arange(-350, 350, 200)) return np.hstack( @@ -54,11 +49,20 @@ def locations(): @pytest.fixture def frequencies(): - # Frequencies being evaluated + """Return frequencies.""" return [1e-1, 2e-1] +@pytest.fixture +def sigma_hs(mesh, active_cells): + """Return background conductivity.""" + sigma_hs = 1e-8 * np.ones(mesh.nC) + sigma_hs[active_cells] = 1e1 + return sigma_hs + + def get_survey(survey_type, orientations, components, locations, frequencies): + """Return test survey.""" if not isinstance(orientations, list): orientations = [orientations] @@ -105,7 +109,8 @@ def get_survey(survey_type, orientations, components, locations, frequencies): rx_list.extend( [ nsem.receivers.Admittance( - locations, + locations_h=locations, + locations_e=np.zeros_like(locations), orientation=orient, component=comp, ) @@ -115,7 +120,47 @@ def get_survey(survey_type, orientations, components, locations, frequencies): # MobileMT is app_cond elif survey_type == "apparent_conductivity": - rx_list.extend([nsem.receivers.ApparentConductivity(locations)]) + rx_list.extend( + [ + nsem.receivers.ApparentConductivity( + locations_h=locations, + locations_e=np.zeros_like(locations), + formula=components[0], + ) + ] + ) + + # Horizontal determinanet + elif survey_type == "det_horizontal": + rx_list = [ + nsem.receivers.HorizontalDeterminant( + locations_h=locations, + locations_base=np.zeros_like(locations), + base_type=orientations[0], + component=comp, + ) + for comp in components + ] + + # Determinant ampliutde of the Gram matrix + elif survey_type == "gram_amp": + rx_list = [ + nsem.receivers.RootGramDeterminant( + locations, + locations_base=np.zeros_like(locations), + base_type=orientations[0], + ) + ] + + # Determinant amplitude of the cross product + elif survey_type == "cross_amp": + rx_list = [ + nsem.receivers.CrossProductAmplitude( + locations, + locations_base=np.zeros_like(locations), + base_type=orientations[0], + ) + ] source_list.append(nsem.sources.PlanewaveXYPrimary(rx_list, f)) @@ -134,12 +179,22 @@ def get_survey(survey_type, orientations, components, locations, frequencies): ("admittance", ["xy", "yx"], ["real", "imag"]), ("admittance", ["xx", "yy"], ["real", "imag"]), ("admittance", ["zx", "zy"], ["real", "imag"]), - ("apparent_conductivity", None, None), + ("cross_amp", "electric", None), + ("cross_amp", "magnetic", None), + ("gram_amp", "electric", None), + ("gram_amp", "magnetic", None), + ("det_horizontal", "electric", ["real", "imag", "amp"]), + ("det_horizontal", "magnetic", ["real", "imag", "amp"]), + ("apparent_conductivity", None, "root_gram_determinant"), + ("apparent_conductivity", None, "cross_product_amplitude"), + ("apparent_conductivity", None, "horizontal_determinant"), ] @pytest.mark.parametrize("survey_type, orientations, components", CASES_LIST) class TestDerivatives: + """Perform derivative convergence test.""" + def get_setup_objects( self, survey_type, @@ -152,6 +207,7 @@ def get_setup_objects( mapping, sigma_hs, ): + """Get test objections.""" survey = get_survey( survey_type, orientations, components, locations, frequencies ) @@ -196,6 +252,7 @@ def test_misfit( mapping, sigma_hs, ): + """Test data misfit.""" m0, dmis = self.get_setup_objects( survey_type, orientations, @@ -231,6 +288,7 @@ def test_adjoint( mapping, sigma_hs, ): + """Perform adjoint test.""" m0, dmis = self.get_setup_objects( survey_type, orientations, diff --git a/tests/em/nsem/inversion/test_Problem1D_Adjoint.py b/tests/em/nsem/inversion/test_Problem1D_Adjoint.py index 28449e0395..53a3cbc851 100644 --- a/tests/em/nsem/inversion/test_Problem1D_Adjoint.py +++ b/tests/em/nsem/inversion/test_Problem1D_Adjoint.py @@ -1,108 +1,120 @@ +"""Adjoint tests for 1D simulations.""" + import numpy as np -import unittest from scipy.constants import mu_0 - from simpeg.electromagnetics import natural_source as nsem from simpeg import maps - +import pytest TOL = 1e-4 -FLR = 1e-20 # "zero", so if residual below this --> pass regardless of order +FLR = 1e-20 CONDUCTIVITY = 1e1 MU = mu_0 -def JvecAdjointTest_1D(sigmaHalf, formulation="PrimSec"): - # Frequencies being measured - frequencies = np.logspace(0, 4, 21) - - # Define a receiver for each data type as a list - receivers_list = [ - nsem.receivers.Impedance([[]], component="real"), - nsem.receivers.Impedance([[]], component="imag"), - nsem.receivers.Impedance([[]], component="app_res"), - nsem.receivers.Impedance([[]], component="phase"), +# --- Fixtures --- +@pytest.fixture +def frequencies(): + """Return test frequencies.""" + return np.logspace(0, 4, 21) + + +@pytest.fixture +def receivers_list(): + """Generate receivers list.""" + return [ + nsem.receivers.Impedance([[]], component="real", orientation="xy"), + nsem.receivers.Impedance([[]], component="imag", orientation="xy"), + nsem.receivers.Impedance([[]], component="app_res", orientation="xy"), + nsem.receivers.Impedance([[]], component="phase", orientation="xy"), + nsem.receivers.Impedance([[]], component="real", orientation="yx"), + nsem.receivers.Impedance([[]], component="imag", orientation="yx"), + nsem.receivers.Impedance([[]], component="app_res", orientation="yx"), + nsem.receivers.Impedance([[]], component="phase", orientation="yx"), ] - # Use a list to define the planewave source at each frequency and assign receivers - source_list = [] - for ii in range(0, len(frequencies)): - source_list.append(nsem.sources.Planewave(receivers_list, frequencies[ii])) - # Define the survey object - survey = nsem.survey.Survey(source_list) +@pytest.fixture +def survey_1d(frequencies, receivers_list): + """Generate 1D survey.""" + source_list = [nsem.sources.Planewave(receivers_list, f) for f in frequencies] + return nsem.survey.Survey(source_list) - # Layer thicknesses - layer_thicknesses = np.array([200, 100]) - # Layer conductivities +@pytest.fixture +def simulation_recursive(survey_1d): + """Set up recursive 1D simulation.""" + layer_thicknesses = np.array([200, 100]) sigma_model = np.array([0.001, 0.01, 0.1]) - # Define a mapping for conductivities, thicknesses mapping = maps.Wires(("sigma", 3), ("thicknesses", 2)) - simulation = nsem.simulation_1d.Simulation1DRecursive( - survey=survey, + sim = nsem.simulation_1d.Simulation1DRecursive( + survey=survey_1d, sigmaMap=mapping.sigma, thicknessesMap=mapping.thicknesses, ) m = np.r_[sigma_model, layer_thicknesses] - u = simulation.fields(m) + u = sim.fields(m) - rng = np.random.default_rng(seed=1983) - v = rng.uniform(size=survey.nD) - w = rng.uniform(size=len(m)) + return sim, m, u - vJw = v.dot(simulation.Jvec(m, w, u)) - wJtv = w.dot(simulation.Jtvec(m, v, u)) - tol = np.max([TOL * (10 ** int(np.log10(np.abs(vJw)))), FLR]) - print(" vJw wJtv vJw - wJtv tol abs(vJw - wJtv) < tol") - print(vJw, wJtv, vJw - wJtv, tol, np.abs(vJw - wJtv) < tol) - return np.abs(vJw - wJtv) < tol +@pytest.fixture +def primary_secondary_setup(): + """Set up primary-secondary simulation.""" + survey, sigma, sigBG, mesh = nsem.utils.test_utils.setup1DSurvey( + 1e-2, tD=False, structure=False + ) -def JvecAdjointTest(sigmaHalf, formulation="PrimSec"): - forType = "PrimSec" not in formulation - survey, sigma, sigBG, m1d = nsem.utils.test_utils.setup1DSurvey( - sigmaHalf, tD=forType, structure=False + sim = nsem.Simulation1DPrimarySecondary( + mesh, + survey=survey, + sigmaPrimary=sigBG, + sigmaMap=maps.IdentityMap(mesh), ) - print("Adjoint test of e formulation for {:s} comp \n".format(formulation)) - - if "PrimSec" in formulation: - problem = nsem.Simulation1DPrimarySecondary( - m1d, survey=survey, sigmaPrimary=sigBG, sigmaMap=maps.IdentityMap(m1d) - ) - else: - raise NotImplementedError( - "Only {} formulations are implemented.".format(formulation) - ) + m = sigma - u = problem.fields(m) + u = sim.fields(m) + + return sim, m, u, survey + + +# --- Tests --- +def test_JvecAdjoint_All(primary_secondary_setup): + """Test adjoint all.""" + simulation, m, u, survey = primary_secondary_setup rng = np.random.default_rng(seed=1983) v = rng.uniform(size=survey.nD) - # print problem.PropMap.PropModel.nP - w = rng.uniform(size=problem.mesh.nC) + w = rng.uniform(size=simulation.mesh.nC) + + vJw = v.ravel().dot(simulation.Jvec(m, w, u)) + wJtv = w.ravel().dot(simulation.Jtvec(m, v, u)) - vJw = v.ravel().dot(problem.Jvec(m, w, u)) - wJtv = w.ravel().dot(problem.Jtvec(m, v, u)) tol = np.max([TOL * (10 ** int(np.log10(np.abs(vJw)))), FLR]) + print(" vJw wJtv vJw - wJtv tol abs(vJw - wJtv) < tol") print(vJw, wJtv, vJw - wJtv, tol, np.abs(vJw - wJtv) < tol) - return np.abs(vJw - wJtv) < tol + + np.testing.assert_allclose(vJw, wJtv, atol=TOL) -class NSEM_1D_AdjointTests(unittest.TestCase): - def setUp(self): - pass +def test_JvecAdjoint_All_1D(simulation_recursive): + """Test adjoint for 1D recursie.""" + simulation, m, u = simulation_recursive - def test_JvecAdjoint_All(self): - self.assertTrue(JvecAdjointTest(1e-2)) + rng = np.random.default_rng(seed=1983) + v = rng.uniform(size=simulation.survey.nD) + w = rng.uniform(size=len(m)) + + vJw = v.dot(simulation.Jvec(m, w, u)) + wJtv = w.dot(simulation.Jtvec(m, v, u)) - def test_JvecAdjoint_All_1D(self): - self.assertTrue(JvecAdjointTest_1D(1e-2)) + tol = np.max([TOL * (10 ** int(np.log10(np.abs(vJw)))), FLR]) + print(" vJw wJtv vJw - wJtv tol abs(vJw - wJtv) < tol") + print(vJw, wJtv, vJw - wJtv, tol, np.abs(vJw - wJtv) < tol) -if __name__ == "__main__": - unittest.main() + np.testing.assert_allclose(vJw, wJtv, atol=TOL) diff --git a/tests/em/nsem/inversion/test_Problem1D_Derivs.py b/tests/em/nsem/inversion/test_Problem1D_Derivs.py index de11c736b4..12b2a33e4a 100644 --- a/tests/em/nsem/inversion/test_Problem1D_Derivs.py +++ b/tests/em/nsem/inversion/test_Problem1D_Derivs.py @@ -1,92 +1,113 @@ -import unittest +"""Test derivatives for 1D simulations.""" + import numpy as np from scipy.constants import mu_0 from simpeg import maps, tests from simpeg.electromagnetics import natural_source as nsem +import pytest TOL = 1e-4 -FLR = 1e-20 # "zero", so if residual below this --> pass regardless of order +FLR = 1e-20 CONDUCTIVITY = 1e1 MU = mu_0 -def DerivJvecTest_1D(halfspace_value, freq=False, expMap=True): - # Frequencies being measured - frequencies = np.logspace(0, 4, 21) - - # Define a receiver for each data type as a list - receivers_list = [ - nsem.receivers.Impedance([[]], component="real"), - nsem.receivers.Impedance([[]], component="imag"), - nsem.receivers.Impedance([[]], component="app_res"), - nsem.receivers.Impedance([[]], component="phase"), +# --- Fixtures --- +@pytest.fixture +def frequencies(): + """Return test frequencies.""" + return np.logspace(0, 4, 21) + + +@pytest.fixture +def receivers_list(): + """Return test receivers list.""" + return [ + nsem.receivers.Impedance([[]], component="real", orientation="xy"), + nsem.receivers.Impedance([[]], component="imag", orientation="xy"), + nsem.receivers.Impedance([[]], component="app_res", orientation="xy"), + nsem.receivers.Impedance([[]], component="phase", orientation="xy"), + nsem.receivers.Impedance([[]], component="real", orientation="yx"), + nsem.receivers.Impedance([[]], component="imag", orientation="yx"), + nsem.receivers.Impedance([[]], component="app_res", orientation="yx"), + nsem.receivers.Impedance([[]], component="phase", orientation="yx"), ] - # Use a list to define the planewave source at each frequency and assign receivers - source_list = [] - for ii in range(0, len(frequencies)): - source_list.append(nsem.sources.Planewave(receivers_list, frequencies[ii])) - # Define the survey object - survey = nsem.survey.Survey(source_list) - - # Layer thicknesses - layer_thicknesses = np.array([200, 100]) +@pytest.fixture +def survey_1d(frequencies, receivers_list): + """Generate 1D survey.""" + source_list = [nsem.sources.Planewave(receivers_list, f) for f in frequencies] + return nsem.survey.Survey(source_list) - # Layer conductivities - sigma_model = np.array([0.001, 0.01, 0.1]) - # Define a mapping for conductivities +@pytest.fixture +def simulation_recursive(survey_1d): + """Simulate data with recursie solution.""" + layer_thicknesses = np.array([200, 100]) mapping = maps.Wires(("sigma", 3), ("thicknesses", 2)) - simulation = nsem.simulation_1d.Simulation1DRecursive( - survey=survey, + sim = nsem.simulation_1d.Simulation1DRecursive( + survey=survey_1d, sigmaMap=mapping.sigma, thicknessesMap=mapping.thicknesses, ) + sigma_model = np.array([0.001, 0.01, 0.1]) x0 = np.r_[sigma_model, layer_thicknesses] - def fun(x): - return simulation.dpred(x), lambda x: simulation.Jvec(x0, x) - - return tests.check_derivative( - fun, x0, num=6, plotIt=False, eps=FLR, random_seed=298376 - ) + return sim, x0 -def DerivJvecTest(halfspace_value, freq=False, expMap=True): +@pytest.fixture +def primary_secondary_setup(): + """Set up primary-secondary simulation.""" survey, sig, sigBG, mesh = nsem.utils.test_utils.setup1DSurvey( - halfspace_value, False, structure=True + 1e-2, False, structure=True ) - simulation = nsem.Simulation1DPrimarySecondary( - mesh, sigmaPrimary=sigBG, sigmaMap=maps.IdentityMap(mesh), survey=survey - ) - print("Using {0} solver for the simulation".format(simulation.solver)) - print( - "Derivative test of Jvec for eForm primary/secondary for 1d comp from {0} to {1} Hz\n".format( - survey.frequencies[0], survey.frequencies[-1] - ) + + sim = nsem.Simulation1DPrimarySecondary( + mesh, + sigmaPrimary=sigBG, + sigmaMap=maps.IdentityMap(mesh), + survey=survey, ) - x0 = sigBG - survey = simulation.survey + return sim, sigBG + + +# --- Tests --- +def test_derivJvec_Z1d_e(simulation_recursive): + """Test formulation derivative.""" + simulation, x0 = simulation_recursive def fun(x): - return simulation.dpred(x), lambda x: simulation.Jvec(x0, x) + return simulation.dpred(x), lambda v: simulation.Jvec(x0, v) - return tests.check_derivative( - fun, x0, num=4, plotIt=False, eps=FLR, random_seed=5553 + result = tests.check_derivative( + fun, x0, num=6, plotIt=False, eps=FLR, random_seed=298376 ) + assert result -class NSEM_DerivTests(unittest.TestCase): - def test_derivJvec_Z1dr(self): - self.assertTrue(DerivJvecTest(1e-2)) - def test_derivJvec_Z1d_e(self): - self.assertTrue(DerivJvecTest_1D(1e-2)) +def test_derivJvec_Z1dr(primary_secondary_setup): + """Test other formulation derivative.""" + simulation, x0 = primary_secondary_setup + + survey = simulation.survey + print(f"Using {simulation.solver} solver for the simulation") + print( + f"Derivative test of Jvec for eForm primary/secondary for 1d comp " + f"from {survey.frequencies[0]} to {survey.frequencies[-1]} Hz\n" + ) + + def fun(x): + return simulation.dpred(x), lambda v: simulation.Jvec(x0, v) + + result = tests.check_derivative( + fun, x0, num=4, plotIt=False, eps=FLR, random_seed=5553 + ) -if __name__ == "__main__": - unittest.main() + assert result diff --git a/tests/em/nsem/inversion/test_Problem3D_Adjoint.py b/tests/em/nsem/inversion/test_Problem3D_Adjoint.py index eb3ec464a4..86a75d2def 100644 --- a/tests/em/nsem/inversion/test_Problem3D_Adjoint.py +++ b/tests/em/nsem/inversion/test_Problem3D_Adjoint.py @@ -3,7 +3,6 @@ from simpeg.electromagnetics import natural_source as nsem from scipy.constants import mu_0 - TOLr = 5e-2 TOL = 1e-4 FLR = 1e-20 # "zero", so if residual below this --> pass regardless of order diff --git a/tests/em/nsem/inversion/test_Problem3D_Derivs.py b/tests/em/nsem/inversion/test_Problem3D_Derivs.py index 41a99d5ce4..ace3018c6b 100644 --- a/tests/em/nsem/inversion/test_Problem3D_Derivs.py +++ b/tests/em/nsem/inversion/test_Problem3D_Derivs.py @@ -62,7 +62,7 @@ def test_Jmatrix(model_simulation_tuple): # compare to JTvec function jtvec = simulation.Jtvec(model, v=vec) - np.testing.assert_allclose(Jmatrix_vec, jtvec) + np.testing.assert_allclose(Jmatrix_vec, jtvec, atol=1e-10) # Test the Jvec derivative diff --git a/tests/em/nsem/utils/test_source_utils.py b/tests/em/nsem/utils/test_source_utils.py new file mode 100644 index 0000000000..337617e5a4 --- /dev/null +++ b/tests/em/nsem/utils/test_source_utils.py @@ -0,0 +1,22 @@ +""" +Extra test for source utils. +""" + +import re +import pytest +import numpy as np +from discretize import TensorMesh +from simpeg.electromagnetics.natural_source.utils.source_utils import ( + project_1d_fields_to_mesh_edges, +) + + +def test_project_1d_fields_invalid_size(): + """ + Test error after invalid size of 1D solution. + """ + mesh = TensorMesh(h=[[(1.0, 5)]]) + invalid_u_1d = np.ones(2) + msg = re.escape("Found invalid 'u_1d' with '2' elements. ") + with pytest.raises(ValueError, match=msg): + project_1d_fields_to_mesh_edges(mesh, invalid_u_1d) diff --git a/tests/em/static/test_DC_2D_jvecjtvecadj.py b/tests/em/static/test_DC_2D_jvecjtvecadj.py index 83c12bff25..62a5e2576f 100644 --- a/tests/em/static/test_DC_2D_jvecjtvecadj.py +++ b/tests/em/static/test_DC_2D_jvecjtvecadj.py @@ -32,10 +32,12 @@ def setUp(self): A0loc = np.r_[-150, 0.0] A1loc = np.r_[-130, 0.0] # rxloc = [np.c_[M, np.zeros(20)], np.c_[N, np.zeros(20)]] - rx1 = dc.receivers.Dipole(M, N) - rx2 = dc.receivers.Dipole(M, N, data_type="apparent_resistivity") - src0 = dc.sources.Pole([rx1, rx2], A0loc) - src1 = dc.sources.Pole([rx1, rx2], A1loc) + rx1 = dc.receivers.Pole(M) + rx2 = dc.receivers.Pole(M, data_type="apparent_resistivity") + rx3 = dc.receivers.Dipole(M, N) + rx4 = dc.receivers.Dipole(M, N, data_type="apparent_resistivity") + src0 = dc.sources.Pole([rx1, rx2, rx3, rx4], A0loc) + src1 = dc.sources.Dipole([rx1, rx2, rx3, rx4], A0loc, A1loc) survey = dc.survey.Survey([src0, src1]) survey.set_geometric_factor() simulation = getattr(dc, self.formulation)( diff --git a/tests/em/static/test_DC_Boundaries.py b/tests/em/static/test_DC_Boundaries.py index 6bffbbd9ef..032982c28f 100644 --- a/tests/em/static/test_DC_Boundaries.py +++ b/tests/em/static/test_DC_Boundaries.py @@ -5,7 +5,6 @@ import simpeg.electromagnetics.static.resistivity as dc - tens_2d = discretize.TensorMesh([8, 9]) tens_3d = discretize.TensorMesh([8, 9, 10]) tree_2d = discretize.TreeMesh([16, 16]) diff --git a/tests/em/static/test_DC_analytic_edge_face_conductivities.py b/tests/em/static/test_DC_analytic_edge_face_conductivities.py new file mode 100644 index 0000000000..4d43472f32 --- /dev/null +++ b/tests/em/static/test_DC_analytic_edge_face_conductivities.py @@ -0,0 +1,198 @@ +"""Analytic tests for hierarchical electrical properties.""" + +import discretize +import numpy as np +from simpeg.utils import ndgrid +from simpeg import maps +from simpeg.electromagnetics.static import resistivity as dcr + +ABS_TOL = 1e-13 +REL_TOL = 0.08 + + +# ONLY PASSES IN THE LINEAR REGIME +def test_layer_conductance_to_analytic(): + """Validate 1D analytic solution for thin layer against layer as face conductances.""" + # Some static parameters + location_a = np.r_[-20, 0, 0] + locations_m = ndgrid(np.linspace(0, 30, 4), 0, 0) + + layer_depth = 40.0 + layer_thickness = 0.1 + layer_conductivity = 1e0 # Only 1 order of magnitude (linear regime) + background_conductivity = 1e-1 + + tau = layer_thickness * layer_conductivity + + # 1D LAYER MODEL + thicknesses = np.array([layer_depth - layer_thickness / 2, layer_thickness]) + n_layer = len(thicknesses) + 1 + + sigma_1d = background_conductivity * np.ones(n_layer) + sigma_1d[1] = layer_conductivity + + sigma_map_1d = maps.IdentityMap(nP=n_layer) + + # Mesh + dh = 2.5 # base cell width + dom_width = 8000.0 # domain width + nbc = 2 ** int(np.round(np.log(dom_width / dh) / np.log(2.0))) # num. base cells + + h = [(dh, nbc)] + mesh = discretize.TreeMesh([h, h, h], x0="CCN") + pts = np.vstack([locations_m, location_a]) + mesh.refine_points( + pts, + level=-1, + padding_cells_by_level=[8, 6, 6, 6], + finalize=False, + ) + x0s = np.vstack([ii * np.c_[-60, -60, -60] for ii in range(1, 5)]) + x1s = np.vstack([ii * np.c_[60, 60, 10] for ii in range(1, 5)]) + + mesh.refine_box(x0s, x1s, levels=[-2, -3, -4, -5], finalize=False) + mesh.finalize() + + sigma_3d = 1e-8 * np.ones(mesh.nC) + sigma_3d[mesh.cell_centers[:, -1] < 0.0] = background_conductivity + + tau_3d = np.zeros(mesh.nF) + tau_3d[np.isclose(mesh.faces[:, -1], -layer_depth)] = tau + tau_map = maps.IdentityMap(nP=mesh.n_faces) + + # DEFINE SURVEY + rx_list = [dcr.receivers.Pole(locations=locations_m)] + + # 1D SURVEY AND SIMULATION + src_1d = [dcr.sources.Pole(rx_list, location=location_a)] + survey_1d = dcr.survey.Survey(src_1d) + + sim_1d = dcr.Simulation1DLayers( + survey=survey_1d, + thicknesses=thicknesses, + sigmaMap=sigma_map_1d, + ) + + # 3D SURVEY AND SIMULATION + src_3d = [dcr.sources.Pole(rx_list, location=location_a)] + + survey_3d = dcr.Survey(src_3d) + + sim_3d = dcr.simulation.Simulation3DHierarchicalNodal( + mesh=mesh, survey=survey_3d, sigma=sigma_3d, face_conductance_map=tau_map + ) + + # COMPUTE ANOMALY + analytic_solution = sim_1d.dpred(sigma_1d) - sim_1d.dpred( + background_conductivity * np.ones(3) + ) + numeric_solution = sim_3d.dpred(tau_3d) - sim_3d.dpred(np.zeros_like(tau_3d)) + + np.testing.assert_allclose( + numeric_solution, analytic_solution, atol=ABS_TOL, rtol=REL_TOL + ) + + +def test_edge_conductivity(): + """Cross check for a thin conductive wire.""" + # Some static parameters + location_a = np.r_[-40, 0, 0] + location_b = np.r_[40, 0, 0] + locations_m = ndgrid(np.linspace(-20, 20, 5), 0, 8) + + wire_depth = 16.0 + wire_width = 1.0 + wire_length = 20.0 + wire_conductivity = 1e0 # Only 1 order of magnitude (linear regime + background_conductivity = 1e-1 + + kappa_value = wire_width**2 * wire_conductivity + + # Mesh + dh = 0.25 # base cell width + dom_width = 2000.0 # domain width + nbc = 2 ** int(np.round(np.log(dom_width / dh) / np.log(2.0))) # num. base cells + + h = [(dh, nbc)] + mesh = discretize.TreeMesh([h, h, h], x0="CCN") + + pts = ndgrid( + np.arange(-wire_length / 2, wire_length / 2 + 1e-6, dh), 0, -wire_depth + ) + mesh.refine_points( + pts, + level=-1, + padding_cells_by_level=[6, 6, 6, 8], + finalize=False, + ) + + pts = np.vstack([locations_m, location_a, location_b]) + mesh.refine_points( + pts, + level=-2, + padding_cells_by_level=[6, 6, 6, 6], + finalize=False, + ) + x0s = np.vstack([ii * np.c_[-60, -60, -30] for ii in range(1, 5)]) + x1s = np.vstack([ii * np.c_[60, 60, 10] for ii in range(1, 5)]) + + mesh.refine_box(x0s, x1s, levels=[-5, -6, -7, -8], finalize=False) + mesh.finalize() + print(mesh.n_cells) + + # Models + ccs = mesh.cell_centers + sigma_0 = 1e-8 * np.ones(mesh.n_cells) + sigma_0[ccs[:, -1] < 0.0] = background_conductivity + + sigma_voxel = sigma_0.copy() + inds_block = ( + (np.abs(ccs[:, 0]) <= wire_length / 2) + & (np.abs(ccs[:, 1]) <= wire_width / 2) + & (np.abs(ccs[:, 2] + wire_depth) <= wire_width / 2) + ) + sigma_voxel[inds_block] = wire_conductivity + print(sum(inds_block)) + + kappa = np.zeros(mesh.n_edges) + edges = mesh.edges + inds_kappa = ( + (np.abs(edges[:, 0]) <= wire_length / 2) + & (np.isclose(edges[:, 1], 0.0)) + & (np.isclose(edges[:, 2], -wire_depth)) + ) + kappa[inds_kappa] = kappa_value + print(sum(inds_kappa)) + + # DEFINE SURVEY + rx_sigma = dcr.receivers.Pole(locations=locations_m) + rx_kappa = dcr.receivers.Pole(locations=locations_m) + + src_sigma = dcr.sources.Dipole( + [rx_sigma], location_a=location_a, location_b=location_b + ) + src_kappa = dcr.sources.Dipole( + [rx_kappa], location_a=location_a, location_b=location_b + ) + + survey_sigma = dcr.Survey([src_sigma]) + survey_kappa = dcr.Survey([src_kappa]) + + sim_sigma = dcr.simulation.Simulation3DNodal( + mesh=mesh, survey=survey_sigma, sigmaMap=maps.IdentityMap(nP=mesh.n_cells) + ) + sim_kappa = dcr.simulation.Simulation3DHierarchicalNodal( + mesh=mesh, + survey=survey_kappa, + sigma=sigma_0, + edge_area_conductance_map=maps.IdentityMap(nP=mesh.n_edges), + ) + + # COMPUTE SOLUTIONS + dpred_0 = sim_sigma.dpred(sigma_0) + true_solution = sim_sigma.dpred(sigma_voxel) - dpred_0 + approx_solution = sim_kappa.dpred(kappa) - dpred_0 + + np.testing.assert_allclose( + true_solution, approx_solution, atol=ABS_TOL, rtol=REL_TOL + ) diff --git a/tests/em/static/test_DC_jvecjtvecadj.py b/tests/em/static/test_DC_jvecjtvecadj.py index c99cb4e274..312d8d68bc 100644 --- a/tests/em/static/test_DC_jvecjtvecadj.py +++ b/tests/em/static/test_DC_jvecjtvecadj.py @@ -13,9 +13,9 @@ ) from simpeg.utils import mkvc from simpeg.electromagnetics import resistivity as dc +from simpeg.electromagnetics.static import utils as static_utils import shutil - TOL = 1e-5 FLR = 1e-20 # "zero", so if residual below this --> pass regardless of order @@ -38,7 +38,27 @@ def setUp(self): ) source_list = dc.utils.WennerSrcList(nElecs, aSpacing, in2D=True) + # Make sure it actually generated sources + assert len(source_list) > 0 + + for survey_type in ["dipole-pole", "pole-dipole", "pole-pole"]: + for data_type in ["volt", "apparent_resistivity"]: + + next_list = static_utils.generate_dcip_sources_line( + survey_type=survey_type, + data_type=data_type, + dimension_type="2D", + end_points=[-surveySize / 2, surveySize / 2], + num_rx_per_src=5, + station_spacing=aSpacing, + topo=0.0, + ) + # Make sure it actually generated sources + assert len(next_list) > 0 + source_list.extend(next_list) survey = dc.survey.Survey(source_list) + survey.set_geometric_factor() + simulation = dc.simulation.Simulation3DCellCentered( mesh=mesh, survey=survey, rhoMap=maps.IdentityMap(mesh) ) @@ -184,7 +204,27 @@ def setUp(self): ) source_list = dc.utils.WennerSrcList(nElecs, aSpacing, in2D=True) + # Make sure it actually generated sources + assert len(source_list) > 0 + + for survey_type in ["dipole-pole", "pole-dipole", "pole-pole"]: + for data_type in ["volt", "apparent_resistivity"]: + + next_list = static_utils.generate_dcip_sources_line( + survey_type=survey_type, + data_type=data_type, + dimension_type="2D", + end_points=[-surveySize / 2, surveySize / 2], + num_rx_per_src=5, + station_spacing=aSpacing, + topo=0.0, + ) + # Make sure it actually generated sources + assert len(next_list) > 0 + source_list.extend(next_list) survey = dc.survey.Survey(source_list) + survey.set_geometric_factor() + simulation = dc.simulation.Simulation3DNodal( mesh=mesh, survey=survey, rhoMap=maps.IdentityMap(mesh) ) diff --git a/tests/em/static/test_DC_jvecjtvecadj_pytest.py b/tests/em/static/test_DC_jvecjtvecadj_pytest.py new file mode 100644 index 0000000000..1cf2fc40de --- /dev/null +++ b/tests/em/static/test_DC_jvecjtvecadj_pytest.py @@ -0,0 +1,346 @@ +"""Derivative and adjoint tests for 3D DC problems.""" + +import numpy as np +import pytest +import discretize +from simpeg import ( + maps, + data_misfit, + regularization, + inversion, + optimization, + inverse_problem, + tests, + utils, +) +from simpeg.utils import mkvc +from simpeg.electromagnetics import resistivity as dc +from simpeg.electromagnetics.static import utils as static_utils +import shutil + +REL_TOL = 1e-5 +ABS_TOL = 1e-20 + + +# ========================= +# Fixtures +# ========================= + + +@pytest.fixture +def base_mesh(): + """Return test mesh.""" + aSpacing = 2.5 + nElecs = 5 + surveySize = nElecs * aSpacing - aSpacing + cs = surveySize / nElecs / 4 + + mesh = discretize.TensorMesh( + [ + [(cs, 10, -1.3), (cs, surveySize / cs), (cs, 10, 1.3)], + [(cs, 3, -1.3), (cs, 3, 1.3)], + ], + "CN", + ) + return mesh, aSpacing, nElecs, surveySize + + +@pytest.fixture(params=["dipole-pole", "pole-dipole", "pole-pole"]) +def survey_type(request): + """Return survey typs.""" + return request.param + + +@pytest.fixture(params=["volt", "apparent_resistivity"]) +def data_type(request): + """Return data type.""" + return request.param + + +@pytest.fixture +def survey(base_mesh, survey_type, data_type): + """Get test survey.""" + mesh, aSpacing, nElecs, surveySize = base_mesh + + source_list = dc.utils.WennerSrcList(nElecs, aSpacing, in2D=True) + assert len(source_list) > 0 + + next_list = static_utils.generate_dcip_sources_line( + survey_type=survey_type, + data_type=data_type, + dimension_type="2D", + end_points=[-surveySize / 2, surveySize / 2], + num_rx_per_src=5, + station_spacing=aSpacing, + topo=0.0, + ) + assert len(next_list) > 0 + + source_list.extend(next_list) + + survey = dc.survey.Survey(source_list) + survey.set_geometric_factor() + return survey + + +@pytest.fixture(params=["cell_centered", "nodal"]) +def simulation(request, base_mesh, survey): + """Get test simulation.""" + mesh, *_ = base_mesh + + if request.param == "cell_centered": + sim = dc.simulation.Simulation3DCellCentered( + mesh=mesh, survey=survey, rhoMap=maps.IdentityMap(mesh) + ) + else: + sim = dc.simulation.Simulation3DNodal( + mesh=mesh, survey=survey, rhoMap=maps.IdentityMap(mesh) + ) + + return sim + + +@pytest.fixture +def inverse_setup(simulation, base_mesh): + """Get setup for inversion.""" + mesh, *_ = base_mesh + + m0 = np.ones(mesh.nC) + dobs = simulation.make_synthetic_data(m0, add_noise=True, random_seed=39) + + dmis = data_misfit.L2DataMisfit(simulation=simulation, data=dobs) + reg = regularization.WeightedLeastSquares(mesh) + + opt = optimization.InexactGaussNewton(maxIterLS=20, maxIter=10, cg_maxiter=6) + + invProb = inverse_problem.BaseInvProblem(dmis, reg, opt, beta=1e4) + inv = inversion.BaseInversion(invProb) + + return { + "simulation": simulation, + "mesh": mesh, + "m0": m0, + "dobs": dobs, + "dmis": dmis, + "inv": inv, + } + + +# ========================= +# Core tests +# ========================= + + +def test_misfit(inverse_setup): + """Test misfit.""" + sim = inverse_setup["simulation"] + m0 = inverse_setup["m0"] + + assert tests.check_derivative( + lambda m: [sim.dpred(m), lambda mx: sim.Jvec(m0, mx)], + m0, + plotIt=False, + num=3, + random_seed=40, + ) + + +def test_adjoint(inverse_setup): + """Test adjoint.""" + sim = inverse_setup["simulation"] + mesh = inverse_setup["mesh"] + m0 = inverse_setup["m0"] + dobs = inverse_setup["dobs"] + + rng = np.random.default_rng(42) + v = rng.uniform(size=mesh.nC) + w = rng.uniform(size=mkvc(dobs).shape[0]) + + wtJv = w.dot(sim.Jvec(m0, v)) + vtJtw = v.dot(sim.Jtvec(m0, w)) + + assert np.abs(wtJv - vtJtw) < 1e-8 + + +def test_dataObj(inverse_setup): + """Test data object.""" + dmis = inverse_setup["dmis"] + m0 = inverse_setup["m0"] + + assert tests.check_derivative( + lambda m: [dmis(m), dmis.deriv(m)], m0, plotIt=False, num=3, random_seed=40 + ) + + +# ========================= +# Fields test (separate) +# ========================= + + +@pytest.fixture +def fields_problem(): + """Get simulation for fields test.""" + cs = 10 + nc = 20 + npad = 10 + + mesh = discretize.CylindricalMesh( + [ + [(cs, nc), (cs, npad, 1.3)], + np.r_[2 * np.pi], + [(cs, npad, -1.3), (cs, nc), (cs, npad, 1.3)], + ] + ) + + mesh.x0 = np.r_[0.0, 0.0, -mesh.h[2][: npad + nc].sum()] + + rx_x = np.linspace(10, 200, 20) + rx_locs = utils.ndgrid([rx_x, np.r_[0], np.r_[-5]]) + + rx_list = [dc.receivers.BaseRx(rx_locs, projField="e", orientation="x")] + + src = dc.sources.Dipole( + rx_list, + location_a=np.r_[0.0, 0.0, -5.0], + location_b=np.r_[55.0, 0.0, -5.0], + ) + + survey = dc.survey.Survey([src]) + + sigma_map = maps.ExpMap(mesh) * maps.InjectActiveCells( + mesh, mesh.gridCC[:, 2] <= 0, np.log(1e-8) + ) + + prob = dc.simulation.Simulation3DCellCentered( + mesh=mesh, + survey=survey, + sigmaMap=sigma_map, + bc_type="Dirichlet", + ) + + return prob, sigma_map + + +def test_fields_derivative(fields_problem): + """Test derivatives for fields.""" + prob, sigma_map = fields_problem + + rng = np.random.default_rng(40) + x0 = -1 + 1e-1 * rng.uniform(size=sigma_map.nP) + + def fun(x): + return prob.dpred(x), lambda x: prob.Jvec(x0, x) + + assert tests.check_derivative(fun, x0, num=3, plotIt=False, random_seed=40) + + +def test_fields_adjoint(fields_problem): + """Test adjoint for fields.""" + prob, sigma_map = fields_problem + + rng = np.random.default_rng(42) + m = -1 + 1e-1 * rng.uniform(size=sigma_map.nP) + + v = rng.uniform(size=prob.survey.nD) + w = rng.uniform(size=sigma_map.nP) + + u = prob.fields(m) + + vJw = v.dot(prob.Jvec(m, w, u)) + wJtv = w.dot(prob.Jtvec(m, v, u)) + + np.testing.assert_allclose(vJw, wJtv, atol=ABS_TOL, rtol=REL_TOL) + + # tol = np.max([REL_TOL * (10 ** int(np.log10(np.abs(vJw)))), ABS_TOL]) + # assert np.abs(vJw - wJtv) < tol + + +# ========================= +# storeJ cleanup test +# ========================= + + +@pytest.fixture +def storeJ_simulation(base_mesh, survey): + """Test store J simulation.""" + mesh, *_ = base_mesh + + sim = dc.simulation.Simulation3DCellCentered( + mesh=mesh, + survey=survey, + rhoMap=maps.IdentityMap(mesh), + storeJ=True, + ) + yield sim + + try: + shutil.rmtree(sim.sensitivity_path) + except FileNotFoundError: + pass + + +def test_storeJ_runs(storeJ_simulation): + """Test that store J runs.""" + mesh = storeJ_simulation.mesh + m0 = np.ones(mesh.nC) + + dobs = storeJ_simulation.make_synthetic_data(m0, add_noise=True) + assert dobs is not None + + +# ========================= +# hierarchical test +# ========================= + + +def test_hierarchical(): + """Test derivatives for hierarchical physical properties.""" + aSpacing = 2.5 + nElecs = 10 + surveySize = nElecs * aSpacing - aSpacing + cs = surveySize / nElecs / 4 + + mesh = discretize.TensorMesh( + [ + [(cs, 10, -1.3), (cs, surveySize / cs), (cs, 10, 1.3)], + [(cs, 10, -1.3), (cs, surveySize / cs), (cs, 10, 1.3)], + [(cs, 5, -1.3), (cs, 10)], + ], + "CCN", + ) + + survey = dc.survey.Survey(dc.utils.WennerSrcList(nElecs, aSpacing, in2D=False)) + + wire_map = maps.Wires( + ("log_sigma", mesh.n_cells), + ("log_tau", mesh.n_faces), + ("log_kappa", mesh.n_edges), + ) + + sim = dc.simulation.Simulation3DHierarchicalNodal( + mesh=mesh, + survey=survey, + sigmaMap=maps.ExpMap(nP=mesh.n_cells) * wire_map.log_sigma, + face_conductance_map=maps.ExpMap(nP=mesh.n_faces) * wire_map.log_tau, + edge_area_conductance_map=maps.ExpMap(nP=mesh.n_edges) * wire_map.log_kappa, + storeJ=False, + ) + + n_params = mesh.n_cells + mesh.n_faces + mesh.n_edges + m0 = np.ones(n_params) + + dobs = sim.make_synthetic_data(m0, add_noise=True) + + rng = np.random.default_rng(42) + v = rng.uniform(size=n_params) + w = rng.uniform(size=mkvc(dobs).shape[0]) + + wtJv = w.dot(sim.Jvec(m0, v)) + vtJtw = v.dot(sim.Jtvec(m0, w)) + + assert np.abs(wtJv - vtJtw) < 1e-8 + + try: + shutil.rmtree(sim.sensitivity_path) + except FileNotFoundError: + pass diff --git a/tests/em/static/test_SPjvecjtvecadj.py b/tests/em/static/test_SPjvecjtvecadj.py index 583d530c6d..abfeda0ee6 100644 --- a/tests/em/static/test_SPjvecjtvecadj.py +++ b/tests/em/static/test_SPjvecjtvecadj.py @@ -7,7 +7,6 @@ from simpeg import maps from discretize.tests import check_derivative, assert_isadjoint - # setup simulation mesh = discretize.TensorMesh([10, 11, 12], "CCN") conductivity = 0.01 diff --git a/tests/em/tdem/test_TDEM_DerivAdjoint.py b/tests/em/tdem/test_TDEM_DerivAdjoint.py index 69514dd054..4bb0388089 100644 --- a/tests/em/tdem/test_TDEM_DerivAdjoint.py +++ b/tests/em/tdem/test_TDEM_DerivAdjoint.py @@ -1,19 +1,21 @@ -import unittest +"""Derivative and adjoint tests.""" + +import pytest import numpy as np -import time import discretize -from simpeg import maps, tests +from simpeg import maps, data_misfit, tests +from simpeg.utils import get_default_solver from simpeg.electromagnetics import time_domain as tdem plotIt = False -testDeriv = True -testAdjoint = True - -TOL = 1e-4 +ADJ_ATOL = 1e-11 +ADJ_RTOL = 2e-5 -def get_mesh(): +@pytest.fixture +def mesh(): + """Return test mesh.""" cs = 10.0 ncx = 4 ncy = 4 @@ -31,365 +33,312 @@ def get_mesh(): ) -def get_mapping(mesh): - active = mesh.cell_centers_z < 0.0 - activeMap = maps.InjectActiveCells( - mesh, active, np.log(1e-8), nC=mesh.shape_cells[2] - ) - return maps.ExpMap(mesh) * maps.SurjectVertical1D(mesh) * activeMap - - -def get_prob(mesh, mapping, formulation, **kwargs): - prb = getattr(tdem, "Simulation3D{}".format(formulation))( - mesh, sigmaMap=mapping, **kwargs - ) - prb.time_steps = [(1e-05, 10), (5e-05, 10), (2.5e-4, 10)] - return prb - - -def get_survey(): - src1 = tdem.Src.MagDipole([], location=np.array([0.0, 0.0, 0.0])) - src2 = tdem.Src.MagDipole([], location=np.array([0.0, 0.0, 8.0])) - return tdem.Survey([src1, src2]) - - -# ====== TEST Jvec ========== # - - -class Base_DerivAdjoint_Test(unittest.TestCase): - @classmethod - def setUpClass(self): - # create a prob where we will store the fields - mesh = get_mesh() - mapping = get_mapping(mesh) - self.survey = get_survey() - self.prob = get_prob(mesh, mapping, self.formulation, survey=self.survey) - rng = np.random.default_rng(seed=42) - self.m = np.log(1e-1) * np.ones(self.prob.sigmaMap.nP) + 1e-3 * rng.normal( - size=self.prob.sigmaMap.nP - ) - print("Solving Fields for problem {}".format(self.formulation)) - t = time.time() - self.fields = self.prob.fields(self.m) - print("... done. Time: {}\n".format(time.time() - t)) - - # create a prob where will be re-computing fields at each jvec - # iteration - mesh = get_mesh() - mapping = get_mapping(mesh) - self.surveyfwd = get_survey() - self.probfwd = get_prob(mesh, mapping, self.formulation, survey=self.surveyfwd) - - def get_rx(self, rxcomp): - rxOffset = 15.0 - rxlocs = np.array([[rxOffset, 0.0, -1e-2]]) - rxtimes = np.logspace(-4, -3, 20) - return getattr(tdem.Rx, "Point{}".format(rxcomp[:-1]))( - locations=rxlocs, times=rxtimes, orientation=rxcomp[-1] - ) - - def set_receiver_list(self, rxcomp): - # append the right rxlist to the surveys - rx = [self.get_rx(rxcomp)] - rxfwd = [self.get_rx(rxcomp)] - - # append to srclists - for source_list, rxlist in zip( - [self.survey.source_list, self.surveyfwd.source_list], [rx, rxfwd] - ): - for src in source_list: - src.receiver_list = rxlist - - def JvecTest(self, rxcomp): - self.set_receiver_list(rxcomp) - - def derChk(m): - return [ - self.probfwd.dpred(m), - lambda mx: self.prob.Jvec(self.m, mx, f=self.fields), - ] - - print( - "test_Jvec_{prbtype}_{rxcomp}".format( - prbtype=self.formulation, rxcomp=rxcomp - ) - ) - tests.check_derivative( - derChk, self.m, plotIt=False, num=2, eps=1e-20, random_seed=12 - ) - - def JvecVsJtvecTest(self, rxcomp): - self.set_receiver_list(rxcomp) - print( - "\nAdjoint Testing Jvec, Jtvec prob {}, {}".format(self.formulation, rxcomp) - ) - - rng = np.random.default_rng(seed=42) - m = rng.uniform(size=self.prob.sigmaMap.nP) - d = rng.normal(size=self.prob.survey.nD) - V1 = d.dot(self.prob.Jvec(self.m, m, f=self.fields)) - V2 = m.dot(self.prob.Jtvec(self.m, d, f=self.fields)) - tol = TOL * (np.abs(V1) + np.abs(V2)) / 2.0 - passed = np.abs(V1 - V2) < tol - - print(f"{self.formulation} {V1} {V2} {passed}") - self.assertTrue(passed) - - -class TDEM_Fields_B_Pieces(Base_DerivAdjoint_Test): - formulation = "MagneticFluxDensity" - - def test_eDeriv_m_adjoint(self): - prb = self.prob - f = self.fields - - print("\n Testing eDeriv_m Adjoint") - - rng = np.random.default_rng(seed=42) - m = rng.uniform(size=len(self.m)) - e = rng.normal(size=prb.mesh.nE) - V1 = e.dot(f._eDeriv_m(1, prb.survey.source_list[0], m)) - V2 = m.dot(f._eDeriv_m(1, prb.survey.source_list[0], e, adjoint=True)) - tol = TOL * (np.abs(V1) + np.abs(V2)) / 2.0 - passed = np.abs(V1 - V2) < tol - - print(" ", V1, V2, np.abs(V1 - V2), tol, passed) - self.assertTrue(passed) - - def test_eDeriv_u_adjoint(self): - print("\n Testing eDeriv_u Adjoint") - - prb = self.prob - f = self.fields - - rng = np.random.default_rng(seed=42) - b = rng.uniform(size=prb.mesh.nF) - e = rng.normal(size=prb.mesh.nE) - V1 = e.dot(f._eDeriv_u(1, prb.survey.source_list[0], b)) - V2 = b.dot(f._eDeriv_u(1, prb.survey.source_list[0], e, adjoint=True)) - tol = TOL * (np.abs(V1) + np.abs(V2)) / 2.0 - passed = np.abs(V1 - V2) < tol - - print(" ", V1, V2, np.abs(V1 - V2), tol, passed) - self.assertTrue(passed) - - -class DerivAdjoint_E(Base_DerivAdjoint_Test): - formulation = "ElectricField" - - if testDeriv: - - def test_Jvec_e_dbxdt(self): - self.JvecTest("MagneticFluxTimeDerivativex") - - def test_Jvec_e_dbzdt(self): - self.JvecTest("MagneticFluxTimeDerivativez") - - def test_Jvec_e_ey(self): - self.JvecTest("ElectricFieldy") - - def test_Jvec_e_dhxdt(self): - self.JvecTest("MagneticFieldTimeDerivativex") - - def test_Jvec_e_dhzdt(self): - self.JvecTest("MagneticFieldTimeDerivativez") - - def test_Jvec_e_jy(self): - self.JvecTest("CurrentDensityy") - - if testAdjoint: - - def test_Jvec_adjoint_e_dbdtx(self): - self.JvecVsJtvecTest("MagneticFluxTimeDerivativex") - - def test_Jvec_adjoint_e_dbdtz(self): - self.JvecVsJtvecTest("MagneticFluxTimeDerivativez") - - def test_Jvec_adjoint_e_ey(self): - self.JvecVsJtvecTest("ElectricFieldy") - - def test_Jvec_adjoint_e_dhdtx(self): - self.JvecVsJtvecTest("MagneticFieldTimeDerivativex") - - def test_Jvec_adjoint_e_dhdtz(self): - self.JvecVsJtvecTest("MagneticFieldTimeDerivativez") - - def test_Jvec_adjoint_e_jy(self): - self.JvecVsJtvecTest("CurrentDensityy") - - -class DerivAdjoint_B(Base_DerivAdjoint_Test): - formulation = "MagneticFluxDensity" - - if testDeriv: +@pytest.fixture +def locations(): + """Return receiver locations.""" + return np.array([[15, 0.0, -1e-2]]) - def test_Jvec_b_bx(self): - self.JvecTest("MagneticFluxDensityx") - def test_Jvec_b_bz(self): - self.JvecTest("MagneticFluxDensityz") +@pytest.fixture +def times(): + """Return receiver times.""" + return np.logspace(-4, -3, 20) - def test_Jvec_b_dbdtx(self): - self.JvecTest("MagneticFluxTimeDerivativex") - def test_Jvec_b_dbdtz(self): - self.JvecTest("MagneticFluxTimeDerivativez") - - def test_Jvec_b_hx(self): - self.JvecTest("MagneticFieldx") - - def test_Jvec_b_hz(self): - self.JvecTest("MagneticFieldz") - - def test_Jvec_b_dhdtx(self): - self.JvecTest("MagneticFieldTimeDerivativex") - - def test_Jvec_b_dhdtz(self): - self.JvecTest("MagneticFieldTimeDerivativez") - - def test_Jvec_b_jy(self): - self.JvecTest("CurrentDensityy") - - if testAdjoint: - - def test_Jvec_adjoint_b_bx(self): - self.JvecVsJtvecTest("MagneticFluxDensityx") - - def test_Jvec_adjoint_b_bz(self): - self.JvecVsJtvecTest("MagneticFluxDensityz") - - def test_Jvec_adjoint_b_dbdtx(self): - self.JvecVsJtvecTest("MagneticFluxTimeDerivativex") - - def test_Jvec_adjoint_b_dbdtz(self): - self.JvecVsJtvecTest("MagneticFluxTimeDerivativez") - - def test_Jvec_adjoint_b_ey(self): - self.JvecVsJtvecTest("ElectricFieldy") - - def test_Jvec_adjoint_b_hx(self): - self.JvecVsJtvecTest("MagneticFieldx") - - def test_Jvec_adjoint_b_hz(self): - self.JvecVsJtvecTest("MagneticFieldz") - - def test_Jvec_adjoint_b_dhdtx(self): - self.JvecVsJtvecTest("MagneticFieldTimeDerivativex") - - def test_Jvec_adjoint_b_dhdtz(self): - self.JvecVsJtvecTest("MagneticFieldTimeDerivativez") - - def test_Jvec_adjoint_b_jy(self): - self.JvecVsJtvecTest("CurrentDensityy") - - -class DerivAdjoint_H(Base_DerivAdjoint_Test): - formulation = "MagneticField" - - if testDeriv: - - def test_Jvec_h_hx(self): - self.JvecTest("MagneticFieldx") - - def test_Jvec_h_hz(self): - self.JvecTest("MagneticFieldz") - - def test_Jvec_h_dhdtx(self): - self.JvecTest("MagneticFieldTimeDerivativex") - - def test_Jvec_h_dhdtz(self): - self.JvecTest("MagneticFieldTimeDerivativez") - - def test_Jvec_h_jy(self): - self.JvecTest("CurrentDensityy") - - def test_Jvec_h_bx(self): - self.JvecTest("MagneticFluxDensityx") - - def test_Jvec_h_bz(self): - self.JvecTest("MagneticFluxDensityz") - - def test_Jvec_h_dbdtx(self): - self.JvecTest("MagneticFluxTimeDerivativex") - - def test_Jvec_h_dbdtz(self): - self.JvecTest("MagneticFluxTimeDerivativez") - - def test_Jvec_h_ey(self): - self.JvecTest("ElectricFieldy") - - if testAdjoint: - - def test_Jvec_adjoint_h_hx(self): - self.JvecVsJtvecTest("MagneticFieldx") - - def test_Jvec_adjoint_h_hz(self): - self.JvecVsJtvecTest("MagneticFieldz") - - def test_Jvec_adjoint_h_dhdtx(self): - self.JvecVsJtvecTest("MagneticFieldTimeDerivativex") - - def test_Jvec_adjoint_h_dhdtz(self): - self.JvecVsJtvecTest("MagneticFieldTimeDerivativez") - - def test_Jvec_adjoint_h_jy(self): - self.JvecVsJtvecTest("CurrentDensityy") +def get_survey(receiver_type, orientation, locations, times): + """Return test survey.""" + rx1 = getattr(tdem.receivers, "Point" + receiver_type)( + locations=locations, times=times, orientation=orientation + ) + rx2 = getattr(tdem.receivers, "Point" + receiver_type)( + locations=locations, times=times, orientation=orientation + ) - def test_Jvec_adjoint_h_bx(self): - self.JvecVsJtvecTest("MagneticFluxDensityx") + src1 = tdem.sources.MagDipole([rx1], location=np.array([0.0, 0.0, 0.0])) + src2 = tdem.sources.MagDipole([rx2], location=np.array([0.0, 0.0, 8.0])) - def test_Jvec_adjoint_h_bz(self): - self.JvecVsJtvecTest("MagneticFluxDensityz") + return tdem.Survey([src1, src2]) - def test_Jvec_adjoint_h_dbdtx(self): - self.JvecVsJtvecTest("MagneticFluxTimeDerivativex") - def test_Jvec_adjoint_h_dbdtz(self): - self.JvecVsJtvecTest("MagneticFluxTimeDerivativez") +def get_simulation(simulation_class, mesh, survey): + """Return test simulation.""" + sim = getattr(tdem, simulation_class)(mesh, survey=survey) - def test_Jvec_adjoint_h_ey(self): - self.JvecVsJtvecTest("ElectricFieldy") + if "Hierarchical" in simulation_class: + sigma_map, tau_map, kappa_map = get_wire_mappings(mesh) + sim.sigmaMap = sigma_map + sim.face_conductance_map = tau_map + sim.edge_area_conductance_map = kappa_map + else: + sigma_map = get_sigma_mapping(mesh) + sim.sigmaMap = sigma_map + sim.solver = get_default_solver() + sim.time_steps = [(1e-05, 10), (5e-05, 10), (2.5e-4, 10)] -class DerivAdjoint_J(Base_DerivAdjoint_Test): - formulation = "CurrentDensity" + return sim - if testDeriv: - def test_Jvec_j_jy(self): - self.JvecTest("CurrentDensityy") +def get_sigma_mapping(mesh): + """Return mapping for sigma.""" + active = mesh.cell_centers_z < 0.0 + activeMap = maps.InjectActiveCells( + mesh, active, np.log(1e-8), nC=mesh.shape_cells[2] + ) + return maps.ExpMap(mesh) * maps.SurjectVertical1D(mesh) * activeMap - def test_Jvec_j_dhdtx(self): - self.JvecTest("MagneticFieldTimeDerivativex") - def test_Jvec_j_dhdtz(self): - self.JvecTest("MagneticFieldTimeDerivativez") +def get_wire_mappings(mesh): + """Return mapping for cell, faces and edges.""" + active_cells = mesh.cell_centers[:, -1] < 0.0 + active_faces = mesh.faces[:, -1] < 0.0 + active_edges = mesh.edges[:, -1] < 0.0 + n_active_cells = np.sum(active_cells) + n_active_faces = np.sum(active_faces) + n_active_edges = np.sum(active_edges) - def test_Jvec_j_ey(self): - self.JvecTest("ElectricFieldy") + wire_map = maps.Wires( + ("log_sigma", n_active_cells), + ("log_tau", n_active_faces), + ("log_kappa", n_active_edges), + ) - def test_Jvec_j_dbdtx(self): - self.JvecTest("MagneticFluxTimeDerivativex") + sigma_map = ( + maps.InjectActiveCells(mesh, active_cells, 1e-8) + * maps.ExpMap(nP=n_active_cells) + * wire_map.log_sigma + ) + tau_map = ( + maps.InjectActiveFaces(mesh, active_faces, 0) + * maps.ExpMap(nP=n_active_faces) + * wire_map.log_tau + ) + kappa_map = ( + maps.InjectActiveEdges(mesh, active_edges, 0) + * maps.ExpMap(nP=n_active_edges) + * wire_map.log_kappa + ) - def test_Jvec_j_dbdtz(self): - self.JvecTest("MagneticFluxTimeDerivativez") + return sigma_map, tau_map, kappa_map + + +CASES_LIST = [ + ("Simulation3DElectricField", "MagneticFluxTimeDerivative", "z"), + ("Simulation3DElectricField", "MagneticFluxTimeDerivative", "x"), + ("Simulation3DElectricField", "ElectricField", "y"), + ("Simulation3DElectricField", "MagneticFieldTimeDerivative", "z"), + ("Simulation3DElectricField", "MagneticFieldTimeDerivative", "x"), + ("Simulation3DElectricField", "CurrentDensity", "y"), + ("Simulation3DHierarchicalElectricField", "MagneticFluxTimeDerivative", "z"), + ("Simulation3DHierarchicalElectricField", "MagneticFluxTimeDerivative", "x"), + ("Simulation3DHierarchicalElectricField", "ElectricField", "y"), + ("Simulation3DHierarchicalElectricField", "MagneticFieldTimeDerivative", "z"), + ("Simulation3DHierarchicalElectricField", "MagneticFieldTimeDerivative", "x"), + ("Simulation3DHierarchicalElectricField", "CurrentDensity", "y"), + ("Simulation3DMagneticFluxDensity", "MagneticFluxTimeDerivative", "z"), + ("Simulation3DMagneticFluxDensity", "MagneticFluxTimeDerivative", "x"), + ("Simulation3DMagneticFluxDensity", "MagneticFluxDensity", "z"), + ("Simulation3DMagneticFluxDensity", "MagneticFluxDensity", "x"), + ("Simulation3DMagneticFluxDensity", "MagneticFieldTimeDerivative", "z"), + ("Simulation3DMagneticFluxDensity", "MagneticFieldTimeDerivative", "x"), + ("Simulation3DMagneticFluxDensity", "MagneticField", "z"), + ("Simulation3DMagneticFluxDensity", "MagneticField", "x"), + ("Simulation3DMagneticFluxDensity", "CurrentDensity", "y"), + ("Simulation3DHierarchicalMagneticFluxDensity", "MagneticFluxDensity", "z"), + ("Simulation3DHierarchicalMagneticFluxDensity", "MagneticFluxDensity", "x"), + ("Simulation3DHierarchicalMagneticFluxDensity", "MagneticFluxTimeDerivative", "z"), + ("Simulation3DHierarchicalMagneticFluxDensity", "MagneticFluxTimeDerivative", "x"), + ("Simulation3DHierarchicalMagneticFluxDensity", "MagneticField", "z"), + ("Simulation3DHierarchicalMagneticFluxDensity", "MagneticField", "x"), + ("Simulation3DHierarchicalMagneticFluxDensity", "MagneticFieldTimeDerivative", "z"), + ("Simulation3DHierarchicalMagneticFluxDensity", "MagneticFieldTimeDerivative", "x"), + ("Simulation3DHierarchicalMagneticFluxDensity", "CurrentDensity", "y"), + ("Simulation3DMagneticField", "MagneticField", "z"), + ("Simulation3DMagneticField", "MagneticField", "x"), + ("Simulation3DMagneticField", "MagneticFieldTimeDerivative", "z"), + ("Simulation3DMagneticField", "MagneticFieldTimeDerivative", "x"), + ("Simulation3DMagneticField", "MagneticFluxDensity", "z"), + ("Simulation3DMagneticField", "MagneticFluxDensity", "x"), + ("Simulation3DMagneticField", "MagneticFluxTimeDerivative", "z"), + ("Simulation3DMagneticField", "MagneticFluxTimeDerivative", "x"), + ("Simulation3DMagneticField", "ElectricField", "y"), + ("Simulation3DMagneticField", "CurrentDensity", "y"), + ("Simulation3DCurrentDensity", "MagneticFieldTimeDerivative", "z"), + ("Simulation3DCurrentDensity", "MagneticFieldTimeDerivative", "x"), + ("Simulation3DCurrentDensity", "MagneticFluxTimeDerivative", "z"), + ("Simulation3DCurrentDensity", "MagneticFluxTimeDerivative", "x"), + ("Simulation3DCurrentDensity", "CurrentDensity", "y"), +] + + +@pytest.mark.parametrize("simulation_class, receiver_type, orientation", CASES_LIST) +class TestDerivatives: + """Derivative and adjoint test for primary-secondary formulation.""" + + def get_setup_objects( + self, + simulation_class, + receiver_type, + orientation, + mesh, + locations, + times, + ): + """Get setup for tests.""" + survey = get_survey( + receiver_type, + orientation, + locations, + times, + ) - if testAdjoint: + sim = get_simulation(simulation_class, mesh, survey) - def test_Jvec_adjoint_j_jy(self): - self.JvecVsJtvecTest("CurrentDensityy") + if "Hierarchical" in simulation_class: + n_sigma = np.sum(mesh.cell_centers[:, -1] < 0.0) + n_tau = np.sum(mesh.faces[:, -1] < 0.0) + n_kappa = np.sum(mesh.edges[:, -1] < 0.0) + m0 = np.r_[ + np.log(1e-1) * np.ones(n_sigma) + 1e-3 * np.random.randn(n_sigma), + np.log(10 * 1e-1) * np.ones(n_tau) + 1e-3 * np.random.randn(n_tau), + np.log(100 * 1e-1) * np.ones(n_kappa) + 1e-3 * np.random.randn(n_kappa), + ] + else: + n_param = sim.sigmaMap.nP + m0 = np.log(1e-1) * np.ones(n_param) + (1e-3 * np.random.randn(n_param)) + + # Define data and misfit + data = sim.make_synthetic_data(m0, add_noise=True, seed=4412) + dmis = data_misfit.L2DataMisfit(simulation=sim, data=data) + + return m0, dmis + + def test_misfit( + self, + simulation_class, + receiver_type, + orientation, + mesh, + locations, + times, + ): + """Test derivative.""" + m0, dmis = self.get_setup_objects( + simulation_class, + receiver_type, + orientation, + mesh, + locations, + times, + ) + sim = dmis.simulation + + passed = tests.check_derivative( + lambda m: (sim.dpred(m), lambda mx: sim.Jvec(m0, mx)), + m0, + plotIt=False, + random_seed=42, + num=3, + ) - def test_Jvec_adjoint_j_dhdtx(self): - self.JvecVsJtvecTest("MagneticFieldTimeDerivativex") + assert passed + + def test_adjoint( + self, + simulation_class, + receiver_type, + orientation, + mesh, + locations, + times, + ): + """Test adjoint.""" + m0, dmis = self.get_setup_objects( + simulation_class, + receiver_type, + orientation, + mesh, + locations, + times, + ) + sim = dmis.simulation + n_data = sim.survey.nD + + f = sim.fields(m0) + + tests.assert_isadjoint( + lambda u: sim.Jvec(m0, u, f=f), + lambda v: sim.Jtvec(m0, v, f=f), + m0.shape, + (n_data,), + rtol=ADJ_RTOL, + atol=ADJ_ATOL, + random_seed=44, + ) - def test_Jvec_adjoint_j_dhdtz(self): - self.JvecVsJtvecTest("MagneticFieldTimeDerivativez") - def test_Jvec_adjoint_j_ey(self): - self.JvecVsJtvecTest("ElectricFieldy") +def _same_factors(sim, factors): + """Check that a simulation holds exactly these factor objects.""" + stored = sim._stored_factors + return stored.keys() == factors.keys() and all( + stored[key] is factor for key, factor in factors.items() + ) - def test_Jvec_adjoint_j_dbdtx(self): - self.JvecVsJtvecTest("MagneticFluxTimeDerivativex") - def test_Jvec_adjoint_j_dbdtz(self): - self.JvecVsJtvecTest("MagneticFluxTimeDerivativez") +@pytest.mark.parametrize( + "simulation_class", + [ + "Simulation3DElectricField", + "Simulation3DMagneticFluxDensity", + "Simulation3DMagneticField", + "Simulation3DCurrentDensity", + ], +) +def test_store_factors(simulation_class, mesh, locations, times): + """Test that storing the factorizations does not change the results.""" + rng = np.random.default_rng(0) + survey = get_survey("MagneticFluxTimeDerivative", "z", locations, times) + sim_store = get_simulation(simulation_class, mesh, survey) + sim_store.store_factors = True + sim_plain = get_simulation(simulation_class, mesh, survey) + + n_param = sim_plain.sigmaMap.nP + m = np.log(1e-1) * np.ones(n_param) + 1e-2 * rng.normal(size=n_param) + v = rng.normal(size=n_param) + w = rng.normal(size=survey.nD) + + f_store = sim_store.fields(m) + f_plain = sim_plain.fields(m) + + # time steps repeat, so there are fewer factors than steps + factors = dict(sim_store._stored_factors) + assert 0 < len(factors) <= 3 + + np.testing.assert_allclose( + sim_store.dpred(m, f=f_store), sim_plain.dpred(m, f=f_plain) + ) + np.testing.assert_allclose( + sim_store.Jvec(m, v, f=f_store), sim_plain.Jvec(m, v, f=f_plain) + ) + np.testing.assert_allclose( + sim_store.Jtvec(m, w, f=f_store), sim_plain.Jtvec(m, w, f=f_plain) + ) + # Jvec and the transposed solves in Jtvec reuse the very same factors + assert _same_factors(sim_store, factors) + + # the same model keeps the factors, even when fields is called again + sim_store.model = m.copy() + assert _same_factors(sim_store, factors) + sim_store.fields(m) + assert _same_factors(sim_store, factors) + + # a new model drops them, and new ones get built + sim_store.model = m + 0.1 + assert not hasattr(sim_store, "_stored_factors") + sim_store.fields(m + 0.1) + assert factors.keys() == sim_store._stored_factors.keys() + assert all(sim_store._stored_factors[k] is not factors[k] for k in factors) + + # turning it off frees everything + sim_store.store_factors = False + assert len(sim_store._stored_factors) == 0 diff --git a/tests/em/tdem/test_TDEM_analytic_edge_face_conductivities.py b/tests/em/tdem/test_TDEM_analytic_edge_face_conductivities.py new file mode 100644 index 0000000000..f786f5b8ed --- /dev/null +++ b/tests/em/tdem/test_TDEM_analytic_edge_face_conductivities.py @@ -0,0 +1,277 @@ +"""Numerical tests for hierarchical properties.""" + +import discretize +import numpy as np +import pytest +from simpeg import maps +from simpeg.utils import ndgrid +from simpeg.electromagnetics import time_domain as tdem + +REL_TOL = 0.1 +ABS_TOL = 1e-13 + +CASES_LIST = [ + ("ElectricField", "CYL"), + ("ElectricField", "TREE"), + ("MagneticFluxDensity", "TREE"), +] + + +@pytest.mark.parametrize("formulation, mesh_type", CASES_LIST) +def test_layer_conductance_to_analytic(formulation, mesh_type): + """Validate 1D analytic solution for thin layer against layer as face conductances.""" + # Some static parameters + times = np.logspace(-3, -2, 6) + + loop_radius = np.pi**-0.5 + receiver_location = np.c_[16.0, 0.0, 1.0] + source_location = np.r_[0.0, 0.0, 1.0] + + layer_depth = 100.0 + layer_thickness = 1.0 + layer_conductivity = 100 + background_conductivity = 1e-2 + + tau = layer_thickness * layer_conductivity + + # 1D LAYER MODEL + thicknesses = np.array([layer_depth - layer_thickness / 2, layer_thickness]) + n_layer = len(thicknesses) + 1 + + sigma_1d = background_conductivity * np.ones(n_layer) + sigma_1d[1] = layer_conductivity + + sigma_map_1d = maps.IdentityMap(nP=n_layer) + + # 3D LAYER MODEL + if mesh_type == "CYL": + hr = [(2.5, 120), (2.5, 25, 1.3)] + hz = [(2.5, 25, -1.3), (2.5, 200), (2.5, 25, 1.3)] + + mesh = discretize.CylindricalMesh([hr, 1, hz], x0="00C") + + ind = np.where(mesh.h[2] == np.min(mesh.h[2]))[0] + ind = ind[int(len(ind) / 2)] + + mesh.origin = mesh.origin - np.r_[0.0, 0.0, mesh.nodes_z[ind] - 50] + + elif mesh_type == "TREE": + dh = 5.0 # base cell width + dom_width = 8000.0 # domain width + nbc = 2 ** int( + np.round(np.log(dom_width / dh) / np.log(2.0)) + ) # num. base cells + + h = [(dh, nbc)] + mesh = discretize.TreeMesh([h, h, h], x0="CCC") + mesh.refine_points( + np.reshape(source_location, (1, 3)), + level=-1, + padding_cells_by_level=[8, 4, 4, 4], + finalize=False, + ) + x0s = np.vstack([ii * np.c_[-120, -120, -120] for ii in range(1, 5)]) + x1s = np.vstack([ii * np.c_[120, 120, 20] for ii in range(1, 5)]) + + mesh.refine_box(x0s, x1s, levels=[-2, -3, -4, -5], finalize=False) + mesh.finalize() + + sigma_3d = 1e-8 * np.ones(mesh.nC) + sigma_3d[mesh.cell_centers[:, -1] < 0.0] = background_conductivity + + tau_3d = np.zeros(mesh.nF) + tau_3d[np.isclose(mesh.faces[:, -1], -layer_depth)] = tau + tau_map = maps.IdentityMap(nP=mesh.n_faces) + + # DEFINE SURVEY + waveform = tdem.sources.StepOffWaveform() + + if formulation == "ElectricField": + rx_list = [ + tdem.receivers.PointMagneticFluxTimeDerivative( + receiver_location, orientation="z", times=times + ) + ] + else: + rx_list = [ + tdem.receivers.PointMagneticFluxDensity( + receiver_location, orientation="z", times=times + ) + ] + + # 1D SURVEY AND SIMULATION + src_1d = [ + tdem.sources.MagDipole( + rx_list, location=np.r_[0.0, 0.0, 1.0], orientation="z", waveform=waveform + ) + ] + survey_1d = tdem.Survey(src_1d) + + sim_1d = tdem.Simulation1DLayered( + survey=survey_1d, + thicknesses=thicknesses, + sigmaMap=sigma_map_1d, + ) + + # 3D SURVEY AND SIMULATION + time_steps = [(5e-5, 20), (2.5e-4, 40)] + + if mesh_type == "CYL": + src_3d = [ + tdem.sources.CircularLoop( + rx_list, + radius=loop_radius, + location=source_location, + waveform=waveform, + ) + ] + else: + src_3d = [ + tdem.sources.MagDipole( + rx_list, + location=source_location, + orientation="z", + waveform=waveform, + ) + ] + + survey_3d = tdem.Survey(src_3d) + + # DEFINE THE SIMULATIONS + if formulation == "MagneticFluxDensity": + sim_3d = tdem.Simulation3DHierarchicalMagneticFluxDensity( + mesh=mesh, + survey=survey_3d, + sigma=sigma_3d, + face_conductance_map=tau_map, + ) + else: + sim_3d = tdem.Simulation3DHierarchicalElectricField( + mesh=mesh, + survey=survey_3d, + sigma=sigma_3d, + face_conductance_map=tau_map, + ) + sim_3d.time_steps = time_steps + + analytic_solution = sim_1d.dpred(sigma_1d) # ALWAYS RETURNS H-FIELD + numeric_solution = sim_3d.dpred(tau_3d) + + np.testing.assert_allclose(numeric_solution, analytic_solution, rtol=REL_TOL) + + +def test_edge_conductivity(): + """Cross check for a thin conductive wire.""" + # Some static parameters + location_a = np.r_[-40, 0, 0] + location_b = np.r_[40, 0, 0] + locations_rx = ndgrid(np.linspace(-10, 10, 4), 0, 8) + times = np.logspace(-4, -3, 3) + + wire_depth = 16.0 + wire_width = 1.0 + wire_length = 20.0 + wire_conductivity = 1e0 # Only 1 order of magnitude (linear regime + background_conductivity = 1e-1 + + kappa_value = wire_width**2 * wire_conductivity + + # Mesh + dh = 0.25 # base cell width + dom_width = 2000.0 # domain width + nbc = 2 ** int(np.round(np.log(dom_width / dh) / np.log(2.0))) # num. base cells + + h = [(dh, nbc)] + mesh = discretize.TreeMesh([h, h, h], x0="CCC") + + pts = ndgrid( + np.arange(-wire_length / 2, wire_length / 2 + 1e-6, dh), 0, -wire_depth + ) + mesh.refine_points( + pts, + level=-1, + padding_cells_by_level=[4, 4, 4, 4], + finalize=False, + ) + + pts = np.vstack([locations_rx, location_a, location_b]) + mesh.refine_points( + pts, + level=-2, + padding_cells_by_level=[4, 4, 4, 4], + finalize=False, + ) + x0s = np.vstack([ii * np.c_[-60, -60, -30] for ii in range(1, 4)]) + x1s = np.vstack([ii * np.c_[60, 60, 10] for ii in range(1, 4)]) + + mesh.refine_box(x0s, x1s, levels=[-5, -6, -7], finalize=False) + mesh.finalize() + print(mesh.n_cells) + + # Models + ccs = mesh.cell_centers + sigma_0 = 1e-8 * np.ones(mesh.n_cells) + sigma_0[ccs[:, -1] < 0.0] = background_conductivity + + sigma_voxel = sigma_0.copy() + inds_block = ( + (np.abs(ccs[:, 0]) <= wire_length / 2) + & (np.abs(ccs[:, 1]) <= wire_width / 2) + & (np.abs(ccs[:, 2] + wire_depth) <= wire_width / 2) + ) + sigma_voxel[inds_block] = wire_conductivity + print(sum(inds_block)) + + kappa = np.zeros(mesh.n_edges) + edges = mesh.edges + inds_kappa = ( + (np.abs(edges[:, 0]) <= wire_length / 2) + & (np.isclose(edges[:, 1], 0.0)) + & (np.isclose(edges[:, 2], -wire_depth)) + ) + kappa[inds_kappa] = kappa_value + print(sum(inds_kappa)) + + # DEFINE SURVEY + rx_sigma = tdem.receivers.PointElectricField( + locations=locations_rx, orientation="x", times=times + ) + rx_kappa = tdem.receivers.PointElectricField( + locations=locations_rx, orientation="x", times=times + ) + + waveform = tdem.sources.StepOffWaveform() + src_sigma = tdem.sources.LineCurrent( + [rx_sigma], location=np.c_[location_a, location_b].T, waveform=waveform + ) + src_kappa = tdem.sources.LineCurrent( + [rx_kappa], location=np.c_[location_a, location_b].T, waveform=waveform + ) + + survey_sigma = tdem.Survey([src_sigma]) + survey_kappa = tdem.Survey([src_kappa]) + + time_steps = [(5e-6, 20), (5e-5, 21)] + + sim_sigma = tdem.simulation.Simulation3DElectricField( + mesh=mesh, + survey=survey_sigma, + sigmaMap=maps.IdentityMap(nP=mesh.n_cells), + time_steps=time_steps, + ) + sim_kappa = tdem.simulation.Simulation3DHierarchicalElectricField( + mesh=mesh, + survey=survey_kappa, + sigma=sigma_0, + edge_area_conductance_map=maps.IdentityMap(nP=mesh.n_edges), + time_steps=time_steps, + ) + + # COMPUTE SOLUTIONS + dpred_0 = sim_sigma.dpred(sigma_0) + true_solution = sim_sigma.dpred(sigma_voxel) - dpred_0 + approx_solution = sim_kappa.dpred(kappa) - dpred_0 + + np.testing.assert_allclose( + true_solution, approx_solution, atol=ABS_TOL, rtol=REL_TOL + ) diff --git a/tests/em/tdem/test_TDEM_inductive_permeable.py b/tests/em/tdem/test_TDEM_inductive_permeable.py index b0bd644f34..94bb1e9e7d 100644 --- a/tests/em/tdem/test_TDEM_inductive_permeable.py +++ b/tests/em/tdem/test_TDEM_inductive_permeable.py @@ -10,7 +10,6 @@ from simpeg.electromagnetics import time_domain as tdem from simpeg import utils, maps - plotIt = False TOL = 1e-4 diff --git a/tests/em/tdem/test_large_loop.py b/tests/em/tdem/test_large_loop.py index 88e08904a1..97f4c24eb6 100644 --- a/tests/em/tdem/test_large_loop.py +++ b/tests/em/tdem/test_large_loop.py @@ -8,7 +8,6 @@ # solver from simpeg.utils.solver_utils import get_default_solver - Solver = get_default_solver() # conductivity values @@ -54,10 +53,8 @@ def setup_mesh_model(tx_halfwidth=50): return mesh, model -def setup_survey(rx_locs, rx_times, tx_halfwidth=50, tx_z=0.5): - # transmitter - tx_halfwidth = 50 - tx_z = 0.5 # put slightly above the surface +def setup_survey(rx_locs, rx_times, tx_halfwidth=50, tx_z=0.5, waveform=None): + # transmitter, by default slightly above the surface tx_points = np.array( [ [-tx_halfwidth, -tx_halfwidth, tx_z], @@ -82,7 +79,8 @@ def setup_survey(rx_locs, rx_times, tx_halfwidth=50, tx_z=0.5): for orientation in ["z"] ] - waveform = tdem.sources.StepOffWaveform() + if waveform is None: + waveform = tdem.sources.StepOffWaveform() src = tdem.sources.LineCurrent( receiver_list=b_receivers + dbdt_receivers, @@ -97,10 +95,12 @@ def setup_survey(rx_locs, rx_times, tx_halfwidth=50, tx_z=0.5): return survey -def setup_simulation(mesh, survey, simulation_type="EB"): +def setup_simulation(mesh, survey, simulation_type="EB", on_time_steps=None): nsteps = 20 - time_steps = [ + if on_time_steps is None: + on_time_steps = [] + time_steps = on_time_steps + [ (3e-6, nsteps), (1e-5, nsteps), (3e-5, nsteps), @@ -178,3 +178,71 @@ def test_large_loop(simulation_type): dpred1d = simulation_1D.dpred(sigma_back) * current np.testing.assert_allclose(dpred_numeric, dpred1d, rtol=REL_TOL) + + +@pytest.mark.parametrize("simulation_type", ["EB", "HJ"]) +def test_large_loop_trapezoid(simulation_type): + """ + Test the on-time source term of the loop. + + For a step-off waveform, the HJ initial fields of an inductive loop come + from the Biot-Savart vector potential and the source term is zero after + t=0, so the direction of the current on the mesh never enters the + simulation. A trapezoid waveform has no initial fields, so the fields are + driven by the source term during the on-time. + """ + + # The mesh has cell centers at +/-40 m. + # The HJ source term moves the loop to the nearest cell centers, + # so use a 40 m half-width at z = 15 m (also on cell centers) so the 3D + # and 1D simulations model the same loop. + tx_halfwidth = 40 + tx_z = 15 + + off_time = 5e-4 + waveform = tdem.sources.TrapezoidWaveform( + ramp_on=[0, 1e-4], ramp_off=[4e-4, off_time] + ) + on_time_steps = [(2e-5, 20), (1e-5, 10)] + + # receiver times: late times are less accurate in the EB solve, so stop at 5 ms + rx_times = off_time + 1e-3 * np.logspace(-1, np.log10(5), 20) + + rx_locs = np.array([[20, 20, 0]]) + + mesh, model = setup_mesh_model() + survey = setup_survey( + rx_locs=rx_locs, + rx_times=rx_times, + tx_halfwidth=tx_halfwidth, + tx_z=tx_z, + waveform=waveform, + ) + simulation = setup_simulation( + mesh, survey, simulation_type, on_time_steps=on_time_steps + ) + dpred_numeric = simulation.dpred(model) + + # 1D simulation with the same source + simulation_1D = tdem.simulation_1d.Simulation1DLayered( + survey=survey, sigmaMap=maps.IdentityMap() + ) + dpred1d = simulation_1D.dpred(sigma_back) + + # Make sure that the numeric and the 1D solutions have the same sign. + # This tests the currents have consistent orientations between the EB and HJ + # formulations, a bug fixed in #1812 + np.testing.assert_equal(np.sign(dpred_numeric), np.sign(dpred1d), strict=True) + + # Compare the numeric b and dbdt with their respective analytic solutions + b_numeric = dpred_numeric[: dpred_numeric.size // 2] + b_1d = dpred1d[: dpred1d.size // 2] + atol = 1e-3 * np.max(np.abs(b_1d)) + np.testing.assert_allclose(b_numeric, b_1d, rtol=REL_TOL, atol=atol, strict=True) + + dbdt_numeric = dpred_numeric[dpred_numeric.size // 2 :] + dbdt_1d = dpred1d[dpred1d.size // 2 :] + atol = 1e-7 * np.max(np.abs(dbdt_1d)) + np.testing.assert_allclose( + dbdt_numeric, dbdt_1d, rtol=REL_TOL, atol=atol, strict=True + ) diff --git a/tests/em/utils/test_linecurrents.py b/tests/em/utils/test_linecurrents.py index f0d94f3cb3..1534e3a448 100644 --- a/tests/em/utils/test_linecurrents.py +++ b/tests/em/utils/test_linecurrents.py @@ -167,5 +167,38 @@ def create_line(points): ) +def test_line_through_faces_direction(): + """ + Test that line_through_faces and segmented_line_current_source_term agree + on the direction of the current: from ``locations[i]`` to ``locations[i + 1]``. + """ + mesh = discretize.TensorMesh([np.full(8, 10.0)] * 3, origin="CCC") + + # closed path through cell centers with segments along +x, +y, +z, -x, -y, -z + a = 25.0 + locations = np.array( + [ + [-a, -a, -a], + [a, -a, -a], + [a, a, -a], + [a, a, a], + [-a, a, a], + [-a, -a, a], + [-a, -a, -a], + ] + ) + faces = line_through_faces(mesh, locations) + edges = segmented_line_current_source_term(mesh, locations) + + # compare the direction of the current in the cells along the path + faces_cc = mesh.average_face_to_cell_vector @ faces + edges_cc = mesh.average_edge_to_cell_vector @ edges + on_path = faces_cc != 0 + assert on_path.sum() > 0 + np.testing.assert_equal( + np.sign(faces_cc[on_path]), np.sign(edges_cc[on_path]), strict=True + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/meta/test_multiprocessing_sim.py b/tests/meta/test_multiprocessing_sim.py index be2431fb10..814b6105c0 100644 --- a/tests/meta/test_multiprocessing_sim.py +++ b/tests/meta/test_multiprocessing_sim.py @@ -1,4 +1,12 @@ +import multiprocessing +import os +import subprocess +import sys +import textwrap +import time + import numpy as np +import pytest from simpeg.potential_fields import gravity from simpeg.electromagnetics.static import resistivity as dc @@ -14,6 +22,25 @@ MultiprocessingSumMetaSimulation, MultiprocessingRepeatedSimulation, ) +from simpeg.meta.multiprocessing import _SimulationProcess + + +class _FlakyFieldsSimulation(dc.Simulation3DNodal): + """A test double whose `fields` call fails exactly once. + + Used to exercise the worker-process error path: the first call raises + while its process is mid-request, and a later call on the same worker + must still succeed cleanly (proving the request/response queue wasn't + left desynced by the earlier failure). + """ + + _fields_call_count = 0 + + def fields(self, m=None, calcJ=True): + self._fields_call_count += 1 + if self._fields_call_count == 1: + raise RuntimeError("synthetic fields failure") + return super().fields(m, calcJ=calcJ) def test_meta_correctness(): @@ -192,6 +219,339 @@ def test_sum_correctness(): parallel_sim.join() +def test_sum_correctness_more_sims_than_processes(): + # Regression test: MultiprocessingSumMetaSimulation must build each + # per-process chunk as a SumMetaSimulation (summing), not the default + # MetaSimulation (concatenating). With only 1 sim per process (as in + # test_sum_correctness) that distinction never showed up: concatenating + # a single array is a no-op. Here we use twice as many sims as + # processes so each worker owns >1 sim and the bug would either crash + # (unequal chunk shapes) or silently sum wrong values (equal chunk + # shapes, concatenated-then-summed instead of summed). + mesh = TensorMesh([16, 16, 16], origin="CCN") + rx_locs = np.mgrid[-0.25:0.25:5j, -0.25:0.25:5j, 0:1:1j].reshape(3, -1).T + rx = gravity.Point(rx_locs, components=["gz"]) + survey = gravity.Survey(gravity.SourceField(rx)) + + n_layers = 4 + edges = np.linspace(0, mesh.shape_cells[2], n_layers + 1, dtype=int) + layer_meshes = [ + TensorMesh( + [mesh.h[0], mesh.h[1], mesh.h[2][edges[i] : edges[i + 1]]], + origin=[mesh.origin[0], mesh.origin[1], mesh.nodes_z[edges[i]]], + ) + for i in range(n_layers) + ] + + g_mappings = [maps.Mesh2Mesh((m, mesh)) for m in layer_meshes] + g_sims = [ + gravity.Simulation3DIntegral( + m, survey=survey, rhoMap=maps.IdentityMap(), n_processes=1 + ) + for m in layer_meshes + ] + + m_test = np.arange(mesh.n_cells) / mesh.n_cells + 0.1 + + serial_sim = SumMetaSimulation(g_sims, g_mappings) + # 4 sims over 2 processes -> chunk_sizes = [2, 2] + parallel_sim = MultiprocessingSumMetaSimulation(g_sims, g_mappings, n_processes=2) + + try: + d_full = serial_sim.dpred(m_test) + d_mult = parallel_sim.dpred(m_test) + np.testing.assert_allclose(d_full, d_mult, rtol=1e-06) + finally: + parallel_sim.join() + + +def test_worker_error_propagation(): + # Regression test: an exception raised inside a worker process while + # computing fields must (a) be raised in the caller as a real + # exception, and (b) not leave the worker's request/response queue + # desynced for later, unrelated calls on the same process. + mesh = TensorMesh([8, 8, 8], origin="CCN") + rx_locs = np.mgrid[-0.25:0.25:3j, -0.25:0.25:3j, 0:1:1j].reshape(3, -1).T + rxs = dc.receivers.Pole(rx_locs) + source_locs = np.mgrid[-0.5:0.5:4j, 0:1:1j, 0:1:1j].reshape(3, -1).T + src_list = [dc.sources.Pole([rxs], location=loc) for loc in source_locs] + survey = dc.Survey(src_list) + + flaky_sim = _FlakyFieldsSimulation(mesh, survey=survey, sigmaMap=maps.IdentityMap()) + reference_sim = dc.Simulation3DNodal( + mesh, survey=survey, sigmaMap=maps.IdentityMap() + ) + + m_test = np.arange(mesh.n_cells) / mesh.n_cells + 0.1 + + parallel_sim = MultiprocessingMetaSimulation( + [flaky_sim], [maps.IdentityMap()], n_processes=1 + ) + serial_sim = MetaSimulation([reference_sim], [maps.IdentityMap()]) + + try: + with pytest.raises(RuntimeError, match="synthetic fields failure"): + parallel_sim.dpred(m_test) + + # The same worker process just failed a request; a fresh call must + # still succeed and match the serial reference, proving no stray + # item was left behind in the result queue by the earlier failure. + d_mult = parallel_sim.dpred(m_test) + d_full = serial_sim.dpred(m_test) + np.testing.assert_allclose(d_full, d_mult, rtol=1e-06) + finally: + parallel_sim.join() + + +class _FlakyModelSimulation: + """Minimal test double (not a real BaseSimulation) whose `model` + setter fails exactly once. Used to check that a failure storing the + model on a worker process is raised immediately by `store_model`, + instead of being deferred until a later, unrelated op touches that + worker. + """ + + _set_count = 0 + + def __init__(self): + self._model = None + + @property + def model(self): + return self._model + + @model.setter + def model(self, value): + self._set_count += 1 + if self._set_count == 1: + raise ValueError("synthetic model failure") + self._model = value + + def fields(self, m): + return None + + def dpred(self, m, f): + return np.zeros(1) + + +def test_store_model_error_propagation(): + # Regression test: a failure while storing the model on a worker + # process must be raised immediately by `store_model` itself, not + # deferred until a later op (e.g. `get_fields`/`dpred`) happens to + # touch that worker. + p = _SimulationProcess() + p.start() + try: + p.set_sim(_FlakyModelSimulation()) + with pytest.raises(ValueError, match="synthetic model failure"): + p.store_model(np.zeros(1)) + + # The same worker just failed a request; a later, unrelated + # request must still succeed cleanly, proving the request/ + # response queue wasn't left desynced by the earlier failure. + p.store_model(np.zeros(1)) + fields_future = p.get_fields() + p.start_dpred(fields_future) + d = p.result() + np.testing.assert_allclose(d, np.zeros(1)) + finally: + p.join() + + +class _FlakyModelDCSimulation(dc.Simulation3DNodal): + """A test double whose `model` setter fails exactly once. + + Used to exercise `MultiprocessingMetaSimulation`'s model setter: + assigning `.model` on the meta-simulation must raise immediately + when a worker fails to store it, rather than deferring the error to + the next unrelated call (e.g. `dpred`). + """ + + _model_set_count = 0 + + @dc.Simulation3DNodal.model.setter + def model(self, value): + if value is not None: + self._model_set_count += 1 + if self._model_set_count == 1: + raise ValueError("synthetic model failure") + dc.Simulation3DNodal.model.fset(self, value) + + +def test_model_assignment_error_propagation(): + # Regression test: a failure storing the model on a worker process + # must be raised immediately by the `.model = ...` assignment that + # triggered it, not deferred until a later, unrelated call. + mesh = TensorMesh([8, 8, 8], origin="CCN") + rx_locs = np.mgrid[-0.25:0.25:3j, -0.25:0.25:3j, 0:1:1j].reshape(3, -1).T + rxs = dc.receivers.Pole(rx_locs) + source_locs = np.mgrid[-0.5:0.5:4j, 0:1:1j, 0:1:1j].reshape(3, -1).T + src_list = [dc.sources.Pole([rxs], location=loc) for loc in source_locs] + survey = dc.Survey(src_list) + + flaky_sim = _FlakyModelDCSimulation( + mesh, survey=survey, sigmaMap=maps.IdentityMap() + ) + reference_sim = dc.Simulation3DNodal( + mesh, survey=survey, sigmaMap=maps.IdentityMap() + ) + + m_test = np.arange(mesh.n_cells) / mesh.n_cells + 0.1 + + parallel_sim = MultiprocessingMetaSimulation( + [flaky_sim], [maps.IdentityMap()], n_processes=1 + ) + serial_sim = MetaSimulation([reference_sim], [maps.IdentityMap()]) + + try: + with pytest.raises(ValueError, match="synthetic model failure"): + parallel_sim.model = m_test + + # A fresh assignment (of a genuinely different model, so it isn't + # skipped as a no-op update) must succeed, and later calls must + # match the serial reference, proving no stray item was left + # behind in the worker's result queue by the earlier failure. + m_retry = m_test * 2 + d_mult = parallel_sim.dpred(m_retry) + d_full = serial_sim.dpred(m_retry) + np.testing.assert_allclose(d_full, d_mult, rtol=1e-06) + finally: + parallel_sim.join() + + +class _BigResultSimulation: + """Minimal test double (not a real BaseSimulation): `fields()` is a + no-op and `dpred()` returns a large array. Used to check that a result + left unread in a worker's result_queue doesn't deadlock `.join()`. + """ + + def __init__(self, size): + self.size = size + self.model = None + + def fields(self, m): + return None + + def dpred(self, m, f): + return np.zeros(self.size) + + +def test_join_does_not_hang_on_unread_result(): + # Regression test: if a caller dispatches work to a worker and then + # never reads its result (e.g. because an earlier collection loop + # raised before getting to it), the worker's feeder thread can be + # left blocked flushing that result once the OS pipe buffer fills up. + # A plain Process.join() would then hang forever. `.join()` must + # drain in the background instead, so it completes promptly. + p = _SimulationProcess() + p.start() + elapsed = None + try: + p.set_sim(_BigResultSimulation(size=2_000_000)) # ~16 MB of float64 + p.store_model(np.zeros(1)) + fields_future = p.get_fields() + p.start_dpred(fields_future) + # Deliberately never call p.result() here. + + start = time.monotonic() + p.join(timeout=10) + elapsed = time.monotonic() - start + finally: + if p.is_alive(): + p.terminate() + + assert elapsed is not None and elapsed < 10 + assert not p.is_alive() + + +def test_init_failure_shuts_down_started_workers(monkeypatch): + # If setting up a later worker fails, workers that were already started + # must be shut down (gracefully, via poison pill) before the error + # propagates, not leaked. + mesh = TensorMesh([4, 4, 4], origin="CCN") + rx_locs = np.mgrid[-0.25:0.25:2j, -0.25:0.25:2j, 0:1:1j].reshape(3, -1).T + rxs = dc.receivers.Pole(rx_locs) + src_list = [dc.sources.Pole([rxs], location=[x, 0, 0]) for x in (-0.5, 0.5)] + survey = dc.Survey(src_list) + sims = [ + dc.Simulation3DNodal(mesh, survey=survey, sigmaMap=maps.IdentityMap()) + for _ in range(2) + ] + + real_set_sim = _SimulationProcess.set_sim + calls = [] + + def failing_set_sim(self, sim): + calls.append(self) + if len(calls) == 2: + raise RuntimeError("synthetic set_sim failure") + return real_set_sim(self, sim) + + monkeypatch.setattr(_SimulationProcess, "set_sim", failing_set_sim) + + with pytest.raises(RuntimeError, match="synthetic set_sim failure"): + MultiprocessingMetaSimulation( + sims, [maps.IdentityMap(), maps.IdentityMap()], n_processes=2 + ) + + assert len(calls) == 2 + assert not any(p.is_alive() for p in calls) + assert multiprocessing.active_children() == [] + + +def test_atexit_cleanup_without_join(): + # Regression test: if a script builds a MultiprocessingMetaSimulation + # and exits (or an exception propagates to the top level) without ever + # calling .join(), the worker processes are non-daemonic and would + # otherwise block Python's own atexit machinery from letting the + # interpreter exit. The atexit fallback registered at construction + # time must terminate them so the process exits promptly on its own. + script = textwrap.dedent(""" + import numpy as np + from discretize import TensorMesh + from simpeg import maps + from simpeg.electromagnetics.static import resistivity as dc + from simpeg.meta import MultiprocessingMetaSimulation + + if __name__ == "__main__": + mesh = TensorMesh([4, 4, 4], origin="CCN") + rx_locs = np.mgrid[-0.25:0.25:2j, -0.25:0.25:2j, 0:1:1j].reshape(3, -1).T + rxs = dc.receivers.Pole(rx_locs) + source_locs = np.mgrid[-0.5:0.5:2j, 0:1:1j, 0:1:1j].reshape(3, -1).T + src_list = [ + dc.sources.Pole([rxs], location=loc) for loc in source_locs + ] + survey = dc.Survey(src_list) + sim = dc.Simulation3DNodal( + mesh, survey=survey, sigmaMap=maps.IdentityMap() + ) + + parallel_sim = MultiprocessingMetaSimulation( + [sim], [maps.IdentityMap()], n_processes=1 + ) + # Intentionally do NOT call parallel_sim.join(): the atexit + # fallback must still let this process exit promptly. + """) + + # Don't let pytest-cov / coverage auto-start inside the child: this test + # only checks exit behaviour, and coverage's startup hook interferes with + # importing numpy in a `-c` script. + env = { + k: v + for k, v in os.environ.items() + if not k.startswith(("COV_CORE", "COVERAGE")) + } + + result = subprocess.run( + [sys.executable, "-c", script], + env=env, + timeout=60, + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stderr + + def test_repeat_correctness(): mesh = TensorMesh([16, 16, 16], origin="CCN") rx_locs = np.mgrid[-0.25:0.25:5j, -0.25:0.25:5j, 0:1:1j].reshape(3, -1).T diff --git a/tests/pf/test_base_pf_simulation.py b/tests/pf/test_base_pf_simulation.py index 94f3a0efe1..0ec16121a4 100644 --- a/tests/pf/test_base_pf_simulation.py +++ b/tests/pf/test_base_pf_simulation.py @@ -331,3 +331,42 @@ def test_removed_property(self, tensor_mesh, mock_simulation_class): msg = "ind_active has been removed, please use active_cells." with pytest.raises(NotImplementedError, match=msg): simulation.ind_active + + +class _NoRowsGravitySimulation(gravity.Simulation3DIntegral): + """Defined at module level so spawned worker processes can unpickle it.""" + + def evaluate_integral(self, receiver_location, components): + # Return fewer rows than there are components. + return super().evaluate_integral(receiver_location, components)[:0] + + +class TestMultiprocessedKernel: + """Test the shared-memory, multiprocessed kernel build.""" + + @pytest.fixture + def sim_args(self): + mesh = TensorMesh([4, 4, 4], origin="CCN") + rx_locs = np.mgrid[-0.5:0.5:3j, -0.5:0.5:3j, 1:2:1j].reshape(3, -1).T + receivers = gravity.Point(rx_locs, components=["gz", "gx"]) + survey = gravity.Survey(gravity.SourceField([receivers])) + return dict( + mesh=mesh, + survey=survey, + rhoMap=simpeg.maps.IdentityMap(nP=mesh.n_cells), + engine="geoana", + store_sensitivities="ram", + sensitivity_dtype=np.float64, + ) + + def test_matches_serial(self, sim_args): + mesh = sim_args.pop("mesh") + serial = gravity.Simulation3DIntegral(mesh, n_processes=1, **sim_args) + parallel = gravity.Simulation3DIntegral(mesh, n_processes=2, **sim_args) + np.testing.assert_allclose(parallel.linear_operator(), serial.linear_operator()) + + def test_row_count_mismatch_raises(self, sim_args): + mesh = sim_args.pop("mesh") + sim = _NoRowsGravitySimulation(mesh, n_processes=2, **sim_args) + with pytest.raises(RuntimeError, match="different number of rows"): + sim.linear_operator() diff --git a/tests/pf/test_forward_mag_differential.py b/tests/pf/test_forward_mag_differential.py index f6571073fe..76b1b4e11b 100644 --- a/tests/pf/test_forward_mag_differential.py +++ b/tests/pf/test_forward_mag_differential.py @@ -3,7 +3,7 @@ import discretize import simpeg.potential_fields as PF from simpeg import utils, maps -from discretize.utils import mkvc, refine_tree_xyz +from discretize.utils import mkvc import numpy as np from tests.utils.ellipsoid import ProlateEllipsoid @@ -22,15 +22,9 @@ def mesh(): hz = dhz * np.ones(nbcz) _mesh = discretize.TreeMesh([hx, hy, hz], x0="CCC") - xp, yp, zp = np.meshgrid([-1400.0, 1400.0], [-1400.0, 1400.0], [-1000.0, 200.0]) - xy = np.c_[mkvc(xp), mkvc(yp), mkvc(zp)] - _mesh = refine_tree_xyz( - _mesh, - xy, - method="box", - finalize=False, - octree_levels=[1, 1, 1, 1], - ) + x0 = np.array([-1400.0, -1400.0, -1000.0]) + x1 = np.array([1400.0, 1400.0, 200.0]) + _mesh.refine_box(x0, x1, levels=-1, finalize=False) _mesh.finalize() return _mesh @@ -343,7 +337,6 @@ def test_invalid_solver_dtype(mesh): ids=["bx", "by", "bz", "tmi", "b_field"], ) class TestGetJ: - @pytest.fixture def mesh_small(self): """ diff --git a/tests/pf/test_mag_MVI_Octree.py b/tests/pf/test_mag_MVI_Octree.py index 667e6d05fa..1004c0599b 100644 --- a/tests/pf/test_mag_MVI_Octree.py +++ b/tests/pf/test_mag_MVI_Octree.py @@ -11,7 +11,7 @@ ) -from discretize.utils import mesh_builder_xyz, refine_tree_xyz, active_from_xyz +from discretize.utils import mesh_builder_xyz, active_from_xyz import numpy as np from simpeg.potential_fields import magnetics as mag import shutil @@ -60,9 +60,7 @@ def setUp(self): mesh = mesh_builder_xyz( xyzLoc, h, padding_distance=padDist, depth_core=100, mesh_type="tree" ) - mesh = refine_tree_xyz( - mesh, topo, method="surface", octree_levels=[4, 4], finalize=True - ) + mesh.refine_surface(topo, padding_cells_by_level=[4, 4], finalize=True) self.mesh = mesh # Define an active cells from topo actv = active_from_xyz(mesh, topo) diff --git a/tests/pf/test_mag_differential_functionality.py b/tests/pf/test_mag_differential_functionality.py index f682b39fe6..afaedefef6 100644 --- a/tests/pf/test_mag_differential_functionality.py +++ b/tests/pf/test_mag_differential_functionality.py @@ -2,7 +2,7 @@ import discretize import simpeg.potential_fields as PF from simpeg import utils, maps -from discretize.utils import mkvc, refine_tree_xyz +from discretize.utils import mkvc import numpy as np from tests.utils.ellipsoid import ProlateEllipsoid @@ -21,15 +21,9 @@ def mesh(): hz = dhz * np.ones(nbcz) _mesh = discretize.TreeMesh([hx, hy, hz], x0="CCC") - xp, yp, zp = np.meshgrid([-1400.0, 1400.0], [-1400.0, 1400.0], [-1000.0, 200.0]) - xy = np.c_[mkvc(xp), mkvc(yp), mkvc(zp)] - _mesh = refine_tree_xyz( - _mesh, - xy, - method="box", - finalize=False, - octree_levels=[1, 1, 1, 1], - ) + x0 = np.array([-1400.0, -1400.0, -1000.0]) + x1 = np.array([1400.0, 1400.0, 200.0]) + _mesh.refine_box(x0, x1, levels=-1, finalize=False) _mesh.finalize() return _mesh diff --git a/tests/pf/test_mag_differential_jvecjtvec.py b/tests/pf/test_mag_differential_jvecjtvec.py index 91daa643d0..70a02c33d5 100644 --- a/tests/pf/test_mag_differential_jvecjtvec.py +++ b/tests/pf/test_mag_differential_jvecjtvec.py @@ -2,7 +2,7 @@ import numpy as np import pytest from simpeg import maps, utils -from discretize.utils import mkvc, refine_tree_xyz +from discretize.utils import mkvc import discretize import simpeg.potential_fields as PF @@ -20,15 +20,9 @@ def mesh(): hz = dhz * np.ones(nbcz) _mesh = discretize.TreeMesh([hx, hy, hz], x0="CCC") - xp, yp, zp = np.meshgrid([-1400.0, 1400.0], [-1400.0, 1400.0], [-1000.0, 200.0]) - xy = np.c_[mkvc(xp), mkvc(yp), mkvc(zp)] - _mesh = refine_tree_xyz( - _mesh, - xy, - method="box", - finalize=False, - octree_levels=[1, 1, 1, 1], - ) + x0 = np.array([-1400.0, -1400.0, -1000.0]) + x1 = np.array([1400.0, 1400.0, 200.0]) + _mesh.refine_box(x0, x1, levels=-1, finalize=False) _mesh.finalize() return _mesh diff --git a/tests/pf/test_mag_inversion_linear_Octree.py b/tests/pf/test_mag_inversion_linear_Octree.py index 46e483c8d8..b1c4faabdc 100644 --- a/tests/pf/test_mag_inversion_linear_Octree.py +++ b/tests/pf/test_mag_inversion_linear_Octree.py @@ -1,9 +1,10 @@ import shutil import unittest import numpy as np + import pytest import matplotlib.pyplot as plt -from discretize.utils import mesh_builder_xyz, refine_tree_xyz, active_from_xyz +from discretize.utils import mesh_builder_xyz, active_from_xyz from simpeg import ( directives, maps, @@ -30,7 +31,7 @@ def setUp(self): # Create a mesh h = [5, 5, 5] padDist = np.ones((3, 2)) * 100 - nCpad = [2, 4, 2] + nCpad = [2, 3, 2] # Create grid of points for topography # Lets create a simple Gaussian topo and set the active cells @@ -70,14 +71,7 @@ def setUp(self): mesh_type="TREE", ) - self.mesh = refine_tree_xyz( - self.mesh, - topo, - method="surface", - octree_levels=nCpad, - octree_levels_padding=nCpad, - finalize=True, - ) + self.mesh.refine_surface(topo, padding_cells_by_level=nCpad, finalize=True) # Define an active cells from topo actv = active_from_xyz(self.mesh, topo) diff --git a/tests/pf/test_mag_nonLinear_Amplitude.py b/tests/pf/test_mag_nonLinear_Amplitude.py index 80033d516b..53a9b4f31c 100644 --- a/tests/pf/test_mag_nonLinear_Amplitude.py +++ b/tests/pf/test_mag_nonLinear_Amplitude.py @@ -15,7 +15,7 @@ from simpeg.potential_fields import magnetics from simpeg import utils from simpeg.utils import mkvc -from discretize.utils import mesh_builder_xyz, refine_tree_xyz, active_from_xyz +from discretize.utils import mesh_builder_xyz, active_from_xyz import unittest import shutil @@ -66,9 +66,7 @@ def setUp(self): mesh = mesh_builder_xyz( rxLoc, h, padding_distance=padDist, depth_core=100, mesh_type="tree" ) - mesh = refine_tree_xyz( - mesh, topo, method="surface", octree_levels=[4, 4], finalize=True - ) + mesh.refine_surface(topo, padding_cells_by_level=[4, 4], finalize=True) # Define an active cells from topo actv = active_from_xyz(mesh, topo) diff --git a/tests/pf/test_mag_vector_amplitude.py b/tests/pf/test_mag_vector_amplitude.py index 87ca2adf7c..daa0d20587 100644 --- a/tests/pf/test_mag_vector_amplitude.py +++ b/tests/pf/test_mag_vector_amplitude.py @@ -13,7 +13,7 @@ ) -from discretize.utils import mesh_builder_xyz, refine_tree_xyz, active_from_xyz +from discretize.utils import mesh_builder_xyz, active_from_xyz import numpy as np from simpeg.potential_fields import magnetics as mag import shutil @@ -62,9 +62,7 @@ def setUp(self): mesh = mesh_builder_xyz( xyzLoc, h, padding_distance=padDist, depth_core=100, mesh_type="tree" ) - mesh = refine_tree_xyz( - mesh, topo, method="surface", octree_levels=[4, 4], finalize=True - ) + mesh.refine_surface(topo, padding_cells_by_level=[4, 4], finalize=True) self.mesh = mesh # Define an active cells from topo actv = active_from_xyz(mesh, topo) diff --git a/tests/pf/test_magnetics_analytics.py b/tests/pf/test_magnetics_analytics.py index c93ac3c27e..b6ddbfaa87 100644 --- a/tests/pf/test_magnetics_analytics.py +++ b/tests/pf/test_magnetics_analytics.py @@ -7,7 +7,6 @@ import numpy as np from scipy.constants import mu_0 - plotIt = False diff --git a/tests/pf/test_pf_quadtree_inversion_linear.py b/tests/pf/test_pf_quadtree_inversion_linear.py index ec1c71ec89..656a9e7425 100644 --- a/tests/pf/test_pf_quadtree_inversion_linear.py +++ b/tests/pf/test_pf_quadtree_inversion_linear.py @@ -3,7 +3,7 @@ import numpy as np from discretize import TensorMesh -from discretize.utils import mesh_builder_xyz, mkvc, refine_tree_xyz +from discretize.utils import mesh_builder_xyz, mkvc from simpeg import ( data_misfit, @@ -50,20 +50,15 @@ def create_mesh(h, padDist, nCpad, topo, data, min_height=1.0): padDist = np.ones((2, 2)) * 100 nCpad = [2, 4] - mesh = mesh_builder_xyz( + self.mesh = mesh_builder_xyz( topo[:, :2], h, padding_distance=padDist, mesh_type="TREE", ) - self.mesh = refine_tree_xyz( - mesh, - data[:, :2], - method="radial", - octree_levels=nCpad, - octree_levels_padding=nCpad, - finalize=True, + self.mesh.refine_points( + data[:, :2], padding_cells_by_level=nCpad, finalize=True ) # elevations are Nx2 array of [bottom-southwest, top-northeast] corners diff --git a/tests/utils/test_default_solver.py b/tests/utils/test_default_solver.py index 4c86b47333..aca4d75325 100644 --- a/tests/utils/test_default_solver.py +++ b/tests/utils/test_default_solver.py @@ -1,5 +1,4 @@ import re -import warnings import pytest from pymatsolver import SolverCG @@ -36,15 +35,8 @@ class Temp: assert initial_default is after_default -def test_deprecation_warning(): - """Test deprecation warning for the warn argument.""" - regex = re.escape("The `warn` argument has been deprecated and will be removed in") - with pytest.warns(FutureWarning, match=regex): +def test_no_warn_argument(): + """Test removal of the warn argument.""" + regex = re.escape("get_default_solver() got an unexpected keyword argument") + with pytest.raises(TypeError, match=regex): get_default_solver(warn=True) - - -def test_no_deprecation_warning(): - """Test if no deprecation warning is issued with default parameters.""" - with warnings.catch_warnings(): - warnings.simplefilter("error") # raise error if warning was raised - get_default_solver() diff --git a/tests/utils/test_deprecate.py b/tests/utils/test_deprecate.py index 924ee56e87..d8e42e7278 100644 --- a/tests/utils/test_deprecate.py +++ b/tests/utils/test_deprecate.py @@ -3,7 +3,6 @@ from importlib import import_module from discretize import TensorMesh - mesh = TensorMesh([2, 2, 2]) locs = np.array([[1.0, 2.0, 3.0]]) diff --git a/tests/utils/test_io_utils.py b/tests/utils/test_io_utils.py index ef6fc2d473..1210d1467a 100644 --- a/tests/utils/test_io_utils.py +++ b/tests/utils/test_io_utils.py @@ -18,7 +18,6 @@ ) import os - #################################################################################### # POTENTIAL FIELDS #################################################################################### diff --git a/tests/utils/test_mesh_utils.py b/tests/utils/test_mesh_utils.py index 71c7d08a27..2d196c64dc 100644 --- a/tests/utils/test_mesh_utils.py +++ b/tests/utils/test_mesh_utils.py @@ -1,3 +1,4 @@ +import re import pytest import numpy as np from discretize import TensorMesh, TreeMesh, SimplexMesh @@ -97,10 +98,18 @@ def test_mesh_type_error(): active_cells = get_active_cells(mesh) pts = get_points(dim) - with pytest.raises(NotImplementedError): + msg = re.escape( + f"Invalid mesh of type '{type(mesh).__name__}'. " + "`shift_to_discrete_topography` only supports TensorMesh and TreeMesh." + ) + with pytest.raises(TypeError, match=msg): shift_to_discrete_topography(mesh, pts, active_cells) - with pytest.raises(NotImplementedError): + msg = re.escape( + f"Invalid mesh of type '{type(mesh).__name__}'. " + "`get_discrete_topography` only supports TensorMesh and TreeMesh." + ) + with pytest.raises(TypeError, match=msg): get_discrete_topography(mesh, active_cells) diff --git a/tutorials/02-linear_inversion/plot_inv_2_inversion_irls.py b/tutorials/02-linear_inversion/plot_inv_2_inversion_irls.py index b8d8c6317e..6a1c883b70 100644 --- a/tutorials/02-linear_inversion/plot_inv_2_inversion_irls.py +++ b/tutorials/02-linear_inversion/plot_inv_2_inversion_irls.py @@ -184,7 +184,7 @@ def g(k): update_Jacobi = directives.UpdatePreconditioner() # Save output at each iteration -saveDict = directives.SaveOutputEveryIteration(save_txt=False) +saveDict = directives.SaveOutputEveryIteration(on_disk=False) # Define the directives as a list directives_list = [ diff --git a/tutorials/06-ip/plot_inv_2_dcip2d.py b/tutorials/06-ip/plot_inv_2_dcip2d.py index 19529d1eaa..fc59741b82 100644 --- a/tutorials/06-ip/plot_inv_2_dcip2d.py +++ b/tutorials/06-ip/plot_inv_2_dcip2d.py @@ -54,7 +54,6 @@ ) from simpeg.utils.io_utils.io_utils_electromagnetics import read_dcip2d_ubc - mpl.rcParams.update({"font.size": 16}) # sphinx_gallery_thumbnail_number = 7 @@ -338,7 +337,7 @@ beta_schedule = directives.BetaSchedule(coolingFactor=3, coolingRate=2) # Options for outputting recovered models and predicted data for each beta. -save_iteration = directives.SaveOutputEveryIteration(save_txt=False) +save_iteration = directives.SaveOutputEveryIteration(on_disk=False) # Setting a stopping criteria for the inversion. target_misfit = directives.TargetMisfit(chifact=1) @@ -559,7 +558,7 @@ update_sensitivity_weighting = directives.UpdateSensitivityWeights(threshold_value=1e-3) starting_beta = directives.BetaEstimate_ByEig(beta0_ratio=1e1) beta_schedule = directives.BetaSchedule(coolingFactor=2, coolingRate=1) -save_iteration = directives.SaveOutputEveryIteration(save_txt=False) +save_iteration = directives.SaveOutputEveryIteration(on_disk=False) target_misfit = directives.TargetMisfit(chifact=1.0) update_jacobi = directives.UpdatePreconditioner() diff --git a/tutorials/06-ip/plot_inv_3_dcip3d.py b/tutorials/06-ip/plot_inv_3_dcip3d.py index 1c5aa8f9bc..55b0e4e288 100644 --- a/tutorials/06-ip/plot_inv_3_dcip3d.py +++ b/tutorials/06-ip/plot_inv_3_dcip3d.py @@ -384,7 +384,7 @@ beta_schedule = directives.BetaSchedule(coolingFactor=2.5, coolingRate=2) # Options for outputting recovered models and predicted data for each beta. -save_iteration = directives.SaveOutputEveryIteration(save_txt=False) +save_iteration = directives.SaveOutputEveryIteration(on_disk=False) # Setting a stopping criteria for the inversion. target_misfit = directives.TargetMisfit(chifact=1) @@ -632,7 +632,7 @@ update_sensitivity_weighting = directives.UpdateSensitivityWeights(threshold_value=1e-3) starting_beta = directives.BetaEstimate_ByEig(beta0_ratio=1e2) beta_schedule = directives.BetaSchedule(coolingFactor=2.5, coolingRate=1) -save_iteration = directives.SaveOutputEveryIteration(save_txt=False) +save_iteration = directives.SaveOutputEveryIteration(on_disk=False) target_misfit = directives.TargetMisfit(chifact=1.0) update_jacobi = directives.UpdatePreconditioner() diff --git a/tutorials/07-fdem/plot_fwd_3_fem_3d.py b/tutorials/07-fdem/plot_fwd_3_fem_3d.py index b7c4345257..d2c02f3d16 100644 --- a/tutorials/07-fdem/plot_fwd_3_fem_3d.py +++ b/tutorials/07-fdem/plot_fwd_3_fem_3d.py @@ -40,7 +40,6 @@ import matplotlib as mpl import matplotlib.pyplot as plt - save_file = False # sphinx_gallery_thumbnail_number = 2 diff --git a/tutorials/07-fdem/plot_inv_1_em1dfm.py b/tutorials/07-fdem/plot_inv_1_em1dfm.py index bb6b88a90a..801187b5de 100644 --- a/tutorials/07-fdem/plot_inv_1_em1dfm.py +++ b/tutorials/07-fdem/plot_inv_1_em1dfm.py @@ -181,7 +181,7 @@ inv_thicknesses = np.logspace(0, 1.5, 25) # Define a mesh for plotting and regularization. -mesh = TensorMesh([(np.r_[inv_thicknesses, inv_thicknesses[-1]])], "0") +mesh = TensorMesh([np.r_[inv_thicknesses, inv_thicknesses[-1]]], "0") ################################################################# @@ -267,7 +267,7 @@ update_Jacobi = directives.UpdatePreconditioner() # Options for outputting recovered models and predicted data for each beta. -save_iteration = directives.SaveOutputEveryIteration(save_txt=False) +save_iteration = directives.SaveOutputEveryIteration(on_disk=False) # Directive for the IRLS update_IRLS = directives.UpdateIRLS(max_irls_iterations=30, irls_cooling_factor=1.5) diff --git a/tutorials/08-tdem/plot_fwd_1_em1dtm_waveforms.py b/tutorials/08-tdem/plot_fwd_1_em1dtm_waveforms.py index bd307c843f..04d9a39596 100644 --- a/tutorials/08-tdem/plot_fwd_1_em1dtm_waveforms.py +++ b/tutorials/08-tdem/plot_fwd_1_em1dtm_waveforms.py @@ -29,7 +29,6 @@ from simpeg import maps import simpeg.electromagnetics.time_domain as tdem - ##################################################################### # Define Waveforms # ---------------- diff --git a/tutorials/08-tdem/plot_fwd_3_tem_3d.py b/tutorials/08-tdem/plot_fwd_3_tem_3d.py index ab7423170a..b67fcc92fc 100644 --- a/tutorials/08-tdem/plot_fwd_3_tem_3d.py +++ b/tutorials/08-tdem/plot_fwd_3_tem_3d.py @@ -40,7 +40,6 @@ import matplotlib.pyplot as plt import os - save_file = False # sphinx_gallery_thumbnail_number = 3 diff --git a/tutorials/08-tdem/plot_inv_1_em1dtm.py b/tutorials/08-tdem/plot_inv_1_em1dtm.py index f5e4bfa0a0..b09f9d5db5 100644 --- a/tutorials/08-tdem/plot_inv_1_em1dtm.py +++ b/tutorials/08-tdem/plot_inv_1_em1dtm.py @@ -170,7 +170,7 @@ inv_thicknesses = np.logspace(0, 1.5, 25) # Define a mesh for plotting and regularization. -mesh = TensorMesh([(np.r_[inv_thicknesses, inv_thicknesses[-1]])], "0") +mesh = TensorMesh([np.r_[inv_thicknesses, inv_thicknesses[-1]]], "0") ######################################################## @@ -256,7 +256,7 @@ update_Jacobi = directives.UpdatePreconditioner() # Options for outputting recovered models and predicted data for each beta. -save_iteration = directives.SaveOutputEveryIteration(save_txt=False) +save_iteration = directives.SaveOutputEveryIteration(on_disk=False) # Directives for the IRLS update_IRLS = directives.UpdateIRLS(max_irls_iterations=30, irls_cooling_factor=1.5) diff --git a/tutorials/12-seismic/plot_inv_1_tomography_2D.py b/tutorials/12-seismic/plot_inv_1_tomography_2D.py index c25adc23c9..9165d5050b 100644 --- a/tutorials/12-seismic/plot_inv_1_tomography_2D.py +++ b/tutorials/12-seismic/plot_inv_1_tomography_2D.py @@ -252,7 +252,7 @@ starting_beta = directives.BetaEstimate_ByEig(beta0_ratio=2e0) # Save output at each iteration -saveDict = directives.SaveOutputEveryIteration(save_txt=False) +saveDict = directives.SaveOutputEveryIteration(on_disk=False) # Define the directives as a list directives_list = [starting_beta, update_IRLS, saveDict] diff --git a/tutorials/13-joint_inversion/plot_inv_3_cross_gradient_pf.py b/tutorials/13-joint_inversion/plot_inv_3_cross_gradient_pf.py index ae20614ebe..ee5a9fe666 100755 --- a/tutorials/13-joint_inversion/plot_inv_3_cross_gradient_pf.py +++ b/tutorials/13-joint_inversion/plot_inv_3_cross_gradient_pf.py @@ -371,7 +371,7 @@ beta_schedule = directives.PairedBetaSchedule(cooling_factor=5, cooling_rate=1) # Options for outputting recovered models and predicted data for each beta. -save_iteration = directives.SimilarityMeasureSaveOutputEveryIteration(save_txt=False) +save_iteration = directives.SimilarityMeasureSaveOutputEveryIteration(on_disk=False) joint_inv_dir = directives.SimilarityMeasureInversionDirective() diff --git a/tutorials/_temporary/plot_4c_fdem3d_inversion.py b/tutorials/_temporary/plot_4c_fdem3d_inversion.py index 06006bf9a0..b3d6e508e4 100644 --- a/tutorials/_temporary/plot_4c_fdem3d_inversion.py +++ b/tutorials/_temporary/plot_4c_fdem3d_inversion.py @@ -346,7 +346,7 @@ beta_schedule = directives.BetaSchedule(coolingFactor=10, coolingRate=3) # Options for outputting recovered models and predicted data for each beta. -save_iteration = directives.SaveOutputEveryIteration(save_txt=False) +save_iteration = directives.SaveOutputEveryIteration(on_disk=False) # Setting a stopping criteria for the inversion. target_misfit = directives.TargetMisfit(chifact=1) diff --git a/tutorials/_temporary/plot_inv_1_em1dtm_stitched_skytem.py b/tutorials/_temporary/plot_inv_1_em1dtm_stitched_skytem.py index 0643bca063..1f3ac6ef20 100644 --- a/tutorials/_temporary/plot_inv_1_em1dtm_stitched_skytem.py +++ b/tutorials/_temporary/plot_inv_1_em1dtm_stitched_skytem.py @@ -321,7 +321,7 @@ update_Jacobi = directives.UpdatePreconditioner() # Options for outputting recovered models and predicted data for each beta. -save_iteration = directives.SaveOutputEveryIteration(save_txt=False) +save_iteration = directives.SaveOutputEveryIteration(on_disk=False) update_IRLS = directives.UpdateIRLS( diff --git a/zizmor.yml b/zizmor.yml index ada6a52fd5..06dc9acc08 100644 --- a/zizmor.yml +++ b/zizmor.yml @@ -17,3 +17,4 @@ rules: reviewdog/action-flake8: ref-pin # Allow to use tags to pin MiraGeoscience actions. MiraGeoscience/*: ref-pin +