pynkowski.data.array
1import numpy as np 2from .base_da import DataField, _masked_variance 3 4 5 6def _eval_field(field, pix): 7 return field[tuple(pix[:,ii] for ii in np.arange(field.ndim))] 8 9def _hotspot_array(field): 10 """Find the local maxima of the input field. 11 12 Arguments 13 --------- 14 field : np.array 15 Array of the pixelized field values. 16 17 Returns 18 ------- 19 pixels : np.array 20 Indices of the pixels which are local maxima. 21 22 values : np.array 23 Values of input map which are local maxima. 24 25 """ 26 ndim = len(field.shape) 27 # First we shift the field in each direction by 1 pixel, and check that the original pixel is larger than all the `2**ndim` neighbours. 28 max_mask = np.all(field > np.array([np.roll(field, shift, axis=ii) for shift in [-1,1] for ii in range(ndim)]), axis=0) 29 30 # We then remove all the pixels in the border to remove the edge effects. 31 for dim in range(max_mask.ndim): 32 # Make current dimension the first dimension 33 array_moved = np.moveaxis(max_mask, dim, 0) 34 # Set border values to `False` in the current dimension 35 array_moved[0] = False 36 array_moved[-1] = False 37 # No need to reorder the dimensions as moveaxis returns a view 38 max_mask = np.pad(max_mask, pad_width=1, mode='constant', constant_values=False) 39 40 pixels = np.argwhere(max_mask) 41 values = _eval_field(field, pixels) 42 return(pixels, values) 43 44class DataArray(DataField): 45 """Class for a pixelized Euclidean data array. 46 47 Parameters 48 ---------- 49 field : np.array 50 Pixelized field as an array of arbitrary dimension. All pixels (or voxels) are expected to be the same size. The pixel shape is not necessarily a cube (see `spacing`). 51 The field can have different sizes in each dimension. The field must be finite: the pixels outside of the region of interest can be set to any finite value and excluded with `mask`. 52 53 normalise : bool, optional 54 If `True`, the map is normalised to have unit variance. Note: the mean of the map is not forced to be 0. 55 Default: `True`. 56 57 mask : np.array or None, optional 58 Mask where the field if considered. It is a bool array of the same shape that `field`. 59 Default: all data is included. 60 61 spacing : float or np.array, optional 62 Spacing between pixels (centres) in each dimension. If a float, the spacing is the same in all dimensions. 63 If an array, it must have the same length as the number of dimensions of the field. 64 It is only used to compute the derivatives with finite differences, i.e., if `first_der` and `second_der` are not given. 65 66 first_der : np.array or None, optional 67 First **covariant** derivatives of the field in an orthonormal basis of the space. Same structure as `field`, and shape `(dim, field.shape)`. 68 If given, they are used instead of finite differences (e.g., Fourier-space derivatives of a periodic box). They must be given together with `second_der`, and they are normalised together with the field if `normalise=True`. 69 Default: computed with finite differences when needed. 70 71 second_der : np.array or None, optional 72 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)`. 73 The order of the derivatives is the same as in `get_second_der`. They must be given together with `first_der`. 74 Default: computed with finite differences when needed. 75 76 pixel_weights : np.array or None, optional 77 Relative weight of each pixel in the averages over the mask (e.g., the volume of the pixels for a grid with non-uniform spacing). 78 It is an array of finite and non-negative values of the same shape that `field`. It is used by the Minkowski Functionals and by the normalisation of the field (weighted variance). 79 Default: all pixels have the same weight. 80 81 Attributes 82 ---------- 83 field : np.array 84 Data of the field as an array. 85 86 dim : int 87 Dimension of the space where the field is defined. For example, 2 for an image and 3 for a data cube.. 88 89 name : str 90 Name of the field. In this case, "DataArray" 91 92 first_der : np.array or None 93 First **covariant** derivatives of the field in an orthonormal basis of the space. Same structure as `field`, and shape `(dim, field.shape)`. 94 95 second_der : np.array or None 96 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)`. 97 98 spacing : float or np.array 99 Spacing between pixels (centres) in each dimension. If a float, the spacing is the same in all dimensions. 100 If an array, it must have the same length as the number of dimensions of the field. 101 102 pixel_weights : np.array or None 103 Relative weight of each pixel in the averages over the mask, or `None` if all pixels have the same weight. 104 105 """ 106 def __init__(self, field, normalise=True, mask=None, spacing=1., first_der=None, second_der=None, pixel_weights=None): 107 dim = len(field.shape) 108 super().__init__(field, dim=dim, name='DataArray', mask=mask, pixel_weights=pixel_weights) 109 if self.mask.shape != self.field.shape: 110 raise ValueError('The map and the mask have different shapes') 111 self._check_finite() 112 sigma = 1. 113 if normalise: 114 sigma = np.sqrt(self.get_variance()) 115 self.field /= sigma 116 self._set_derivatives(first_der, second_der, scale=sigma) 117 self.spacing = spacing 118 119 def get_variance(self): 120 """Compute the variance of the field within the mask, weighted by `pixel_weights` if given. 121 122 Returns 123 ------- 124 var : float 125 The variance of the input field within the mask. 126 127 """ 128 return _masked_variance(self.field, self.mask, self.pixel_weights) 129 130 def get_first_der(self): 131 """Compute the covariant first derivatives of the field. 132 It stores the derivatives in order. E.g., in a 3D array: 133 134 - first covariant derivative wrt e₁ in self.first_der[0] 135 - first covariant derivative wrt e₂ in self.first_der[1] 136 - first covariant derivative wrt e₃ in self.first_der[2] 137 138 """ 139 self.first_der = np.array(np.gradient(self.field, self.spacing, edge_order=2)) 140 141 def get_second_der(self): 142 """Compute the covariant second derivatives of the field. 143 It stores the second derivatives in the following order: first, all the diagonal derivatives, then the cross derivatives with e₁, then with e₂, and so on. 144 E.g., in a 3D array: 145 146 - second covariant derivative wrt e₁e₁ in self.second_der[0] 147 - second covariant derivative wrt e₂e₂ in self.second_der[1] 148 - second covariant derivative wrt e₃e₃ in self.second_der[2] 149 - second covariant derivative wrt e₁e₂ in self.second_der[3] 150 - second covariant derivative wrt e₁e₃ in self.second_der[4] 151 - second covariant derivative wrt e₂e₃ in self.second_der[5] 152 153 """ 154 if self.first_der is None: 155 self.get_first_der() 156 self.second_der = np.zeros((self.dim*(self.dim+1)//2, *self.field.shape)) 157 d = self.dim 158 for i in np.arange(self.dim, dtype=int): 159 indeces = [i] 160 for j in np.arange(i+1, self.dim, dtype=int): 161 indeces.append((d*(d-1)/2) - (d-i)*((d-i)-1)/2 + j - i - 1 + d) 162 indeces = np.array(indeces, dtype=int) 163 self.second_der[indeces] = np.gradient(self.first_der[i], self.spacing, edge_order=2)[i:d] 164 165 def maxima_list(self): 166 """Find the local maxima of the field. 167 168 Returns 169 ------- 170 values : np.array 171 Values of input map which are local maxima. 172 173 """ 174 pixels, values = _hotspot_array(self.field) 175 return values[_eval_field(self.mask, pixels)] 176 177 def minima_list(self): 178 """Find the local minima of the field. 179 180 Returns 181 ------- 182 values : np.array 183 Values of input map which are local minima. 184 185 """ 186 pixels, values = _hotspot_array(-self.field) 187 return -values[_eval_field(self.mask, pixels)] 188 189 190 191__all__ = ["DataArray"] 192__docformat__ = "numpy"
45class DataArray(DataField): 46 """Class for a pixelized Euclidean data array. 47 48 Parameters 49 ---------- 50 field : np.array 51 Pixelized field as an array of arbitrary dimension. All pixels (or voxels) are expected to be the same size. The pixel shape is not necessarily a cube (see `spacing`). 52 The field can have different sizes in each dimension. The field must be finite: the pixels outside of the region of interest can be set to any finite value and excluded with `mask`. 53 54 normalise : bool, optional 55 If `True`, the map is normalised to have unit variance. Note: the mean of the map is not forced to be 0. 56 Default: `True`. 57 58 mask : np.array or None, optional 59 Mask where the field if considered. It is a bool array of the same shape that `field`. 60 Default: all data is included. 61 62 spacing : float or np.array, optional 63 Spacing between pixels (centres) in each dimension. If a float, the spacing is the same in all dimensions. 64 If an array, it must have the same length as the number of dimensions of the field. 65 It is only used to compute the derivatives with finite differences, i.e., if `first_der` and `second_der` are not given. 66 67 first_der : np.array or None, optional 68 First **covariant** derivatives of the field in an orthonormal basis of the space. Same structure as `field`, and shape `(dim, field.shape)`. 69 If given, they are used instead of finite differences (e.g., Fourier-space derivatives of a periodic box). They must be given together with `second_der`, and they are normalised together with the field if `normalise=True`. 70 Default: computed with finite differences when needed. 71 72 second_der : np.array or None, optional 73 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)`. 74 The order of the derivatives is the same as in `get_second_der`. They must be given together with `first_der`. 75 Default: computed with finite differences when needed. 76 77 pixel_weights : np.array or None, optional 78 Relative weight of each pixel in the averages over the mask (e.g., the volume of the pixels for a grid with non-uniform spacing). 79 It is an array of finite and non-negative values of the same shape that `field`. It is used by the Minkowski Functionals and by the normalisation of the field (weighted variance). 80 Default: all pixels have the same weight. 81 82 Attributes 83 ---------- 84 field : np.array 85 Data of the field as an array. 86 87 dim : int 88 Dimension of the space where the field is defined. For example, 2 for an image and 3 for a data cube.. 89 90 name : str 91 Name of the field. In this case, "DataArray" 92 93 first_der : np.array or None 94 First **covariant** derivatives of the field in an orthonormal basis of the space. Same structure as `field`, and shape `(dim, field.shape)`. 95 96 second_der : np.array or None 97 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)`. 98 99 spacing : float or np.array 100 Spacing between pixels (centres) in each dimension. If a float, the spacing is the same in all dimensions. 101 If an array, it must have the same length as the number of dimensions of the field. 102 103 pixel_weights : np.array or None 104 Relative weight of each pixel in the averages over the mask, or `None` if all pixels have the same weight. 105 106 """ 107 def __init__(self, field, normalise=True, mask=None, spacing=1., first_der=None, second_der=None, pixel_weights=None): 108 dim = len(field.shape) 109 super().__init__(field, dim=dim, name='DataArray', mask=mask, pixel_weights=pixel_weights) 110 if self.mask.shape != self.field.shape: 111 raise ValueError('The map and the mask have different shapes') 112 self._check_finite() 113 sigma = 1. 114 if normalise: 115 sigma = np.sqrt(self.get_variance()) 116 self.field /= sigma 117 self._set_derivatives(first_der, second_der, scale=sigma) 118 self.spacing = spacing 119 120 def get_variance(self): 121 """Compute the variance of the field within the mask, weighted by `pixel_weights` if given. 122 123 Returns 124 ------- 125 var : float 126 The variance of the input field within the mask. 127 128 """ 129 return _masked_variance(self.field, self.mask, self.pixel_weights) 130 131 def get_first_der(self): 132 """Compute the covariant first derivatives of the field. 133 It stores the derivatives in order. E.g., in a 3D array: 134 135 - first covariant derivative wrt e₁ in self.first_der[0] 136 - first covariant derivative wrt e₂ in self.first_der[1] 137 - first covariant derivative wrt e₃ in self.first_der[2] 138 139 """ 140 self.first_der = np.array(np.gradient(self.field, self.spacing, edge_order=2)) 141 142 def get_second_der(self): 143 """Compute the covariant second derivatives of the field. 144 It stores the second derivatives in the following order: first, all the diagonal derivatives, then the cross derivatives with e₁, then with e₂, and so on. 145 E.g., in a 3D array: 146 147 - second covariant derivative wrt e₁e₁ in self.second_der[0] 148 - second covariant derivative wrt e₂e₂ in self.second_der[1] 149 - second covariant derivative wrt e₃e₃ in self.second_der[2] 150 - second covariant derivative wrt e₁e₂ in self.second_der[3] 151 - second covariant derivative wrt e₁e₃ in self.second_der[4] 152 - second covariant derivative wrt e₂e₃ in self.second_der[5] 153 154 """ 155 if self.first_der is None: 156 self.get_first_der() 157 self.second_der = np.zeros((self.dim*(self.dim+1)//2, *self.field.shape)) 158 d = self.dim 159 for i in np.arange(self.dim, dtype=int): 160 indeces = [i] 161 for j in np.arange(i+1, self.dim, dtype=int): 162 indeces.append((d*(d-1)/2) - (d-i)*((d-i)-1)/2 + j - i - 1 + d) 163 indeces = np.array(indeces, dtype=int) 164 self.second_der[indeces] = np.gradient(self.first_der[i], self.spacing, edge_order=2)[i:d] 165 166 def maxima_list(self): 167 """Find the local maxima of the field. 168 169 Returns 170 ------- 171 values : np.array 172 Values of input map which are local maxima. 173 174 """ 175 pixels, values = _hotspot_array(self.field) 176 return values[_eval_field(self.mask, pixels)] 177 178 def minima_list(self): 179 """Find the local minima of the field. 180 181 Returns 182 ------- 183 values : np.array 184 Values of input map which are local minima. 185 186 """ 187 pixels, values = _hotspot_array(-self.field) 188 return -values[_eval_field(self.mask, pixels)]
Class for a pixelized Euclidean data array.
Parameters
- field (np.array):
Pixelized field as an array of arbitrary dimension. All pixels (or voxels) are expected to be the same size. The pixel shape is not necessarily a cube (see
spacing). The field can have different sizes in each dimension. The field must be finite: the pixels outside of the region of interest can be set to any finite value and excluded withmask. - normalise (bool, optional):
If
True, the map is normalised to have unit variance. Note: the mean of the map is not forced to be 0. Default:True. - mask (np.array or None, optional):
Mask where the field if considered. It is a bool array of the same shape that
field. Default: all data is included. - spacing (float or np.array, optional):
Spacing between pixels (centres) in each dimension. If a float, the spacing is the same in all dimensions.
If an array, it must have the same length as the number of dimensions of the field.
It is only used to compute the derivatives with finite differences, i.e., if
first_derandsecond_derare not given. - 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). If given, they are used instead of finite differences (e.g., Fourier-space derivatives of a periodic box). They must be given together withsecond_der, and they are normalised together with the field ifnormalise=True. Default: computed with finite differences when needed. - 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 the same as inget_second_der. They must be given together withfirst_der. Default: computed with finite differences when needed. - pixel_weights (np.array or None, optional):
Relative weight of each pixel in the averages over the mask (e.g., the volume of the pixels for a grid with non-uniform spacing).
It is an array of finite and non-negative values of the same shape that
field. It is used by the Minkowski Functionals and by the normalisation of the field (weighted variance). Default: all pixels have the same weight.
Attributes
- field (np.array): Data of the field as an array.
- dim (int): Dimension of the space where the field is defined. For example, 2 for an image and 3 for a data cube..
- name (str): Name of the field. In this case, "DataArray"
- 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). - spacing (float or np.array): Spacing between pixels (centres) in each dimension. If a float, the spacing is the same in all dimensions. If an array, it must have the same length as the number of dimensions of the field.
- pixel_weights (np.array or None):
Relative weight of each pixel in the averages over the mask, or
Noneif all pixels have the same weight.
DataArray( field, normalise=True, mask=None, spacing=1.0, first_der=None, second_der=None, pixel_weights=None)
107 def __init__(self, field, normalise=True, mask=None, spacing=1., first_der=None, second_der=None, pixel_weights=None): 108 dim = len(field.shape) 109 super().__init__(field, dim=dim, name='DataArray', mask=mask, pixel_weights=pixel_weights) 110 if self.mask.shape != self.field.shape: 111 raise ValueError('The map and the mask have different shapes') 112 self._check_finite() 113 sigma = 1. 114 if normalise: 115 sigma = np.sqrt(self.get_variance()) 116 self.field /= sigma 117 self._set_derivatives(first_der, second_der, scale=sigma) 118 self.spacing = spacing
def
get_variance(self):
120 def get_variance(self): 121 """Compute the variance of the field within the mask, weighted by `pixel_weights` if given. 122 123 Returns 124 ------- 125 var : float 126 The variance of the input field within the mask. 127 128 """ 129 return _masked_variance(self.field, self.mask, self.pixel_weights)
Compute the variance of the field within the mask, weighted by pixel_weights if given.
Returns
- var (float): The variance of the input field within the mask.
def
get_first_der(self):
131 def get_first_der(self): 132 """Compute the covariant first derivatives of the field. 133 It stores the derivatives in order. E.g., in a 3D array: 134 135 - first covariant derivative wrt e₁ in self.first_der[0] 136 - first covariant derivative wrt e₂ in self.first_der[1] 137 - first covariant derivative wrt e₃ in self.first_der[2] 138 139 """ 140 self.first_der = np.array(np.gradient(self.field, self.spacing, edge_order=2))
Compute the covariant first derivatives of the field. It stores the derivatives in order. E.g., in a 3D array:
- first covariant derivative wrt e₁ in self.first_der[0]
- first covariant derivative wrt e₂ in self.first_der[1]
- first covariant derivative wrt e₃ in self.first_der[2]
def
get_second_der(self):
142 def get_second_der(self): 143 """Compute the covariant second derivatives of the field. 144 It stores the second derivatives in the following order: first, all the diagonal derivatives, then the cross derivatives with e₁, then with e₂, and so on. 145 E.g., in a 3D array: 146 147 - second covariant derivative wrt e₁e₁ in self.second_der[0] 148 - second covariant derivative wrt e₂e₂ in self.second_der[1] 149 - second covariant derivative wrt e₃e₃ in self.second_der[2] 150 - second covariant derivative wrt e₁e₂ in self.second_der[3] 151 - second covariant derivative wrt e₁e₃ in self.second_der[4] 152 - second covariant derivative wrt e₂e₃ in self.second_der[5] 153 154 """ 155 if self.first_der is None: 156 self.get_first_der() 157 self.second_der = np.zeros((self.dim*(self.dim+1)//2, *self.field.shape)) 158 d = self.dim 159 for i in np.arange(self.dim, dtype=int): 160 indeces = [i] 161 for j in np.arange(i+1, self.dim, dtype=int): 162 indeces.append((d*(d-1)/2) - (d-i)*((d-i)-1)/2 + j - i - 1 + d) 163 indeces = np.array(indeces, dtype=int) 164 self.second_der[indeces] = np.gradient(self.first_der[i], self.spacing, edge_order=2)[i:d]
Compute the covariant second derivatives of the field. It stores the second derivatives in the following order: first, all the diagonal derivatives, then the cross derivatives with e₁, then with e₂, and so on. E.g., in a 3D array:
- second covariant derivative wrt e₁e₁ in self.second_der[0]
- second covariant derivative wrt e₂e₂ in self.second_der[1]
- second covariant derivative wrt e₃e₃ in self.second_der[2]
- second covariant derivative wrt e₁e₂ in self.second_der[3]
- second covariant derivative wrt e₁e₃ in self.second_der[4]
- second covariant derivative wrt e₂e₃ in self.second_der[5]
def
maxima_list(self):
166 def maxima_list(self): 167 """Find the local maxima of the field. 168 169 Returns 170 ------- 171 values : np.array 172 Values of input map which are local maxima. 173 174 """ 175 pixels, values = _hotspot_array(self.field) 176 return values[_eval_field(self.mask, pixels)]
Find the local maxima of the field.
Returns
- values (np.array): Values of input map which are local maxima.
def
minima_list(self):
178 def minima_list(self): 179 """Find the local minima of the field. 180 181 Returns 182 ------- 183 values : np.array 184 Values of input map which are local minima. 185 186 """ 187 pixels, values = _hotspot_array(-self.field) 188 return -values[_eval_field(self.mask, pixels)]
Find the local minima of the field.
Returns
- values (np.array): Values of input map which are local minima.