Skip to content

BUG: Logic for getJ #1358

Closed
Closed

Description

@lheagy

Describe the issue:

Right now, we cache Jmatrix in a lot of places (which is good for saving computation!) but we are not careful about checking if the m that is provided to getJ is indeed consistent with self.model and therefore with the Jmatrix that is returned. This can lead to some confusing behaviour

For example, if you are performing a sensitivity analysis, you could get yourself into a confusing spot

Reproducible code example:

model1 = halfspace 
model2 = model_with_structure 

sim = dc.Simulation2DNodal(mesh, survey, storeJ=True)  # because I later want to run an inversion 

J1 = sim.getJ(model1) 
J2 = sim.getJ(model2)  # this will return J1 -- wrong!

Error message:

No response

Runtime information:

latest SimPEG version

Context for the issue:

This is a conceptual bug. Although it could be resolved if we set storeJ=False, the behaviour is non-intuitive and is something that we should address.

The issue lies here

def getJ(self, m, f=None):
"""
Generate Full sensitivity matrix
"""
if getattr(self, "_Jmatrix", None) is None:
if self.verbose:
print("Calculating J and storing")
self.model = m
if f is None:
f = self.fields(m)
self._Jmatrix = (self._Jtvec(m, v=None, f=f)).T
return self._Jmatrix

My suggestion, include a check that the model provided is basically the same as self.model. If this is computationally expensive enough that we don't want to be calling it every time, then we could also allow m=None and we return the cached J. Something like the following:

def getJ(self, m=None, f=None):
    """
    Generate Full sensitivity matrix
    """
    if m is None:
        if self._Jmatrix is not None:
            return self._Jmatrix   # early return if no model provided and J has been created

    elif not np.all_close(m, self.model):
        self.model = m    # this will clear self._Jmatrix if it exists 

    if getattr(self, "_Jmatrix", None) is None:
        if self.verbose:
            print("Calculating J and storing")     
        if f is None:
            f = self.fields(m)
        self._Jmatrix = (self._Jtvec(self.model, v=None, f=f)).T
    return self._Jmatrix

Thanks @anna1963 for catching this!

Note that I only highlighted this for DC, but it will be common to wherever we have getJ

