Skip to content

Set the model when calling getJ in DC and SIP simulations - #1361

Merged
santisoler merged 15 commits into
mainfrom
getJ
Apr 24, 2025
Merged

santisoler merged 15 commits into
mainfrom
getJ

Conversation

@lheagy

@lheagy lheagy commented Feb 17, 2024 •

Copy link
Copy Markdown
Member

Summary

make sure we set the model when calling getJ. This will ensure that if the model is changed, the sensitivity matrix is cleared (for nonlinear problems) and the sensitivity recomputed. This will close #1358

PR Checklist

  • If this is a work in progress PR, set as a Draft PR
  • Linted my code according to the style guides.
  • Added tests to verify changes to the code.
  • Added necessary documentation to any new functions/classes following the
    expect style.
  • Marked as ready for review (if this is was a draft PR), and converted
    to a Pull Request
  • Tagged @simpeg/simpeg-developers when ready for review.

Reference issue

Closes #1358

@codecov

codecov Bot commented Feb 17, 2024 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 96.26168% with 4 lines in your changes missing coverage. Please review.

Project coverage is 86.03%. Comparing base (725a09b) to head (14a01b8).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
tests/em/static/test_model_assignment.py 96.11% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1361      +/-   ##
==========================================
+ Coverage   86.01%   86.03%   +0.02%     
==========================================
  Files         411      412       +1     
  Lines       54250    54356     +106     
  Branches     5106     5106              
==========================================
+ Hits        46661    46765     +104     
+ Misses       6171     6170       -1     
- Partials     1418     1421       +3     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@lheagy

lheagy commented Feb 21, 2024

Copy link
Copy Markdown
Member Author

@simpeg/simpeg-developers: this is ready for review!

@santisoler santisoler left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for tackling this @lheagy.

The fixes are very straightforward, but since this is a bugfix, I would suggest adding some tests that would fail without them, so we can be sure we are not facing them again in the future.

Something like this:

import pytest
import numpy as np

from discretize import TensorMesh
from SimPEG import utils
from SimPEG.maps import IdentityMap
from SimPEG.electromagnetics import resistivity as dc


@pytest.fixture
def mesh():
    """Sample mesh."""
    cs = 0.5
    npad = 11
    hx = [(cs, npad, -1.5), (cs, 15), (cs, npad, 1.5)]
    hy = [(cs, npad, -1.5), (cs, 15), (cs, npad, 1.5)]
    hz = [(cs, npad, -1.5), (cs, 15), (cs, npad, 1.5)]
    mesh = TensorMesh([hx, hy, hz], x0="CCC")
    return mesh


@pytest.fixture
def survey(mesh):
    """Sample survey."""
    # Set up survey parameters for numeric solution
    x = mesh.nodes_x[(mesh.nodes_x > -75.0) & (mesh.nodes_x < 75.0)]
    y = mesh.nodes_y[(mesh.nodes_y > -75.0) & (mesh.nodes_y < 75.0)]

    Aloc = np.r_[1.25, 0.0, 0.0]
    Bloc = np.r_[-1.25, 0.0, 0.0]
    M = utils.ndgrid(x - 25.0, y, np.r_[0.0])
    N = utils.ndgrid(x + 25.0, y, np.r_[0.0])

    rx = dc.receivers.Dipole(M, N)
    src = dc.sources.Dipole([rx], Aloc, Bloc)
    survey = dc.survey.Survey([src])
    return survey


def test_getj_model_assignment(mesh, survey):
    """
    Test model assignment when calling the Simulation3DNodal.getJ method
    """
    simulation = dc.simulation.Simulation3DNodal(
        mesh=mesh, survey=survey, sigmaMap=IdentityMap(mesh)
    )
    model_1 = np.ones(mesh.nC) * 1e-2
    model_2 = np.ones(mesh.nC) * 1e-1
    j_1 = simulation.getJ(model_1)
    j_2 = simulation.getJ(model_2)
    # Check if the two Js are different
    assert not np.allclose(j_1, j_2)

Tests like this should be included for each class that has been modified.

@santisoler santisoler mentioned this pull request Feb 22, 2024
@lheagy

lheagy commented Feb 26, 2024

Copy link
Copy Markdown
Member Author

Many thanks @santisoler! These are great suggestions for the tests. If you have the time to add those, that would be awesome. I know it is a small thing, but I won't be able to get back to this for a bit. If not, no worries, I can try to find some time later in the week.

