pynkowski.data.base_da

This submodule contains the base abstract class for data fields.

  1'''This submodule contains the base abstract class for data fields.'''
  2import numpy as np
  3
  4
  5def _masked_variance(x, mask=None, weights=None):
  6    """Compute the variance of `x` within `mask`, weighting each pixel by `weights` if given.
  7
  8    Parameters
  9    ----------
 10    x : np.array
 11        Values of the field.
 12
 13    mask : np.array or None, optional
 14        Bool array of the same shape as `x`. If `None`, all pixels are included.
 15
 16    weights : np.array or None, optional
 17        Weights of the pixels, of the same shape as `x`. If `None`, all pixels have the same weight.
 18
 19    Returns
 20    -------
 21    var : float
 22        The (weighted) variance of `x` within `mask`.
 23
 24    """
 25    if mask is not None:
 26        x = x[mask]
 27        weights = None if weights is None else weights[mask]
 28    if weights is None:
 29        return np.var(x)
 30    mean = np.average(x, weights=weights)
 31    return np.average((x - mean)**2., weights=weights)
 32
 33
 34def _prepare_pixel_weights(pixel_weights, shape):
 35    """Check the pixel weights and return them as a float array (or `None`)."""
 36    if pixel_weights is None:
 37        return None
 38    pixel_weights = np.asarray(pixel_weights, dtype=np.float64)
 39    if pixel_weights.shape != shape:
 40        raise ValueError(f"`pixel_weights` must have the same shape as the field, {shape}, not {pixel_weights.shape}.")
 41    if not (np.isfinite(pixel_weights).all() and (pixel_weights >= 0.).all()):
 42        raise ValueError("`pixel_weights` must be finite and non-negative.")
 43    return pixel_weights
 44
 45
 46class DataField():
 47    """General class for Data fields, to be used as base for all fields.
 48
 49    Parameters
 50    ----------
 51    field : np.array
 52        Data of the field in an undefined structure.
 53    
 54    dim : int
 55        Dimension of the space where the field is defined.
 56        
 57    name : str, optional
 58        Name of the field.
 59        Defaul : `'DataField'`
 60    
 61    first_der : np.array or None, optional
 62        First **covariant** derivatives of the field in an orthonormal basis of the space. Same structure as `field`, and shape `(dim, field.shape)`.
 63    
 64    second_der : np.array or None, optional
 65        Second **covariant** derivatives of the field in an orthonormal basis of the space. Same structure as `field`, and shape `(dim*(dim+1)/2, field.shape)`.
 66        The order of the derivatives is diagonal first, e.g. in `dim=3`: `11`, `22`, `33`, `12`, `13`, `23`.
 67        
 68    mask : np.array or None, optional
 69        Mask where the field if considered. It is a bool array of the same shape that `field`.
 70
 71    pixel_weights : np.array or None, optional
 72        Relative weight of each pixel in the averages over the mask, such as the area of the pixels for pixelisations with pixels of different sizes.
 73        It is an array of finite and non-negative values of the same shape that `field`.
 74        It is used by the computation of the Minkowski Functionals (except for fields with their own method, such as the $SO(3)$ fields) and by the normalisation of the field.
 75        It is not used by the maxima and minima distributions.
 76        Default: all pixels have the same weight.
 77        
 78    Attributes
 79    ----------
 80    field : np.array
 81        Data of the field in an undefined structure.
 82    
 83    dim : int
 84        Dimension of the space where the field is defined.
 85        
 86    name : str
 87        Name of the field.
 88    
 89    first_der : np.array or None
 90        First **covariant** derivatives of the field in an orthonormal basis of the space. Same structure as `field`, and shape `(dim, field.shape)`.
 91    
 92    second_der : np.array or None
 93        Second **covariant** derivatives of the field in an orthonormal basis of the space. Same structure as `field`, and shape `(dim*(dim+1)/2, field.shape)`.
 94        The order of the derivatives is diagonal first, e.g. in `dim=3`: `11`, `22`, `33`, `12`, `13`, `23`.
 95        
 96    mask : np.array
 97        Mask where the field if considered. It is a bool array of the same shape that `field`.
 98
 99    pixel_weights : np.array or None
100        Relative weight of each pixel in the averages over the mask, or `None` if all pixels have the same weight.
101        
102    """   
103    
104    def __init__(self, field, dim, name="DataField", first_der=None, second_der=None, mask=None, pixel_weights=None):
105        self.field = field.copy()
106        self.dim = dim
107        self.name = name
108        if mask is None:
109            self.mask = np.ones_like(self.field, dtype='bool')
110        else:
111            self.mask = mask
112        self.first_der = first_der
113        self.second_der = second_der
114        self.pixel_weights = _prepare_pixel_weights(pixel_weights, self.field.shape)
115        
116    def __repr__(self):
117        return(f'{self.name} DataField: {self.field}')
118
119    def _check_finite(self):
120        """Raise a `ValueError` if the field is not finite."""
121        if not np.isfinite(self.field).all():
122            raise ValueError("The field must be finite (no NaN or inf). Please set the pixels outside of the region of interest to a finite value and exclude them with `mask`.")
123
124    def _set_derivatives(self, first_der, second_der, scale=1.):
125        """Check the given covariant derivatives, divide them by `scale`, and store them. If both are `None`, they are computed later when needed.
126
127        Parameters
128        ----------
129        first_der : np.array or None
130            First **covariant** derivatives of the field, with shape `(dim, field.shape)`.
131
132        second_der : np.array or None
133            Second **covariant** derivatives of the field, with shape `(dim*(dim+1)/2, field.shape)`.
134
135        scale : float, optional
136            The derivatives are divided by this value (e.g., the standard deviation used to normalise the field).
137            Default: 1.
138
139        """
140        if (first_der is None) != (second_der is None):
141            raise ValueError("`first_der` and `second_der` must be given together.")
142        if first_der is not None:
143            first_der, second_der = np.asarray(first_der), np.asarray(second_der)
144            shape1 = (self.dim, *self.field.shape)
145            shape2 = (self.dim * (self.dim + 1) // 2, *self.field.shape)
146            if first_der.shape != shape1 or second_der.shape != shape2:
147                raise ValueError(f"`first_der` and `second_der` must have shapes {shape1} and {shape2}, not {first_der.shape} and {second_der.shape}.")
148            if not (np.isfinite(first_der).all() and np.isfinite(second_der).all()):
149                raise ValueError("`first_der` and `second_der` must be finite (no NaN or inf).")
150            if scale != 1.:
151                first_der = first_der / scale
152                second_der = second_der / scale
153        self.first_der = first_der
154        self.second_der = second_der
155       
156
157
158__all__ = ["DataField"]
159
160__docformat__ = "numpy"
class DataField:
 47class DataField():
 48    """General class for Data fields, to be used as base for all fields.
 49
 50    Parameters
 51    ----------
 52    field : np.array
 53        Data of the field in an undefined structure.
 54    
 55    dim : int
 56        Dimension of the space where the field is defined.
 57        
 58    name : str, optional
 59        Name of the field.
 60        Defaul : `'DataField'`
 61    
 62    first_der : np.array or None, optional
 63        First **covariant** derivatives of the field in an orthonormal basis of the space. Same structure as `field`, and shape `(dim, field.shape)`.
 64    
 65    second_der : np.array or None, optional
 66        Second **covariant** derivatives of the field in an orthonormal basis of the space. Same structure as `field`, and shape `(dim*(dim+1)/2, field.shape)`.
 67        The order of the derivatives is diagonal first, e.g. in `dim=3`: `11`, `22`, `33`, `12`, `13`, `23`.
 68        
 69    mask : np.array or None, optional
 70        Mask where the field if considered. It is a bool array of the same shape that `field`.
 71
 72    pixel_weights : np.array or None, optional
 73        Relative weight of each pixel in the averages over the mask, such as the area of the pixels for pixelisations with pixels of different sizes.
 74        It is an array of finite and non-negative values of the same shape that `field`.
 75        It is used by the computation of the Minkowski Functionals (except for fields with their own method, such as the $SO(3)$ fields) and by the normalisation of the field.
 76        It is not used by the maxima and minima distributions.
 77        Default: all pixels have the same weight.
 78        
 79    Attributes
 80    ----------
 81    field : np.array
 82        Data of the field in an undefined structure.
 83    
 84    dim : int
 85        Dimension of the space where the field is defined.
 86        
 87    name : str
 88        Name of the field.
 89    
 90    first_der : np.array or None
 91        First **covariant** derivatives of the field in an orthonormal basis of the space. Same structure as `field`, and shape `(dim, field.shape)`.
 92    
 93    second_der : np.array or None
 94        Second **covariant** derivatives of the field in an orthonormal basis of the space. Same structure as `field`, and shape `(dim*(dim+1)/2, field.shape)`.
 95        The order of the derivatives is diagonal first, e.g. in `dim=3`: `11`, `22`, `33`, `12`, `13`, `23`.
 96        
 97    mask : np.array
 98        Mask where the field if considered. It is a bool array of the same shape that `field`.
 99
100    pixel_weights : np.array or None
101        Relative weight of each pixel in the averages over the mask, or `None` if all pixels have the same weight.
102        
103    """   
104    
105    def __init__(self, field, dim, name="DataField", first_der=None, second_der=None, mask=None, pixel_weights=None):
106        self.field = field.copy()
107        self.dim = dim
108        self.name = name
109        if mask is None:
110            self.mask = np.ones_like(self.field, dtype='bool')
111        else:
112            self.mask = mask
113        self.first_der = first_der
114        self.second_der = second_der
115        self.pixel_weights = _prepare_pixel_weights(pixel_weights, self.field.shape)
116        
117    def __repr__(self):
118        return(f'{self.name} DataField: {self.field}')
119
120    def _check_finite(self):
121        """Raise a `ValueError` if the field is not finite."""
122        if not np.isfinite(self.field).all():
123            raise ValueError("The field must be finite (no NaN or inf). Please set the pixels outside of the region of interest to a finite value and exclude them with `mask`.")
124
125    def _set_derivatives(self, first_der, second_der, scale=1.):
126        """Check the given covariant derivatives, divide them by `scale`, and store them. If both are `None`, they are computed later when needed.
127
128        Parameters
129        ----------
130        first_der : np.array or None
131            First **covariant** derivatives of the field, with shape `(dim, field.shape)`.
132
133        second_der : np.array or None
134            Second **covariant** derivatives of the field, with shape `(dim*(dim+1)/2, field.shape)`.
135
136        scale : float, optional
137            The derivatives are divided by this value (e.g., the standard deviation used to normalise the field).
138            Default: 1.
139
140        """
141        if (first_der is None) != (second_der is None):
142            raise ValueError("`first_der` and `second_der` must be given together.")
143        if first_der is not None:
144            first_der, second_der = np.asarray(first_der), np.asarray(second_der)
145            shape1 = (self.dim, *self.field.shape)
146            shape2 = (self.dim * (self.dim + 1) // 2, *self.field.shape)
147            if first_der.shape != shape1 or second_der.shape != shape2:
148                raise ValueError(f"`first_der` and `second_der` must have shapes {shape1} and {shape2}, not {first_der.shape} and {second_der.shape}.")
149            if not (np.isfinite(first_der).all() and np.isfinite(second_der).all()):
150                raise ValueError("`first_der` and `second_der` must be finite (no NaN or inf).")
151            if scale != 1.:
152                first_der = first_der / scale
153                second_der = second_der / scale
154        self.first_der = first_der
155        self.second_der = second_der

General class for Data fields, to be used as base for all fields.

Parameters
  • field (np.array): Data of the field in an undefined structure.
  • dim (int): Dimension of the space where the field is defined.
  • name (str, optional): Name of the field. Defaul : 'DataField'
  • first_der (np.array or None, optional): First covariant derivatives of the field in an orthonormal basis of the space. Same structure as field, and shape (dim, field.shape).
  • second_der (np.array or None, optional): Second covariant derivatives of the field in an orthonormal basis of the space. Same structure as field, and shape (dim*(dim+1)/2, field.shape). The order of the derivatives is diagonal first, e.g. in dim=3: 11, 22, 33, 12, 13, 23.
  • mask (np.array or None, optional): Mask where the field if considered. It is a bool array of the same shape that field.
  • pixel_weights (np.array or None, optional): Relative weight of each pixel in the averages over the mask, such as the area of the pixels for pixelisations with pixels of different sizes. It is an array of finite and non-negative values of the same shape that field. It is used by the computation of the Minkowski Functionals (except for fields with their own method, such as the $SO(3)$ fields) and by the normalisation of the field. It is not used by the maxima and minima distributions. Default: all pixels have the same weight.
Attributes
  • field (np.array): Data of the field in an undefined structure.
  • dim (int): Dimension of the space where the field is defined.
  • name (str): Name of the field.
  • first_der (np.array or None): First covariant derivatives of the field in an orthonormal basis of the space. Same structure as field, and shape (dim, field.shape).
  • second_der (np.array or None): Second covariant derivatives of the field in an orthonormal basis of the space. Same structure as field, and shape (dim*(dim+1)/2, field.shape). The order of the derivatives is diagonal first, e.g. in dim=3: 11, 22, 33, 12, 13, 23.
  • mask (np.array): Mask where the field if considered. It is a bool array of the same shape that field.
  • pixel_weights (np.array or None): Relative weight of each pixel in the averages over the mask, or None if all pixels have the same weight.
DataField( field, dim, name='DataField', first_der=None, second_der=None, mask=None, pixel_weights=None)
105    def __init__(self, field, dim, name="DataField", first_der=None, second_der=None, mask=None, pixel_weights=None):
106        self.field = field.copy()
107        self.dim = dim
108        self.name = name
109        if mask is None:
110            self.mask = np.ones_like(self.field, dtype='bool')
111        else:
112            self.mask = mask
113        self.first_der = first_der
114        self.second_der = second_der
115        self.pixel_weights = _prepare_pixel_weights(pixel_weights, self.field.shape)
field
dim
name
first_der
second_der
pixel_weights