From bc0f026168debfa3f8ee314a5836b4fd11c8c3e4 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Thu, 24 Sep 2026 11:09:30 -0700 Subject: [PATCH 01/38] Start populating the User Guide Use the `jupyter-sphinx` extension to execute Python cells in the rst files. --- docs/conf.py | 1 + docs/user-guide/index.rst | 8 + docs/user-guide/inversion-concept.rst | 14 ++ docs/user-guide/minimizer.rst | 4 + docs/user-guide/objective-function.rst | 271 +++++++++++++++++++++++++ environment.yml | 1 + requirements-dev.txt | 1 + 7 files changed, 300 insertions(+) create mode 100644 docs/user-guide/inversion-concept.rst create mode 100644 docs/user-guide/minimizer.rst create mode 100644 docs/user-guide/objective-function.rst diff --git a/docs/conf.py b/docs/conf.py index c637d7a2..1ea4d7d8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -19,6 +19,7 @@ "sphinx.ext.intersphinx", "sphinx_design", "numpydoc", + "jupyter_sphinx", ] intersphinx_mapping = { diff --git a/docs/user-guide/index.rst b/docs/user-guide/index.rst index 018ea001..61b26e9b 100644 --- a/docs/user-guide/index.rst +++ b/docs/user-guide/index.rst @@ -2,3 +2,11 @@ User Guide ---------- + +.. toctree:: + :maxdepth: 2 + :caption: Basic concepts + + inversion-concept + objective-function + minimizer diff --git a/docs/user-guide/inversion-concept.rst b/docs/user-guide/inversion-concept.rst new file mode 100644 index 00000000..53aa5b4a --- /dev/null +++ b/docs/user-guide/inversion-concept.rst @@ -0,0 +1,14 @@ +Inversion problem +================= + +SimPEG’s new inversion framework is targeted to solve **deterministic inversion problems** particularly in the field of geophysics. +These are generally defined as an optimization problem in which we want to minimize a given objective function :math:`\phi(\mathbf{m})` that depends on a *model* vector :math:`\mathbf{m}` given certain conditions. +Mathematically this can be expressed as: + +.. math:: + + \mathbf{m}^* = \min\limits_{\mathbf{m}} \phi(\mathbf{m}) + +where :math:`\mathbf{m}^*` is the model that minimizes that objective function. + +In order to set up this problem we’ll need two main pieces: the :ref:`objective-function` and the :ref:`minimizer`. diff --git a/docs/user-guide/minimizer.rst b/docs/user-guide/minimizer.rst new file mode 100644 index 00000000..b0ee7a96 --- /dev/null +++ b/docs/user-guide/minimizer.rst @@ -0,0 +1,4 @@ +.. _minimizer: + +Minimizer +========= diff --git a/docs/user-guide/objective-function.rst b/docs/user-guide/objective-function.rst new file mode 100644 index 00000000..7f16da08 --- /dev/null +++ b/docs/user-guide/objective-function.rst @@ -0,0 +1,271 @@ +.. _objective-function: + +Objective function +================== + +Any objective function is defined as a vector function :math:`\phi: \mathbb{R}^M \rightarrow \mathbb{R}`, i.e. it takes a model vector :math:`\mathbf{m}` with :math:`M` elements and returns a single value. + +In the new SimPEG's inversion framework, objective functions are represented by a child of the :class:`inversion_ideas.base.Objective`, like the :class:`inversion_ideas.DataMisfit` for example. + +.. jupyter-execute:: + + import numpy as np + import inversion_ideas as ii + + # Define a linear regressor as a simulation + n_data, n_params = 10, 15 + simulation = ii.simulations.LinearRegressor.create_random(n_data, n_params, seed=42) + + # Create some random data and uncertainties + data = np.random.default_rng(seed=1414).uniform(size=n_data) + uncertainties = 1e-3 * np.ones_like(data) + + # Define a data misfit function + data_misfit = ii.DataMisfit(data, uncertainties, simulation) + data_misfit + +Once defined, the objective functions can only be evaluated on model vectors with ``n_params`` elements. We can check that property on every objective function: + +.. jupyter-execute:: + + print("Expected size of model vector:", data_misfit.n_params) + +Objective functions can be evaluated by calling them: + +.. jupyter-execute:: + + # Define some model + model = np.arange(n_params, dtype=np.float64) + + # Evaluate the data_misfit on that model + data_misfit(model) + +All objective functions have two methods to compute its derivatives: + +* :meth:`~inversion_ideas.base.Objective.gradient` computes the gradient of the objective function: :math:`\nabla \phi(\mathbf{m})`. +* :meth:`~inversion_ideas.base.Objective.hessian` computes the Hessian of the objective function, i.e. the matrix of the second derivatives: :math:`\nabla^2 \phi(\mathbf{m})`. + +.. jupyter-execute:: + + # Get gradient + gradient = data_misfit.gradient(model) + gradient + +.. jupyter-execute:: + + # Get Hessian + hessian = data_misfit.hessian(model) + hessian + + +.. important:: + + By default, the :class:`~inversion_ideas.DataMisfit` and many other + objective functions in the framework won't build the whole Hessian matrix, but + return a :class:`~scipy.sparse.linalg.LinearOperator` instead. + Hessian matrices are ``n_params`` :math:`\times` ``n_params`` square matrices + that can grow very large when ``n_params`` is big. + A :class:`~scipy.sparse.linalg.LinearOperator` allows us to operate with such + matrix as if it were an array, but without storing it entirely in memory. + + +Renaming a function +------------------- + +An objective function can be renamed using the :meth:`~inversion_ideas.base.Objective.set_name` method. For example: + +.. jupyter-execute:: + + data_misfit.set_name("data_misfit") + data_misfit + +Let's rename it to its previous name: + +.. jupyter-execute:: + + data_misfit.set_name("d") + data_misfit + +.. tip:: + + The :meth:`~inversion_ideas.base.Objective.set_name` method returns the same objective function, so we can use it directly when defining a new one. For example: + + .. code:: python + + data_misfit = ii.DataMisfit(data, uncertainties, simulation).set_name("data_misfit") + + + +Combining objective functions +----------------------------- + +Add two objective functions +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +It's possible to define any linear combination of objective functions. + +Consider we have a :class:`~inversion_ideas.TikhonovZero` regularization function: + +.. jupyter-execute:: + + zeroth = ii.TikhonovZero(n_params) + zeroth + +We can add it to the ``data_misfit`` one by summing them together to obtain a new objective function: + +.. jupyter-execute:: + + phi = data_misfit + zeroth + phi + +This :class:`inversion_ideas.base.Combo` is an objective function that works as its mathematical counterpart :math:`\phi(\mathbf{m}) = \phi_\text{d}(\mathbf{m}) + \phi_\text{0}(\mathbf{m})` does: we can evaluate it on a given model, get its gradient and Hessian: + +.. jupyter-execute:: + + phi(model) + +.. jupyter-execute:: + + phi.gradient(model) + +.. jupyter-execute:: + + phi.hessian(model) + +.. important:: + + The :class:`inversion_ideas.base.Combo` class is not meant to be instantiated. + Add two or more objective functions together to obtain one. + +The :class:`inversion_ideas.base.Combo` works as a collection of objective functions. This means that we can get the number of objective functions it contains through the :func:`len` function, and we can also access each one of its terms by index: + +.. jupyter-execute:: + + len(phi) + +.. jupyter-execute:: + + print(phi[0]) + print(phi[1]) + +.. jupyter-execute:: + + for i, term in enumerate(phi): + print(f"Term {i}: {term}") + +.. jupyter-execute:: + + print(data_misfit in phi) + print(zeroth in phi) + +Add multiple objective functions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +We can also add more than two objective functions together. For example, consider that we want to add the ``data_misfit`` and the ``zeroth`` regularization with a :class:`~inversion_ideas.TikhonovFirst` regularization: + +.. jupyter-execute:: + + # TODO: Use TikhonovFirst here! + first = ii.TikhonovZero(n_params).set_name("1") + first + +.. jupyter-execute:: + + phi = data_misfit + zeroth + first + phi + +By default, when adding more than two objective functions together, we'll get a *nested* :class:`inversion_ideas.base.Combo` object: the first element will be a :class:`inversion_ideas.base.Combo` containing the ``data_misfit`` and the ``zeroth`` regularization, and the second element will be the ``first`` regularization. + +.. jupyter-execute:: + + print(len(phi)) + print(phi[0]) + print(phi[1]) + +And since the first element is a :class:`~inversion_ideas.base.Combo`, we can also treat it as a collection: + +.. jupyter-execute:: + + print(len(phi[0])) + print(phi[0][0]) + print(phi[0][1]) + +If we don't want to have this kind of structure, we can +*flatten* any :class:`~inversion_ideas.base.Combo` through the +:meth:`~inversion_ideas.base.Combo.flatten` method: + +.. jupyter-execute:: + + flat_phi = phi.flatten() + flat_phi + +.. jupyter-execute:: + + len(flat_phi) + +.. jupyter-execute:: + + print(flat_phi[0]) + print(flat_phi[1]) + print(flat_phi[2]) + +.. jupyter-execute:: + + data_misfit in flat_phi + +.. jupyter-execute:: + + zeroth in flat_phi + +.. jupyter-execute:: + + first in flat_phi + +Is in or contains? +~~~~~~~~~~~~~~~~~~ + +When using the ``in`` statement to check whether an objective function is part of a :class:`~inversion_ideas.base.Combo`, we are only checking if that function is one of its elements, but not a recursive search through its nested :class:`~inversion_ideas.base.Combo`. + +For example, in we know that ``first`` is the second element of ``phi``: + +.. jupyter-execute:: + + phi + + +.. jupyter-execute:: + + phi[1] + +So, we know that ``first in phi`` should be ``True``: + +.. jupyter-execute:: + + first in phi + +But, the first element of ``phi`` is a :class:`~inversion_ideas.base.Combo` containing ``data_misfit`` and ``zeroth``, so ``data_misfit in phi`` should be ``False``: + +.. jupyter-execute:: + + data_misfit in phi + +And the same goes for ``zeroth``: + +.. jupyter-execute:: + + zeroth in phi + +Alternatively, we can use the :meth:`~inversion_ideas.base.Combo.contains` method to check recursively for a particular term: + +.. jupyter-execute:: + + phi.contains(data_misfit) + +.. jupyter-execute:: + + phi.contains(zeroth) + +.. jupyter-execute:: + + phi.contains(first) + diff --git a/environment.yml b/environment.yml index a0d2a7a6..a3186b55 100644 --- a/environment.yml +++ b/environment.yml @@ -31,3 +31,4 @@ dependencies: - numpydoc - pydata-sphinx-theme - sphinx-design + - jupyter_sphinx diff --git a/requirements-dev.txt b/requirements-dev.txt index d34ec11b..a6bdfa65 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -15,4 +15,5 @@ sphinx numpydoc pydata-sphinx-theme sphinx_design +jupyter-sphinx choclo From 54e457cc261c153f693e074fad38a662b06ac624 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Thu, 24 Sep 2026 11:59:12 -0700 Subject: [PATCH 02/38] Add more content to objective functions --- docs/user-guide/objective-function.rst | 174 +++++++++++++++++++++++-- 1 file changed, 162 insertions(+), 12 deletions(-) diff --git a/docs/user-guide/objective-function.rst b/docs/user-guide/objective-function.rst index 7f16da08..f4d0fca3 100644 --- a/docs/user-guide/objective-function.rst +++ b/docs/user-guide/objective-function.rst @@ -3,6 +3,9 @@ Objective function ================== +Defining objective functions +---------------------------- + Any objective function is defined as a vector function :math:`\phi: \mathbb{R}^M \rightarrow \mathbb{R}`, i.e. it takes a model vector :math:`\mathbf{m}` with :math:`M` elements and returns a single value. In the new SimPEG's inversion framework, objective functions are represented by a child of the :class:`inversion_ideas.base.Objective`, like the :class:`inversion_ideas.DataMisfit` for example. @@ -13,12 +16,14 @@ In the new SimPEG's inversion framework, objective functions are represented by import inversion_ideas as ii # Define a linear regressor as a simulation - n_data, n_params = 10, 15 + n_data, n_params = 3, 5 simulation = ii.simulations.LinearRegressor.create_random(n_data, n_params, seed=42) - # Create some random data and uncertainties - data = np.random.default_rng(seed=1414).uniform(size=n_data) - uncertainties = 1e-3 * np.ones_like(data) + # Create some synthetic data and uncertainties + true_model = np.array([-5., 2., -3., 4., 1.]) + std = 1e-2 + data = simulation(true_model) + np.random.default_rng(seed=42).normal(size=n_data, scale=std) + uncertainties = std * np.ones_like(data) # Define a data misfit function data_misfit = ii.DataMisfit(data, uncertainties, simulation) @@ -35,7 +40,7 @@ Objective functions can be evaluated by calling them: .. jupyter-execute:: # Define some model - model = np.arange(n_params, dtype=np.float64) + model = np.array([-2., -1., 0., 1., 2.]) # Evaluate the data_misfit on that model data_misfit(model) @@ -68,6 +73,13 @@ All objective functions have two methods to compute its derivatives: A :class:`~scipy.sparse.linalg.LinearOperator` allows us to operate with such matrix as if it were an array, but without storing it entirely in memory. + For example, we can compute the dot product of the ``hessian`` with the + ``model`` vector: + + .. jupyter-execute:: + + hessian @ model + Renaming a function ------------------- @@ -95,12 +107,61 @@ Let's rename it to its previous name: data_misfit = ii.DataMisfit(data, uncertainties, simulation).set_name("data_misfit") +Scaling a function +------------------ + +We can easily multiply an :class:`~inversion_ideas.base.Objective` function by a scalar, obtaining a :class:`inversion_ideas.base.Scaled` object. +The :class:`inversion_ideas.base.Scaled` is another type of objective functions that represents an objective function (encapsulated in the :attr:`~inversion_ideas.base.Scaled.function` attribute) multiplied by a scalar (encapsulated in the :attr:`~inversion_ideas.base.Scaled.multiplier` attribute). + +For example, we can build a new ``scaled`` function by multiplying the ``data_misfit`` by a ``float``: + +.. jupyter-execute:: + + scaled = 5.0 * data_misfit + scaled + +We can still access the underlying objects: + +.. jupyter-execute:: + + scaled.multiplier + +.. jupyter-execute:: + + scaled.function + + +.. important:: + + The :attr:`~inversion_ideas.base.Scaled.function` variable stores a reference to the original objective function. The + :class:`~inversion_ideas.base.Scaled` doesn't perform any copy of it. Therefore ``scaled.function`` **is** the ``data_misfit`` object: + + .. jupyter-execute:: + + scaled.function is data_misfit + + +We can evaluate the ``scaled`` function and get its gradient and Hessian as with any other objective function: + +.. jupyter-execute:: + + scaled(model) + +.. jupyter-execute:: + + scaled.gradient(model) + +.. jupyter-execute:: + + scaled.hessian(model) -Combining objective functions ------------------------------ -Add two objective functions -~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Combining functions +------------------- + +Add two functions +~~~~~~~~~~~~~~~~~ It's possible to define any linear combination of objective functions. @@ -158,8 +219,8 @@ The :class:`inversion_ideas.base.Combo` works as a collection of objective funct print(data_misfit in phi) print(zeroth in phi) -Add multiple objective functions -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Add multiple functions +~~~~~~~~~~~~~~~~~~~~~~ We can also add more than two objective functions together. For example, consider that we want to add the ``data_misfit`` and the ``zeroth`` regularization with a :class:`~inversion_ideas.TikhonovFirst` regularization: @@ -222,7 +283,7 @@ If we don't want to have this kind of structure, we can first in flat_phi Is in or contains? -~~~~~~~~~~~~~~~~~~ +^^^^^^^^^^^^^^^^^^ When using the ``in`` statement to check whether an objective function is part of a :class:`~inversion_ideas.base.Combo`, we are only checking if that function is one of its elements, but not a recursive search through its nested :class:`~inversion_ideas.base.Combo`. @@ -269,3 +330,92 @@ Alternatively, we can use the :meth:`~inversion_ideas.base.Combo.contains` metho phi.contains(first) + +Linear combination of functions +------------------------------- + +Since it's possible to scale objective functions and also to add them up, we can define any linear combination of objective functions. +For example, we could build an classic objective function like: + +.. math:: + + \phi(\mathbf{m}) = \phi_\text{d}(\mathbf{m}) + \beta \left[ \phi_\text{0}(\mathbf{m}) + \alpha \phi_\text{1}(\mathbf{m}) \right] + + +as follows: + +.. jupyter-execute:: + + beta = 1e2 + alpha = 3.0 + phi = data_misfit + beta * (zeroth + alpha * first) + phi + +We can evaluate the ``phi`` function and get its gradient and Hessian as with any other objective function: + +.. jupyter-execute:: + + phi(model) + +.. jupyter-execute:: + + phi.gradient(model) + +.. jupyter-execute:: + + phi.hessian(model) + + +Internal structure +~~~~~~~~~~~~~~~~~~ + +The ``phi`` object is a :class:`~inversion_ideas.base.Combo` with a nested structure. It contains two elements: the ``data_misfit`` and a :class:`~inversion_ideas.base.Scaled` object that represents the :math:`\beta \left[ phi_\text{0}(\mathbf{m}) + \alpha \phi_\text{1}(\mathbf{m}) \right]`: + +.. jupyter-execute:: + + len(phi) + + +.. jupyter-execute:: + + phi[0] + +.. jupyter-execute:: + + phi[1] + + +Because the ``phi[1]`` is a :class:`~inversion_ideas.base.Scaled`, it has a ``multiplier`` (the value of :math:`\beta`) and a ``function``: + +.. jupyter-execute:: + + phi[1].multiplier + +.. jupyter-execute:: + + phi[1].function + +The ``phi[1].function`` is another :class:`~inversion_ideas.base.Combo` that contains the ``zeroth`` and a scaled version of ``first``. + +.. jupyter-execute:: + + phi[1].function[0] + +.. jupyter-execute:: + + phi[1].function[1] + +We can use the :meth:`~inversion_ideas.base.Combo.contains` to perform a recursive check for a given objective function within the ``phi`` function. This recursive check also explores +:class:`~inversion_ideas.base.Scaled` objects: + +.. jupyter-execute:: + + phi.contains(data_misfit) + +.. jupyter-execute:: + + phi.contains(zeroth) + +.. jupyter-execute:: + + phi.contains(first) From 8e50cf74e7627b699834d927456d948c153675d2 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Thu, 24 Sep 2026 11:59:44 -0700 Subject: [PATCH 03/38] Modify the low and high bounds in LinearRegressor --- src/inversion_ideas/simulations.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/inversion_ideas/simulations.py b/src/inversion_ideas/simulations.py index 7be3b740..caac94e4 100644 --- a/src/inversion_ideas/simulations.py +++ b/src/inversion_ideas/simulations.py @@ -279,7 +279,7 @@ def create_random(cls, n_data: int, n_params: int, *, seed=None, **kwargs): the constructor of :class:`~inversion_ideas.LinearRegressor`. """ shape = (n_data, n_params) - matrix = np.random.default_rng(seed=seed).uniform(size=shape) + matrix = np.random.default_rng(seed=seed).uniform(low=-1, high=1, size=shape) return cls(matrix, **kwargs) @property From d4ee99af7bce86f394e7e748d7e87c9bc61f9aae Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Thu, 24 Sep 2026 15:59:55 -0700 Subject: [PATCH 04/38] Add content to minimizer.rst --- docs/user-guide/minimizer.rst | 95 +++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/docs/user-guide/minimizer.rst b/docs/user-guide/minimizer.rst index b0ee7a96..486e4d68 100644 --- a/docs/user-guide/minimizer.rst +++ b/docs/user-guide/minimizer.rst @@ -2,3 +2,98 @@ Minimizer ========= + +Once we defined the :ref:`objective function ` for our inversion, we need to find a model vector that would minimize it. +To do so we need to make use of a **minimizer**. + +In the new framework, a **minimizer** can be a function that takes the objective +function (and other arguments, like an initial model) and returns the *inverted +model* or *recovered model*, i.e. the model that minimize that objective function. + +Linear minimizers +----------------- + +If our inversion is linear, we can make use of linear minimizers, like :func:`inversion_ideas.conjugate_gradient` to minimize the objective function. +The :func:`~inversion_ideas.conjugate_gradient` function will ask the objective function and an initial model from which it'll start the conjugate gradient algorithm, and it will return the recovered model after convergence has been achieved. + +For example, let's consider the :class:`~inversion_ideas.LinearRegressor` simulation and the ``data_misfit`` object we built when we introduced the :ref:`objective function `: + +.. jupyter-execute:: + :hide-code: + + import numpy as np + import inversion_ideas as ii + + # Define a linear regressor as a simulation + n_data, n_params = 3, 5 + simulation = ii.simulations.LinearRegressor.create_random(n_data, n_params, seed=42) + + # Create some synthetic data and uncertainties + true_model = np.array([-5., 2., -3., 4., 1.]) + std = 1e-2 + data = simulation(true_model) + np.random.default_rng(seed=42).normal(size=n_data, scale=std) + uncertainties = std * np.ones_like(data) + +.. jupyter-execute:: + + data_misfit = ii.DataMisfit(data, uncertainties, simulation) + data_misfit + +where the ``true_model`` was: + +.. jupyter-execute:: + + true_model + + +Let's define an objective function by adding a :class:`~inversion_ideas.TikhonovZero` regularization: + +.. jupyter-execute:: + + beta = 30.0 + phi = data_misfit + beta * ii.TikhonovZero(n_params) + phi + +And use the :func:`~inversion_ideas.conjugate_gradient` to minimize it by setting an initial model full of zeros: + +.. jupyter-execute:: + + initial_model = np.zeros(n_params, dtype=np.float64) + model = ii.conjugate_gradient(phi, initial_model) + model + +We were able to recover a model that is close to the true model used to generate the synthetic data. + +We can make use of the :meth:`inversion_ideas.DataMisfit.chi_factor` method to see if we are over- or under-fitting the data. + +- :math:`\chi \approx 1.0` would mean that we are recovering the data within the known uncertainties. +- :math:`\chi > 1.0` would mean that we are under-fitting the data. +- :math:`\chi < 1.0` would mean that we are over-fitting the data. + +.. jupyter-execute:: + + data_misfit.chi_factor(model) + + +Non-linear minimizers +--------------------- + +> TODO + + +Third-party minimizers +---------------------- + +It's also possible to plug our :class:`~inversion_ideas.base.Objective` function objects into third-party minimizers, likes the ones available in :mod:`scipy`. + +For example, we could use :func:`scipy.optimize.minimize` to minimize our objective function using a conjugate gradient algorithm: + +.. jupyter-execute:: + + from scipy.optimize import minimize + + # Pass the phi.gradient method as the `jac` argument + result = minimize(phi, x0=initial_model, method="CG", jac=phi.gradient) + + inverted_model = result.x + inverted_model From af0a794f0aabd4204ea23c68c00ff31d44deb89f Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Thu, 24 Sep 2026 16:13:58 -0700 Subject: [PATCH 05/38] Add entry for non-linear minimizers The snippet doesn't execute, it's just static code. But it should be good for now. --- docs/user-guide/minimizer.rst | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/docs/user-guide/minimizer.rst b/docs/user-guide/minimizer.rst index 486e4d68..a9cb04e5 100644 --- a/docs/user-guide/minimizer.rst +++ b/docs/user-guide/minimizer.rst @@ -13,7 +13,7 @@ model* or *recovered model*, i.e. the model that minimize that objective functio Linear minimizers ----------------- -If our inversion is linear, we can make use of linear minimizers, like :func:`inversion_ideas.conjugate_gradient` to minimize the objective function. +If our inversion is linear (e.g. potential field inversions), we can make use of linear minimizers, like :func:`inversion_ideas.conjugate_gradient` to minimize the objective function. The :func:`~inversion_ideas.conjugate_gradient` function will ask the objective function and an initial model from which it'll start the conjugate gradient algorithm, and it will return the recovered model after convergence has been achieved. For example, let's consider the :class:`~inversion_ideas.LinearRegressor` simulation and the ``data_misfit`` object we built when we introduced the :ref:`objective function `: @@ -78,7 +78,33 @@ We can make use of the :meth:`inversion_ideas.DataMisfit.chi_factor` method to s Non-linear minimizers --------------------- -> TODO +If our inversion is non-linear (DC-IP, EM inversions, etc.), we'll need to use a suitable minimizer for non-linear inversion problems, like the Gauss-Newton method. + +The :class:`inversion_ideas.GaussNewtonConjugateGradient` object implements a Gauss-Newton algorithm using Conjugate Gradient to find search directions, and performing a backtracking line search. + +We can use it to minimize the non-linear objective function through the :meth:`inversion_ideas.GaussNewtonConjugateGradient.run` method: + +.. code:: python + + minimizer = GaussNewtonConjugateGradient() + inverted_model = minimizer.run(phi, initial_model) + + +Alternatively we can iterate over it after calling the minimizer: + +.. code:: python + + minimizer = GaussNewtonConjugateGradient() + + for model in minimizer(phi, initial_model): + # The model is the one obtained after each Gauss-Newton iteration + ... + # We can perform stuff here, like plot the model, print information, + # save stuff to disk, etc. + ... + + # The inverted model is the last value of the `model` variable + inverted_model = model.copy() Third-party minimizers From f8c677f98fd7053d04f691c0dfed1c0aeb58dfe7 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Thu, 24 Sep 2026 16:29:32 -0700 Subject: [PATCH 06/38] Reorganize docs Remove the Getting Started section and move it as a toc under the User Guide. Add some pages as placeholders for future content in the docs. --- docs/index.rst | 17 +---------------- docs/user-guide/dc-inversion.rst | 4 ++++ docs/user-guide/gravity-inversion.rst | 4 ++++ docs/user-guide/index.rst | 14 ++++++++++++-- .../index.rst => user-guide/installing.rst} | 9 +++------ docs/user-guide/what.rst | 2 ++ 6 files changed, 26 insertions(+), 24 deletions(-) create mode 100644 docs/user-guide/dc-inversion.rst create mode 100644 docs/user-guide/gravity-inversion.rst rename docs/{getting-started/index.rst => user-guide/installing.rst} (88%) create mode 100644 docs/user-guide/what.rst diff --git a/docs/index.rst b/docs/index.rst index 27d888c4..a37dac77 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -16,26 +16,12 @@ The main goal of this repository is to build a working prototype of a new invers :padding: 0 0 0 0 :gutter: 4 - .. grid-item-card:: :fas:`book-open` Getting Started - :text-align: center - :class-title: sd-fs-5 - :class-card: sd-p-3 - - Start using the framework. - - .. button-ref:: getting-started - :ref-type: ref - :click-parent: - :color: primary - :shadow: - :expand: - .. grid-item-card:: :fas:`book-open` User Guide :text-align: center :class-title: sd-fs-5 :class-card: sd-p-3 - Learn how to use the framework. + Get started and learn how to use the framework. .. button-ref:: user-guide :ref-type: ref @@ -63,6 +49,5 @@ The main goal of this repository is to build a working prototype of a new invers :caption: Contents: :hidden: - getting-started/index.rst user-guide/index.rst reference/index.rst diff --git a/docs/user-guide/dc-inversion.rst b/docs/user-guide/dc-inversion.rst new file mode 100644 index 00000000..99c6a310 --- /dev/null +++ b/docs/user-guide/dc-inversion.rst @@ -0,0 +1,4 @@ +DC Inversion +============ + +Coming soon... diff --git a/docs/user-guide/gravity-inversion.rst b/docs/user-guide/gravity-inversion.rst new file mode 100644 index 00000000..639355c2 --- /dev/null +++ b/docs/user-guide/gravity-inversion.rst @@ -0,0 +1,4 @@ +Gravity Inversion +================= + +Coming soon... diff --git a/docs/user-guide/index.rst b/docs/user-guide/index.rst index 61b26e9b..118ca3f3 100644 --- a/docs/user-guide/index.rst +++ b/docs/user-guide/index.rst @@ -4,9 +4,19 @@ User Guide ---------- .. toctree:: - :maxdepth: 2 - :caption: Basic concepts + :maxdepth: 1 + :caption: Getting started + + what + installing + gravity-inversion + dc-inversion + +.. toctree:: + :maxdepth: 1 + :caption: Fundamentals inversion-concept objective-function minimizer + diff --git a/docs/getting-started/index.rst b/docs/user-guide/installing.rst similarity index 88% rename from docs/getting-started/index.rst rename to docs/user-guide/installing.rst index 6ef58535..109e63c3 100644 --- a/docs/getting-started/index.rst +++ b/docs/user-guide/installing.rst @@ -1,10 +1,7 @@ -.. _getting-started: - -Getting Started -=============== +.. _installing: Installing ----------- +========== Since this framework will not be maintained, you will not find it available in PyPI nor conda-forge. But, it's still possible to install it through pip with: @@ -13,7 +10,7 @@ Since this framework will not be maintained, you will not find it available in P pip install git+https://github.com/simpeg/inversion-design-ideas Install from source -~~~~~~~~~~~~~~~~~~~ +------------------- Alternatively, we could clone the repository and install the package from source. diff --git a/docs/user-guide/what.rst b/docs/user-guide/what.rst new file mode 100644 index 00000000..52cca7ff --- /dev/null +++ b/docs/user-guide/what.rst @@ -0,0 +1,2 @@ +What is this new framework? +=========================== From b9cba9971951a6ede67e58a58cdc91d9d57c04fa Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Thu, 24 Sep 2026 16:53:14 -0700 Subject: [PATCH 07/38] Add guide on debugging and logging --- docs/user-guide/index.rst | 5 +++ docs/user-guide/logging.rst | 70 +++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 docs/user-guide/logging.rst diff --git a/docs/user-guide/index.rst b/docs/user-guide/index.rst index 118ca3f3..b481c2b1 100644 --- a/docs/user-guide/index.rst +++ b/docs/user-guide/index.rst @@ -20,3 +20,8 @@ User Guide objective-function minimizer +.. toctree:: + :maxdepth: 1 + :caption: How To + + logging diff --git a/docs/user-guide/logging.rst b/docs/user-guide/logging.rst new file mode 100644 index 00000000..2c31f6b8 --- /dev/null +++ b/docs/user-guide/logging.rst @@ -0,0 +1,70 @@ +.. _logging: + +Logging and debugging +===================== + +The new inversion framework uses the :mod:`logging` module to print messages while inversions are run. +Some classes and functions of the new framework will log events like starting a new iteration, caching a result, updating some parameter, etc. +These events are logged through a global :class:`logging.Logger` that we can access through the :func:`inversion_ideas.utils.get_logger` function. + +.. code:: python + + import inversion_ideas as ii + + logger = ii.utils.get_logger() + + +Logging messages +---------------- + +Users can use this logger to log messages in their own codes. +For example, we can log an :obj:`logging.INFO` message through the :meth:`logging.Logger.info` method: + +.. code:: python + + import inversion_ideas as ii + + logger = ii.utils.get_logger() + logger.info("This is a custom message") + +.. code:: + + [INFO] This is a custom message + + +Or a :obj:`logging.DEBUG` message through the :meth:`logging.Logger.debug` method: + +.. code:: python + + logger.debug("This is a custom debug message") + +.. note:: + + Debug messages are not shown by default. Learn how to :ref:`adjust the logging level ` so they can be shown. + + +.. _adjust-logging-level: + +Adjusting the logging level +--------------------------- + +By default this logger will only print out messages of the :obj:`logging.INFO` `level `__ or above. +Many of the messages logged by the framework's functions and classes are under the :obj:`logging.DEBUG` category. +If we want to receive those messages we need to adjust the logging level of the logger, for example: + +.. code:: python + + import inversion_ideas as ii + + logger = ii.utils.get_logger() + logger.setLevel("DEBUG") + + logger.debug("This is a custom debug message") + +.. code:: + + [DEBUG] This is a custom debug message + + + + From 78cb01b41f785c7072d058c50dc3e82b6d367171 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Mon, 28 Sep 2026 12:14:40 -0700 Subject: [PATCH 08/38] Use emph in heading --- docs/user-guide/objective-function.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/user-guide/objective-function.rst b/docs/user-guide/objective-function.rst index f4d0fca3..d9379be1 100644 --- a/docs/user-guide/objective-function.rst +++ b/docs/user-guide/objective-function.rst @@ -282,8 +282,8 @@ If we don't want to have this kind of structure, we can first in flat_phi -Is in or contains? -^^^^^^^^^^^^^^^^^^ +*Is in* or *contains*? +^^^^^^^^^^^^^^^^^^^^^^ When using the ``in`` statement to check whether an objective function is part of a :class:`~inversion_ideas.base.Combo`, we are only checking if that function is one of its elements, but not a recursive search through its nested :class:`~inversion_ideas.base.Combo`. From 5df3b8e878e248e25db1d3814db82c6a8dab3838 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Mon, 28 Sep 2026 17:05:47 -0700 Subject: [PATCH 09/38] Replace `TikhonovZero` for `SimpleSmallness` --- docs/user-guide/minimizer.rst | 4 +-- docs/user-guide/objective-function.rst | 50 +++++++++++++------------- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/docs/user-guide/minimizer.rst b/docs/user-guide/minimizer.rst index a9cb04e5..8ee41226 100644 --- a/docs/user-guide/minimizer.rst +++ b/docs/user-guide/minimizer.rst @@ -46,12 +46,12 @@ where the ``true_model`` was: true_model -Let's define an objective function by adding a :class:`~inversion_ideas.TikhonovZero` regularization: +Let's define an objective function by adding a :class:`~inversion_ideas.SimpleSmallness` regularization: .. jupyter-execute:: beta = 30.0 - phi = data_misfit + beta * ii.TikhonovZero(n_params) + phi = data_misfit + beta * ii.SimpleSmallness(n_params) phi And use the :func:`~inversion_ideas.conjugate_gradient` to minimize it by setting an initial model full of zeros: diff --git a/docs/user-guide/objective-function.rst b/docs/user-guide/objective-function.rst index d9379be1..35fdcea4 100644 --- a/docs/user-guide/objective-function.rst +++ b/docs/user-guide/objective-function.rst @@ -165,18 +165,18 @@ Add two functions It's possible to define any linear combination of objective functions. -Consider we have a :class:`~inversion_ideas.TikhonovZero` regularization function: +Consider we have a :class:`~inversion_ideas.SimpleSmallness` regularization function: .. jupyter-execute:: - zeroth = ii.TikhonovZero(n_params) - zeroth + smallness = ii.SimpleSmallness(n_params) + smallness We can add it to the ``data_misfit`` one by summing them together to obtain a new objective function: .. jupyter-execute:: - phi = data_misfit + zeroth + phi = data_misfit + smallness phi This :class:`inversion_ideas.base.Combo` is an objective function that works as its mathematical counterpart :math:`\phi(\mathbf{m}) = \phi_\text{d}(\mathbf{m}) + \phi_\text{0}(\mathbf{m})` does: we can evaluate it on a given model, get its gradient and Hessian: @@ -217,25 +217,25 @@ The :class:`inversion_ideas.base.Combo` works as a collection of objective funct .. jupyter-execute:: print(data_misfit in phi) - print(zeroth in phi) + print(smallness in phi) Add multiple functions ~~~~~~~~~~~~~~~~~~~~~~ -We can also add more than two objective functions together. For example, consider that we want to add the ``data_misfit`` and the ``zeroth`` regularization with a :class:`~inversion_ideas.TikhonovFirst` regularization: +We can also add more than two objective functions together. For example, consider that we want to add the ``data_misfit`` and the ``smallness`` regularization with a :class:`~inversion_ideas.SimpleFlatness` regularization: .. jupyter-execute:: - # TODO: Use TikhonovFirst here! - first = ii.TikhonovZero(n_params).set_name("1") - first + # TODO: Use SimpleFlatness here! + flatness = ii.SimpleSmallness(n_params).set_name("1") + flatness .. jupyter-execute:: - phi = data_misfit + zeroth + first + phi = data_misfit + smallness + flatness phi -By default, when adding more than two objective functions together, we'll get a *nested* :class:`inversion_ideas.base.Combo` object: the first element will be a :class:`inversion_ideas.base.Combo` containing the ``data_misfit`` and the ``zeroth`` regularization, and the second element will be the ``first`` regularization. +By default, when adding more than two objective functions together, we'll get a *nested* :class:`inversion_ideas.base.Combo` object: the first element will be a :class:`inversion_ideas.base.Combo` containing the ``data_misfit`` and the ``smallness`` regularization, and the second element will be the ``flatness`` regularization. .. jupyter-execute:: @@ -276,18 +276,18 @@ If we don't want to have this kind of structure, we can .. jupyter-execute:: - zeroth in flat_phi + smallness in flat_phi .. jupyter-execute:: - first in flat_phi + flatness in flat_phi *Is in* or *contains*? ^^^^^^^^^^^^^^^^^^^^^^ When using the ``in`` statement to check whether an objective function is part of a :class:`~inversion_ideas.base.Combo`, we are only checking if that function is one of its elements, but not a recursive search through its nested :class:`~inversion_ideas.base.Combo`. -For example, in we know that ``first`` is the second element of ``phi``: +For example, in we know that ``flatness`` is the second element of ``phi``: .. jupyter-execute:: @@ -298,23 +298,23 @@ For example, in we know that ``first`` is the second element of ``phi``: phi[1] -So, we know that ``first in phi`` should be ``True``: +So, we know that ``flatness in phi`` should be ``True``: .. jupyter-execute:: - first in phi + flatness in phi -But, the first element of ``phi`` is a :class:`~inversion_ideas.base.Combo` containing ``data_misfit`` and ``zeroth``, so ``data_misfit in phi`` should be ``False``: +But, the flatness element of ``phi`` is a :class:`~inversion_ideas.base.Combo` containing ``data_misfit`` and ``smallness``, so ``data_misfit in phi`` should be ``False``: .. jupyter-execute:: data_misfit in phi -And the same goes for ``zeroth``: +And the same goes for ``smallness``: .. jupyter-execute:: - zeroth in phi + smallness in phi Alternatively, we can use the :meth:`~inversion_ideas.base.Combo.contains` method to check recursively for a particular term: @@ -324,11 +324,11 @@ Alternatively, we can use the :meth:`~inversion_ideas.base.Combo.contains` metho .. jupyter-execute:: - phi.contains(zeroth) + phi.contains(smallness) .. jupyter-execute:: - phi.contains(first) + phi.contains(flatness) Linear combination of functions @@ -348,7 +348,7 @@ as follows: beta = 1e2 alpha = 3.0 - phi = data_misfit + beta * (zeroth + alpha * first) + phi = data_misfit + beta * (smallness + alpha * flatness) phi We can evaluate the ``phi`` function and get its gradient and Hessian as with any other objective function: @@ -395,7 +395,7 @@ Because the ``phi[1]`` is a :class:`~inversion_ideas.base.Scaled`, it has a ``m phi[1].function -The ``phi[1].function`` is another :class:`~inversion_ideas.base.Combo` that contains the ``zeroth`` and a scaled version of ``first``. +The ``phi[1].function`` is another :class:`~inversion_ideas.base.Combo` that contains the ``smallness`` and a scaled version of ``flatness``. .. jupyter-execute:: @@ -414,8 +414,8 @@ We can use the :meth:`~inversion_ideas.base.Combo.contains` to perform a recurs .. jupyter-execute:: - phi.contains(zeroth) + phi.contains(smallness) .. jupyter-execute:: - phi.contains(first) + phi.contains(flatness) From 54617f7f1cf554ed91900905a0e3a884049258f9 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Wed, 7 Oct 2026 13:57:43 -0700 Subject: [PATCH 10/38] Restructure the user guide into folders --- .../{ => fundamentals}/inversion-concept.rst | 0 docs/user-guide/{ => fundamentals}/minimizer.rst | 0 .../{ => fundamentals}/objective-function.rst | 0 .../{ => getting-started}/dc-inversion.rst | 0 .../{ => getting-started}/gravity-inversion.rst | 0 .../{ => getting-started}/installing.rst | 0 docs/user-guide/{ => getting-started}/what.rst | 0 docs/user-guide/{ => how-to}/logging.rst | 0 docs/user-guide/index.rst | 16 ++++++++-------- 9 files changed, 8 insertions(+), 8 deletions(-) rename docs/user-guide/{ => fundamentals}/inversion-concept.rst (100%) rename docs/user-guide/{ => fundamentals}/minimizer.rst (100%) rename docs/user-guide/{ => fundamentals}/objective-function.rst (100%) rename docs/user-guide/{ => getting-started}/dc-inversion.rst (100%) rename docs/user-guide/{ => getting-started}/gravity-inversion.rst (100%) rename docs/user-guide/{ => getting-started}/installing.rst (100%) rename docs/user-guide/{ => getting-started}/what.rst (100%) rename docs/user-guide/{ => how-to}/logging.rst (100%) diff --git a/docs/user-guide/inversion-concept.rst b/docs/user-guide/fundamentals/inversion-concept.rst similarity index 100% rename from docs/user-guide/inversion-concept.rst rename to docs/user-guide/fundamentals/inversion-concept.rst diff --git a/docs/user-guide/minimizer.rst b/docs/user-guide/fundamentals/minimizer.rst similarity index 100% rename from docs/user-guide/minimizer.rst rename to docs/user-guide/fundamentals/minimizer.rst diff --git a/docs/user-guide/objective-function.rst b/docs/user-guide/fundamentals/objective-function.rst similarity index 100% rename from docs/user-guide/objective-function.rst rename to docs/user-guide/fundamentals/objective-function.rst diff --git a/docs/user-guide/dc-inversion.rst b/docs/user-guide/getting-started/dc-inversion.rst similarity index 100% rename from docs/user-guide/dc-inversion.rst rename to docs/user-guide/getting-started/dc-inversion.rst diff --git a/docs/user-guide/gravity-inversion.rst b/docs/user-guide/getting-started/gravity-inversion.rst similarity index 100% rename from docs/user-guide/gravity-inversion.rst rename to docs/user-guide/getting-started/gravity-inversion.rst diff --git a/docs/user-guide/installing.rst b/docs/user-guide/getting-started/installing.rst similarity index 100% rename from docs/user-guide/installing.rst rename to docs/user-guide/getting-started/installing.rst diff --git a/docs/user-guide/what.rst b/docs/user-guide/getting-started/what.rst similarity index 100% rename from docs/user-guide/what.rst rename to docs/user-guide/getting-started/what.rst diff --git a/docs/user-guide/logging.rst b/docs/user-guide/how-to/logging.rst similarity index 100% rename from docs/user-guide/logging.rst rename to docs/user-guide/how-to/logging.rst diff --git a/docs/user-guide/index.rst b/docs/user-guide/index.rst index b481c2b1..c6304af8 100644 --- a/docs/user-guide/index.rst +++ b/docs/user-guide/index.rst @@ -7,21 +7,21 @@ User Guide :maxdepth: 1 :caption: Getting started - what - installing - gravity-inversion - dc-inversion + getting-started/what + getting-started/installing + getting-started/gravity-inversion + getting-started/dc-inversion .. toctree:: :maxdepth: 1 :caption: Fundamentals - inversion-concept - objective-function - minimizer + fundamentals/inversion-concept + fundamentals/objective-function + fundamentals/minimizer .. toctree:: :maxdepth: 1 :caption: How To - logging + how-to/logging From 79d349c26594cd569b2726b9123f369d63c816b8 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Wed, 7 Oct 2026 13:58:23 -0700 Subject: [PATCH 11/38] Improve wording when defining objective function --- docs/user-guide/fundamentals/objective-function.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user-guide/fundamentals/objective-function.rst b/docs/user-guide/fundamentals/objective-function.rst index 35fdcea4..1cf8e5bc 100644 --- a/docs/user-guide/fundamentals/objective-function.rst +++ b/docs/user-guide/fundamentals/objective-function.rst @@ -6,7 +6,7 @@ Objective function Defining objective functions ---------------------------- -Any objective function is defined as a vector function :math:`\phi: \mathbb{R}^M \rightarrow \mathbb{R}`, i.e. it takes a model vector :math:`\mathbf{m}` with :math:`M` elements and returns a single value. +Any objective function is defined as a scalar field :math:`\phi: \mathbb{R}^M \rightarrow \mathbb{R}`, i.e. it takes a model vector :math:`\mathbf{m}` with :math:`M` elements and returns a single real value. In the new SimPEG's inversion framework, objective functions are represented by a child of the :class:`inversion_ideas.base.Objective`, like the :class:`inversion_ideas.DataMisfit` for example. From b50f85add4192274ae299fefd335e6c2d04ae559 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Wed, 7 Oct 2026 18:00:47 -0700 Subject: [PATCH 12/38] Add page for Inversions --- docs/user-guide/fundamentals/inversion.rst | 316 +++++++++++++++++++++ docs/user-guide/index.rst | 1 + 2 files changed, 317 insertions(+) create mode 100644 docs/user-guide/fundamentals/inversion.rst diff --git a/docs/user-guide/fundamentals/inversion.rst b/docs/user-guide/fundamentals/inversion.rst new file mode 100644 index 00000000..3f414e89 --- /dev/null +++ b/docs/user-guide/fundamentals/inversion.rst @@ -0,0 +1,316 @@ +.. _inversions: + +Inversions +========== + +Most of the inversion we run involve multiple minimization steps. +These inversions usually modify the objective function's hyperparameters +in between minimization steps in order to converge to a desired value of +those hyperparameters during the inversion process itself, or to implement a +particular algorithms (e.g. Iterative-Reweighted Least Squares). + +Beta-cooling: simple +-------------------- + +One common example is the *beta cooling schedule* that consists in defining an +objective function in the form of + +.. math:: + + \phi(\mathbf{m}) = \phi_\text{d}(\mathbf{m}) + \beta_0 \phi\text{m}(\mathbf{m}), + +where :math:`\phi_\text{d}(\mathbf{m})` is the data misfit term, +:math:`\phi\text{m}(\mathbf{m})` is the model norm, and :math:`\beta_0` is an +initial value for the trade-off parameter, which is usually chosen to be a high value. +We proceed to minimize the objective function to obtain an inverted model, and then +*cool down* the trade-off parameter by dividing it by a constant factor. +Then we carry another minimization step, and another cooling step, and so on until a certain condition is met, usually that the data is fitted up to their uncertainties. + +We can achieve that in the new inversion framework with just a ``for`` loop. +For example, consider a :class:`~inversion_ideas.DataMisfit` object that uses a +:class:`~inversion_ideas.LinearRegressor` simulation, like the one we defined in +:ref:`objective-function`: + +.. jupyter-execute:: + :hide-code: + + import numpy as np + import inversion_ideas as ii + + # Define a linear regressor as a simulation + n_data, n_params = 3, 5 + simulation = ii.simulations.LinearRegressor.create_random(n_data, n_params, seed=42) + + # Create some synthetic data and uncertainties + true_model = np.array([-5., 2., -3., 4., 1.]) + std = 1e-2 + data = simulation(true_model) + np.random.default_rng(seed=42).normal(size=n_data, scale=std) + uncertainties = std * np.ones_like(data) + + # Define a data misfit function + data_misfit = ii.DataMisfit(data, uncertainties, simulation) + +.. jupyter-execute:: + + data_misfit + +Let's define a :class:`~inversion_ideas.SimpleSmallness` regularization: + +.. jupyter-execute:: + + smallness = ii.SimpleSmallness(data_misfit.n_params) + smallness + +And create our objective function with a high value for our starting trade-off parameter ``beta``: + +.. jupyter-execute:: + + beta_0 = 200.0 + regularization = beta_0 * smallness + phi = data_misfit + regularization + phi + +.. note:: + + A *high value* for the trade-off parameter depends on the type of problem we + are facing. For one problem a value of 200.0 might be high enough, but for other + it might need to be several order of magnitudes larger. + +Since we can access the value of the trade-off parameter through ``regularization.multiplier``, we can also change it. +Let's use this capability to implement a simple beta-cooling schedule: + +.. jupyter-execute:: + + # Define an initial model + model = np.zeros(data_misfit.n_params) + + # Perform a beta cooling schedule + while True: + + # Minimize the objective function using a conjugate gradient minimizer. + # Overwrite the model variable with the minimized model. + model = ii.conjugate_gradient(phi, model) + + # Define a stopping criterion: + # finish the inversion if the chi factor is below 1. + if data_misfit.chi_factor(model) <= 1.0: + break + + # Cool down beta using a factor of 2 + regularization.multiplier /= 2.0 + +The final inverted model will be stored in the ``model`` variable: + +.. jupyter-execute:: + + inverted_model = model.copy() + inverted_model + +We can also see the final value of the trade-off parameter by displaying the objective function: + +.. jupyter-execute:: + + phi + + +Beta-cooling: with custom objects +--------------------------------- + +The new framework ships some objects that would make writing this inversion in a slicker way. +First, instead of defining our tradeoff parameter as a ``float`` and manually cooling it down, we can use a :class:`inversion_ideas.hyperparams.CooledMultiplier`. +This object acts like a float, but it has an +:meth:`~inversion_ideas.hyperparams.CooledMultiplier.update` method that can automatically perform the cooling step. + +Following the previous example, we can define our objective function as: + +.. jupyter-execute:: + + # Define trade-off parameter as a hyperparameter object. + # Set its initial value to 200.0 and the factor that will be used to cool it down to 2.0. + beta = ii.hyperparams.CooledMultiplier(200.0, cooling_factor=2.0) + + # Use this beta as any other number + phi = data_misfit + beta * smallness + phi + +.. seealso:: + + Learn more about custom hyperparameter objects in **TODO** + + +We can also define a stopping criterion to define when our inversion should stop. +In this case we can make use of :class:`inversion_ideas.conditions.ChiTarget` to check if the :math:`\chi` factor for the ``data_misfit`` falls below a desired threshold: + +.. jupyter-execute:: + + # Define a stopping criterion + chi_target = ii.conditions.ChiTarget(data_misfit, chi_target=1.0) + + +And finally re-write our inversion in a slicker way: + +.. jupyter-execute:: + + # Define an initial model + model = np.zeros(data_misfit.n_params) + + # Perform a beta cooling schedule + while True: + + # Minimize the objective function + model = ii.conjugate_gradient(phi, model) + + # Finish the inversion if the stopping criterion is met + if chi_target(model): + break + + # Cool down beta + beta.update() + + # Define inverted model as last model in the iterations + inverted_model = model.copy() + inverted_model + + +We can also explore the custom ``beta`` hyperparameter and see how its value changed: + +.. jupyter-execute:: + + print(beta) + + +.. hint:: + + We can easily insert any custom code in between iterations. + For example we could print information about the inversion process: + + .. jupyter-execute:: + + # Define objective function + beta = ii.hyperparams.CooledMultiplier(200.0, cooling_factor=2.0) + phi = data_misfit + beta * smallness + + # Define an initial model + model = np.zeros(data_misfit.n_params) + + # Perform a beta cooling schedule + iteration = 0 + while True: + + # Minimize the objective function + model = ii.conjugate_gradient(phi, model) + + # Print information + iteration += 1 + print(f"Iteration: {iteration:2d}") + print("-------------") + print(f"- model: {model}") + print(f"- beta: {beta}") + print(f"- chi factor: {data_misfit.chi_factor(model)}") + print("") + + # Finish the inversion if the stopping criterion is met + if chi_target(model): + break + + # Cool down beta + beta.update() + + +Beta cooling: with an :class:`~inversion_ideas.Inversion` +--------------------------------------------------------- + +Writing such for loops for each inversion we want to run might be a bit too cumbersome. +Alternatively, we can pack the whole inversion process into a single :class:`inversion_ideas.Inversion` object. + +In order to define it we need: + +- the **objective function** we'll minimize (in its initial stage), +- an **initial model** from which the inversion will start, +- the **minimizer** we'll use in each iteration, and +- a **stopping criterion** that the inversion use to decide if it should finish or continue. + +For example, let's define the following :class:`~inversion_ideas.Inversion`: + +.. jupyter-execute:: + + # Define objective function + beta = ii.hyperparams.CooledMultiplier(200.0, cooling_factor=2.0) + phi = data_misfit + beta * smallness + + # Define a stopping criterion + chi_target = ii.conditions.ChiTarget(data_misfit, chi_target=1.0) + + # Define an initial model + initial_model = np.ones(data_misfit.n_params) + + # Define the inversion + inversion = ii.Inversion( + phi, + initial_model, + minimizer=ii.conjugate_gradient, + directives=[beta.update], + stopping_criterion=chi_target, + ) + +We can run this inversion through its +:meth:`~inversion_ideas.Inversion.run` method, or we can iterate over it. +For each iteration, the :class:`~inversion_ideas.Inversion` will broadly: + +1. Check if the stopping condition is met and finish the process if that's the case. +2. Minimize the objective function and update its :attr:`~inversion_ideas.Inversion.model` attribute. +3. Call each one of the ``directives``. + +.. jupyter-execute:: + + inverted_model = inversion.run() + + +.. note:: + + The :class:`~inversion_ideas.Inversion` keep by default an *inversion log* + through which we can access to some details about the whole inversion process, + both during the inversion is running and after the inversion has finished. + + .. jupyter-execute:: + + inversion.log.table + +Alternatively, we can iterate over the :class:`~inversion_ideas.Inversion` object. +This allows us to easily insert any custom code in between iterations. + +.. jupyter-execute:: + + # Define objective function + beta = ii.hyperparams.CooledMultiplier(200.0, cooling_factor=2.0) + phi = data_misfit + beta * smallness + + # Define a stopping criterion + chi_target = ii.conditions.ChiTarget(data_misfit, chi_target=1.0) + + # Define an initial model + initial_model = np.ones(data_misfit.n_params) + + # Define the inversion + inversion = ii.Inversion( + phi, + initial_model, + minimizer=ii.conjugate_gradient, + directives=[beta.update], + stopping_criterion=chi_target, + ) + + # Iterate over the inversion. + # The inversion will return the inverted model obtained after each iteration. + for model in inversion: + # Print information + print(f"model: {model}") + print(f"chi factor: {data_misfit.chi_factor(model)}") + + # Plot results + ... + + # Save stuff to disk + ... + + diff --git a/docs/user-guide/index.rst b/docs/user-guide/index.rst index c6304af8..5d12ceb0 100644 --- a/docs/user-guide/index.rst +++ b/docs/user-guide/index.rst @@ -19,6 +19,7 @@ User Guide fundamentals/inversion-concept fundamentals/objective-function fundamentals/minimizer + fundamentals/inversion .. toctree:: :maxdepth: 1 From 5b8de51804e1068377ef6d72ef49fded20323358 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Thu, 8 Oct 2026 14:51:19 -0700 Subject: [PATCH 13/38] Introduce directives --- docs/user-guide/fundamentals/inversion.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/user-guide/fundamentals/inversion.rst b/docs/user-guide/fundamentals/inversion.rst index 3f414e89..b2bd6aa3 100644 --- a/docs/user-guide/fundamentals/inversion.rst +++ b/docs/user-guide/fundamentals/inversion.rst @@ -230,6 +230,10 @@ In order to define it we need: - the **minimizer** we'll use in each iteration, and - a **stopping criterion** that the inversion use to decide if it should finish or continue. +We can optionally pass a set of **directives**: these are functions that will be called after each iteration. +We can use these directives to modify the objective function and update +hyperparameters, like cooling down the trade-off parameter. + For example, let's define the following :class:`~inversion_ideas.Inversion`: .. jupyter-execute:: From 5ec2c416d8e2af326bef44c3d8c00bdb9c11088e Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Thu, 8 Oct 2026 16:32:58 -0700 Subject: [PATCH 14/38] Add more content to the Inversion page Split the Inversion page in two subsections: one for simple inversions with a for loop, and another one using the Inversion class. --- docs/conf.py | 1 + docs/user-guide/fundamentals/beta-cooling.rst | 211 ++++++++++++ .../fundamentals/inversion-class.rst | 219 ++++++++++++ docs/user-guide/fundamentals/inversion.rst | 313 +----------------- docs/user-guide/index.rst | 4 +- 5 files changed, 441 insertions(+), 307 deletions(-) create mode 100644 docs/user-guide/fundamentals/beta-cooling.rst create mode 100644 docs/user-guide/fundamentals/inversion-class.rst diff --git a/docs/conf.py b/docs/conf.py index 1ea4d7d8..a0e676a8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -28,6 +28,7 @@ "numba": ("https://numba.readthedocs.io/en/stable/", None), "scipy": ("https://docs.scipy.org/doc/scipy/", None), "simpeg": ("https://docs.simpeg.xyz/latest/", None), + "pandas": ("https://pandas.pydata.org/docs/", None), } templates_path = ["_templates"] diff --git a/docs/user-guide/fundamentals/beta-cooling.rst b/docs/user-guide/fundamentals/beta-cooling.rst new file mode 100644 index 00000000..f6f72f4d --- /dev/null +++ b/docs/user-guide/fundamentals/beta-cooling.rst @@ -0,0 +1,211 @@ +.. _beta-cooling: + +Beta-cooling schedule +===================== + +One common example is the *beta cooling schedule* that consists in defining an +objective function in the form of + +.. math:: + + \phi(\mathbf{m}) = \phi_\text{d}(\mathbf{m}) + \beta_0 \phi_\text{m}(\mathbf{m}), + +where :math:`\phi_\text{d}(\mathbf{m})` is the data misfit term, +:math:`\phi_\text{m}(\mathbf{m})` is the model norm, and :math:`\beta_0` is an +initial value for the trade-off parameter, which is usually chosen to be a high value. +We proceed to minimize the objective function to obtain an inverted model, and then +*cool down* the trade-off parameter by dividing it by a constant factor. +Then we carry another minimization step, and another cooling step, and so on until a certain condition is met, usually that the data is fitted up to their uncertainties. + + +Beta-cooling: simple +-------------------- +We can achieve that in the new inversion framework with just a ``for`` loop. +For example, consider a :class:`~inversion_ideas.DataMisfit` object that uses a +:class:`~inversion_ideas.LinearRegressor` simulation, like the one we defined in +:ref:`objective-function`: + +.. jupyter-execute:: + :hide-code: + + import numpy as np + import inversion_ideas as ii + + # Define a linear regressor as a simulation + n_data, n_params = 3, 5 + simulation = ii.simulations.LinearRegressor.create_random(n_data, n_params, seed=42) + + # Create some synthetic data and uncertainties + true_model = np.array([-5., 2., -3., 4., 1.]) + std = 1e-2 + data = simulation(true_model) + np.random.default_rng(seed=42).normal(size=n_data, scale=std) + uncertainties = std * np.ones_like(data) + + # Define a data misfit function + data_misfit = ii.DataMisfit(data, uncertainties, simulation) + +.. jupyter-execute:: + + data_misfit + +Let's define a :class:`~inversion_ideas.SimpleSmallness` regularization: + +.. jupyter-execute:: + + smallness = ii.SimpleSmallness(data_misfit.n_params) + smallness + +And create our objective function with a high value for our starting trade-off parameter ``beta``: + +.. jupyter-execute:: + + beta_0 = 200.0 + regularization = beta_0 * smallness + phi = data_misfit + regularization + phi + +.. note:: + + A *high value* for the trade-off parameter depends on the type of problem we + are facing. For one problem a value of 200.0 might be high enough, but for other + it might need to be several order of magnitudes larger. + +Since we can access the value of the trade-off parameter through ``regularization.multiplier``, we can also change it. +Let's use this capability to implement a simple beta-cooling schedule: + +.. jupyter-execute:: + + # Define an initial model + model = np.zeros(data_misfit.n_params) + + # Perform a beta cooling schedule + while True: + + # Minimize the objective function using a conjugate gradient minimizer. + # Overwrite the model variable with the minimized model. + model = ii.conjugate_gradient(phi, model) + + # Define a stopping criterion: + # finish the inversion if the chi factor is below 1. + if data_misfit.chi_factor(model) <= 1.0: + break + + # Cool down beta using a factor of 2 + regularization.multiplier /= 2.0 + +The final inverted model will be stored in the ``model`` variable: + +.. jupyter-execute:: + + inverted_model = model.copy() + inverted_model + +We can also see the final value of the trade-off parameter by displaying the objective function: + +.. jupyter-execute:: + + phi + + +Beta-cooling: with custom objects +--------------------------------- + +The new framework ships some objects that would make writing this inversion in a slicker way. +First, instead of defining our tradeoff parameter as a ``float`` and manually cooling it down, we can use a :class:`inversion_ideas.hyperparams.CooledMultiplier`. +This object acts like a float, but it has an +:meth:`~inversion_ideas.hyperparams.CooledMultiplier.update` method that can automatically perform the cooling step. + +Following the previous example, we can define our objective function as: + +.. jupyter-execute:: + + # Define trade-off parameter as a hyperparameter object. + # Set its initial value to 200.0 and the factor that will be used to cool it down to 2.0. + beta = ii.hyperparams.CooledMultiplier(200.0, cooling_factor=2.0) + + # Use this beta as any other number + phi = data_misfit + beta * smallness + phi + +.. seealso:: + + Learn more about custom hyperparameter objects in **TODO** + + +We can also define a stopping criterion to define when our inversion should stop. +In this case we can make use of :class:`inversion_ideas.conditions.ChiTarget` to check if the :math:`\chi` factor for the ``data_misfit`` falls below a desired threshold: + +.. jupyter-execute:: + + # Define a stopping criterion + chi_target = ii.conditions.ChiTarget(data_misfit, chi_target=1.0) + + +And finally re-write our inversion in a slicker way: + +.. jupyter-execute:: + + # Define an initial model + model = np.zeros(data_misfit.n_params) + + # Perform a beta cooling schedule + while True: + + # Minimize the objective function + model = ii.conjugate_gradient(phi, model) + + # Finish the inversion if the stopping criterion is met + if chi_target(model): + break + + # Cool down beta + beta.update() + + # Define inverted model as last model in the iterations + inverted_model = model.copy() + inverted_model + + +We can also explore the custom ``beta`` hyperparameter and see how its value changed: + +.. jupyter-execute:: + + print(beta) + + +.. hint:: + + We can easily insert any custom code in between iterations. + For example we could print information about the inversion process: + + .. jupyter-execute:: + + # Define objective function + beta = ii.hyperparams.CooledMultiplier(200.0, cooling_factor=2.0) + phi = data_misfit + beta * smallness + + # Define an initial model + model = np.zeros(data_misfit.n_params) + + # Perform a beta cooling schedule + iteration = 0 + while True: + + # Minimize the objective function + model = ii.conjugate_gradient(phi, model) + + # Print information + iteration += 1 + print(f"Iteration: {iteration:2d}") + print("-------------") + print(f"- model: {model}") + print(f"- beta: {beta}") + print(f"- chi factor: {data_misfit.chi_factor(model)}") + print("") + + # Finish the inversion if the stopping criterion is met + if chi_target(model): + break + + # Cool down beta + beta.update() diff --git a/docs/user-guide/fundamentals/inversion-class.rst b/docs/user-guide/fundamentals/inversion-class.rst new file mode 100644 index 00000000..6ee3ea08 --- /dev/null +++ b/docs/user-guide/fundamentals/inversion-class.rst @@ -0,0 +1,219 @@ +.. _inversion_class: + +The :class:`~inversion_ideas.Inversion` class +============================================= + +Writing full inversions using ``for`` loops -like we've seen in :ref:`beta-cooling`- could be cumbersome. +An alternative would be to pack the whole inversion process into a single :class:`inversion_ideas.Inversion` object. +Such objects will group together all the pieces required to run the inversion, and provide an easy way to run all iterations, either through the :meth:`~inversion_ideas.Inversion.run` method, or by iterating over it. + +In order to define any :class:`~inversion_ideas.Inversion` object we need the following pieces: + +- the **objective function** we'll minimize (in its initial stage), +- an **initial model** from which the inversion will start, +- the **minimizer** we'll use in each iteration, and +- a **stopping criterion** that the inversion use to decide if it should finish or continue. + +We can optionally pass a set of **directives**: these are functions that will be called after each iteration. +We can use these directives to modify the objective function and update +hyperparameters, like cooling down the trade-off parameter. + +For example, an :class:`~inversion_ideas.Inversion` object can be defined as: + +.. code:: python + + inversion = ii.Inversion( + phi, + initial_model, + minimizer=minimizer, + directives=directives, + stopping_criterion=stopping_criterion, + ) + +Once defined, we can run the :class:`~inversion_ideas.Inversion` through the :meth:`~inversion_ideas.Inversion.run` method: + +.. code:: python + + inverted_model = inversion.run() + + +Or we can iterate over it: + +.. code:: python + + for model in inversion: + # Print information + print(f"model: {model}") + print(f"chi factor: {data_misfit.chi_factor(model)}") + + # Plot results + ... + + # Save stuff to disk + ... + +This allows us to easily insert any custom code in between iterations. +The ``for`` loop will finish once the ``stopping_criterion`` has been met. + +.. hint:: + + The ``model`` variable will store the inverted model for each one of the + iterations in the inversion. The inverted model will be the last value of it. + +In general, the :class:`~inversion_ideas.Inversion` will perform the following +tasks per iteration: + +1. Check if the stopping condition is met and finish the process if that's the case. +2. Minimize the objective function and update its :attr:`~inversion_ideas.Inversion.model` attribute. +3. Call each one of the functions in the ``directives`` list. + +Beta-cooling with :class:`~inversion_ideas.Inversion` +----------------------------------------------------- + +Let's define an :class:`~inversion_ideas.Inversion` object that implements the same beta-cooling schedule we've seen in :ref:`beta-cooling`. + +.. jupyter-execute:: + :hide-code: + + import numpy as np + import inversion_ideas as ii + + # Define a linear regressor as a simulation + n_data, n_params = 3, 5 + simulation = ii.simulations.LinearRegressor.create_random(n_data, n_params, seed=42) + + # Create some synthetic data and uncertainties + true_model = np.array([-5., 2., -3., 4., 1.]) + std = 1e-2 + data = simulation(true_model) + np.random.default_rng(seed=42).normal(size=n_data, scale=std) + uncertainties = std * np.ones_like(data) + + # Define a data misfit function + data_misfit = ii.DataMisfit(data, uncertainties, simulation) + + # Define a smallness regularization + smallness = ii.SimpleSmallness(data_misfit.n_params) + + +Let's start by defining our objective function with a :class:`~inversion_ideas.hyperparams.CooledMultiplier` as our trade-off parameter: + +.. jupyter-execute:: + + beta = ii.hyperparams.CooledMultiplier(200.0, cooling_factor=2.0) + phi = data_misfit + beta * smallness + phi + +And the remaining pieces to build our inversion: + +.. jupyter-execute:: + + # Define a stopping criterion + chi_target = ii.conditions.ChiTarget(data_misfit, chi_target=1.0) + + # Define an initial model + initial_model = np.ones(data_misfit.n_params) + +Finally, let's create our :class:`~inversion_ideas.Inversion` object. We'll add the :meth:`~inversion_ideas.hyperparams.CooledMultiplier.beta` method of ``beta`` as the sole directive for this + +.. jupyter-execute:: + + # Define the inversion + inversion = ii.Inversion( + phi, + initial_model, + minimizer=ii.conjugate_gradient, + directives=[beta.update], + stopping_criterion=chi_target, + ) + + +We can run it using the :meth:`~inversion_ideas.Inversion.run` method: + +.. jupyter-execute:: + + inverted_model = inversion.run() + + +Alternatively, we can iterate over the :class:`~inversion_ideas.Inversion` object, and insert some custom code in between iterations: + +.. jupyter-execute:: + + # Define objective function + beta = ii.hyperparams.CooledMultiplier(200.0, cooling_factor=2.0) + phi = data_misfit + beta * smallness + + # Define a stopping criterion + chi_target = ii.conditions.ChiTarget(data_misfit, chi_target=1.0) + + # Define an initial model + initial_model = np.ones(data_misfit.n_params) + + # Define the inversion + inversion = ii.Inversion( + phi, + initial_model, + minimizer=ii.conjugate_gradient, + directives=[beta.update], + stopping_criterion=chi_target, + ) + + # Iterate over the inversion. + # The inversion will return the inverted model obtained after each iteration. + for model in inversion: + # Print information + print(f"model: {model}") + print(f"chi factor: {data_misfit.chi_factor(model)}") + + +The inversion log +----------------- +The :class:`~inversion_ideas.Inversion` keep by default an *inversion log* +through which we can access to some details about the whole inversion process, +both during the inversion is running and after the inversion has finished. + +.. jupyter-execute:: + + inversion.log.table + + +We can convert it to a :class:`pandas.DataFrame`: + +.. jupyter-execute:: + + df = inversion.log.to_pandas() + df + +And use it to generate some convergence plots: + +.. jupyter-execute:: + + import matplotlib.pyplot as plt + + fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1, sharex=True, figsize=(6.4, 8)) + + ax1.plot(df.index, df.beta, "-o") + ax1.set_ylabel(r"$\beta$") + + ax2.plot(df.index, df.phi_d, "-o") + ax2.set_yscale("log") + ax2.set_ylabel(r"$\phi_\text{d}$") + + ax3.plot(df.index, df.phi_m, "-o") + ax3.set_ylabel(r"$\phi_\text{m}$") + + for ax in (ax1, ax2, ax3): + ax.grid(True) + + plt.show() + + +.. hint:: + + We can also access the inverted model for each iteration through the + :attr:`~inversion_ideas.Inversion.models` attribute. Models will be cached + if the ``cache_models`` argument is set to ``True`` when intantiating the + :class:`~inversion_ideas.Inversion` object. + + .. jupyter-execute:: + + inversion.models diff --git a/docs/user-guide/fundamentals/inversion.rst b/docs/user-guide/fundamentals/inversion.rst index b2bd6aa3..f7ba427d 100644 --- a/docs/user-guide/fundamentals/inversion.rst +++ b/docs/user-guide/fundamentals/inversion.rst @@ -9,312 +9,15 @@ in between minimization steps in order to converge to a desired value of those hyperparameters during the inversion process itself, or to implement a particular algorithms (e.g. Iterative-Reweighted Least Squares). -Beta-cooling: simple --------------------- +In the following pages we'll see examples of different ways of running +inversions with the inversion framework. -One common example is the *beta cooling schedule* that consists in defining an -objective function in the form of +.. toctree:: + :hidden: + :maxdepth: 1 + :caption: Getting started -.. math:: - - \phi(\mathbf{m}) = \phi_\text{d}(\mathbf{m}) + \beta_0 \phi\text{m}(\mathbf{m}), - -where :math:`\phi_\text{d}(\mathbf{m})` is the data misfit term, -:math:`\phi\text{m}(\mathbf{m})` is the model norm, and :math:`\beta_0` is an -initial value for the trade-off parameter, which is usually chosen to be a high value. -We proceed to minimize the objective function to obtain an inverted model, and then -*cool down* the trade-off parameter by dividing it by a constant factor. -Then we carry another minimization step, and another cooling step, and so on until a certain condition is met, usually that the data is fitted up to their uncertainties. - -We can achieve that in the new inversion framework with just a ``for`` loop. -For example, consider a :class:`~inversion_ideas.DataMisfit` object that uses a -:class:`~inversion_ideas.LinearRegressor` simulation, like the one we defined in -:ref:`objective-function`: - -.. jupyter-execute:: - :hide-code: - - import numpy as np - import inversion_ideas as ii - - # Define a linear regressor as a simulation - n_data, n_params = 3, 5 - simulation = ii.simulations.LinearRegressor.create_random(n_data, n_params, seed=42) - - # Create some synthetic data and uncertainties - true_model = np.array([-5., 2., -3., 4., 1.]) - std = 1e-2 - data = simulation(true_model) + np.random.default_rng(seed=42).normal(size=n_data, scale=std) - uncertainties = std * np.ones_like(data) - - # Define a data misfit function - data_misfit = ii.DataMisfit(data, uncertainties, simulation) - -.. jupyter-execute:: - - data_misfit - -Let's define a :class:`~inversion_ideas.SimpleSmallness` regularization: - -.. jupyter-execute:: - - smallness = ii.SimpleSmallness(data_misfit.n_params) - smallness - -And create our objective function with a high value for our starting trade-off parameter ``beta``: - -.. jupyter-execute:: - - beta_0 = 200.0 - regularization = beta_0 * smallness - phi = data_misfit + regularization - phi - -.. note:: - - A *high value* for the trade-off parameter depends on the type of problem we - are facing. For one problem a value of 200.0 might be high enough, but for other - it might need to be several order of magnitudes larger. - -Since we can access the value of the trade-off parameter through ``regularization.multiplier``, we can also change it. -Let's use this capability to implement a simple beta-cooling schedule: - -.. jupyter-execute:: - - # Define an initial model - model = np.zeros(data_misfit.n_params) - - # Perform a beta cooling schedule - while True: - - # Minimize the objective function using a conjugate gradient minimizer. - # Overwrite the model variable with the minimized model. - model = ii.conjugate_gradient(phi, model) - - # Define a stopping criterion: - # finish the inversion if the chi factor is below 1. - if data_misfit.chi_factor(model) <= 1.0: - break - - # Cool down beta using a factor of 2 - regularization.multiplier /= 2.0 - -The final inverted model will be stored in the ``model`` variable: - -.. jupyter-execute:: - - inverted_model = model.copy() - inverted_model - -We can also see the final value of the trade-off parameter by displaying the objective function: - -.. jupyter-execute:: - - phi - - -Beta-cooling: with custom objects ---------------------------------- - -The new framework ships some objects that would make writing this inversion in a slicker way. -First, instead of defining our tradeoff parameter as a ``float`` and manually cooling it down, we can use a :class:`inversion_ideas.hyperparams.CooledMultiplier`. -This object acts like a float, but it has an -:meth:`~inversion_ideas.hyperparams.CooledMultiplier.update` method that can automatically perform the cooling step. - -Following the previous example, we can define our objective function as: - -.. jupyter-execute:: - - # Define trade-off parameter as a hyperparameter object. - # Set its initial value to 200.0 and the factor that will be used to cool it down to 2.0. - beta = ii.hyperparams.CooledMultiplier(200.0, cooling_factor=2.0) - - # Use this beta as any other number - phi = data_misfit + beta * smallness - phi - -.. seealso:: - - Learn more about custom hyperparameter objects in **TODO** - - -We can also define a stopping criterion to define when our inversion should stop. -In this case we can make use of :class:`inversion_ideas.conditions.ChiTarget` to check if the :math:`\chi` factor for the ``data_misfit`` falls below a desired threshold: - -.. jupyter-execute:: - - # Define a stopping criterion - chi_target = ii.conditions.ChiTarget(data_misfit, chi_target=1.0) - - -And finally re-write our inversion in a slicker way: - -.. jupyter-execute:: - - # Define an initial model - model = np.zeros(data_misfit.n_params) - - # Perform a beta cooling schedule - while True: - - # Minimize the objective function - model = ii.conjugate_gradient(phi, model) - - # Finish the inversion if the stopping criterion is met - if chi_target(model): - break - - # Cool down beta - beta.update() - - # Define inverted model as last model in the iterations - inverted_model = model.copy() - inverted_model - - -We can also explore the custom ``beta`` hyperparameter and see how its value changed: - -.. jupyter-execute:: - - print(beta) - - -.. hint:: - - We can easily insert any custom code in between iterations. - For example we could print information about the inversion process: - - .. jupyter-execute:: - - # Define objective function - beta = ii.hyperparams.CooledMultiplier(200.0, cooling_factor=2.0) - phi = data_misfit + beta * smallness - - # Define an initial model - model = np.zeros(data_misfit.n_params) - - # Perform a beta cooling schedule - iteration = 0 - while True: - - # Minimize the objective function - model = ii.conjugate_gradient(phi, model) - - # Print information - iteration += 1 - print(f"Iteration: {iteration:2d}") - print("-------------") - print(f"- model: {model}") - print(f"- beta: {beta}") - print(f"- chi factor: {data_misfit.chi_factor(model)}") - print("") - - # Finish the inversion if the stopping criterion is met - if chi_target(model): - break - - # Cool down beta - beta.update() - - -Beta cooling: with an :class:`~inversion_ideas.Inversion` ---------------------------------------------------------- - -Writing such for loops for each inversion we want to run might be a bit too cumbersome. -Alternatively, we can pack the whole inversion process into a single :class:`inversion_ideas.Inversion` object. - -In order to define it we need: - -- the **objective function** we'll minimize (in its initial stage), -- an **initial model** from which the inversion will start, -- the **minimizer** we'll use in each iteration, and -- a **stopping criterion** that the inversion use to decide if it should finish or continue. - -We can optionally pass a set of **directives**: these are functions that will be called after each iteration. -We can use these directives to modify the objective function and update -hyperparameters, like cooling down the trade-off parameter. - -For example, let's define the following :class:`~inversion_ideas.Inversion`: - -.. jupyter-execute:: - - # Define objective function - beta = ii.hyperparams.CooledMultiplier(200.0, cooling_factor=2.0) - phi = data_misfit + beta * smallness - - # Define a stopping criterion - chi_target = ii.conditions.ChiTarget(data_misfit, chi_target=1.0) - - # Define an initial model - initial_model = np.ones(data_misfit.n_params) - - # Define the inversion - inversion = ii.Inversion( - phi, - initial_model, - minimizer=ii.conjugate_gradient, - directives=[beta.update], - stopping_criterion=chi_target, - ) - -We can run this inversion through its -:meth:`~inversion_ideas.Inversion.run` method, or we can iterate over it. -For each iteration, the :class:`~inversion_ideas.Inversion` will broadly: - -1. Check if the stopping condition is met and finish the process if that's the case. -2. Minimize the objective function and update its :attr:`~inversion_ideas.Inversion.model` attribute. -3. Call each one of the ``directives``. - -.. jupyter-execute:: - - inverted_model = inversion.run() - - -.. note:: - - The :class:`~inversion_ideas.Inversion` keep by default an *inversion log* - through which we can access to some details about the whole inversion process, - both during the inversion is running and after the inversion has finished. - - .. jupyter-execute:: - - inversion.log.table - -Alternatively, we can iterate over the :class:`~inversion_ideas.Inversion` object. -This allows us to easily insert any custom code in between iterations. - -.. jupyter-execute:: - - # Define objective function - beta = ii.hyperparams.CooledMultiplier(200.0, cooling_factor=2.0) - phi = data_misfit + beta * smallness - - # Define a stopping criterion - chi_target = ii.conditions.ChiTarget(data_misfit, chi_target=1.0) - - # Define an initial model - initial_model = np.ones(data_misfit.n_params) - - # Define the inversion - inversion = ii.Inversion( - phi, - initial_model, - minimizer=ii.conjugate_gradient, - directives=[beta.update], - stopping_criterion=chi_target, - ) - - # Iterate over the inversion. - # The inversion will return the inverted model obtained after each iteration. - for model in inversion: - # Print information - print(f"model: {model}") - print(f"chi factor: {data_misfit.chi_factor(model)}") - - # Plot results - ... - - # Save stuff to disk - ... + beta-cooling + inversion-class diff --git a/docs/user-guide/index.rst b/docs/user-guide/index.rst index 5d12ceb0..c49851a1 100644 --- a/docs/user-guide/index.rst +++ b/docs/user-guide/index.rst @@ -13,7 +13,7 @@ User Guide getting-started/dc-inversion .. toctree:: - :maxdepth: 1 + :maxdepth: 2 :caption: Fundamentals fundamentals/inversion-concept @@ -22,7 +22,7 @@ User Guide fundamentals/inversion .. toctree:: - :maxdepth: 1 + :maxdepth: 2 :caption: How To how-to/logging From 03e21e0ca750d3bfc7616d8ec322defbe58310b9 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Thu, 8 Oct 2026 17:10:29 -0700 Subject: [PATCH 15/38] Add placeholders for upcoming pages --- docs/user-guide/fundamentals/conditions.rst | 6 ++++++ docs/user-guide/fundamentals/hyperparameters.rst | 6 ++++++ docs/user-guide/fundamentals/simulations.rst | 6 ++++++ docs/user-guide/index.rst | 3 +++ 4 files changed, 21 insertions(+) create mode 100644 docs/user-guide/fundamentals/conditions.rst create mode 100644 docs/user-guide/fundamentals/hyperparameters.rst create mode 100644 docs/user-guide/fundamentals/simulations.rst diff --git a/docs/user-guide/fundamentals/conditions.rst b/docs/user-guide/fundamentals/conditions.rst new file mode 100644 index 00000000..3f52b75a --- /dev/null +++ b/docs/user-guide/fundamentals/conditions.rst @@ -0,0 +1,6 @@ +.. _conditions: + +Conditions +========== + +TODO diff --git a/docs/user-guide/fundamentals/hyperparameters.rst b/docs/user-guide/fundamentals/hyperparameters.rst new file mode 100644 index 00000000..3f323385 --- /dev/null +++ b/docs/user-guide/fundamentals/hyperparameters.rst @@ -0,0 +1,6 @@ +.. _hyperparameters: + +Hyperparameters +=============== + +TODO diff --git a/docs/user-guide/fundamentals/simulations.rst b/docs/user-guide/fundamentals/simulations.rst new file mode 100644 index 00000000..32b674cb --- /dev/null +++ b/docs/user-guide/fundamentals/simulations.rst @@ -0,0 +1,6 @@ +.. _simulations: + +Simulations +=========== + +TODO diff --git a/docs/user-guide/index.rst b/docs/user-guide/index.rst index c49851a1..b49846fc 100644 --- a/docs/user-guide/index.rst +++ b/docs/user-guide/index.rst @@ -20,6 +20,9 @@ User Guide fundamentals/objective-function fundamentals/minimizer fundamentals/inversion + fundamentals/conditions + fundamentals/hyperparameters + fundamentals/simulations .. toctree:: :maxdepth: 2 From a1cb3dfca6173b572f8d2938411b94e888070922 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Thu, 8 Oct 2026 17:20:42 -0700 Subject: [PATCH 16/38] Add more placeholders --- docs/user-guide/how-to/extend-base.rst | 4 ++++ docs/user-guide/how-to/extend-objective.rst | 4 ++++ docs/user-guide/how-to/extend-simulations.rst | 4 ++++ docs/user-guide/how-to/extend.rst | 13 +++++++++++++ docs/user-guide/index.rst | 1 + 5 files changed, 26 insertions(+) create mode 100644 docs/user-guide/how-to/extend-base.rst create mode 100644 docs/user-guide/how-to/extend-objective.rst create mode 100644 docs/user-guide/how-to/extend-simulations.rst create mode 100644 docs/user-guide/how-to/extend.rst diff --git a/docs/user-guide/how-to/extend-base.rst b/docs/user-guide/how-to/extend-base.rst new file mode 100644 index 00000000..ba99f957 --- /dev/null +++ b/docs/user-guide/how-to/extend-base.rst @@ -0,0 +1,4 @@ +.. _extend-base: + +The :mod:`~inversion_ideas.base` submodule +========================================== diff --git a/docs/user-guide/how-to/extend-objective.rst b/docs/user-guide/how-to/extend-objective.rst new file mode 100644 index 00000000..3dae4940 --- /dev/null +++ b/docs/user-guide/how-to/extend-objective.rst @@ -0,0 +1,4 @@ +.. _extend-objective: + +Writing new objective functions +=============================== diff --git a/docs/user-guide/how-to/extend-simulations.rst b/docs/user-guide/how-to/extend-simulations.rst new file mode 100644 index 00000000..935fe79e --- /dev/null +++ b/docs/user-guide/how-to/extend-simulations.rst @@ -0,0 +1,4 @@ +.. _extend-simulations: + +Writing new simulations +======================= diff --git a/docs/user-guide/how-to/extend.rst b/docs/user-guide/how-to/extend.rst new file mode 100644 index 00000000..9cc09680 --- /dev/null +++ b/docs/user-guide/how-to/extend.rst @@ -0,0 +1,13 @@ +.. _extend: + +Extending the framework +======================= + +.. toctree:: + :hidden: + :maxdepth: 2 + :caption: Extending the framework + + extend-base + extend-objective + extend-simulations diff --git a/docs/user-guide/index.rst b/docs/user-guide/index.rst index b49846fc..31982fb0 100644 --- a/docs/user-guide/index.rst +++ b/docs/user-guide/index.rst @@ -29,3 +29,4 @@ User Guide :caption: How To how-to/logging + how-to/extend From 71cc999292a5f0b761b33c52f582ffbf63265f45 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Wed, 14 Oct 2026 10:23:28 -0700 Subject: [PATCH 17/38] Add pandas to `requirements-dev.txt` --- requirements-dev.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements-dev.txt b/requirements-dev.txt index 6413ac7c..6938e3c4 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -18,3 +18,4 @@ pydata-sphinx-theme sphinx_design jupyter-sphinx choclo +pandas From 41031d0c4fd7138c1d0ae52d069466ceaf9c2044 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Mon, 19 Oct 2026 15:48:04 -0700 Subject: [PATCH 18/38] Update import of `minimize.conjugate_gradient` in User Guide --- docs/user-guide/fundamentals/beta-cooling.rst | 6 +++--- docs/user-guide/fundamentals/inversion-class.rst | 4 ++-- docs/user-guide/fundamentals/minimizer.rst | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/user-guide/fundamentals/beta-cooling.rst b/docs/user-guide/fundamentals/beta-cooling.rst index f6f72f4d..1e50a233 100644 --- a/docs/user-guide/fundamentals/beta-cooling.rst +++ b/docs/user-guide/fundamentals/beta-cooling.rst @@ -83,7 +83,7 @@ Let's use this capability to implement a simple beta-cooling schedule: # Minimize the objective function using a conjugate gradient minimizer. # Overwrite the model variable with the minimized model. - model = ii.conjugate_gradient(phi, model) + model = ii.minimize.conjugate_gradient(phi, model) # Define a stopping criterion: # finish the inversion if the chi factor is below 1. @@ -152,7 +152,7 @@ And finally re-write our inversion in a slicker way: while True: # Minimize the objective function - model = ii.conjugate_gradient(phi, model) + model = ii.minimize.conjugate_gradient(phi, model) # Finish the inversion if the stopping criterion is met if chi_target(model): @@ -192,7 +192,7 @@ We can also explore the custom ``beta`` hyperparameter and see how its value cha while True: # Minimize the objective function - model = ii.conjugate_gradient(phi, model) + model = ii.minimize.conjugate_gradient(phi, model) # Print information iteration += 1 diff --git a/docs/user-guide/fundamentals/inversion-class.rst b/docs/user-guide/fundamentals/inversion-class.rst index 6ee3ea08..0966fa27 100644 --- a/docs/user-guide/fundamentals/inversion-class.rst +++ b/docs/user-guide/fundamentals/inversion-class.rst @@ -121,7 +121,7 @@ Finally, let's create our :class:`~inversion_ideas.Inversion` object. We'll add inversion = ii.Inversion( phi, initial_model, - minimizer=ii.conjugate_gradient, + minimizer=ii.minimize.conjugate_gradient, directives=[beta.update], stopping_criterion=chi_target, ) @@ -152,7 +152,7 @@ Alternatively, we can iterate over the :class:`~inversion_ideas.Inversion` objec inversion = ii.Inversion( phi, initial_model, - minimizer=ii.conjugate_gradient, + minimizer=ii.minimize.conjugate_gradient, directives=[beta.update], stopping_criterion=chi_target, ) diff --git a/docs/user-guide/fundamentals/minimizer.rst b/docs/user-guide/fundamentals/minimizer.rst index 8ee41226..0e7843d0 100644 --- a/docs/user-guide/fundamentals/minimizer.rst +++ b/docs/user-guide/fundamentals/minimizer.rst @@ -13,8 +13,8 @@ model* or *recovered model*, i.e. the model that minimize that objective functio Linear minimizers ----------------- -If our inversion is linear (e.g. potential field inversions), we can make use of linear minimizers, like :func:`inversion_ideas.conjugate_gradient` to minimize the objective function. -The :func:`~inversion_ideas.conjugate_gradient` function will ask the objective function and an initial model from which it'll start the conjugate gradient algorithm, and it will return the recovered model after convergence has been achieved. +If our inversion is linear (e.g. potential field inversions), we can make use of linear minimizers, like :func:`inversion_ideas.minimize.conjugate_gradient` to minimize the objective function. +The :func:`~inversion_ideas.minimize.conjugate_gradient` function will ask the objective function and an initial model from which it'll start the conjugate gradient algorithm, and it will return the recovered model after convergence has been achieved. For example, let's consider the :class:`~inversion_ideas.LinearRegressor` simulation and the ``data_misfit`` object we built when we introduced the :ref:`objective function `: @@ -54,12 +54,12 @@ Let's define an objective function by adding a :class:`~inversion_ideas.SimpleSm phi = data_misfit + beta * ii.SimpleSmallness(n_params) phi -And use the :func:`~inversion_ideas.conjugate_gradient` to minimize it by setting an initial model full of zeros: +And use the :func:`~inversion_ideas.minimize.conjugate_gradient` to minimize it by setting an initial model full of zeros: .. jupyter-execute:: initial_model = np.zeros(n_params, dtype=np.float64) - model = ii.conjugate_gradient(phi, initial_model) + model = ii.minimize.conjugate_gradient(phi, initial_model) model We were able to recover a model that is close to the true model used to generate the synthetic data. From d549e57eaece35da89c1ccf128dd8e5d654d64f5 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Mon, 19 Oct 2026 15:49:07 -0700 Subject: [PATCH 19/38] Update import of GaussNewtonConjugateGradient --- docs/user-guide/fundamentals/minimizer.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/user-guide/fundamentals/minimizer.rst b/docs/user-guide/fundamentals/minimizer.rst index 0e7843d0..0433c499 100644 --- a/docs/user-guide/fundamentals/minimizer.rst +++ b/docs/user-guide/fundamentals/minimizer.rst @@ -80,13 +80,13 @@ Non-linear minimizers If our inversion is non-linear (DC-IP, EM inversions, etc.), we'll need to use a suitable minimizer for non-linear inversion problems, like the Gauss-Newton method. -The :class:`inversion_ideas.GaussNewtonConjugateGradient` object implements a Gauss-Newton algorithm using Conjugate Gradient to find search directions, and performing a backtracking line search. +The :class:`inversion_ideas.minimize.GaussNewtonConjugateGradient` object implements a Gauss-Newton algorithm using Conjugate Gradient to find search directions, and performing a backtracking line search. -We can use it to minimize the non-linear objective function through the :meth:`inversion_ideas.GaussNewtonConjugateGradient.run` method: +We can use it to minimize the non-linear objective function through the :meth:`inversion_ideas.minimize.GaussNewtonConjugateGradient.run` method: .. code:: python - minimizer = GaussNewtonConjugateGradient() + minimizer = ii.minimize.GaussNewtonConjugateGradient() inverted_model = minimizer.run(phi, initial_model) @@ -94,7 +94,7 @@ Alternatively we can iterate over it after calling the minimizer: .. code:: python - minimizer = GaussNewtonConjugateGradient() + minimizer = ii.minimize.GaussNewtonConjugateGradient() for model in minimizer(phi, initial_model): # The model is the one obtained after each Gauss-Newton iteration From de4e4c8239f37397fb2a122e9a6dbd93b2d9bdd5 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Mon, 19 Oct 2026 15:49:23 -0700 Subject: [PATCH 20/38] Add custom CSS style for the jupyter-execute cells --- docs/_static/custom.css | 19 +++++++++++++++++++ docs/conf.py | 3 ++- 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 docs/_static/custom.css diff --git a/docs/_static/custom.css b/docs/_static/custom.css new file mode 100644 index 00000000..22a57c3e --- /dev/null +++ b/docs/_static/custom.css @@ -0,0 +1,19 @@ +/* Try to make the jupyter-sphinx style match sphinx-gallery for consistency */ +div.jupyter_container { + border: none; + box-shadow: none; +} + +div.jupyter_container .cell_input { + margin-bottom: 1.15rem; + border-radius: 0.4em; + box-shadow: 1px 1px 1px #d8d8d8; +} + +div.jupyter_container .cell_output { + margin-bottom: 1.15rem; +} + +.jupyter_container div.code_cell pre { + padding: 10px; +} diff --git a/docs/conf.py b/docs/conf.py index cd9c0f5d..88c00c37 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -82,4 +82,5 @@ "github_version": "main", "doc_path": "docs", } -html_static_path = [] # avoid warning by overwriting the default ["_static"] +html_static_path = ["_static"] +html_css_files = ["custom.css"] From da4656b323368b765fe86957f66855f560e17c02 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Mon, 19 Oct 2026 15:55:26 -0700 Subject: [PATCH 21/38] Make use of SimpleFlatness --- docs/user-guide/fundamentals/objective-function.rst | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/user-guide/fundamentals/objective-function.rst b/docs/user-guide/fundamentals/objective-function.rst index 1cf8e5bc..22adf6b5 100644 --- a/docs/user-guide/fundamentals/objective-function.rst +++ b/docs/user-guide/fundamentals/objective-function.rst @@ -226,8 +226,7 @@ We can also add more than two objective functions together. For example, conside .. jupyter-execute:: - # TODO: Use SimpleFlatness here! - flatness = ii.SimpleSmallness(n_params).set_name("1") + flatness = ii.SimpleFlatness(n_params).set_name("1") flatness .. jupyter-execute:: From 6547edda42b679b4491f2679e1890dcebec930a0 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Mon, 19 Oct 2026 15:55:37 -0700 Subject: [PATCH 22/38] Add link to Hyperparameters page --- docs/user-guide/fundamentals/beta-cooling.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user-guide/fundamentals/beta-cooling.rst b/docs/user-guide/fundamentals/beta-cooling.rst index 1e50a233..4e109e29 100644 --- a/docs/user-guide/fundamentals/beta-cooling.rst +++ b/docs/user-guide/fundamentals/beta-cooling.rst @@ -129,7 +129,7 @@ Following the previous example, we can define our objective function as: .. seealso:: - Learn more about custom hyperparameter objects in **TODO** + Learn more about custom hyperparameter objects in :ref:`hyperparameters`. We can also define a stopping criterion to define when our inversion should stop. From 5b23d58dbe3df9e3b9ec2c4385d76c376243072d Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Mon, 19 Oct 2026 17:07:58 -0700 Subject: [PATCH 23/38] Removed unneeded caption in toc --- docs/user-guide/fundamentals/inversion.rst | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/user-guide/fundamentals/inversion.rst b/docs/user-guide/fundamentals/inversion.rst index f7ba427d..209b493a 100644 --- a/docs/user-guide/fundamentals/inversion.rst +++ b/docs/user-guide/fundamentals/inversion.rst @@ -15,7 +15,6 @@ inversions with the inversion framework. .. toctree:: :hidden: :maxdepth: 1 - :caption: Getting started beta-cooling inversion-class From f8ee1b9f1e9f39c2e81065be2528e8027d260d60 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Mon, 19 Oct 2026 17:08:25 -0700 Subject: [PATCH 24/38] Add user guide pages for simulations --- .../fundamentals/simulations-simpeg.rst | 140 ++++++++++++++++++ docs/user-guide/fundamentals/simulations.rst | 120 ++++++++++++++- 2 files changed, 259 insertions(+), 1 deletion(-) create mode 100644 docs/user-guide/fundamentals/simulations-simpeg.rst diff --git a/docs/user-guide/fundamentals/simulations-simpeg.rst b/docs/user-guide/fundamentals/simulations-simpeg.rst new file mode 100644 index 00000000..5a11c652 --- /dev/null +++ b/docs/user-guide/fundamentals/simulations-simpeg.rst @@ -0,0 +1,140 @@ +.. _simulations-simpeg: + +Plugging in SimPEG simulations +------------------------------ + +.. warning:: + + Plugging in SimPEG simulations into the new inversion framwork is still in + experimental stages. If you run into any issue following these instructions, + please `open an Issue `__ + to report it. + +SimPEG simulations are not yet fully compatible with the new inversion framework, but we can *wrap* them in a custom :class:`~inversion_ideas.WrappedSimulation` class that will expose the right interface for it to work with the new inversion framework. + +For example, let's define a SimPEG's gravity simulation using the integral formulation: + +.. jupyter-execute:: + + import numpy as np + import bordado as bd + import discretize + import simpeg + from simpeg.potential_fields.gravity import ( + Point, + Simulation3DIntegral, + SourceField, + Survey, + ) + import inversion_ideas as ii + + # Define a mesh + h = [(5.0, 40)] + mesh = discretize.TensorMesh(h=[h, h, h], origin="CCN") + mesh + + # Define a set of receivers in a regular grid at zeroth height + region = (-100, 100, -100, 100) + shape = (11, 11) + height = 0 + coordinates = bd.grid_coordinates(region, shape=shape, non_dimensional_coords=height) + + # Define the SimPEG gravity survey + locations = np.vstack(tuple(c.ravel() for c in coordinates)).T + receivers = Point(locations, components="gz") + source = SourceField(receiver_list=[receivers]) + survey = Survey(source) + + # Define the SimPEG simulation + simulation_simpeg = Simulation3DIntegral( + mesh, survey=survey, rhoMap=simpeg.maps.IdentityMap(mesh), engine="choclo" + ) + simulation_simpeg + +Such simulation can be evaluated through the ``dpred`` method by passing a given ``model``. +Let's consider a model that contains two rectangular blocks with different densities: + +.. jupyter-execute:: + + model = np.zeros(mesh.n_cells) + + # Define block through their west-south-lower and east-north-upper vertices + blocks = [ + [(-60, -10, -70), (-40, 10, -50)], + [(40, -10, -70), (60, 10, -50)], + ] + densities = [-0.2, 0.2] # in g/cc + + for (p0, p1), density in zip(blocks, densities, strict=True): + model = simpeg.utils.model_builder.add_block( + mesh.cell_centers, model, p0, p1, density + ) + +.. jupyter-execute:: + + import matplotlib.pyplot as plt + + (tmp,) = mesh.plot_slice(model, normal="Y", slice_loc=0) + plt.colorbar(tmp, label="densities [g/cc]") + plt.show() + +And get the predicted gravity data for that model: + +.. jupyter-execute:: + + gz = simulation_simpeg.dpred(model) + +.. jupyter-execute:: + + maxabs = np.abs(gz).max() + easting, northing, _ = coordinates + plt.pcolormesh(easting, northing, gz.reshape(shape), vmin=-maxabs, vmax=maxabs) + plt.colorbar(label="gz [mgal]") + plt.gca().set_aspect("equal") + plt.show() + +Let's now wrap this simulation to make it compatible within the new inversion framework: + +.. jupyter-execute:: + + simulation = ii.WrappedSimulation(simulation_simpeg) + simulation + +We can use the :meth:`inversion_ideas.WrappedSimulation.__call__` method to evaluate it: + +.. jupyter-execute:: + + gz = simulation(model) + + maxabs = np.abs(gz).max() + easting, northing, _ = coordinates + plt.pcolormesh(easting, northing, gz.reshape(shape), vmin=-maxabs, vmax=maxabs) + plt.colorbar(label="gz [mgal]") + plt.gca().set_aspect("equal") + plt.show() + + +And the :meth:`inversion_ideas.WrappedSimulation.jacobian` to compute its Jacobian matrix: + +.. jupyter-execute:: + + jacobian = simulation.jacobian(model) + jacobian + +.. hint:: + + By default the :class:`~inversion_ideas.WrappedSimulation` will not build the + Jacobian matrix, but create a :class:`~scipy.sparse.linalg.LinearOperator` + that connects to the ``Jvec`` and ``Jtvec`` methods of the SimPEG + simulation. + + For some SimPEG simulations we can force the :class:`~inversion_ideas.WrappedSimulation` to build the Jacobian matrix and store it in memory by setting ``store_jacobian=True``: + + .. jupyter-execute:: + + sim = ii.WrappedSimulation(simulation_simpeg, store_jacobian=True) + sim + + .. jupyter-execute:: + + sim.jacobian(model) diff --git a/docs/user-guide/fundamentals/simulations.rst b/docs/user-guide/fundamentals/simulations.rst index 32b674cb..daf668e3 100644 --- a/docs/user-guide/fundamentals/simulations.rst +++ b/docs/user-guide/fundamentals/simulations.rst @@ -3,4 +3,122 @@ Simulations =========== -TODO +.. toctree:: + :hidden: + :maxdepth: 1 + + simulations-simpeg + +Generally speaking, any inversion require at least one *forward modelling function*, i.e. a function that can predict data based on a given model. +It is usually represented by a function :math:`\mathbf{f}: \mathbb{R}^M \rightarrow \mathbb{R}^N`, and it's usually incorporated to the inversion through the data misfit term :math:`\phi_\text{d}(\mathbf{m})`: + +.. math:: + + \phi_\text{d}(\mathbf{m}) = + \sum\limits_{i=1}^N + \frac{ + \left\lvert f_i(\mathbf{m}) - d_i^\text{obs} \right\rvert^2 + }{ + \epsilon_i^2 + } + +where :math:`\mathbf{m}` is the model vector, :math:`d_i^\text{obs}` is the +:math:`i`-th observed datum, :math:`f_i(\mathbf{m})` is the :math:`i`-th element +of the :math:`\mathbf{f}(\mathbf{m})` vector, and :math:`\epsilon_i` is the +uncertainty of the :math:`i`-th datum. + +The inversion will require the ability to evaluate that function :math:`\mathbf{f}` on any model vector :math:`\mathbf{m}`, and also its Jacobian matrix :math:`\mathbf{J}_\mathbf{f}(\mathbf{m})`, i.e. the matrix of first derivatives: + +.. math:: + + \mathbf{J}_\mathbf{f} = + \begin{bmatrix} + \frac{\partial f_1}{\partial m_1} & \dots & \frac{\partial f_1}{\partial m_M} \\ + \vdots & \ddots & \vdots \\ + \frac{\partial f_N}{\partial m_1} & \dots & \frac{\partial f_N}{\partial m_M} + \end{bmatrix} + + +In the inversion framework the forward modelling functions are represented through :class:`~inversion_ideas.base.Simulation` classes. These classes always provide two attributes: + +* :attr:`~inversion_ideas.base.Simulation.n_params`: the number of elements in the expected ``model`` array. +* :attr:`~inversion_ideas.base.Simulation.n_data`: the number of elements of the array with predicted data. + +and two methods: + +* :meth:`~inversion_ideas.base.Simulation.__call__`: evaluates the function :math:`\mathbf{f}` on the provided ``model`` array (with ``n_params`` elements). It will always return an array with ``n_data`` elements. +* :meth:`~inversion_ideas.base.Simulation.jacobian`: returns the Jacobian matrix of the function :math:`\mathbf{f}` evaluated on the provided ``model`` array (with ``n_params`` elements). It can either return a dense or sparse 2D array (with shape ``(n_data, n_params)``), or a :class:`~scipy.sparse.linalg.LinearOperator` object. + + +For example, let's define a :class:`inversion_ideas.LinearRegressor` simulation with a random matrix: + +.. jupyter-execute:: + + import inversion_ideas as ii + + n_data = 5 + n_params = 10 + simulation = ii.LinearRegressor.create_random(n_data, n_params, seed=42) + +We can call the ``simulation`` with a given model vector to evaluate the function. + +.. jupyter-execute:: + + import numpy as np + + rng = np.random.default_rng(seed=43) + model = rng.uniform(low=-1.0, high=1.0, size=n_params) + simulation(model) + +We can also get its Jacobian matrix for the same ``model``: + +.. jupyter-execute:: + + jacobian = simulation.jacobian(model) + jacobian + +.. jupyter-execute:: + + jacobian.shape + + +Alternatively, we could configure the :class:`~inversion_ideas.LinearRegressor` to return a +:class:`~scipy.sparse.linalg.LinearOperator` as a Jacobian. In this example, we need to pass ``build_jacobian=False`` as argument while creating the simulation: + +.. jupyter-execute:: + + simulation = ii.LinearRegressor.create_random(n_data, n_params, seed=42, build_jacobian=False) + +.. hint:: + + The ``build_jacobian`` option in :class:`~inversion_ideas.LinearRegressor` forces its :meth:`~inversion_ideas.LinearRegressor.jacobian` method to return a + :class:`~scipy.sparse.linalg.LinearOperator` for learning and testing purposes, but it will still store the whole matrix in memory under the hood. + +Let's now generate its Jacobian matrix for a given ``model``: + +.. jupyter-execute:: + + jacobian = simulation.jacobian(model) + jacobian + +As we can see it no longer returns a dense matrix, but a ``MatrixLinearOperator``, which is a child class of :class:`~scipy.sparse.linalg.LinearOperator`. +We can use this object to compute dot products with any other array, as if it were a regular matrix: + +.. jupyter-execute:: + + vector = rng.random(size=n_params) + jacobian @ vector + +We can also compute the dot product of its transpose against a vector: + +.. jupyter-execute:: + + vector = rng.random(size=n_data) + jacobian.T @ vector + +.. important:: + + The Jacobian matrix of any simulation will contain ``n_data * n_params`` elements. For large problems with high ``n_params`` and/or high ``n_data``, those matrices can grow to big that they don't fit in memory. + In those cases it's preferrable to work with :class:`~scipy.sparse.linalg.LinearOperator` objects that are capable of computing dot products on the fly, without the need to store all the matrix elements in memory. + + The capability of each simulation my depend on its implementation, and users are encouraged to read the specific documentation of each one of them. From ace9de3bb3b439f9d8e4f263dbbfc8300b0a4e96 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Mon, 19 Oct 2026 17:22:14 -0700 Subject: [PATCH 25/38] Minor improvements to the simulations page --- docs/user-guide/fundamentals/simulations.rst | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/docs/user-guide/fundamentals/simulations.rst b/docs/user-guide/fundamentals/simulations.rst index daf668e3..f65f1da8 100644 --- a/docs/user-guide/fundamentals/simulations.rst +++ b/docs/user-guide/fundamentals/simulations.rst @@ -31,13 +31,15 @@ The inversion will require the ability to evaluate that function :math:`\mathbf{ .. math:: - \mathbf{J}_\mathbf{f} = + \mathbf{J}_\mathbf{f}(\mathbf{m}) = \begin{bmatrix} - \frac{\partial f_1}{\partial m_1} & \dots & \frac{\partial f_1}{\partial m_M} \\ + \frac{\partial f_1(\mathbf{m})}{\partial m_1} & \dots & \frac{\partial f_1(\mathbf{m})}{\partial m_M} \\ \vdots & \ddots & \vdots \\ - \frac{\partial f_N}{\partial m_1} & \dots & \frac{\partial f_N}{\partial m_M} + \frac{\partial f_N(\mathbf{m})}{\partial m_1} & \dots & \frac{\partial f_N(\mathbf{m})}{\partial m_M} \end{bmatrix} +where :math:`\frac{\partial f_i(\mathbf{m})}{\partial m_j}` is the derivative of the :math:`i`-th element of the forward modelling function with respect to the :math:`j`-th element of the model vector evaluated on a given model :math:`\mathbf{m}`. + In the inversion framework the forward modelling functions are represented through :class:`~inversion_ideas.base.Simulation` classes. These classes always provide two attributes: @@ -60,7 +62,13 @@ For example, let's define a :class:`inversion_ideas.LinearRegressor` simulation n_params = 10 simulation = ii.LinearRegressor.create_random(n_data, n_params, seed=42) -We can call the ``simulation`` with a given model vector to evaluate the function. +We can access the ``n_params`` and ``n_data`` attributes of the simulation: + +.. jupyter-execute:: + + simulation.n_data, simulation.n_params + +We can call the ``simulation`` with a given model vector to evaluate the forward modelling function: .. jupyter-execute:: @@ -68,6 +76,7 @@ We can call the ``simulation`` with a given model vector to evaluate the functio rng = np.random.default_rng(seed=43) model = rng.uniform(low=-1.0, high=1.0, size=n_params) + simulation(model) We can also get its Jacobian matrix for the same ``model``: From 9f3340ecc92446b4cbe124bcecf00ca7e413d096 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Tue, 20 Oct 2026 10:14:40 -0700 Subject: [PATCH 26/38] Add content to page about conditions --- docs/user-guide/fundamentals/conditions.rst | 313 +++++++++++++++++++- 1 file changed, 312 insertions(+), 1 deletion(-) diff --git a/docs/user-guide/fundamentals/conditions.rst b/docs/user-guide/fundamentals/conditions.rst index 3f52b75a..616f4617 100644 --- a/docs/user-guide/fundamentals/conditions.rst +++ b/docs/user-guide/fundamentals/conditions.rst @@ -3,4 +3,315 @@ Conditions ========== -TODO +When we covered :ref:`inversion_class` we made use of the ``stopping_criterion`` argument that the :class:`~inversion_ideas.Inversion` uses to determine if it should finish or continue with the next iteration. + +The ``stopping_criterion`` can be a simple function (or any *callable*) that takes the ``model`` as argument and returns a bool variable (``True`` or ``False``). + +For example, the following function that checks if a given model is close to zero would be a valid argument: + +.. code:: python + + def is_close_to_zero(model): + if np.all(np.abs(model) <= 1e-13): + return True + return False + +But in most situations, the stopping criteria for an inversion will not only depend on the current model, but on the values of certain functions when they are evaluated on the current model. + +For such cases, the new framework offers a :class:`inversion_ideas.base.Condition` class that implements a ``__call__`` method that takes the ``model`` as argument and returns either ``True`` or ``False`` depending if the desired conditions is met or not. +For example, the :class:`inversion_ideas.conditions.ChiTarget` holds a +:class:`~inversion_ideas.DataMisfit` object, and everytime its +:meth:`inversion_ideas.conditions.ChiTarget.__call__` method gets called, it will evaluate the data misfit term, get its :math:`\chi` factor, and return ``True`` or ``False`` if it's below or equal to 1. + +Consider the same ``data_misfit`` object we created in :ref:`objective-function`: + +.. jupyter-execute:: + :hide-code: + + import numpy as np + import inversion_ideas as ii + + # Define a linear regressor as a simulation + n_data, n_params = 3, 5 + simulation = ii.simulations.LinearRegressor.create_random(n_data, n_params, seed=42) + + # Create some synthetic data and uncertainties + true_model = np.array([-5., 2., -3., 4., 1.]) + std = 1e-2 + data = simulation(true_model) + np.random.default_rng(seed=42).normal(size=n_data, scale=std) + uncertainties = std * np.ones_like(data) + + # Define a data misfit function + data_misfit = ii.DataMisfit(data, uncertainties, simulation) + +.. jupyter-execute:: + + data_misfit + +And define a :class:`inversion_ideas.conditions.ChiTarget` object for it: + +.. jupyter-execute:: + + import inversion_ideas as ii + + condition = ii.conditions.ChiTarget(data_misfit) + condition + +If we evaluate it with any model that doesn't fit the data, the :math:`\chi` factor will be higher than one and therefore the condition will be ``False``: + +.. jupyter-execute:: + + import numpy as np + + rng = np.random.default_rng(seed=4149) + model = rng.random(size=data_misfit.n_params) + condition(model) + +.. jupyter-execute:: + :hide-code: + + assert not condition(model) + +.. jupyter-execute:: + + data_misfit.chi_factor(model) + +But if we evaluate it with a model that fits the data, it will return ``True``: + +.. jupyter-execute:: + + condition(true_model) + +.. jupyter-execute:: + :hide-code: + + assert condition(true_model) + +.. jupyter-execute:: + + data_misfit.chi_factor(true_model) + + +Combining conditions +-------------------- + +The :class:`~inversion_ideas.Inversion` takes a single callable as the ``stopping_criterion`` argument. +But in some situations we might want the inversion to stop when multiple conditions are satisfied at the same time, or when at least one of them is. +For those cases, we can combine :class:`~inversion_ideas.base.Condition` objects together through the logical binary operators ``&`` (AND), ``|`` (OR), and ``^`` (XOR). + +For example, consider this very simple :class:`~inversion_ideas.base.Condition` classes: +.. note:: + + These classes are presented for learning purposes, not intended to be used in real-world inversions. + +.. jupyter-execute:: + + import numpy as np + import inversion_ideas as ii + + class IsPositive(ii.base.Condition): + """Simple condition that checks if every value in the model is positive.""" + + def __call__(self, model) -> bool: + return bool(np.all(model > 0)) + + class IsEven(ii.base.Condition): + """Simple condition that checks if every value in the model is even.""" + + def __call__(self, model) -> bool: + return bool(np.all(model % 2 == 0)) + +Let's create one instance of each: + +.. jupyter-execute:: + + is_positive = IsPositive() + is_even = IsEven() + +And see how they work with a given model: + +.. jupyter-execute:: + + is_positive(np.array([1., 2., 3.])) + +.. jupyter-execute:: + + is_positive(np.array([1., -2., 3.])) + +.. jupyter-execute:: + + is_even(np.array([2., 4., 6.])) + +.. jupyter-execute:: + + is_even(np.array([1., 4., 6.])) + +The ``&`` (AND) operator +~~~~~~~~~~~~~~~~~~~~~~~~ + +Let's combine them through the ``&`` (AND) operator: + +.. jupyter-execute:: + + condition = is_positive & is_even + +This condition will be ``True`` only if all values in the model are positive and even: + +.. jupyter-execute:: + + condition(np.array([2., 4., 6.])) + +But it will fail if at least one of them doesn't satisfy both conditions: + +.. jupyter-execute:: + + # A single odd number in the model + condition(np.array([1., 4., 6.])) + +.. jupyter-execute:: + + # A single non-positive number in the model + condition(np.array([2., -4., 6.])) + +.. jupyter-execute:: + + # A non-positive and an odd number in the model + condition(np.array([2., -4., 7.])) + +The ``~`` (OR) operator +~~~~~~~~~~~~~~~~~~~~~~~ + +Analougsly, we can combine them with an ``|`` (OR) operator: + +.. jupyter-execute:: + + condition = is_positive | is_even + +If at least one of the two conditions is satisfied, the ``condition`` will return ``True``: + +.. jupyter-execute:: + + # All positive numbers in the model + condition(np.array([1., 3., 5.])) + +.. jupyter-execute:: + + # All even numbers in the model + condition(np.array([2., 4., 6.])) + +But if either of them is satisfied, it will return ``False``: + +.. jupyter-execute:: + + condition(np.array([-1., 4., 6.])) + +The ``^`` (XOR) operator +~~~~~~~~~~~~~~~~~~~~~~~~ + +We can also combine them using the `exclusive or `__ operator (``^``): + +.. jupyter-execute:: + + condition = is_positive ^ is_even + +Similarly to the ``|`` operator, if both conditions are ``False``, then ``condition`` will also be ``False``: + +.. jupyter-execute:: + + condition(np.array([-1., 4., 6.])) + +And if one of them is ``True`` and the other one is ``False``, then it will be ``True``: + +.. jupyter-execute:: + + # All positive numbers in the model (but not all even) + condition(np.array([1., 2., 3.])) + +.. jupyter-execute:: + + # All even numbers in the model (but not all positive) + condition(np.array([0., 2., 4.])) + +But if both are ``True``, then ``condition`` will be ``False``: + +.. jupyter-execute:: + + # All even numbers in the model (but not all positive) + condition(np.array([2., 4., 6.])) + +Combining multiple conditions +----------------------------- + +We can also combine multiple conditions with these operators. +For example, let's consider a third condition class: + +.. jupyter-execute:: + + class IsCloseToZero(ii.base.Condition): + """Simple condition that checks if every value in the model is close to zero.""" + + def __call__(self, model) -> bool: + return bool(np.all(np.abs(model) <= 1e-13)) + + + is_close_to_zero = IsCloseToZero() + +And combine the three of them: + +.. jupyter-execute:: + + condition = (is_positive & is_even) | is_close_to_zero + +.. hint:: + + We can use parenthesis to group together logical operations. + +This new condition will be ``True`` if all values in the model are positive **and** even, **or** if they are all close to zero. + +.. jupyter-execute:: + + model = np.array([2., 4., 6.]) + condition(model) + +.. jupyter-execute:: + + model = np.array([1e-14, -2e-15, 0.]) + condition(model) + +But it will fail otherwise: + +.. jupyter-execute:: + + model = np.array([1., 2., 0.]) + condition(model) + +Showing information +------------------- + +We can see more detailed information about a composed conditions to see which one of the internal conditions is being satisfied and which one is not. +For that we can use the :meth:`inversion_ideas.base.Condition.info` method: + +.. jupyter-execute:: + + model = np.array([2., 4., 6.]) + condition.info(model) + + +Real-world use cases +-------------------- + +Some common use case for combining conditions is to force the inversion to stop if the :math:`\chi` factor of the data misfit term reaches the target **or** if the whole objective function hasn't changed significantly since the previous iteration. +We can then combine a :class:`inversion_ideas.conditions.ChiTarget` and a :class:`inversion_ideas.conditions.ObjectiveChanged`: + +.. jupyter-execute:: + + # Define the objective function + smallness = ii.SimpleSmallness(n_params) + phi = data_misfit + 0.2 * smallness + + # Define the two conditions + chi_target = ii.conditions.ChiTarget(data_misfit) + objective_changed = ii.conditions.ObjectiveChanged(phi, rtol=1e-2) + + # Combine them into a single stopping criterion + stopping_criterion = chi_target | objective_changed From ff387449196049d082c29cfa44bf09d6fa6a8e28 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Tue, 20 Oct 2026 10:30:00 -0700 Subject: [PATCH 27/38] Fix a few style issues in the conditions page --- docs/user-guide/fundamentals/conditions.rst | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/user-guide/fundamentals/conditions.rst b/docs/user-guide/fundamentals/conditions.rst index 616f4617..885393a7 100644 --- a/docs/user-guide/fundamentals/conditions.rst +++ b/docs/user-guide/fundamentals/conditions.rst @@ -18,7 +18,7 @@ For example, the following function that checks if a given model is close to zer But in most situations, the stopping criteria for an inversion will not only depend on the current model, but on the values of certain functions when they are evaluated on the current model. -For such cases, the new framework offers a :class:`inversion_ideas.base.Condition` class that implements a ``__call__`` method that takes the ``model`` as argument and returns either ``True`` or ``False`` depending if the desired conditions is met or not. +For such cases, the new framework offers a :class:`inversion_ideas.base.Condition` class that implements a :meth:`~inversion_ideas.base.Condition.__call__` method that takes the ``model`` as argument and returns either ``True`` or ``False`` depending if the desired conditions is met or not. For example, the :class:`inversion_ideas.conditions.ChiTarget` holds a :class:`~inversion_ideas.DataMisfit` object, and everytime its :meth:`inversion_ideas.conditions.ChiTarget.__call__` method gets called, it will evaluate the data misfit term, get its :math:`\chi` factor, and return ``True`` or ``False`` if it's below or equal to 1. @@ -100,9 +100,6 @@ But in some situations we might want the inversion to stop when multiple conditi For those cases, we can combine :class:`~inversion_ideas.base.Condition` objects together through the logical binary operators ``&`` (AND), ``|`` (OR), and ``^`` (XOR). For example, consider this very simple :class:`~inversion_ideas.base.Condition` classes: -.. note:: - - These classes are presented for learning purposes, not intended to be used in real-world inversions. .. jupyter-execute:: @@ -121,6 +118,11 @@ For example, consider this very simple :class:`~inversion_ideas.base.Condition` def __call__(self, model) -> bool: return bool(np.all(model % 2 == 0)) +.. note:: + + These classes are presented for learning purposes, not intended to be used in real-world inversions. + + Let's create one instance of each: .. jupyter-execute:: From e17b3437e227d2856615b74a89420b9ebf4636de Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Tue, 20 Oct 2026 11:06:03 -0700 Subject: [PATCH 28/38] Add content to the hyperparameters page --- .../fundamentals/hyperparameters.rst | 126 +++++++++++++++++- 1 file changed, 125 insertions(+), 1 deletion(-) diff --git a/docs/user-guide/fundamentals/hyperparameters.rst b/docs/user-guide/fundamentals/hyperparameters.rst index 3f323385..ac8b44b0 100644 --- a/docs/user-guide/fundamentals/hyperparameters.rst +++ b/docs/user-guide/fundamentals/hyperparameters.rst @@ -3,4 +3,128 @@ Hyperparameters =============== -TODO +In the :ref:`beta-cooling` page we made use of the :class:`hyperparams.CooledMultiplier ` to easily implement the beta cooling schedule through an object that knows how to *cool down** itself. + +The framework offers classes for such objects, that we call **hyperparameters** or **dynamic hyperparameters**. They work as their underlying values (a ``float`` or a Numpy array), but they also have some mechanisms to easily update those values when needed. Usually the updating process happens when their ``update`` method gets called (see :meth:`CooledMultiplier.update ` as an example). + +Scalar hyperparameters +---------------------- + +We've seen how the +:class:`hyperparams.CooledMultiplier ` represents a ``float`` that can be updated throughout an inversion. +That class inherits from the :class:`inversion_ideas.base.Multiplier`, which simply wraps a ``float`` value and implements all the required interface to behave like one. + +For example, we can instantiate it with a given value: + +.. jupyter-execute:: + + import inversion_ideas as ii + + multiplier = ii.base.Multiplier(3.14) + print(multiplier) + +This ``multiplier`` holds the 3.14 float in its ``value`` attribute: + +.. jupyter-execute:: + + multiplier.value + +We can use that ``multiplier`` object as any other ``float``. For example, to perform any aritmetic operation with another ``float``: + +.. jupyter-execute:: + + print(multiplier + 3.0) + print(multiplier - 1.0) + print(multiplier * 2.0) + print(multiplier / 2.0) + print(multiplier**3) + +.. important:: + + Note that when we operate a :class:`~inversion_ideas.base.Multiplier` with a ``float`` we obtain a new ``float``, not another :class:`~inversion_ideas.base.Multiplier` object. + +We can also use it to operate with Numpy arrays: + +.. jupyter-execute:: + + import numpy as np + + array = np.array([1., 2., 3., 4.]) + multiplier * array + +.. important:: + + Note that when we operate a :class:`~inversion_ideas.base.Multiplier` with a Numpy array we obtain a new array with the resulting values of the operation. + Modifying the :class:`~inversion_ideas.base.Multiplier` after the operation will not change the value of the resulting array. + +The only exception is when we multiply it by an :class:`~inversion_ideas.base.Objective` function. In such case, the resulting :class:`~inversion_ideas.base.Scaled` function will hold the whole :class:`~inversion_ideas.base.Multiplier` as its +:class:`Scaled.multiplier `, instead of only its value as a ``float``. + +.. jupyter-execute:: + + smallness = ii.SimpleSmallness(n_params=10) + + scaled = multiplier * smallness + print(scaled) + +.. jupyter-execute:: + + # Check that the multiplier in the scaled objective function is + # our `multiplier` object: + scaled.multiplier is multiplier + + +Array hyperparameters +--------------------- + +Analougsly, we can wrap a Numpy array inside a :class:`base.WrappedArray `: + +.. jupyter-execute:: + + wrapped = ii.base.WrappedArray(np.array([1., 2., 3.])) + wrapped + +The wrapped array lives in its ``array`` attribute: + +.. jupyter-execute:: + + wrapped.array + +Similarly, we can operate with this object as if it were a regular Numpy array: + +.. jupyter-execute:: + + print(wrapped * 2.0) + print(wrapped / 2.0) + +.. jupyter-execute:: + + wrapped * np.array([10., 20., 30.]) + +.. jupyter-execute:: + + matrix = np.arange(9).reshape(3, 3) + print(matrix) + + matrix @ wrapped + +.. important:: + + Note that when we operate with a :class:`~inversion_ideas.base.WrappedArray` we obtain a new array with the resulting values of the operation. + Modifying the :class:`~inversion_ideas.base.WrappedArray` after the operation will not change the value of the resulting array. + +We can also pass it to Numpy functions: + +.. jupyter-execute:: + + np.mean(wrapped) + +And even index it: + +.. jupyter-execute:: + + wrapped[0] + +.. jupyter-execute:: + + wrapped[:2] From b2e71ab672961b858f3eef10cc1a742acc8d383f Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Tue, 20 Oct 2026 11:41:20 -0700 Subject: [PATCH 29/38] Add bordado to requirements-dev.txt --- requirements-dev.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements-dev.txt b/requirements-dev.txt index 6938e3c4..3595c5da 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -19,3 +19,4 @@ sphinx_design jupyter-sphinx choclo pandas +bordado From 5122b2b7cdd008419f5a5dd910f473c92e09af73 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Tue, 20 Oct 2026 16:01:11 -0700 Subject: [PATCH 30/38] Add content to the What section --- docs/user-guide/getting-started/what.rst | 26 ++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/docs/user-guide/getting-started/what.rst b/docs/user-guide/getting-started/what.rst index 52cca7ff..06824ee3 100644 --- a/docs/user-guide/getting-started/what.rst +++ b/docs/user-guide/getting-started/what.rst @@ -1,2 +1,28 @@ +.. _what-is: + What is this new framework? =========================== + +The `simpeg/inversion-design-ideas `__ +is a repo that holds a prototype for a redesign of SimPEG's inversion framework. +The main goal of the redesign is to create a new public inversion framework in +SimPEG that: + +* Is modular, allowing users to plug custom or third-party minimizers, + simulations, regularizations, etc. +* Can be easily extended (with minimum extra work) to problems outside the + traditional :math:`\phi(m) = \phi_d(m) + \beta \phi_m(m)` inversion problem. +* Is implemented in such way that is easier to read, study, and understand by + beginners that are taking their first steps in inversion theory. +* Is implemented in such way that can be easily extended to more complex and/or + complicated use cases. +* Defines a clear and minimal interface for each one of the classes. +* Makes use of `abstract classes `__ + to enforce implementation of required methods and properties. +* Simplifies the inheritance tree by lowering the amount of inheritance levels. + +.. warning:: + + This repository is still in experimental stages. + Its purpose is to have a place where we can freely try new ideas without having + to worry about breaking existing code, and supporting backward compatibility. From 245778ef8e5b67b3e3f078080e3db31cc5e905ab Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Tue, 20 Oct 2026 17:28:26 -0700 Subject: [PATCH 31/38] Add page on preconditioners --- docs/user-guide/fundamentals/minimizer.rst | 6 + .../fundamentals/preconditioners.rst | 125 ++++++++++++++++++ 2 files changed, 131 insertions(+) create mode 100644 docs/user-guide/fundamentals/preconditioners.rst diff --git a/docs/user-guide/fundamentals/minimizer.rst b/docs/user-guide/fundamentals/minimizer.rst index 0433c499..fe101d72 100644 --- a/docs/user-guide/fundamentals/minimizer.rst +++ b/docs/user-guide/fundamentals/minimizer.rst @@ -3,6 +3,12 @@ Minimizer ========= +.. toctree:: + :maxdepth: 2 + :hidden: + + preconditioners.rst + Once we defined the :ref:`objective function ` for our inversion, we need to find a model vector that would minimize it. To do so we need to make use of a **minimizer**. diff --git a/docs/user-guide/fundamentals/preconditioners.rst b/docs/user-guide/fundamentals/preconditioners.rst new file mode 100644 index 00000000..d6a751bb --- /dev/null +++ b/docs/user-guide/fundamentals/preconditioners.rst @@ -0,0 +1,125 @@ +.. _preconditioners: + +Preconditioners +=============== + +Some optimization methods, like the conjugate gradient, benefit from using a *preconditioner* matrix. + +Some optimization methods, like the conjugate gradient, can be accelerated by transforming the linear system they need to iteratively solve in such a way that improves the eigenvalue distribution of the matrix :math:`\mathbf{A}`. +One way to achieve this is to perform a change of variables through a *preconditioning* matrix (see [NocedalWright1999]_, page 118). + +We can pass a preconditioner to most of the minimizers of the new framework, and it offers some functions to generate appropriate preconditioners for a given objective function. + +Preconditioning the conjugate gradient +-------------------------------------- + +The :func:`minimize.conjugate_gradient ` +function through the ``preconditioner`` argument. + +For example, consider an objective function ``phi``. +We can use the :func:`~inversion_ideas.get_jacobi_preconditioner` to obtain a suitable preconditioner matrix for it: + +.. jupyter-execute:: + :hide-code: + + import numpy as np + import inversion_ideas as ii + + # Define a linear regressor as a simulation + n_data, n_params = 3, 5 + simulation = ii.simulations.LinearRegressor.create_random(n_data, n_params, seed=42) + + # Create some synthetic data and uncertainties + true_model = np.array([-5., 2., -3., 4., 1.]) + std = 1e-2 + data = simulation(true_model) + np.random.default_rng(seed=42).normal(size=n_data, scale=std) + uncertainties = std * np.ones_like(data) + + # Define a data misfit function + data_misfit = ii.DataMisfit(data, uncertainties, simulation) + + # Define smallness + smallness = ii.SimpleSmallness(n_params) + + # Define objective function + model = np.zeros(n_params) + beta = ii.utils.estimate_tradeoff_parameter(data_misfit, smallness, model, seed=42) + phi = data_misfit + beta * smallness + + +.. jupyter-execute:: + + import inversion_ideas as ii + + initial_model = np.zeros(n_params) + preconditioner = ii.get_jacobi_preconditioner(phi, initial_model) + preconditioner + +.. jupyter-execute:: + + preconditioner.toarray() + +Now let's minimize it using :func:`~inversion_ideas.minimize.conjugate_gradient` and use that matrix as a preconditioner: + +.. jupyter-execute:: + + inverted_model = ii.minimize.conjugate_gradient( + phi, initial_model, preconditioner=preconditioner + ) + + +Preconditioning the Gauss-Newton conjugate gradient +--------------------------------------------------- + +When minimizing non-linear functions we'll some non-linear minimizer like :class:`minimize.GaussNewtonConjugateGradient `. When calling this object we can also pass a ``preconditioner`` object: + +.. jupyter-execute:: + + # Define the minimizer + minimizer = ii.minimize.GaussNewtonConjugateGradient() + + # Run it using the `run()` method, and pass the preconditioner + inverted_model = minimizer.run( + phi, initial_model, preconditioner=preconditioner + ) + +The preconditioner will be passed by the +:class:`minimize.GaussNewtonConjugateGradient ` to the conjugate gradient algorithm that runs once per Gauss-Newton iteration. + +The issue of this approach is that the linear system that gets passed to the conjugate gradient function is different for each iteration: the Hessian matrix depends on the current model in the Gauss-Newton step, and because the problem is non-linear, that Hessian will be different for each iteration. +Trying to use the same preconditioner for each one of those systems might be unproductive. Instead, it's better to calculate a new preconditioner for each Gauss-Newton step. + +We can achieve that by using a *dynamic preconditioner* object, like the +:class:`inversion_ideas.JacobiPreconditioner`, and pass it to the minimizer as the ``preconditioner`` argument. +The :class:`minimize.GaussNewtonConjugateGradient ` will run the ``update`` method of the passed precondtioner object before running the conjugate gradient algorithm, and it'll pass it as argument to it. + +For example: + +.. jupyter-execute:: + + # Define a dynamic Jacobi preconditioner + preconditioner = ii.JacobiPreconditioner(phi) + preconditioner + +.. note:: + + These dynamic preconditioner are :class:`~scipy.sparse.linalg.LinearOperator` objects that under the hood they hold the preconditioning matrix after it gets updated or recomputed. + +We can pass it to the minimizer when running it: + +.. jupyter-execute:: + + # Run it using the `run()` method, and pass the preconditioner + inverted_model = minimizer.run( + phi, initial_model, preconditioner=preconditioner + ) + +.. seealso:: + + Find more **dynamic preconditioners** in the :ref:`API Reference `. + + +References +---------- + +.. [NocedalWright1999] Nocedal, J., & Wright, S. J. (1999). Numerical optimization. Springer. From 053ab51f026ea05d912c0c716c382576c2ce345b Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Tue, 20 Oct 2026 18:55:41 -0700 Subject: [PATCH 32/38] Add gravity inversion example to User Guide --- .../getting-started/gravity-inversion.rst | 218 +++++++++++++++++- 1 file changed, 217 insertions(+), 1 deletion(-) diff --git a/docs/user-guide/getting-started/gravity-inversion.rst b/docs/user-guide/getting-started/gravity-inversion.rst index 639355c2..4756bd53 100644 --- a/docs/user-guide/getting-started/gravity-inversion.rst +++ b/docs/user-guide/getting-started/gravity-inversion.rst @@ -1,4 +1,220 @@ Gravity Inversion ================= -Coming soon... +Let's start this gravity inversion example by generating a synthetic gravity dataset that consists in two prisms with opposite density constrast: + +.. jupyter-execute:: + :hide-code: + + import bordado as bd + import harmonica as hm + import numpy as np + import xarray as xr + + # Create some synthetic data + # ========================== + # Define a set of observation points + region = (-100, 100, -100, 100) + shape = (31, 31) + height = 0 + coordinates = bd.grid_coordinates( + region, shape=shape, non_dimensional_coords=height + ) + + # Define two rectangular prisms with different densities + prisms = [ + (-60, -40, -10, 10, -70, -50), + (40, 60, -10, 10, -70, -50), + ] + densities = np.array([-200, 200]) # SI units + + # Compute the gz field they generate on the observation points + gz = hm.prism_gravity(coordinates, prisms, densities, field="g_z") + gz *= -1 # Invert sign to work with upward component + + # Add noise + stderr = np.max(np.abs(gz)) * 0.01 + gz += np.random.default_rng(seed=51).normal(scale=stderr, size=gz.shape) + gz_std = stderr * np.ones_like(gz) + + # Build an xr.DataArray with the synthetic data + dims = ("northing", "easting") + easting, northing, upward = coordinates + easting, northing = easting[0, :], northing[:, 0] + coords = {"easting": easting, "northing": northing, "upward": (dims, upward)} + dataset = xr.Dataset({"gz": (dims, gz), "gz_std": (dims, gz_std)}, coords=coords) + dataset + +.. jupyter-execute:: + + # Plot synthetic data + import matplotlib.pyplot as plt + + dataset.gz.plot.pcolormesh(cbar_kwargs={"label": "gz [mGal]"}) + plt.show() + + +.. juypter-execute:: + + from matplotlib.patches import Rectangle + + _, ax = plt.subplots() + + +Start by defining SimPEG's gravity simulation for the inversion: + +.. jupyter-execute:: + + import discretize + import simpeg + from simpeg.potential_fields import gravity + + # Define the mesh + h = [(5.0, 40)] + mesh = discretize.TensorMesh(h=[h, h, h], origin="CCN") + + # Define gravity survey based on the location of the observation points + easting, northing = dataset.easting, dataset.northing + easting, northing = np.meshgrid(easting, northing) + coordinates = (easting, northing, dataset.upward.values) + + locations = np.vstack(tuple(c.ravel() for c in coordinates)).T + receivers = gravity.Point(locations, components="gz") + source = gravity.SourceField(receiver_list=[receivers]) + survey = gravity.Survey(source) + + # Define SimPEG's gravity simulation + simulation_simpeg = gravity.Simulation3DIntegral( + mesh, survey=survey, rhoMap=simpeg.maps.IdentityMap(mesh) + ) + + +We need to *wrap* the simulation to make it compatible with the new inversion framework: + +.. jupyter-execute:: + + import inversion_ideas as ii + + simulation = ii.WrappedSimulation(simulation_simpeg, store_jacobian=True) + +Now we can start defining the objective function we want to invert. Let's start by defining the data misfit using the synthetic data, its errors, and the wrapped simulation: + +.. jupyter-execute:: + + # Define the data misfit + data = dataset.gz.values.ravel() + uncertainties = dataset.gz_std.values.ravel() + data_misfit = ii.DataMisfit(data, uncertainties, simulation) + +Now let's continue with the regularization: + +.. jupyter-execute:: + + initial_model = np.zeros(mesh.n_cells) + depth_weights = simpeg.utils.depth_weighting(mesh, 0) ** 2 + smallness = ii.Smallness(mesh=mesh, cell_weights=depth_weights) + flatness_x, flatness_y, flatness_z = tuple( + ii.Flatness(mesh=mesh, direction=direction, cell_weights=depth_weights) + for direction in ("x", "y", "z") + ) + alpha_x, alpha_y, alpha_z = tuple( + ii.utils.estimate_tradeoff_parameter(smallness, flatness, initial_model) + for flatness in (flatness_x, flatness_y, flatness_z) + ) + model_norm = ( + smallness + + alpha_x * flatness_x + + alpha_y * flatness_y + + alpha_z * flatness_z + ).flatten() + model_norm + +Estimate a trade-off parameter between the ``data_misfit`` and the ``model_norm``, and use it as an initial value for the :class:`hyperparams.CooledMultiplier `: + +.. jupyter-execute:: + + # Define objective function + beta_0 = 4 * ii.utils.estimate_tradeoff_parameter(data_misfit, model_norm, initial_model) + beta = ii.hyperparams.CooledMultiplier(beta_0, cooling_factor=2) + beta + +And finally, define the objective function: + +.. jupyter-execute:: + + phi = data_misfit + beta * model_norm + phi + + +Build the inversion +------------------- + +Define a stopping condition: stop the inversion if the :math:`\chi` factor falls below 1: + +.. jupyter-execute:: + + stopping_criterion = ii.conditions.ChiTarget(data_misfit, chi_target=1.0) + +Create a *dynamic* Jacobi preconditioner that will get updated throughout the inversion. +Since we'll need the :class:`~inversion_ideas.Inversion` to pass it to the minimizer, we'll pass it to it through the ``minimizer_kwargs``: + +.. jupyter-execute:: + + preconditioner = ii.JacobiPreconditioner(phi) + minimizer_kwargs = {"preconditioner": preconditioner} + +Now we can define the inversion with: + +* the objective function we want to invert (``phi``), +* the initial model we'll use to start the inversion process, +* a :func:`minimize.conjugate_gradient ` as the minimizer, +* the :meth:`beta.update ` method as the only directive, +* the :class:`~inversion_ideas.conditions.ChiTarget` condition as a stopping criterion, +* and the preconditioner inside the ``minimizer_kwargs`` dictionary. + +.. jupyter-execute:: + + inversion = ii.Inversion( + phi, + initial_model, + ii.minimize.conjugate_gradient, + directives=[beta.update], + stopping_criterion=stopping_criterion, + minimizer_kwargs=minimizer_kwargs, + ) + +And run it! + +.. jupyter-execute:: + + inverted_model = inversion.run() + +We can access the ``inversion.log`` and convert it to a :class:`pandas.DataFrame`, and also use it to plot convergence curves: + +.. jupyter-execute:: + + log = inversion.log.to_pandas() + log + +.. jupyter-execute:: + + fig, axes = plt.subplots(nrows=3, ncols=1, sharex=True, figsize=(6, 8)) + axes[0].plot(log.index, log.beta, "o-") + axes[0].set_ylabel("Beta") + + axes[1].plot(log.index, log.phi_d, "o-") + axes[1].axhline(data_misfit.n_data, linestyle="--", color="grey") + axes[1].set_ylabel("Data misfit") + axes[1].set_yscale("log") + + axes[2].plot(log.index, log.phi_m, "o-") + axes[2].set_ylabel("Model norm") + plt.show() + +Finally, let's plot the model: + +.. jupyter-execute:: + + (tmp,) = mesh.plot_slice(inverted_model, normal="Y", slice_loc=0) + plt.colorbar(tmp, label="g/cc") + plt.show() From adb3e9d11826ce603673b1b090490d98baa82e40 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Tue, 20 Oct 2026 19:01:59 -0700 Subject: [PATCH 33/38] Minor tweaks to the gravity inversion --- docs/user-guide/getting-started/gravity-inversion.rst | 9 --------- 1 file changed, 9 deletions(-) diff --git a/docs/user-guide/getting-started/gravity-inversion.rst b/docs/user-guide/getting-started/gravity-inversion.rst index 4756bd53..efa177aa 100644 --- a/docs/user-guide/getting-started/gravity-inversion.rst +++ b/docs/user-guide/getting-started/gravity-inversion.rst @@ -4,7 +4,6 @@ Gravity Inversion Let's start this gravity inversion example by generating a synthetic gravity dataset that consists in two prisms with opposite density constrast: .. jupyter-execute:: - :hide-code: import bordado as bd import harmonica as hm @@ -53,14 +52,6 @@ Let's start this gravity inversion example by generating a synthetic gravity dat dataset.gz.plot.pcolormesh(cbar_kwargs={"label": "gz [mGal]"}) plt.show() - -.. juypter-execute:: - - from matplotlib.patches import Rectangle - - _, ax = plt.subplots() - - Start by defining SimPEG's gravity simulation for the inversion: .. jupyter-execute:: From 6c3345c315bf0f300f2a955e32355d4522f834bb Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Tue, 20 Oct 2026 19:05:18 -0700 Subject: [PATCH 34/38] Add Harmonica to requirements-dev.txt --- requirements-dev.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/requirements-dev.txt b/requirements-dev.txt index 3595c5da..00e3898b 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -20,3 +20,4 @@ jupyter-sphinx choclo pandas bordado +harmonica From 2faf58a8f2abee56505b54291b5b25aeed22624e Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Wed, 21 Oct 2026 11:44:39 -0700 Subject: [PATCH 35/38] Add content on the base submodule to the How To guide --- docs/reference/base.rst | 8 ++-- docs/user-guide/how-to/extend-base.rst | 53 ++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/docs/reference/base.rst b/docs/reference/base.rst index 8ecb2f4d..421abd62 100644 --- a/docs/reference/base.rst +++ b/docs/reference/base.rst @@ -5,16 +5,16 @@ Base submodule ============== -The :mod:`inversion_ideas.base` submodule contains abstract classes and base classes that work as the foundation of the framework. Inherit from these classes when defining your own subclasses. +The :mod:`inversion_ideas.base` submodule contains mostly abstract classes and base classes that work as the foundation of the framework. Inherit from these classes when defining your own subclasses. -.. admonition:: important - These classes are not meant to be instantiated. They are abstract classes only intended to be inherited from, or containers (like :class:`inversion_ideas.base.Scaled` and :class:`inversion_ideas.base.Combo`) that should not be instantiated by end users either. +.. important:: + + Most of these classes are not meant to be instantiated. They are abstract classes only intended to be inherited from, or containers (like :class:`inversion_ideas.base.Scaled` and :class:`inversion_ideas.base.Combo`) that should not be instantiated by end users. .. autosummary:: :toctree: api/ - base base.Objective base.Scaled base.Combo diff --git a/docs/user-guide/how-to/extend-base.rst b/docs/user-guide/how-to/extend-base.rst index ba99f957..554052e0 100644 --- a/docs/user-guide/how-to/extend-base.rst +++ b/docs/user-guide/how-to/extend-base.rst @@ -2,3 +2,56 @@ The :mod:`~inversion_ideas.base` submodule ========================================== + +The new inversion framework is built on top of a set of *base* classes that specify the interface of the child ones that will finally implement the particular methods. +These base classes live in the :mod:`inversion_ideas.base` submodule (see the :ref:`API reference for the base submodule `). +The majority of the base classes are `abstract classes `__ that require child classes to implement all the `abstract methods `__ for that class to be instatiable. +We can understand these abstract classes as a design layout that the child classes are forced to follow. + +For example, the :class:`inversion_ideas.base.Objective` is an abstract class that works as a base class for every objective function. +The :class:`base.Objective ` implements a few methods and properties that will be shared by all objective functions, but define some abstract methods that any child should implement: + +* the :meth:`Objective.__call__ ` method, +* the :meth:`Objective.gradient ` method, +* the :meth:`Objective.hessian ` method, and +* the :attr:`Objective.n_params ` property. + +We cannot directly instantiate this class: + +.. jupyter-execute:: + :raises: TypeError + + import inversion_ideas as ii + + ii.base.Objective() + +But we can instantiate the :class:`inversion_ideas.SimpleSmallness` a subclass of +:class:`base.Objective ` that implements all its abstract methods and properties. + +.. jupyter-execute:: + + smallness = ii.SimpleSmallness(4) + +.. note:: + + The use of abstract classes makes it easier to guarantee that + non-abstract classes implement the same interface as all its sibling + classes. This make the framework more modular: a minimizer like + :class:`~inversion_ideas.minimize.GaussNewtonConjugateGradient` can take + any :class:`base.Objective ` object as an + objective function, regardless how it's implemented and where it comes from, + as long as it correctly implements its abstract methods. + + +The :mod:`inversion_ideas.base` submodule also contains container classes like the :class:`base.Combo ` and :class:`base.Combo `. These classes are non-abstract :class:`~inversion_ideas.base.Objective` that implements all of its abstract methods, but they are not intended to be instantiated by end users: they are formed when adding together two :class:`~inversion_ideas.base.Objective` functions, or when multiplying one of them by a scalar. + +.. jupyter-execute:: + + flatness = ii.SimpleFlatness(4) + combo = smallness + flatness + type(combo) + +.. jupyter-execute:: + + scaled = 2.4 * smalness + type(scaled) From f278fb3dffaec3334bfb81847ea55f5e7928a481 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Wed, 21 Oct 2026 14:09:36 -0700 Subject: [PATCH 36/38] Add content to Writing your objective function Change verb tense in titles of How To guide. --- docs/reference/base.rst | 1 + docs/user-guide/how-to/extend-base.rst | 5 +- docs/user-guide/how-to/extend-objective.rst | 315 +++++++++++++++++- docs/user-guide/how-to/extend-simulations.rst | 4 +- docs/user-guide/how-to/extend.rst | 4 +- 5 files changed, 321 insertions(+), 8 deletions(-) diff --git a/docs/reference/base.rst b/docs/reference/base.rst index 421abd62..5f21ecbb 100644 --- a/docs/reference/base.rst +++ b/docs/reference/base.rst @@ -15,6 +15,7 @@ The :mod:`inversion_ideas.base` submodule contains mostly abstract classes and b .. autosummary:: :toctree: api/ + base base.Objective base.Scaled base.Combo diff --git a/docs/user-guide/how-to/extend-base.rst b/docs/user-guide/how-to/extend-base.rst index 554052e0..929f26ba 100644 --- a/docs/user-guide/how-to/extend-base.rst +++ b/docs/user-guide/how-to/extend-base.rst @@ -43,7 +43,8 @@ But we can instantiate the :class:`inversion_ideas.SimpleSmallness` a subclass o as long as it correctly implements its abstract methods. -The :mod:`inversion_ideas.base` submodule also contains container classes like the :class:`base.Combo ` and :class:`base.Combo `. These classes are non-abstract :class:`~inversion_ideas.base.Objective` that implements all of its abstract methods, but they are not intended to be instantiated by end users: they are formed when adding together two :class:`~inversion_ideas.base.Objective` functions, or when multiplying one of them by a scalar. +The :mod:`inversion_ideas.base` submodule also contains container classes like the :class:`base.Combo ` and :class:`base.Combo `. +These classes are non-abstract :class:`~inversion_ideas.base.Objective` that implements all of its abstract methods, but they are not intended to be instantiated by end users: they are formed when adding together two :class:`~inversion_ideas.base.Objective` functions, or when multiplying one of them by a scalar. .. jupyter-execute:: @@ -53,5 +54,5 @@ The :mod:`inversion_ideas.base` submodule also contains container classes like t .. jupyter-execute:: - scaled = 2.4 * smalness + scaled = 2.4 * smallness type(scaled) diff --git a/docs/user-guide/how-to/extend-objective.rst b/docs/user-guide/how-to/extend-objective.rst index 3dae4940..ed46b544 100644 --- a/docs/user-guide/how-to/extend-objective.rst +++ b/docs/user-guide/how-to/extend-objective.rst @@ -1,4 +1,315 @@ .. _extend-objective: -Writing new objective functions -=============================== +Write new objective functions +============================= + +One of the goals of the new inversion framework is to be more modular and allow users to write their own objective functions and easily plug them into the inversion framework. +To do so, we need to create our own class for our new objective function and make it a child of :class:`base.Objective `. +Then, we'll need to write implementations for its ``__call__``, ``gradient``, and ``hessian`` methods with the same signatures as the ones in +:class:`base.Objective `, and its ``n_params`` property. +Optionally, we can also add an ``__init__`` method to our new class to be able to pass the required arguments for it to function. + +For example, let's consider the following objective function that simply evaluates the norm of the model values: + +.. math:: + + \phi_\text{m}(\mathbf{m}) + = \sum\limits_{i=1}^M |m_i|^2 + = \lVert \mathbf{m} \rVert^2 + = \mathbf{m}^\text{T} \mathbf{m} + +Its gradient will be given by: + +.. math:: + + \nabla \phi_\text{m}(\mathbf{m}) = 2 \mathbf{m} + +And its Hessian it's the identity matrix: + +.. math:: + + \nabla^2 \phi_\text{m}(\mathbf{m}) = 2 \mathbb{I} + +We can implement this objective function as follows: + +.. jupyter-execute:: + + import numpy as np + + import inversion_ideas as ii + + + class ModelNorm(ii.base.Objective): + """ + Simple model norm regularization. + + Parameters + ---------- + n_params : int + Number of elements expected in the ``model`` array. + """ + + def __init__(self, n_params): + self._n_params = n_params + self._name = "norm" + + @property + def n_params(self): + return self._n_params + + def __call__(self, model): + return model.T @ model + + def gradient(self, model): + return 2 * model + + def hessian(self, model): + return 2 * np.eye(self.n_params) + + +We can instantiate this function and use its methods: + +.. jupyter-execute:: + + n_params = 5 + model_norm = ModelNorm(n_params) + print(model_norm) + +.. jupyter-execute:: + + model = np.arange(n_params, dtype=np.float64) + model_norm(model) + +.. jupyter-execute:: + + model_norm.gradient(model) + +.. jupyter-execute:: + + model_norm.hessian(model) + + +We can also choose to change its default name through its ``_name`` attribute: + +.. jupyter-execute:: + + class ModelNorm(ii.base.Objective): + """ + Simple model norm regularization. + + Parameters + ---------- + n_params : int + Number of elements expected in the ``model`` array. + """ + + def __init__(self, n_params): + self._n_params = n_params + self._name = "norm" + + @property + def n_params(self): + return self._n_params + + def __call__(self, model): + return model.T @ model + + def gradient(self, model): + return 2 * model + + def hessian(self, model): + return 2 * np.eye(self.n_params) + +.. jupyter-execute:: + + model_norm = ModelNorm(n_params) + print(model_norm) + + +Optimizing the Hessian matrix +----------------------------- + +In the last implementation of ``ModelNorm`` we choose to return a dense matrix in the ``hessian`` method: + +.. jupyter-execute:: + + model_norm.hessian(model) + + +If ``n_params`` is too large, then this matrix can grow too big to fit in memory. +Since it's mostly filled with zeros in the non-diagonal elements, it might not be strictly needed to occupy all that memory. + +One alternative would be to return a sparse matrix that represents the identity matrix: + +.. jupyter-execute:: + + import numpy as np + from scipy.sparse import eye_array + + import inversion_ideas as ii + + + class ModelNorm(ii.base.Objective): + """ + Simple model norm regularization. + + Parameters + ---------- + n_params : int + Number of elements expected in the ``model`` array. + """ + + def __init__(self, n_params): + self._n_params = n_params + self._name = "norm" + + @property + def n_params(self): + return self._n_params + + def __call__(self, model): + return model.T @ model + + def gradient(self, model): + return 2 * model + + def hessian(self, model): + return 2 * eye_array(self.n_params) + +.. jupyter-execute:: + + model_norm = ModelNorm(n_params) + model_norm.hessian(model) + +This strategy avoids storing all those non-diagonal zero elements in the matrix, but we are still storing all the twos in the diagonal. +We could reduce the memory requirements even more by making the ``hessian`` method to return a :class:`~scipy.sparse.linalg.LinearOperator` objects that implements dot products in the same way as +the identity matrix scaled by 2: + +.. jupyter-execute:: + + import numpy as np + from scipy.sparse.linalg import LinearOperator + + import inversion_ideas as ii + + + class ModelNorm(ii.base.Objective): + """ + Simple model norm regularization. + + Parameters + ---------- + n_params : int + Number of elements expected in the ``model`` array. + """ + + def __init__(self, n_params): + self._n_params = n_params + self._name = "norm" + + @property + def n_params(self): + return self._n_params + + def __call__(self, model): + return model.T @ model + + def gradient(self, model): + return 2 * model + + def hessian(self, model): + + def matvec(v): + "Dot product of 2I with vector." + return 2 * v + + def rmatvec(v): + "Dot product of transpose of 2I with vector." + return 2 * v + + hessian = LinearOperator( + shape=(self.n_params, self.n_params), + dtype=np.float64, + matvec=matvec, + rmatvec=rmatvec, + ) + return hessian + +.. jupyter-execute:: + + model_norm = ModelNorm(n_params) + hessian = model_norm.hessian(model) + hessian + +We can use this :class:`~scipy.sparse.linalg.LinearOperator` to compute dot products: + +.. jupyter-execute:: + + vector = np.random.default_rng(seed=52).random(n_params) + + hessian @ vector + + +Plugging custom objective functions +----------------------------------- + +Once we defined our objective function in a correct way, we can plug it into our inversion framework as with any other objective function from it. + +For example, consider the same ``data_misfit`` term we defined in :ref:`objective-function`: + +.. jupyter-execute:: + :hide-code: + + import numpy as np + import inversion_ideas as ii + + # Define a linear regressor as a simulation + n_data, n_params = 3, 5 + simulation = ii.simulations.LinearRegressor.create_random(n_data, n_params, seed=42) + + # Create some synthetic data and uncertainties + true_model = np.array([-5., 2., -3., 4., 1.]) + std = 1e-2 + data = simulation(true_model) + np.random.default_rng(seed=42).normal(size=n_data, scale=std) + uncertainties = std * np.ones_like(data) + + # Define a data misfit function + data_misfit = ii.DataMisfit(data, uncertainties, simulation) + +.. jupyter-execute:: + + data_misfit + +Let's build a ``ModelNorm`` regularization for this problem: + +.. jupyter-execute:: + + model_norm = ModelNorm(data_misfit.n_params) + +.. We can estimate a tradeoff-parameter between the ``data_misfit`` and our custom ``model_norm``: + +.. .. jupyter-execute:: + +.. initial_model = np.zeros(data_misfit.n_params) +.. beta = ii.utils.estimate_tradeoff_parameter(data_misfit, model_norm, initial_model) +.. beta + +We can build a linear combination for the two objective functions and choose a trade-off parameter for the ``model_norm``: + +.. jupyter-execute:: + + phi = data_misfit + 30.0 * model_norm + phi + +We can minimize this objective function with the :func:`minimize.conjugate_gradient ` (since the problem is linear): + + +.. jupyter-execute:: + + initial_model = np.zeros(data_misfit.n_params) + + inverted_model = ii.minimize.conjugate_gradient(phi, initial_model) + inverted_model + + + diff --git a/docs/user-guide/how-to/extend-simulations.rst b/docs/user-guide/how-to/extend-simulations.rst index 935fe79e..aeeb6fa7 100644 --- a/docs/user-guide/how-to/extend-simulations.rst +++ b/docs/user-guide/how-to/extend-simulations.rst @@ -1,4 +1,4 @@ .. _extend-simulations: -Writing new simulations -======================= +Write new simulations +===================== diff --git a/docs/user-guide/how-to/extend.rst b/docs/user-guide/how-to/extend.rst index 9cc09680..c4f33285 100644 --- a/docs/user-guide/how-to/extend.rst +++ b/docs/user-guide/how-to/extend.rst @@ -1,7 +1,7 @@ .. _extend: -Extending the framework -======================= +Extend the framework +==================== .. toctree:: :hidden: From 9a704398598741a1c87fd405f0732a18b6029231 Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Wed, 21 Oct 2026 14:23:09 -0700 Subject: [PATCH 37/38] Start filling the simulation How To section --- docs/user-guide/how-to/extend-simulations.rst | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/user-guide/how-to/extend-simulations.rst b/docs/user-guide/how-to/extend-simulations.rst index aeeb6fa7..3d7ba5e3 100644 --- a/docs/user-guide/how-to/extend-simulations.rst +++ b/docs/user-guide/how-to/extend-simulations.rst @@ -2,3 +2,17 @@ Write new simulations ===================== + +We've seen that it's possible to :ref:`write new objective functions ` and plug them into the new inversion framework by inheriting from the :class:`base.Objective ` abstract class and implementing its abstract methods. + +We can do something similar if we want to write our own simulations. +In that case we need to create a class that inherits from :class:`base.Simulation ` and implements its +:attr:`base.Simulation.n_data ` +and +:attr:`base.Simulation.n_params ` +abstract properties, +and its +:attr:`base.Simulation.__call__ ` +and +:attr:`base.Simulation.jacobian ` +asbtract methods. From 0c988a01dce0d05532424a85a1d8c7ea4f92c94f Mon Sep 17 00:00:00 2001 From: Santiago Soler Date: Wed, 21 Oct 2026 14:24:50 -0700 Subject: [PATCH 38/38] Remove empty DC inversion in Getting Started --- docs/user-guide/getting-started/dc-inversion.rst | 4 ---- docs/user-guide/index.rst | 1 - 2 files changed, 5 deletions(-) delete mode 100644 docs/user-guide/getting-started/dc-inversion.rst diff --git a/docs/user-guide/getting-started/dc-inversion.rst b/docs/user-guide/getting-started/dc-inversion.rst deleted file mode 100644 index 99c6a310..00000000 --- a/docs/user-guide/getting-started/dc-inversion.rst +++ /dev/null @@ -1,4 +0,0 @@ -DC Inversion -============ - -Coming soon... diff --git a/docs/user-guide/index.rst b/docs/user-guide/index.rst index 31982fb0..b602e25a 100644 --- a/docs/user-guide/index.rst +++ b/docs/user-guide/index.rst @@ -10,7 +10,6 @@ User Guide getting-started/what getting-started/installing getting-started/gravity-inversion - getting-started/dc-inversion .. toctree:: :maxdepth: 2