@santisoler

Copy link
Copy Markdown
Member

@lheagy, I've just pushed some tests for the DC simulations, plus one test for the SIP simulation. The DC tests are all passing, and they fail if we run them on main.

The test for SIP is falling into an error, but because I'm doing something wrong. Here I copy the traceback of the test failure:

=============================================== FAILURES ===============================================
________________________________ TestSIPSimulations.test_simulation_3d _________________________________

self = <tests.em.static.test_model_assignment.TestSIPSimulations object at 0x7fbf1f1e3810>
mesh_3d =
  TensorMesh: 8,820 cells

                      MESH EXTENT             CELL WIDTH      FACTOR
  dir    nC        mi...-262.50        262.50     25.00     25.00    1.00
   z     20       -500.00          0.00     25.00     25.00    1.00


survey_3d = <SimPEG.electromagnetics.static.spectral_induced_polarization.survey.Survey object at 0x7fbf24d8b5d0>

    def test_simulation_3d(self, mesh_3d, survey_3d):
        """
        Test model assignment on the ``getJ`` method of 3d simulations
        """
        wires = Wires(("eta", mesh_3d.nC), ("taui", mesh_3d.nC))
        sigma = np.ones(mesh_3d.nC) * 1e-2
        simulation = sip.Simulation3DNodal(
            mesh_3d,
            sigma=sigma,
            survey=survey_3d,
            etaMap=wires.eta,
            tauiMap=wires.taui,
        )
        model_1 = np.r_[sigma, 1.0 / sigma]
        model_2 = np.r_[sigma * 2, 1.0 / sigma]
        # Call `getJ` passing a model and check if it was correctly assigned
>       j_1 = simulation.getJ(model_1)

tests/em/static/test_model_assignment.py:161:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <SimPEG.electromagnetics.static.spectral_induced_polarization.simulation.Simulation3DNodal object at 0x7fbf1f222b50>
m = array([1.e-02, 1.e-02, 1.e-02, ..., 1.e+02, 1.e+02, 1.e+02])
f = <SimPEG.electromagnetics.static.resistivity.fields.Fields3DNodal object at 0x7fbf3613f750>

    def getJ(self, m, f=None):
        """
        Generate Full sensitivity matrix
        """
        self.model = m

        if self._Jmatrix is not None:
            return self._Jmatrix
        else:
            if self.verbose:
                print("Calculating J and storing")
            if f is None:
                f = self.fields(m)

            Jt = np.zeros(
>               (self._P.shape[1], int(self.survey.nD / self.survey.unique_times.size)),
                order="F",
            )
E           AttributeError: 'Simulation3DNodal' object has no attribute '_P'

SimPEG/electromagnetics/static/spectral_induced_polarization/simulation.py:373: AttributeError

Would you take a look at it and see why is this failing?

After that we would just need to write tests for the 2D SIP simulations. With that I think we should be able to merge this PR.

@jcapriot

Copy link
Copy Markdown
Member

It looks like self._P is only ever assigned if the user passes an actind array. There's actually a lot of logic that will probably not work for the SpectralInducedPolarization class when storeJ==True, and probably should be a separate PR fix.

@santisoler santisoler added this to the 0.25.0 milestone Apr 24, 2025
@santisoler santisoler modified the milestones: 0.25.0, 0.24.0 Apr 24, 2025
@santisoler santisoler changed the title set the model when calling getJ Set the model when calling getJ in DC and SIP simulations Apr 24, 2025
@santisoler

Copy link
Copy Markdown
Member

I'm merging this. The tests for the SIP are currently failing, but decorated with xfail, so the tests pass. I'll open an Issue to keep track of the issues on that simulation.

@santisoler
santisoler merged commit 24bf81e into main Apr 24, 2025
johnweis0480 pushed a commit to johnweis0480/simpeg_johnweis that referenced this pull request Jun 9, 2025
)

Make sure we set the model when calling getJ. This will ensure that if
the model is changed, the sensitivity matrix is cleared (for nonlinear
problems) and the sensitivity recomputed. This will close simpeg#1358

---------

Co-authored-by: Santiago Soler <[email protected]>
@santisoler
santisoler deleted the getJ branch September 17, 2025 23:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: Logic for getJ

3 participants