Skip to content

Commit

Permalink
Merge pull request #24 from Vital-Fernandez/dev
Browse files Browse the repository at this point in the history
Innate 0.1.11
  • Loading branch information
Vital-Fernandez authored Jun 28, 2024
2 parents cff3569 + 32d41cb commit 237295c
Show file tree
Hide file tree
Showing 11 changed files with 207 additions and 54 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,6 @@ __pycache__/
# Temporary files
tmp/
temp/

.coverage*

7 changes: 3 additions & 4 deletions README.rst
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
|pytest CI| |pre-commit| |Documentation Status| |License|
|pytest CI| |Documentation Status| |codecov| |pre-commit|

This library provides a set of tools to approximate data grids, either via interpolation or regression. This project aims
to provide an uniform and fast workflow for tensor operations while maintaining the accuracy and precision on the approximation.
Expand All @@ -24,9 +24,6 @@ Please commit to dev branch.
:align: center
:alt: INNATE library logo.

.. |License| image:: https://img.shields.io/badge/License-MIT%202.0-blue.svg
:alt: License

.. |Documentation Status| image:: https://readthedocs.org/projects/innate/badge/?version=latest
:target: https://innate.readthedocs.io/?badge=latest

Expand All @@ -36,3 +33,5 @@ Please commit to dev branch.
.. |pre-commit| image:: https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit
:target: https://github.com/pre-commit/pre-commit

.. |codecov| image:: https://codecov.io/gh/Vital-Fernandez/innate/branch/master/graph/badge.svg
:target: https://codecov.io/gh/Vital-Fernandez/innate
Binary file added docs/source/_static/matrix_plot_example.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
release = '06/25/2024'

# The full version, including alpha/beta/rc tags
release = '0.1.10'
release = '0.1.11'

# -- Moving documentation building data functions ----------------------------

Expand Down
21 changes: 21 additions & 0 deletions docs/source/introduction/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,27 @@ Inputs/outputs
Core objects
------------

.. autoclass:: innate.Grid

.. autoclass:: innate.DataSet

.. autofunction:: innate.DataSet.from_file


Interpolation techniques
------------------------

.. autofunction:: innate.interpolation.pytensor.regular_grid_interp

Regression techniques
---------------------

.. autofunction:: innate.regression.methods.parse_string_equation

Plots
-----

.. autofunction:: innate.plotting.Plotter.matrix_diagnostic

.. image:: ../_static/matrix_plot_example.png
:align: center
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "innate-stable"
version = "0.1.10"
version = "0.1.11"
readme = "README.rst"
requires-python = ">=3.10"
license = {file = "COPYING"}
Expand All @@ -25,3 +25,4 @@ pythonpath = ["src"]
mpl-baseline-path = 'tests/baseline'
mpl-results-path = 'tests/outputs'
mpl-results-always = false
addopts = "--cov-report term --cov-report xml"
2 changes: 1 addition & 1 deletion src/innate/config.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[metadata]
version = '0.1.10'
version = '0.1.11'

[parameter_labels]