Activity

  1. ghwilliams commented on Feb 13, 2024

    @ghwilliams
    Contributor

    I had already experienced this too. My solution was to do
    sim1._Jmatrix = None
    sim1.getJ(myModel)
    in order to force getJ to return J for myModel.

  2. jcapriot commented on Feb 13, 2024

    @jcapriot
    Member

    We need to be vigilant about assigning to the model on calls to any function where the model is an argument.

    I.e. it should be:

    def getJ(self, m, f=None):
        self.model = m
        if self._Jmatrix is None:  #or getattr(self, '_Jmatrix', None)
           # build the Jmatrix

    Which should erase the cached _Jmatrix if the model has changed.

    We are only doing this on certain calls, in certain cases. It should be everywhere.

  3. ghwilliams commented on Feb 13, 2024

    @ghwilliams
    Contributor

    We could use checksum to check if the model has changed. Very vague idea here.

  4. santisoler commented on Feb 22, 2024

    @santisoler
    Member

    I've just reviewed @lheagy's PR (#1361) and I think we should go forward with that, but nonetheless I wanted to leave my two cents in this discussion.

    The proposed fix in #1361 (and how some other simulations handle the assignment of the model) can be error prone. By assigning the model with:

    self.model = m

    we are assigning the model attribute as a reference to the passed model. Therefore we could be changing that model from outside, what might introduce unwanted behaviour without any hint.

    For example, lets say we have the following simulation:

    from discretize import TensorMesh
    import numpy as np
    
    from SimPEG import utils
    
    from SimPEG.electromagnetics import resistivity as dc
    from SimPEG.maps import IdentityMap
    
    
    # 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")
    
    
    # Survey
    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])
    
    
    # Create simulation
    simulation = dc.simulation.Simulation3DNodal(
        mesh=mesh, survey=survey, sigmaMap=IdentityMap(mesh)
    )

    Then let's define a conductivity model and run getJ:

    sigma = np.ones(mesh.nC) * 1e-2
    simulation.getJ(sigma)

    Now, if we modify the sigma array:

    sigma[0] = 100

    we are also changing the stored model in the simulation:

    print(np.allclose(sigma, simulation.model))
    True
    

    This means that now the cached _Jmatrix doesn't correspond to the one of the assigned model.

    One possible solution is to assign a deep copy of the m array:

    self.model = m.copy()

    But this impacts performance: requires more RAM and allocates an array on every call. Another way to make sure that the current J corresponds to the right model is through a checksum, as @ghwilliams proposed.


    I'm just mentioning this to keep it in mind. We probably don't need to tackle this for this bugfix, but at some point it would be nice to revisit this.

  5. jcapriot commented on Feb 23, 2024

    @jcapriot
    Member

    I've just reviewed @lheagy's PR (#1361) and I think we should go forward with that, but nonetheless I wanted to leave my two cents in this discussion.

    The proposed fix in #1361 (and how some other simulations handle the assignment of the model) can be error prone. By assigning the model with:

    self.model = m

    we are assigning the model attribute as a reference to the passed model. Therefore we could be changing that model from outside, what might introduce unwanted behaviour without any hint.

    For example, lets say we have the following simulation:

    from discretize import TensorMesh
    import numpy as np
    
    from SimPEG import utils
    
    from SimPEG.electromagnetics import resistivity as dc
    from SimPEG.maps import IdentityMap
    
    
    # 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")
    
    
    # Survey
    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])
    
    
    # Create simulation
    simulation = dc.simulation.Simulation3DNodal(
        mesh=mesh, survey=survey, sigmaMap=IdentityMap(mesh)
    )

    Then let's define a conductivity model and run getJ:

    sigma = np.ones(mesh.nC) * 1e-2
    simulation.getJ(sigma)

    Now, if we modify the sigma array:

    sigma[0] = 100

    we are also changing the stored model in the simulation:

    print(np.allclose(sigma, simulation.model))
    True
    

    This means that now the cached _Jmatrix doesn't correspond to the one of the assigned model.

    One possible solution is to assign a deep copy of the m array:

    self.model = m.copy()

    But this impacts performance: requires more RAM and allocates an array on every call. Another way to make sure that the current J corresponds to the right model is through a checksum, as @ghwilliams proposed.

    I'm just mentioning this to keep it in mind. We probably don't need to tackle this for this bugfix, but at some point it would be nice to revisit this.

    That’s a very good point as well. I think what we could do is only copy it when it changes… The relevant bits are in the HasModel class. There it checks if the passed model is close to whatever came before. If it changes “enough” it stores the passed array on the model. Instead we could store it as a copy. We could even set the Writeable flag on this copied model to False to prevent people from modifying the stored copy.

  6. jcapriot commented on Feb 23, 2024

    @jcapriot
    Member

    self._model = value
    This is the line that would be updated.

  7. jcapriot commented on Feb 23, 2024

    @jcapriot
    Member

    As a note about checksums, since we’re talking about it. I don’t think it will be a realistic solution for this, because the checksum operation is not unique.

    Two arrays could have different values but the same checksum. This is referred to as a collision. So when two arrays would have the same check sum, you would still need to actually compare all of the values of the arrays… which means we would still need to store an immutable copy of the model to check against. So the operation would go:

    • pass in a model
    • Compute its checksum
    • If checksums are different:
      • arrays are different
    • If checksums are the same:
      • compare all of the elements of the array to an immutable copy of the stored array.
      • if any element is not equal:
        • arrays are different

    So, I don’t see anyway to get around storing an immutable copy of the array and just checking all of the values.

    I don’t have anything other than a feeling for this next bit: It’s also likely slower when the arrays are equal (which is the timing we actually care about). When the arrays are equal you would have to loop over the elements of the array to compute a checksum, then loop over all of the elements again to compare equality.

  8. santisoler commented on Feb 23, 2024

    @santisoler
    Member

    You're right that checksums might lead to collisions, but the sha256 hashes of two different arrays have a collision probability of $\simeq 1 / 2^{256}$, which is extremely low. In practical applications we could consider that two arrays with equal hashes have the same values.

    This is good enough for security applications, so I think we should be fine with using checksums to assess if the passed model is the same one as before or not.

  9. jcapriot commented on Feb 26, 2024

    @jcapriot
    Member

    That's true, then we would need to consider a few things:

    Our current logic, which happens after the input has been tested for consistent shape, type, etc.

    if new_model is not old_model:
        if not all_close(new_model, old_model):
            clear_caches()
    old_model = new_model

    Clearly this cannot catch in-place changes to the model.

    That being said, a few things it does well:

    1. If they are the same object it is very fast
    2. Only clears the cache if they are beyond an all_close
    3. Always re-stores the passed model (meaning it could eventually not pass an all_close after many changes.)

    Assuming we still want to be able to access the model vector last assigned to a simulation from sim.model

    The problem is that it can't check for inplace operations done to the model.
    A few potential solutions then:
    1) Store a copy of the new array (will never be able to short-circuit by checking two models are the same object)
    2) Hash the new input and compare to previous hash value
    3) Make the passed model immutable on storage model.flags['WRITEABLE'] = False.

    In general the timing we are most concerned with, is when we repeatedly pass the same model to the functions Jvec and Jtvec, as those are usually called repeatedly inside iterative CG solvers.

    Option 1 would require the most memory and more time than 3.
    Option 2 would require more time than 3 but similar amounts of memory as 3
    Option 3 would result in the quickest timing of the three (due to being able to check if they are the same object), but it could cause a few headaches to users.

    Something to consider about checking if the model is changed:

    • Do we want to continue using an all_close call to check for changes in the model?

      • If so, hashing is not applicable.
    • If 2 does take more time, is the amount of time even impactful?

    Some rough timing on machines, on an array of float64:

    • sha256 hashing and np.allclose take about the same amount of time. This is about 2-3 ms for a 1 million length array.
    • np.array_equal is about 10x as fast as the previous.
    • arr is arr is essentially free (<10ns).

    My first guess is that hashing probably won't take up that much time relative to doing the bigger operation of Jvec/Jtvec (we should also be conscious of if calling one of those with a stored J matrix will make multiple passes at assigning the model).

  10. santisoler commented on Feb 27, 2024

    @santisoler
    Member

    Thanks for sharing those thoughts @jcapriot.

    Just some personal opinions and preferences after reading them:

    Have clear scopes for the model attribute

    I think we should be super explicit at separating the scope and ownership of the class attributes. In this particular case, I think the model in the simulation shouldn't be a vector owned by the user, which could lead to unwanted behaviour in case that model gets change from outside the simulation class.

    I don't quite like the model.flags['WRITEABLE'] = False option. It's hard to document that, it's non-intuitive among scientific Python users, and if something goes wrong error messages will come from anywhere down the line (e.g.: try to edit the model after running the inversion), which would be a nightmare to debug.

    Keep simulation.model?

    Considering these opinions: if we really want to be able to access the last model passed to the simulation, I think the straight forward solution is to store a copy of the passed model:

    self.model = m.copy()

    Then the checks for updates could be done as you mentioned (np.allclose, np.array_equal).

    If we are not going to store the model in the simulation...

    If we choose that we can live without having the previous model in the simulation, then I think the hash solution is great. We would need to keep record of the hash of the last model passed to the simulation, and check against it everytime we need to return the J matrix. Something like:

    def getJ(self, model):
        model_hash = get_hash(model)
        if model_hash != self.model_hash:
            # Compute J matrix
            self._Jmatrix = ...
            # Update model_hash
            self.model_hash = model_hash
        return self._Jmatrix
  11. added a commit that references this issue on Jun 9, 2025
    e7e6c03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions