diff --git a/docs/conf.py b/docs/conf.py index c637d7a2..be8fbdab 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -19,6 +19,7 @@ "sphinx.ext.intersphinx", "sphinx_design", "numpydoc", + "myst_nb", ] intersphinx_mapping = { diff --git a/docs/reference/simulations.rst b/docs/reference/simulations.rst index d2759f3b..a8d8ef45 100644 --- a/docs/reference/simulations.rst +++ b/docs/reference/simulations.rst @@ -25,3 +25,4 @@ framework, we offer a *wrapper class* that allow us to extend them through a wrap_simulation WrappedSimulation + LinearRegressor 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.md b/docs/user-guide/inversion-concept.md new file mode 100644 index 00000000..3eca7aaf --- /dev/null +++ b/docs/user-guide/inversion-concept.md @@ -0,0 +1,12 @@ +# 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 [**objective function**](./objective-function.md) and the [**minimizer**](./minimizer.md). diff --git a/docs/user-guide/minimizer.md b/docs/user-guide/minimizer.md new file mode 100644 index 00000000..ec54ebf3 --- /dev/null +++ b/docs/user-guide/minimizer.md @@ -0,0 +1,7 @@ +--- +kernelspec: + display_name: Python 3 + name: python3 +--- + +# Minimizer diff --git a/docs/user-guide/objective-function.md b/docs/user-guide/objective-function.md new file mode 100644 index 00000000..de3194bb --- /dev/null +++ b/docs/user-guide/objective-function.md @@ -0,0 +1,274 @@ +--- +file_format: mystnb +kernelspec: + display_name: Python 3 + name: python3 +--- + +# 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 {py:class}`inversion_ideas.base.Objective`, like the {py:class}`inversion_ideas.DataMisfit` for example. + +```{code-cell} python +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, build_hessian=True, 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: + +```{code-cell} python +print("Expected size of model vector:", data_misfit.n_params) +``` + +Objective functions can be evaluated by calling them: + +```{code-cell} python +# 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: + +* {py:meth}`~inversion_ideas.base.Objective.gradient` computes the gradient of the objective function: {math}`\nabla \phi(\mathbf{m})`. +* {py: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})`. + +```{code-cell} python +# Get gradient +gradient = data_misfit.gradient(model) +gradient +``` + +```{code-cell} python +# Get Hessian +hessian = data_misfit.hessian(model) +hessian +``` + +> By default, the {py:class}`~inversion_ideas.DataMisfit` and many other +> objective functions in the framework won't build the whole Hessian matrix, but +> return a {py: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 {py: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 {py:meth}`~inversion_ideas.base.Objective.set_name` method. For example: + +```{code-cell} python +data_misfit.set_name("data_misfit") +data_misfit +``` + +Let's rename it to its previous name: + +```{code-cell} python +data_misfit.set_name("d") +data_misfit +``` + +> The {py: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: +> +> ```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 {py:class}`~inversion_ideas.TikhonovZero` regularization function: + +```{code-cell} python +zero = ii.TikhonovZero(n_params) +zero +``` + +We can add it to the ``data_misfit`` one by summing them together to obtain a new objective function: + +```{code-cell} python +phi = data_misfit + zero +phi +``` + +This {py: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: + +```{code-cell} python +phi(model) +``` + +```{code-cell} python +phi.gradient(model) +``` + +```{code-cell} python +phi.hessian(model) +``` + +> The {py:class}`inversion_ideas.base.Combo` class is not meant to be +> instantiated. Add two or more objective functions together to obtain one. + +The {py: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 ``len`` function, and we can also access each one of its +terms by index: + +```{code-cell} python +len(phi) +``` + +```{code-cell} python +print(phi[0]) +print(phi[1]) +``` + +```{code-cell} python +for i, term in enumerate(phi): + print(f"Term {i}: {term}") +``` + +```{code-cell} python +print(data_misfit in phi) +print(zero 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 ``zero`` regularization with a {py:class}`~inversion_ideas.TikhonovFirst` regularization: + +> **TODO:** Use TikhonovFirst here! + +```{code-cell} python +first = ii.TikhonovZero(n_params).set_name("1") +first +``` + +```{code-cell} python +phi = data_misfit + zero + first +phi +``` + +By default, when adding more than two objective functions together, we'll get +a *nested* {py:class}`inversion_ideas.base.Combo` object: the first element +will be a {py:class}`inversion_ideas.base.Combo` containing the `data_misfit` +and the `zero` regularization, and the second element will be the `first` +regularization. + +```{code-cell} python +print(len(phi)) +print(phi[0]) +print(phi[1]) +``` + +And since the first element is a {py:class}`~inversion_ideas.base.Combo`, we can also treat it as a collection: + +```{code-cell} python +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 {py:class}`~inversion_ideas.base.Combo` through the +{py:meth}`~inversion_ideas.base.Combo.flatten` method: + +```{code-cell} python +flat_phi = phi.flatten() +flat_phi +``` + +```{code-cell} python +len(flat_phi) +``` + +```{code-cell} python +print(flat_phi[0]) +print(flat_phi[1]) +print(flat_phi[2]) +``` + +```{code-cell} python +data_misfit in flat_phi +``` +```{code-cell} python +zero in flat_phi +``` +```{code-cell} python +first in flat_phi +``` + +#### Is in or contains? + +When using the ``in`` statement to check whether an objective function is part of a +{py: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 +{py:class}`~inversion_ideas.base.Combo`. + +For example, in we know that `first` is the second element of `phi`: + +```{code-cell} python +phi +``` + +```{code-cell} python +phi[1] +``` + +So, we know that `first in phi` should be `True`: + + +```{code-cell} python +first in phi +``` + +But, the first element of `phi` is a {py:class}`~inversion_ideas.base.Combo` +containing `data_misfit` and `zero`, so `data_misfit in phi` should be `False`: + +```{code-cell} python +data_misfit in phi +``` + +And the same goes for zero: + +```{code-cell} python +zero in phi +``` + +Alternatively, we can use the {py:meth}`~inversion_ideas.base.Combo.contains` +method to check recursively for a particular term: + +```{code-cell} python +phi.contains(data_misfit) +``` + +```{code-cell} python +phi.contains(zero) +``` + +```{code-cell} python +phi.contains(first) +``` + diff --git a/environment.yml b/environment.yml index a0d2a7a6..232ec4b9 100644 --- a/environment.yml +++ b/environment.yml @@ -31,3 +31,4 @@ dependencies: - numpydoc - pydata-sphinx-theme - sphinx-design + - myst-nb diff --git a/requirements-dev.txt b/requirements-dev.txt index d34ec11b..602d91aa 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -16,3 +16,4 @@ numpydoc pydata-sphinx-theme sphinx_design choclo +myst-nb diff --git a/src/inversion_ideas/__init__.py b/src/inversion_ideas/__init__.py index b84d4e8f..7cc7c6f4 100644 --- a/src/inversion_ideas/__init__.py +++ b/src/inversion_ideas/__init__.py @@ -19,7 +19,7 @@ create_tikhonov_regularization, ) from .regularization import Flatness, Smallness, SparseSmallness, TikhonovZero -from .simulations import WrappedSimulation, wrap_simulation +from .simulations import LinearRegressor, WrappedSimulation, wrap_simulation __all__ = [ "BFGSPreconditioner", @@ -30,6 +30,7 @@ "InversionLog", "InversionLogRich", "JacobiPreconditioner", + "LinearRegressor", "Smallness", "SparseSmallness", "TikhonovZero", diff --git a/src/inversion_ideas/base/objective_function.py b/src/inversion_ideas/base/objective_function.py index a51a96ea..478ba12e 100644 --- a/src/inversion_ideas/base/objective_function.py +++ b/src/inversion_ideas/base/objective_function.py @@ -146,7 +146,8 @@ def __repr__(self): def _repr_latex_(self): repr_ = f"{self._base_latex}" if self.name is not None: - repr_ += rf"_{{{self.name}}}" + name = self.name.replace("_", "-") + repr_ += r"_\text{" + name + "}" return f"${repr_} (m)$" def info(self): diff --git a/src/inversion_ideas/simulations.py b/src/inversion_ideas/simulations.py index 1723b863..304923a4 100644 --- a/src/inversion_ideas/simulations.py +++ b/src/inversion_ideas/simulations.py @@ -4,7 +4,7 @@ import numpy as np import numpy.typing as npt -from scipy.sparse.linalg import LinearOperator +from scipy.sparse.linalg import LinearOperator, aslinearoperator from simpeg.base.pde_simulation import BasePDESimulation from ._utils import array_to_str, compute_hash, hash_to_str @@ -220,3 +220,80 @@ def _get_fields(self, model): get_logger().debug(msg) # --- return fields + + +class LinearRegressor(Simulation): + r""" + Linear regressor simulation. + + Implements a linear regressor that generates data values as the product between its + matrix and a given model vector. + + .. important:: + + This class is included mainly as an example of a simple simulation class that + could be created and used within the inversion framework. + + Parameters + ---------- + matrix : (n_data, n_params) array + Matrix used in the definition of the linear regressor. + build_hessian : bool, optional + Whether the Hessian matrix will be created as a dense matrix (True) or as a :class:`LinearOperator`. Default to False. + cache : bool, optional + Whether to cache the results of the ``__call__`` method for the last model + vector or not. Default to True. + + Notes + ----- + Given the matrix :math:`\mathbf{X}`, the linear regressor simulation computes the + data vector :math:`\mathbf{y}` for a given model vector :math:`\mathbf{m}` as + follows: + + .. math:: + + \mathbf{y} = \mathbf{X} \cdot \mathbf{m} + """ + + def __init__(self, matrix, *, build_hessian=False, cache=True): + self.matrix = matrix + self.build_hessian = build_hessian + self.cache = cache + + @classmethod + def create_random( + cls, n_data: int, n_params: int, *, seed=None, **kwargs + ): + """Create a linear regressor with a random matrix. + + Parameters + ---------- + n_data: int + Number of data values that the simulation will generate. + n_params : int + Number of elements in the model vector. + seed : int or None, optional + Random seed or random state used to generate the matrix. + **kwargs + Keyword arguents passed to :meth:`~inversion_ideas.simulations.LinearRegressor.__init__`. + """ + shape = (n_data, n_params) + matrix = np.random.default_rng(seed=seed).uniform(size=shape) + return cls(matrix, **kwargs) + + @property + def n_params(self) -> int: + return self.matrix.shape[1] + + @property + def n_data(self) -> int: + return self.matrix.shape[0] + + @cache_on_model + def __call__(self, model) -> npt.NDArray[np.float64]: + return self.matrix @ model + + def jacobian(self, model) -> npt.NDArray[np.float64] | LinearOperator: # noqa: ARG002 + if not self.build_hessian: + return aslinearoperator(self.matrix) + return self.matrix