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 1890b5ba..88c00c37 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -19,6 +19,7 @@ "sphinx.ext.intersphinx", "sphinx_design", "numpydoc", + "jupyter_sphinx", ] intersphinx_mapping = { @@ -27,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"] @@ -80,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"] 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/reference/base.rst b/docs/reference/base.rst index 8ecb2f4d..5f21ecbb 100644 --- a/docs/reference/base.rst +++ b/docs/reference/base.rst @@ -5,11 +5,12 @@ 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/ diff --git a/docs/user-guide/fundamentals/beta-cooling.rst b/docs/user-guide/fundamentals/beta-cooling.rst new file mode 100644 index 00000000..4e109e29 --- /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.minimize.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 :ref:`hyperparameters`. + + +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.minimize.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.minimize.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/conditions.rst b/docs/user-guide/fundamentals/conditions.rst new file mode 100644 index 00000000..885393a7 --- /dev/null +++ b/docs/user-guide/fundamentals/conditions.rst @@ -0,0 +1,319 @@ +.. _conditions: + +Conditions +========== + +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 :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. + +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: + +.. 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)) + +.. 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:: + + 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 diff --git a/docs/user-guide/fundamentals/hyperparameters.rst b/docs/user-guide/fundamentals/hyperparameters.rst new file mode 100644 index 00000000..ac8b44b0 --- /dev/null +++ b/docs/user-guide/fundamentals/hyperparameters.rst @@ -0,0 +1,130 @@ +.. _hyperparameters: + +Hyperparameters +=============== + +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] diff --git a/docs/user-guide/fundamentals/inversion-class.rst b/docs/user-guide/fundamentals/inversion-class.rst new file mode 100644 index 00000000..0966fa27 --- /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.minimize.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.minimize.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-concept.rst b/docs/user-guide/fundamentals/inversion-concept.rst new file mode 100644 index 00000000..53aa5b4a --- /dev/null +++ b/docs/user-guide/fundamentals/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/fundamentals/inversion.rst b/docs/user-guide/fundamentals/inversion.rst new file mode 100644 index 00000000..209b493a --- /dev/null +++ b/docs/user-guide/fundamentals/inversion.rst @@ -0,0 +1,22 @@ +.. _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). + +In the following pages we'll see examples of different ways of running +inversions with the inversion framework. + +.. toctree:: + :hidden: + :maxdepth: 1 + + beta-cooling + inversion-class + + diff --git a/docs/user-guide/fundamentals/minimizer.rst b/docs/user-guide/fundamentals/minimizer.rst new file mode 100644 index 00000000..fe101d72 --- /dev/null +++ b/docs/user-guide/fundamentals/minimizer.rst @@ -0,0 +1,131 @@ +.. _minimizer: + +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**. + +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 (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 `: + +.. 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.SimpleSmallness` regularization: + +.. jupyter-execute:: + + beta = 30.0 + phi = data_misfit + beta * ii.SimpleSmallness(n_params) + phi + +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.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. + +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 +--------------------- + +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.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.minimize.GaussNewtonConjugateGradient.run` method: + +.. code:: python + + minimizer = ii.minimize.GaussNewtonConjugateGradient() + inverted_model = minimizer.run(phi, initial_model) + + +Alternatively we can iterate over it after calling the minimizer: + +.. code:: python + + minimizer = ii.minimize.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 +---------------------- + +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 diff --git a/docs/user-guide/fundamentals/objective-function.rst b/docs/user-guide/fundamentals/objective-function.rst new file mode 100644 index 00000000..22adf6b5 --- /dev/null +++ b/docs/user-guide/fundamentals/objective-function.rst @@ -0,0 +1,420 @@ +.. _objective-function: + +Objective function +================== + +Defining objective functions +---------------------------- + +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. + +.. jupyter-execute:: + + 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) + 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.array([-2., -1., 0., 1., 2.]) + + # 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. + + For example, we can compute the dot product of the ``hessian`` with the + ``model`` vector: + + .. jupyter-execute:: + + hessian @ model + + +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") + + +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 functions +------------------- + +Add two functions +~~~~~~~~~~~~~~~~~ + +It's possible to define any linear combination of objective functions. + +Consider we have a :class:`~inversion_ideas.SimpleSmallness` regularization function: + +.. jupyter-execute:: + + 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 + 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: + +.. 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(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 ``smallness`` regularization with a :class:`~inversion_ideas.SimpleFlatness` regularization: + +.. jupyter-execute:: + + flatness = ii.SimpleFlatness(n_params).set_name("1") + flatness + +.. jupyter-execute:: + + 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 ``smallness`` regularization, and the second element will be the ``flatness`` 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:: + + smallness in flat_phi + +.. jupyter-execute:: + + 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 ``flatness`` is the second element of ``phi``: + +.. jupyter-execute:: + + phi + + +.. jupyter-execute:: + + phi[1] + +So, we know that ``flatness in phi`` should be ``True``: + +.. jupyter-execute:: + + flatness in phi + +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 ``smallness``: + +.. jupyter-execute:: + + smallness 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(smallness) + +.. jupyter-execute:: + + phi.contains(flatness) + + +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 * (smallness + alpha * flatness) + 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 ``smallness`` and a scaled version of ``flatness``. + +.. 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(smallness) + +.. jupyter-execute:: + + phi.contains(flatness) 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. 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 new file mode 100644 index 00000000..f65f1da8 --- /dev/null +++ b/docs/user-guide/fundamentals/simulations.rst @@ -0,0 +1,133 @@ +.. _simulations: + +Simulations +=========== + +.. 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}(\mathbf{m}) = + \begin{bmatrix} + \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(\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: + +* :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 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:: + + 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. diff --git a/docs/user-guide/getting-started/gravity-inversion.rst b/docs/user-guide/getting-started/gravity-inversion.rst new file mode 100644 index 00000000..efa177aa --- /dev/null +++ b/docs/user-guide/getting-started/gravity-inversion.rst @@ -0,0 +1,211 @@ +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:: + + 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() + +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() diff --git a/docs/getting-started/index.rst b/docs/user-guide/getting-started/installing.rst similarity index 88% rename from docs/getting-started/index.rst rename to docs/user-guide/getting-started/installing.rst index 6ef58535..109e63c3 100644 --- a/docs/getting-started/index.rst +++ b/docs/user-guide/getting-started/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/getting-started/what.rst b/docs/user-guide/getting-started/what.rst new file mode 100644 index 00000000..06824ee3 --- /dev/null +++ b/docs/user-guide/getting-started/what.rst @@ -0,0 +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. 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..929f26ba --- /dev/null +++ b/docs/user-guide/how-to/extend-base.rst @@ -0,0 +1,58 @@ +.. _extend-base: + +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 * smallness + type(scaled) 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..ed46b544 --- /dev/null +++ b/docs/user-guide/how-to/extend-objective.rst @@ -0,0 +1,315 @@ +.. _extend-objective: + +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 new file mode 100644 index 00000000..3d7ba5e3 --- /dev/null +++ b/docs/user-guide/how-to/extend-simulations.rst @@ -0,0 +1,18 @@ +.. _extend-simulations: + +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. diff --git a/docs/user-guide/how-to/extend.rst b/docs/user-guide/how-to/extend.rst new file mode 100644 index 00000000..c4f33285 --- /dev/null +++ b/docs/user-guide/how-to/extend.rst @@ -0,0 +1,13 @@ +.. _extend: + +Extend the framework +==================== + +.. toctree:: + :hidden: + :maxdepth: 2 + :caption: Extending the framework + + extend-base + extend-objective + extend-simulations diff --git a/docs/user-guide/how-to/logging.rst b/docs/user-guide/how-to/logging.rst new file mode 100644 index 00000000..2c31f6b8 --- /dev/null +++ b/docs/user-guide/how-to/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 + + + + diff --git a/docs/user-guide/index.rst b/docs/user-guide/index.rst index 018ea001..b602e25a 100644 --- a/docs/user-guide/index.rst +++ b/docs/user-guide/index.rst @@ -2,3 +2,30 @@ User Guide ---------- + +.. toctree:: + :maxdepth: 1 + :caption: Getting started + + getting-started/what + getting-started/installing + getting-started/gravity-inversion + +.. toctree:: + :maxdepth: 2 + :caption: Fundamentals + + fundamentals/inversion-concept + fundamentals/objective-function + fundamentals/minimizer + fundamentals/inversion + fundamentals/conditions + fundamentals/hyperparameters + fundamentals/simulations + +.. toctree:: + :maxdepth: 2 + :caption: How To + + how-to/logging + how-to/extend diff --git a/environment.yml b/environment.yml index f9470f81..5701093b 100644 --- a/environment.yml +++ b/environment.yml @@ -32,3 +32,4 @@ dependencies: - numpydoc - pydata-sphinx-theme - sphinx-design + - jupyter_sphinx diff --git a/requirements-dev.txt b/requirements-dev.txt index 6bd77f35..00e3898b 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -16,4 +16,8 @@ sphinx numpydoc pydata-sphinx-theme sphinx_design +jupyter-sphinx choclo +pandas +bordado +harmonica 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