Expand Down
49 changes: 29 additions & 20 deletions src/innate/interpolation/pytensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,26 +68,27 @@ def interpolation_coordinates(data_grid, axes_range_list, z_range=None, interp_t


def regular_grid_interp(points, values, coords, *, fill_value=None):
"""Perform a linear interpolation in N-dimensions w a regular grid

"""
Linear interpolation on a regular grid in arbitrary dimensions.
The data must be defined on a filled regular grid, but the spacing may be
uneven in any of the dimensions.
This implementation is based on the implementation in the
``scipy.interpolate.RegularGridInterpolator`` class which, in turn, is
based on the implementation from Johannes Buchner's ``regulargrid``
package https://github.com/JohannesBuchner/regulargrid.
Parameters
----------
points : list of array-like
A list of vectors with shapes ``(m1,), ... (mn,)``. These define the grid points in each dimension.
values : array-like
A tensor defining the values at each point in the grid defined by ``points``. This must have the shape ``(m1, ... mn, ..., nout)``.
Returns
-------
result : array-like
Interpolated values at the requested points.
Args:
points: A list of vectors with shapes ``(m1,), ... (mn,)``. These
define the grid points in each dimension.
values: A tensor defining the values at each point in the grid
defined by ``points``. This must have the shape
``(m1, ... mn, ..., nout)``.
coords: A matrix defining the coordinates where the interpolation
should be evaluated. This must have the shape ``(ntest, ndim)``.
"""

points = [as_tensor_variable(p) for p in points]
ndim = len(points)
values = as_tensor_variable(values)
Expand Down Expand Up @@ -120,17 +121,25 @@ def regular_grid_interp(points, values, coords, *, fill_value=None):

class RegularGridInterpolator:

"""Linear interpolation on a regular grid in arbitrary dimensions
"""
Linear interpolation on a regular grid in arbitrary dimensions.
The data must be defined on a filled regular grid, but the spacing may be
uneven in any of the dimensions.
Args:
points: A list of vectors with shapes ``(m1,), ... (mn,)``. These
define the grid points in each dimension.
values: A tensor defining the values at each point in the grid
defined by ``points``. This must have the shape
``(m1, ... mn, ..., nout)``.
Parameters
----------
points : list of array-like
A list of vectors with shapes ``(m1,), ... (mn,)``. These define the grid points in each dimension.
values : array-like
A tensor defining the values at each point in the grid defined by ``points``. This must have the shape ``(m1, ... mn, ..., nout)``.
Returns
-------
result : array-like
Interpolated values at the requested points.
"""

def __init__(self, points, values, fill_value=None, **kwargs):
Expand Down
95 changes: 68 additions & 27 deletions src/innate/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,49 @@ def reconstruct_axes_range(data_label, axes, data_cfg, data_shape):

class Grid:

"""
A class used to represent an innate Grid, which consits in a (numpy) data array and a set of configuration entries.
In the case of interpolation techniques the user can specify the tensor library, which is used to compile the approximations.
Parameters
----------
grid_label : str
The label for the grid.
data_array : array-like
The data array.
data_cfg : dict
Configuration dictionary for the data, containing the array dimensions information.
tensor_library : str, optional
The tensor library to use (default is 'pytensor').
Attributes
----------
label : str
The label for the grid.
description : str
Description of the data parameter.
data : array-like
The data array.
axes : list
List of axes for the data.
shape : tuple
Shape of the data array.
axes_range : list
Range of the axes for the data.
approx : Approximator
An approximator instance for handling data approximations.
plot : Plotter
A plotter instance for visualizing the data.
Methods
-------
reconstruct_axes_range(grid_label, axes, data_cfg, shape)
Reconstructs the range of axes for the grid.
"""

def __init__(self, grid_label, data_array, data_cfg, tensor_library='pytensor'):

# Class attributes
Expand Down Expand Up @@ -60,37 +103,35 @@ def __init__(self, grid_label, data_array, data_cfg, tensor_library='pytensor'):

class DataSet(dict):

def __init__(self, array_dict, common_cfg, local_cfg, **kwargs):
"""
"""
A class used to represent a Dataset, inheriting from Python's built-in dictionary.
A class used to represent a Dataset, inheriting from Python's built-in dictionary.
This class is initialized with data arrays and configuration parameters,
and it unpacks these into the class dictionary.
This class is initialized with data arrays and configuration parameters,
and it unpacks these into the class dictionary.
Parameters
----------
array_dict : dict
Dictionary containing data arrays.
common_cfg : dict
Dictionary containing common configuration parameters.
local_cfg : dict
Dictionary containing local configuration parameters.
Attributes
----------
data_labels : None or list
Placeholder for data labels. Initialized as None.
shape_array : None or tuple
Placeholder for the shape of the data arrays. Initialized as None.
"""

def __init__(self, array_dict, common_cfg, local_cfg, **kwargs):

Parameters
----------
array_dict : dict
Dictionary containing data arrays.
common_cfg : dict
Dictionary containing common configuration parameters.
local_cfg : dict
Dictionary containing local configuration parameters.
**kwargs
Additional keyword arguments to be passed to the method.
Attributes
----------
data_labels : None or list
Placeholder for data labels. Initialized as None.
shape_array : None or tuple
Placeholder for the shape of the data arrays. Initialized as None.

Methods
-------
_compile_grids(array_dict, common_cfg, local_cfg, **kwargs)
Unpacks the individual grids into the class dictionary.
"""

# Attributes
self.data_labels = None
Expand Down
38 changes: 38 additions & 0 deletions src/innate/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,44 @@ def __init__(self, grid):
def matrix_diagnostic(self, output_address=None, num_points=15, technique='rgi', in_fig=None, fig_cfg={}, ax_cfg={},
maximize=False):

"""
This function plots the 2D grid array as a surface plot where at even intervals the scatter points color represent
the absolute divergence between the array data and the selected approximation.
Parameters
----------
output_address : str, optional
The file path to save the output figure. If None, the figure will be displayed on the screen.
num_points : int, optional
The number of points per axis to test the discrepancy between the grid data and the approximation. Default is 15.
technique : str, optional
The interpolation technique to use. Default is 'rgi'.
in_fig : matplotlib.figure.Figure, optional
An existing figure to plot on. If None, a new figure will be created.
fig_cfg : dict, optional
Configuration dictionary for the figure settings. Default is an empty dictionary.
ax_cfg : dict, optional
Configuration dictionary for the axes settings. Default is an empty dictionary.
maximize : bool, optional
Whether to maximize the figure window. Default is False.
Returns
-------
in_fig : matplotlib.figure.Figure
The figure object containing the diagnostic plot.
Notes
-----
This function prepares the data by extracting the grid, parameters, and axes ranges. It computes the test points
and the discrepancies between the interpolated and actual data values. The results are plotted on a figure,
highlighting areas with discrepancies below and above 1%.
Examples
--------
>>> fig = obj.matrix_diagnostic(output_address='output.png', num_points=20, technique='rgi')
>>> plt.show(fig)
"""

# Prepare the data
grid = self._grid.data
params = self._grid.axes
Expand Down
41 changes: 41 additions & 0 deletions src/innate/regression/methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,47 @@ def extract_variables_names(expression, suffix='_range'):

def parse_string_equation(data_label, str_eqn, coeffs_eqn, variable_names):

"""
Parse a string equation and its coefficients (as float array) to generate its programatic object using numpy.
If the equation or coefficients are not provided, it logs a warning message.
Parameters
----------
data_label : str
The label for the data set.
str_eqn : str or None
The string representation of the equation. Can be None.
coeffs_eqn : dict or None
A dictionary containing the coefficients for the equation. Can be None.
variable_names : list of str
A list of variable names used in the equation.
Returns
-------
eqn : function or None
The generated specific function based on the equation and coefficients. Returns None if
the equation or coefficients are missing.
coeffs_dict : dict or None
A dictionary of coefficients extracted from `coeffs_eqn`. Returns None if the equation or
coefficients are missing.
Notes
-----
If the `str_eqn` or `coeffs_eqn` is None, a warning message is logged specifying which part is
missing from the data set configuration.
Examples
--------
>>> eqn, coeffs_dict = parse_string_equation("example_data", "a*x + b", {"a": 1, "b": 2}, ["x"])
>>> print(eqn)
<function ...>
>>> print(coeffs_dict)
{'a': 1, 'b': 2}
"""

if (str_eqn is not None) or (coeffs_eqn is not None):
coef_names = extract_coef_names(str_eqn)
coeffs_dict = create_coef_dict(coef_names, coeffs_eqn)
Expand Down

0 comments on commit 237295c

Please sign in to comment.