Skip to content

Set physical properties as maps - #1593

Closed
jcapriot wants to merge 114 commits into
simpeg:mainfrom
jcapriot:set_property_map
Closed

jcapriot wants to merge 114 commits into
simpeg:mainfrom
jcapriot:set_property_map

Conversation

@jcapriot

Copy link
Copy Markdown
Member

Summary

Allows physical properties to be directly set as maps

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

More simulation cleanup

What does this implement/fix?

Currently in simpeg, we have two ways of interacting with a simulations physical properties.

  1. Setting sim.rho to be an array
  2. Setting sim.rhoMap to be a mapping, which means that accessing sim.rho will calculate sim.rho using the mapping from the model to the physical property.

I'm proposing unifying these two operations into only the physical property attribute itself. I.E. I want to be able to set sim.rho = mapping, and have it be functionally the same as interaction 2) above.

sim.rho = array

or

sim.rho = mapping

which allows us to then deprecate sim.rhoMap.

Additional information

A few details:

  • The PhysicalProperty class is now a subclass of property, allowing a more intuitive behavior than before.
    • Previously a PhysicalProperty is transformed into a property by the PhysicalPropertyMeta metaclass. This meant, there was not a good way to modify a physical properties getter or setters (See the awkward hijacking of __getattr__ in the BaseMagneticPDE simulation).
  • If a PhysicalProperty is not invertible, assigning a mapping is disallowed
  • You can change the invertibility of a PhysicalProperty on a class-by-class basis.
  • PhysicalProperty` derivatives are privatized,
  • I think removing public access to the stored mapping and the deriv function will not impact end users, (for developers there is still a way to access the map, and I think it's a cleaner method for when we must modify the behavior, e.g. the IP class.)

The previous functionality of:

  • props.Mapping
  • props.Derivative
  • props.Invertible
  • props.Reciprocal

is now unified into props.PhysicalProperty

Better represent that the object passes is a class (and not an instance of it).
Allows to be more descriptive and catch better errors on the simulations that need specific mesh types.
Better represent that the object passes is a class (and not an instance of it).
@codecov

codecov Bot commented Dec 19, 2024 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 96.68285% with 41 lines in your changes missing coverage. Please review.

Project coverage is 86.62%. Comparing base (d6819fa) to head (3d71718).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
simpeg/props.py 91.70% 16 Missing and 3 partials ⚠️
simpeg/base/physical_property.py 95.31% 4 Missing and 2 partials ⚠️
...static/spectral_induced_polarization/simulation.py 78.26% 3 Missing and 2 partials ⚠️
.../electromagnetics/static/resistivity/simulation.py 50.00% 1 Missing and 1 partial ⚠️
...ectromagnetics/static/self_potential/simulation.py 83.33% 0 Missing and 2 partials ⚠️
simpeg/flow/richards/simulation.py 77.77% 2 Missing ⚠️
...impeg/electromagnetics/frequency_domain/sources.py 91.66% 0 Missing and 1 partial ⚠️
...etics/viscous_remanent_magnetization/simulation.py 94.44% 0 Missing and 1 partial ⚠️
simpeg/meta/__init__.py 0.00% 1 Missing ⚠️
simpeg/potential_fields/gravity/simulation.py 80.00% 1 Missing ⚠️
... and 1 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1593      +/-   ##
==========================================
+ Coverage   86.51%   86.62%   +0.10%     
==========================================
  Files         409      413       +4     
  Lines       52692    53029     +337     
  Branches     5000     5038      +38     
==========================================
+ Hits        45589    45935     +346     
+ Misses       5681     5680       -1     
+ Partials     1422     1414       -8     

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

@santisoler santisoler mentioned this pull request Jan 8, 2025
6 tasks done
@lheagy

lheagy commented Jan 12, 2025 •

Copy link
Copy Markdown
Member

Thanks for kicking this off Joe, and my apologies for not having time to jump in sooner on this idea. As I mentioned in our last SimPEG meeting, I am quite concerned about the potential confusion that could be introduced by collapsing the physical property (e.g. rho) with the mapping (e.g. rhoMap). There are a few reasons for my concerns.

First, mappings are a challenging concept for people to grasp when they are first introduced to SimPEG. This is fair, it is an abstract concept. Right now, we can explain that if you set a rhoMap then rho is an invertible property in the inversion. If we combine the two, that statement becomes more complex.

Importantly, this implementation also means that what sim.rho is depends on the state. If we instantiate rho as a mapping, then there are two possible states

  • if sim.model = None, then sim.rho is a mapping
  • but, if sim.model is not None then sim.rho is a vector, which is the mapped physical property

I think this is dangerous. It is quite a common pattern to instantiate the simulation class and then access the mapping from there,

e.g.

sim = tdem.Simulation1D(thicknesses = thicknesses, sigmaMap=sigma_map)
sigma0 = sim.sigmaMap * starting model

and after the inversion

sigma_recovered = sim.sigmaMap * mrec

This is fine in the current implementation, but if we combine the two, then this could lead to some unexpected behaviours
e.g.

sim = tdem.Simulation1D(thicknesses = thicknesses, sigma=sigma_map)
sigma0 = sim.sigma * starting model  # this is valid and will perform the mapping of our starting model

and after the inversion

sigma_recovered = sim.sigma * mrec  # this now makes no sense! After the inversion, the simulation will have a model, so this is multiplying two vectors

This example is particularly dangerous if the mapping is a one-to-one mapping (e.g. like an exp map), because if the model is set on the simulation sim.sigma will be a vector of the same size as mrec. So the two quantities will be valid to multiply. However, the output of that multiplication is meaningless as it would be the mapped physical property times the unmapped model vector. This will be difficult to debug, and there is nothing we can do to guard against it because it would multiplying two numpy vectors.

It is a common pattern amongst our users to access the mapping from the simulation. We even do this in our own tutorials (e.g. the SEG NS 2024 tutorial)
image

So I don't think we can reasonably ask our users to unlearn the pattern of accessing the mapping from the simulation. I think we are much better of staying explicit when defining simulations and that propMap is always a Map and prop is a vector defining the physical property.

Edit In looking more at the code, it wasn't clear to me what sim.sigma would return if the model has not been set, but in any case, I think if the user sets a map on the simulation, they should still always be able to access that.

@jcapriot

jcapriot commented Jan 13, 2025 •

Copy link
Copy Markdown
Member Author

The functionality I'm proposing here is a little bit different than what you've interpreted it there.

Basically these things would happen:

If you set sigma to something besides a map, it will be a not be dependent on the model.

>>> sim.sigma = [1,2,3]
>>> sim.sigma
[1, 2, 3]

If you set sigma as a map, it becomes a dynamic property dependent on sim.model:

>>> sim.model = [1, 2, 3]
>>> sim.sigma = maps.IdentityMap()
>>> sim.sigma
[1, 2, 3]
>>> sim.model = [3, 4, 5]
>>> sim.sigma
[3, 4, 5]

The only difference between this and what we have now is that we would currently have to write: sim.sigmaMap = map instead of sim.sigma = map to achieve this behavior.

If you have not set a model then:

>>> sim.sigma = maps.IdentityMap()
>>> sim.sigma
AttributeError: Saying something about sigma was set as a mapping, and requires a model, but a model wasn't set

If you haven't given sigma a value at all (and it is not an optional property) then it would raise an attribute error.

>>> sim.sigma
AttributeError: You haven't given sigma a value nor a mapping...

I suspect that PhysicalProperty attributes are the least understood aspects of simpeg simulations that users interact with everyday.

I do see your point about allowing users retrieve the assigned mapping to a simulation, for which this method would add a public method along the lines of sim.get_property_mapping('sigma').

One of the clunky things that I've found while writing simpeg is especially apparent on the IP, Spectral IP, and Self-Potential methods. You can't really change whether a PhysicalProperty is invertible on subclasses. These classes all subclass DC simulations (where sigma is invertible) yet sigma is not invertible on those child classes. Inheriting the DC sims reduce a significant amount of code duplication, but there's no way to remove sigmaMap from the class's attributes. This functionality makes it possible to do this.

The cleanest thing I like about this approach (which is something that I think we could change without doing this entire approach) Is that PhysicalProperty implements the Descriptor protocol (see https://docs.python.org/3/howto/descriptor.html for more details on descriptors). Right now we are basically using a MetaClass to mimic all of the functionalities of descriptors instead of just using descriptors. I know metaclasses took me a while to understand and I suspect it is also beyond the scope of many python developers. Implementing the PhysicalProperty items as descriptors would allow us to get rid of the PhysicalPropertyMetaclass altogether in the future, hopefully simplifying this bit of code.

Also, something I'd love to tackle in the future is to really extend the power of PhysicalProperty beyond just allowing for maps, i.e. #1345. So having sigmaMap could be limiting us! Potentially allowing folding the NestedModeler into the PhysicalProperty attribute.

@jcapriot

jcapriot commented Jan 14, 2025 •

Copy link
Copy Markdown
Member Author

Thinking on the interface a bit more overnight, and I think I've got something that could make the concept of Maps clearer, while also allowing for future extensions to a physical property's functionality.

What if instead we made mapping a physical property a method instead?

>>> sim.parametrize('sigma', maps.IdentityMap())

And for a user retrieving it:

>>> mapping = sim.parametrizations.sigma

This is very similar to what pytorch does (where you can re-parametrize a neural network's parameters). See their tutorial here: https://pytorch.org/tutorials/intermediate/parametrizations.html

It would accomplish the major goals I have:

  • At a first glance, it is clear what the mapping is actually doing. It's parametrizing the sigma physical property. Potentially making the concept of Maps easier to understand.
  • Easy to retrieve the object used to parameterize the property
  • You can alter a physical property's invertibility on subclasses (simply disallow it to be parametrized)
  • Reduces namespace clutter on simulations with multiple invertible physical properties.
  • pep8!

Another point of discussion would be what to do for a simulation's call signature.

I'd be in favor of using a single argument to the simulation to handle both cases.

>>> sim = SigmaSimulation(mesh, survey, 1.0)  # constant sigma

>>> sim = SigmaSimulation(mesh, survey, maps.IdentityMap())  # parameterized sigma

Where:

class SigmaSimulation():
    def __init__(self, mesh, survey, sigma, **kwargs):
        if isinstance(sigma, IdentityMap):
            self.parameterize('sigma', sigma)
        else:
            self.sigma = sigma
        ...

Which would allow us to make the simulation's call signature even clearer by promoting sigma to a required argument. (though in the cases of reciprocal property inputs, they would of course have to be given default None values and checked for having both assigned). Having an argument's type determine behavior of a method is probably much more common throughout python land anyways.

@jcapriot jcapriot mentioned this pull request Jan 28, 2025
6 tasks done
@jcapriot

jcapriot commented Feb 5, 2025

Copy link
Copy Markdown
Member Author

Closing in favor of working towards #1601

@jcapriot jcapriot closed this Feb 5, 2025
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.

2 participants