pynkowski.stats.minkowski

This submodule contains the functions to compute the Minkowski Functionals of a field.

For data fields, the Minkowski Functionals are computed with a single pass over the field: each pixel is assigned to its threshold bin, and its contribution is accumulated with np.bincount. In this way, the computational cost does not grow with the number of thresholds. The pixels can be processed in chunks of chunk_voxels pixels, in parallel with threads threads (by default, one per available CPU, limited by OMP_NUM_THREADS if it is set).

The data fields only need to provide the field, the mask, the covariant derivatives (or the methods get_first_der and get_second_der to compute them), and optionally the weights of the pixels (pixel_weights). A data field can also define its own methods _V0, _V1, _V2 and _V3 (e.g., the fields in the $SO(3)$ formalism, see pynkowski.data.so3data), which are then used instead of the general computation.

  1'''This submodule contains the functions to compute the Minkowski Functionals of a field.
  2
  3For data fields, the Minkowski Functionals are computed with a single pass over the field: each pixel is assigned to its threshold bin,
  4and its contribution is accumulated with `np.bincount`. In this way, the computational cost does not grow with the number of thresholds.
  5The pixels can be processed in chunks of `chunk_voxels` pixels, in parallel with `threads` threads (by default, one per available CPU, limited by `OMP_NUM_THREADS` if it is set).
  6
  7The data fields only need to provide the field, the mask, the covariant derivatives (or the methods `get_first_der` and `get_second_der`
  8to compute them), and optionally the weights of the pixels (`pixel_weights`). A data field can also define its own methods `_V0`, `_V1`,
  9`_V2` and `_V3` (e.g., the fields in the $SO(3)$ formalism, see `pynkowski.data.so3data`), which are then used instead of the general computation.
 10'''
 11import numbers
 12import os
 13from concurrent.futures import ThreadPoolExecutor
 14import numpy as np
 15from scipy.special import comb, gamma
 16from .utils_st import subsample_us, define_ubins
 17from ..data.base_da import DataField
 18from ..theory.base_th import TheoryField
 19
 20
 21def _MF_prefactor(d,j):
 22    """Compute the prefactor in the definition of Minkowski Functionals. This factor multiplies the integral of the curvatures.
 23
 24    Parameters
 25    ----------
 26    d : int
 27        The dimension of the ambient space (e.g., 2 for the sphere).
 28        
 29    j : int
 30        The index of the Minkowski functional (`j>=1`).
 31    
 32    Returns
 33    -------
 34    prefactor : float
 35        The prefactor in the definition of MFs.
 36    
 37    """
 38    return 1./ (comb(d,j) * j * np.pi**(j/2.) / gamma(j/2. +1.))
 39
 40
 41def _curvature(order, g, h=None):
 42    """Compute the symmetrised polynomial of the principal curvatures of order `order`, multiplied by the modulus of the gradient,
 43    from the covariant derivatives of the field. The curvatures are computed in closed form, without building the Hessian matrix at every pixel.
 44
 45    Parameters
 46    ----------
 47    order : int
 48        Order of the polynomial of the curvatures (`0` for the modulus of the gradient).
 49
 50    g : list of np.array
 51        First covariant derivatives of the field, in the same order as `first_der`.
 52
 53    h : list of np.array or None, optional
 54        Second covariant derivatives of the field, in the same order as `second_der`. Only used if `order>=1`.
 55
 56    Returns
 57    -------
 58    curvature : np.array
 59        The value of the polynomial at each pixel. It is `nan` where the gradient vanishes (for `order>=1`).
 60
 61    """
 62    dim = len(g)
 63    if order == 0:
 64        return np.sqrt(sum(gi * gi for gi in g))
 65    if dim == 2 and order == 1:  # Geodesic curvature κ  (times |∇f|)
 66        g1, g2 = g
 67        a, b, c = h
 68        return (2. * g1 * g2 * c - g1 * g1 * b - g2 * g2 * a) / (g1 * g1 + g2 * g2)
 69    if dim == 3 and order in (1, 2):
 70        gx, gy, gz = g
 71        a, b, c, d, e, f = h     # Order: 11, 22, 33, 12, 13, 23
 72        g2 = gx * gx + gy * gy + gz * gz
 73        if order == 1:  # Mean curvature (times 2), 2H = κ_1 + κ_2   (times |∇f|)
 74            return (gx * gx * a + gy * gy * b + gz * gz * c + 2. * (gx * gy * d + gx * gz * e + gy * gz * f)) / g2 - (a + b + c)
 75        # Gaussian curvature, K = κ_1 · κ_2   (times |∇f|). The gradient is contracted with the adjugate of the Hessian
 76        quad = (gx * gx * (b * c - f * f) + gy * gy * (a * c - e * e) + gz * gz * (a * b - d * d)
 77                + 2. * gx * gy * (e * f - d * c) + 2. * gx * gz * (d * f - b * e) + 2. * gy * gz * (d * e - a * f))
 78        return quad / np.sqrt(g2) ** 3
 79    if dim > 3:
 80        raise NotImplementedError("The computation of principal curvatures in not implemented for spaces with 4 or more dimensions. If you need this, please get in touch.")
 81        # I am not sure if there is a easy expression for the principal curvatures of implicit surfaces in higher dimensions. Typically, one would need to create
 82        # the second fundamental form of the surface with the orthonormal bais of the tangent space; its eigenvalues are the principal curvatures at that point.
 83    raise ValueError("The order of the polynomial has to be less than the dimension of the field.")
 84
 85
 86def general_curvature(field, order):
 87    """Computes the symmetrised polynomial of the principal curvatures of order `order`, multiplied by the modulus of the gradient, at every pixel.
 88
 89    Parameters
 90    ----------
 91    field : DataField
 92        Field on which to compute the general curvatures. Its derivatives must have been computed.
 93
 94    order : int
 95        Order of the polynomial of the curvatures.
 96
 97    Returns
 98    -------
 99    curvature : np.array
100        The value of the polynomial at each pixel.
101
102        For example:
103        `field.dim = 2`, `order=1` : geodesic curvature $\\kappa$
104        `field.dim = 3`, `order=1` : mean curvature (H = ($\\kappa_1$ + $\\kappa_2$)/2 )
105        `field.dim = 3`, `order=2` : Gaussian curvature (K = $\\kappa_1 \\cdot \\kappa_2$)
106    
107    """
108    assert isinstance(field, DataField), "The field must be a DataField (or subclass)"
109    assert field.dim > 1, "The field must be at least 2D"
110    if order >= field.dim:
111        raise ValueError("The order of the polynomial has to be less than the dimension of the field.")
112    return _curvature(order, list(field.first_der), None if order == 0 else list(field.second_der))
113
114
115def _env_thread_limit(name):
116    """Return the number of threads set by the environment variable `name`, or `None` if it is not set or not valid.
117    For `OMP_NUM_THREADS`, a comma-separated list (one value per nesting level) is accepted, and its first value is used."""
118    value = os.environ.get(name, '').split(',')[0].strip()
119    if value.isdigit() and int(value) > 0:
120        return int(value)
121    return None
122
123
124def _available_cpus():
125    """Return the default number of threads: the number of CPUs available to this process, limited by
126    `OMP_NUM_THREADS` and `SLURM_CPUS_PER_TASK` if they are set."""
127    try:
128        n = len(os.sched_getaffinity(0))    # Linux
129    except AttributeError:
130        n = os.cpu_count() or 1             # macOS and Windows
131    for name in ('OMP_NUM_THREADS', 'SLURM_CPUS_PER_TASK'):
132        limit = _env_thread_limit(name)
133        if limit is not None:
134            n = min(n, limit)
135    return max(n, 1)
136
137
138def _map_chunks(fn, n, threads, chunk_voxels):
139    """Apply `fn` to consecutive slices of `chunk_voxels` pixels (out of `n`), in parallel if `threads > 1`, and return the list of results.
140    If `threads` is None, the number of threads is given by `_available_cpus`."""
141    if threads is None:
142        threads = _available_cpus()
143    if not (isinstance(threads, numbers.Integral) and threads >= 1):
144        raise ValueError(f"`threads` must be a positive integer or None, not {threads}.")
145    if not (isinstance(chunk_voxels, numbers.Integral) and chunk_voxels >= 1):
146        raise ValueError(f"`chunk_voxels` must be a positive integer, not {chunk_voxels}.")
147    slices = [slice(i, min(i + chunk_voxels, n)) for i in range(0, n, chunk_voxels)]
148    if threads > 1 and len(slices) > 1:
149        with ThreadPoolExecutor(min(threads, len(slices))) as ex:
150            return list(ex.map(fn, slices))
151    return [fn(sl) for sl in slices]
152
153
154def _flat_data(field):
155    """Return the flattened field, mask and pixel weights (or `None`) of a data field, checking that the field is finite."""
156    f = np.reshape(field.field, -1)
157    if not np.isfinite(f).all():
158        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`.")
159    m = np.reshape(np.asarray(field.mask, dtype=bool), -1)
160    if m.shape != f.shape:
161        raise ValueError('The field and the mask have different shapes')
162    w = getattr(field, 'pixel_weights', None)
163    if w is not None:
164        w = np.reshape(w, -1)
165        if w.shape != f.shape:
166            raise ValueError('The field and `pixel_weights` have different shapes')
167    return f, m, w
168
169
170def _V0_data(field, us, threads, chunk_voxels):
171    """Compute $V_0$ of a data field at the thresholds `us`, which can be in any order, with a single pass over the field."""
172    f, m, w = _flat_data(field)
173    us = np.asarray(us, dtype=np.float64)
174    # The thresholds are sorted for `np.searchsorted`, and the result is given back in the original order
175    order = np.argsort(us, kind='stable')
176    us_sorted = us[order]
177
178    def process(sl):
179        sel = m[sl]
180        fl = np.asarray(f[sl][sel], dtype=np.float64)
181        ww = None if w is None else np.asarray(w[sl][sel], dtype=np.float64)
182        # For each pixel, we count the number of thresholds strictly below its value
183        counts = np.bincount(np.searchsorted(us_sorted, fl, side='left'), weights=ww, minlength=len(us) + 1)
184        return counts, (fl.size if w is None else ww.sum())
185
186    results = _map_chunks(process, f.size, threads, chunk_voxels)
187    counts = sum(r[0] for r in results)
188    total = sum(r[1] for r in results)
189    v0 = np.empty(len(us))
190    # The pixels above `us_sorted[i]` are those with more than `i` thresholds below their value
191    v0[order] = np.cumsum(counts[::-1])[::-1][1:] / total
192    return v0
193
194
195def _Vj_data(field, j, us, dus, threads, chunk_voxels):
196    """Compute the Minkowski Functional $V_j$ (`j>=1`) of a data field in the bins of centres `us` and widths `dus`, with a single pass over the field."""
197    order = j - 1    # Order of the polynomial of the curvatures
198    if order >= 1 and field.dim > 3:
199        raise NotImplementedError("The computation of principal curvatures in not implemented for spaces with 4 or more dimensions. If you need this, please get in touch.")
200    if field.first_der is None:
201        field.get_first_der()
202    if order >= 1 and field.second_der is None:
203        field.get_second_der()
204
205    f, m, w = _flat_data(field)
206    us = np.asarray(us, dtype=np.float64)
207    dus = np.asarray(dus, dtype=np.float64)
208    edges = np.append(us - dus / 2., us[-1] + dus[-1] / 2.)
209    if not np.all(np.diff(edges) > 0):
210        raise ValueError("The thresholds `us` must be increasing.")
211    nb = len(us)
212    fd = np.reshape(field.first_der, (field.dim, -1))
213    sd = np.reshape(field.second_der, (-1, f.size)) if order >= 1 else None
214
215    def process(sl):
216        idx = np.digitize(np.asarray(f[sl], dtype=np.float64), edges) - 1
217        mm = m[sl]
218        c = _curvature(order, [np.asarray(g[sl], dtype=np.float64) for g in fd],
219                       None if sd is None else [np.asarray(h[sl], dtype=np.float64) for h in sd])
220        isnan = np.isnan(c)
221        if w is not None:
222            ww = np.asarray(w[sl], dtype=np.float64)
223            c = c * ww
224        # The pixels outside of the bins or of the mask, or with an undefined curvature, go to an extra bin that is discarded
225        bad = (idx < 0) | (idx >= nb) | ~mm | isnan
226        tot = np.bincount(np.where(bad, nb, idx), weights=np.where(isnan, 0., c), minlength=nb + 1)[:nb]
227        if w is None:
228            return tot, np.count_nonzero(mm & isnan), np.count_nonzero(mm)
229        return tot, ww[mm & isnan].sum(), ww[mm].sum()
230
231    results = _map_chunks(process, f.size, threads, chunk_voxels)
232    tot = sum(r[0] for r in results)
233    nan_total = sum(r[1] for r in results)
234    mask_total = sum(r[2] for r in results)
235    # The pixels with an undefined curvature (|∇f| = 0) are excluded from the average for V2 and V3 (as with `np.nanmean`), but not for V1
236    denom = mask_total if order == 0 else mask_total - nan_total
237    return _MF_prefactor(field.dim, j) * tot / (dus * denom)
238
239
240def V0(field, us, edges=False, verbose=True, threads=None, chunk_voxels=1 << 17):
241    """Compute the first Minkowski Functional, $V_0$, normalized by the volume of the space.
242
243    Parameters
244    ----------
245    field : DataField or TheoryField
246        Field on which to compute $V_0$, which can be a theoretical field or a data field.
247        
248    us : np.array
249        The thresholds where $V_0$ is computed.
250        
251    edges : bool, optional
252        If False (default), the given `us` is assumed to be an array of uniformly distributed thresholds, which are taken as the central values of the bins.
253        If True, input `us` is assumed to be a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform distributions of thresholds. 
254        In the latter case, the effective thresholds are the central value of the given bins.
255        
256    verbose : bool, optional
257        If True (default), progress bars are shown for the computations on data fields that support them (currently, the $SO(3)$ fields).
258
259    threads : int or None, optional
260        Number of threads used for the computation on data fields. Only used by the general computation (i.e., not by fields with their own method, such as the $SO(3)$ fields).
261        Default: None, i.e., one thread per CPU available to the process, limited by the environment variables `OMP_NUM_THREADS` and `SLURM_CPUS_PER_TASK` if they are set.
262
263    chunk_voxels : int, optional
264        Number of pixels processed at once by each thread in the computation on data fields. Lower values reduce the memory usage.
265        The peak memory grows as `threads*chunk_voxels`. Only used by the general computation.
266        Default: 2**17.
267
268    Returns
269    -------
270    V0 : np.array
271        The values of the first Minkowski Functional at the given thresholds.
272    
273    """
274    us = np.atleast_1d(us)
275    us, dus = define_ubins(us, edges)
276    
277    if isinstance(field, TheoryField):
278        us = subsample_us(us, dus)
279        try:
280            return np.nanmean(field.V0(us), axis=1)
281        except AttributeError:
282            raise NotImplementedError(f"The theoretical expectation of V0 for {field.name} fields is not implemented. If you know an expression, please get in touch.")
283        
284    elif isinstance(field, DataField):
285        if hasattr(field, '_V0'):
286            return field._V0(us, dus, verbose=verbose)
287        return _V0_data(field, us, threads, chunk_voxels)
288        
289    else:
290        raise TypeError(f"The field must be either TheoryField or DataField (or a subclass).")
291    
292
293def V1(field, us, edges=False, verbose=True, threads=None, chunk_voxels=1 << 17):
294    """Compute the second Minkowski Functional, $V_1$, normalized by the volume of the space.
295
296    Parameters
297    ----------
298    field : DataField or TheoryField
299        Field on which to compute $V_1$, which can be a theoretical field or a data field.
300        
301    us : np.array
302        The thresholds where $V_1$ is computed. For data fields, they must be increasing.
303        
304    edges : bool, optional
305        If False (default), the given `us` is assumed to be an array of uniformly distributed thresholds, which are taken as the central values of the bins.
306        If True, input `us` is assumed to be a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform distributions of thresholds. 
307        In the latter case, the effective thresholds are the central value of the given bins.
308        
309    verbose : bool, optional
310        If True (default), progress bars are shown for the computations on data fields that support them (currently, the $SO(3)$ fields).
311
312    threads : int or None, optional
313        Number of threads used for the computation on data fields. Only used by the general computation (i.e., not by fields with their own method, such as the $SO(3)$ fields).
314        Default: None, i.e., one thread per CPU available to the process, limited by the environment variables `OMP_NUM_THREADS` and `SLURM_CPUS_PER_TASK` if they are set.
315
316    chunk_voxels : int, optional
317        Number of pixels processed at once by each thread in the computation on data fields. Lower values reduce the memory usage.
318        The peak memory grows as `threads*chunk_voxels`. Only used by the general computation.
319        Default: 2**17.
320
321    Returns
322    -------
323    V1 : np.array
324        The values of the second Minkowski Functional at the given thresholds.
325    
326    """
327    us = np.atleast_1d(us)
328    us, dus = define_ubins(us, edges)
329    
330    if isinstance(field, TheoryField):
331        us = subsample_us(us, dus)
332        try:
333            return np.nanmean(field.V1(us), axis=1)
334        except AttributeError:
335            raise NotImplementedError(f"The theoretical expectation of V1 for {field.name} fields is not implemented. If you know an expression, please get in touch.") from None
336        
337    elif isinstance(field, DataField):
338        if hasattr(field, '_V1'):
339            return field._V1(us, dus, verbose=verbose)
340        return _Vj_data(field, 1, us, dus, threads, chunk_voxels)
341        
342    else:
343        raise TypeError(f"The field must be either TheoryField or DataField (or a subclass).")
344        
345
346def V2(field, us, edges=False, verbose=True, threads=None, chunk_voxels=1 << 17):
347    """Compute the third Minkowski Functional, $V_2$, normalized by the volume of the space.
348
349    Parameters
350    ----------
351    field : DataField or TheoryField
352        Field on which to compute $V_2$, which can be a theoretical field or a data field. Its dimension must be at least 2.
353        
354    us : np.array
355        The thresholds where $V_2$ is computed. For data fields, they must be increasing.
356        
357    edges : bool, optional
358        If False (default), the given `us` is assumed to be an array of uniformly distributed thresholds, which are taken as the central values of the bins.
359        If True, input `us` is assumed to be a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform distributions of thresholds. 
360        In the latter case, the effective thresholds are the central value of the given bins.
361        
362    verbose : bool, optional
363        If True (default), progress bars are shown for the computations on data fields that support them (currently, the $SO(3)$ fields).
364
365    threads : int or None, optional
366        Number of threads used for the computation on data fields. Only used by the general computation (i.e., not by fields with their own method, such as the $SO(3)$ fields).
367        Default: None, i.e., one thread per CPU available to the process, limited by the environment variables `OMP_NUM_THREADS` and `SLURM_CPUS_PER_TASK` if they are set.
368
369    chunk_voxels : int, optional
370        Number of pixels processed at once by each thread in the computation on data fields. Lower values reduce the memory usage.
371        The peak memory grows as `threads*chunk_voxels`. Only used by the general computation.
372        Default: 2**17.
373
374    Returns
375    -------
376    V2 : np.array
377        The values of the second Minkowski Functional at the given thresholds.
378    
379    """
380    if field.dim<2:
381        raise ValueError(f"V2 is defined for fields with at least 2 dimensions, but this field is {field.dim}D.")
382        
383    us = np.atleast_1d(us)
384    us, dus = define_ubins(us, edges)
385    
386    if isinstance(field, TheoryField):
387        us = subsample_us(us, dus)
388        try:
389            return np.nanmean(field.V2(us), axis=1)
390        except AttributeError:
391            raise NotImplementedError(f"The theoretical expectation of V2 for {field.name} fields is not implemented. If you know an expression, please get in touch.") from None
392        
393    elif isinstance(field, DataField):
394        if hasattr(field, '_V2'):
395            return field._V2(us, dus, verbose=verbose)
396        return _Vj_data(field, 2, us, dus, threads, chunk_voxels)
397        
398    else:
399        raise TypeError(f"The field must be either TheoryField or DataField (or a subclass).")
400        
401
402def V3(field, us, edges=False, verbose=True, threads=None, chunk_voxels=1 << 17):
403    """Compute the fourth Minkowski Functional, $V_3$, normalized by the volume of the space.
404
405    Parameters
406    ----------
407    field : DataField or TheoryField
408        Field on which to compute $V_3$, which can be a theoretical field or a data field. Its dimension must be at least 3.
409        
410    us : np.array
411        The thresholds where $V_3$ is computed. For data fields, they must be increasing.
412        
413    edges : bool, optional
414        If False (default), the given `us` is assumed to be an array of uniformly distributed thresholds, which are taken as the central values of the bins.
415        If True, input `us` is assumed to be a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform distributions of thresholds. 
416        In the latter case, the effective thresholds are the central value of the given bins.
417        
418    verbose : bool, optional
419        If True (default), progress bars are shown for the computations on data fields that support them (currently, the $SO(3)$ fields).
420
421    threads : int or None, optional
422        Number of threads used for the computation on data fields. Only used by the general computation (i.e., not by fields with their own method, such as the $SO(3)$ fields).
423        Default: None, i.e., one thread per CPU available to the process, limited by the environment variables `OMP_NUM_THREADS` and `SLURM_CPUS_PER_TASK` if they are set.
424
425    chunk_voxels : int, optional
426        Number of pixels processed at once by each thread in the computation on data fields. Lower values reduce the memory usage.
427        The peak memory grows as `threads*chunk_voxels`. Only used by the general computation.
428        Default: 2**17.
429
430    Returns
431    -------
432    V3 : np.array()
433        The values of the fourth Minkowski Functional at the given thresholds.
434    
435    """
436    if field.dim<3:
437        raise ValueError(f"V3 is defined for fields with at least 3 dimensions, but this field is {field.dim}D.")
438        
439    us = np.atleast_1d(us)
440    us, dus = define_ubins(us, edges)
441    
442    if isinstance(field, TheoryField):
443        us = subsample_us(us, dus)
444        try:
445            return np.nanmean(field.V3(us), axis=1)
446        except AttributeError:
447            raise NotImplementedError(f"The theoretical expectation of V3 for {field.name} fields is not implemented. If you know an expression, please get in touch.") from None
448        
449    elif isinstance(field, DataField):
450        if hasattr(field, '_V3'):
451            return field._V3(us, dus, verbose=verbose)
452        return _Vj_data(field, 3, us, dus, threads, chunk_voxels)
453        
454    else:
455        raise TypeError(f"The field must be either TheoryField or DataField (or a subclass).")
456
457
458__all__ = ["V0", "V1", "V2", "V3", "general_curvature"]
459
460__docformat__ = "numpy"
def V0( field, us, edges=False, verbose=True, threads=None, chunk_voxels=131072):
241def V0(field, us, edges=False, verbose=True, threads=None, chunk_voxels=1 << 17):
242    """Compute the first Minkowski Functional, $V_0$, normalized by the volume of the space.
243
244    Parameters
245    ----------
246    field : DataField or TheoryField
247        Field on which to compute $V_0$, which can be a theoretical field or a data field.
248        
249    us : np.array
250        The thresholds where $V_0$ is computed.
251        
252    edges : bool, optional
253        If False (default), the given `us` is assumed to be an array of uniformly distributed thresholds, which are taken as the central values of the bins.
254        If True, input `us` is assumed to be a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform distributions of thresholds. 
255        In the latter case, the effective thresholds are the central value of the given bins.
256        
257    verbose : bool, optional
258        If True (default), progress bars are shown for the computations on data fields that support them (currently, the $SO(3)$ fields).
259
260    threads : int or None, optional
261        Number of threads used for the computation on data fields. Only used by the general computation (i.e., not by fields with their own method, such as the $SO(3)$ fields).
262        Default: None, i.e., one thread per CPU available to the process, limited by the environment variables `OMP_NUM_THREADS` and `SLURM_CPUS_PER_TASK` if they are set.
263
264    chunk_voxels : int, optional
265        Number of pixels processed at once by each thread in the computation on data fields. Lower values reduce the memory usage.
266        The peak memory grows as `threads*chunk_voxels`. Only used by the general computation.
267        Default: 2**17.
268
269    Returns
270    -------
271    V0 : np.array
272        The values of the first Minkowski Functional at the given thresholds.
273    
274    """
275    us = np.atleast_1d(us)
276    us, dus = define_ubins(us, edges)
277    
278    if isinstance(field, TheoryField):
279        us = subsample_us(us, dus)
280        try:
281            return np.nanmean(field.V0(us), axis=1)
282        except AttributeError:
283            raise NotImplementedError(f"The theoretical expectation of V0 for {field.name} fields is not implemented. If you know an expression, please get in touch.")
284        
285    elif isinstance(field, DataField):
286        if hasattr(field, '_V0'):
287            return field._V0(us, dus, verbose=verbose)
288        return _V0_data(field, us, threads, chunk_voxels)
289        
290    else:
291        raise TypeError(f"The field must be either TheoryField or DataField (or a subclass).")

Compute the first Minkowski Functional, $V_0$, normalized by the volume of the space.

Parameters
  • field (DataField or TheoryField): Field on which to compute $V_0$, which can be a theoretical field or a data field.
  • us (np.array): The thresholds where $V_0$ is computed.
  • edges (bool, optional): If False (default), the given us is assumed to be an array of uniformly distributed thresholds, which are taken as the central values of the bins. If True, input us is assumed to be a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform distributions of thresholds. In the latter case, the effective thresholds are the central value of the given bins.
  • verbose (bool, optional): If True (default), progress bars are shown for the computations on data fields that support them (currently, the $SO(3)$ fields).
  • threads (int or None, optional): Number of threads used for the computation on data fields. Only used by the general computation (i.e., not by fields with their own method, such as the $SO(3)$ fields). Default: None, i.e., one thread per CPU available to the process, limited by the environment variables OMP_NUM_THREADS and SLURM_CPUS_PER_TASK if they are set.
  • chunk_voxels (int, optional): Number of pixels processed at once by each thread in the computation on data fields. Lower values reduce the memory usage. The peak memory grows as threads*chunk_voxels. Only used by the general computation. Default: 2**17.
Returns
  • V0 (np.array): The values of the first Minkowski Functional at the given thresholds.
def V1( field, us, edges=False, verbose=True, threads=None, chunk_voxels=131072):
294def V1(field, us, edges=False, verbose=True, threads=None, chunk_voxels=1 << 17):
295    """Compute the second Minkowski Functional, $V_1$, normalized by the volume of the space.
296
297    Parameters
298    ----------
299    field : DataField or TheoryField
300        Field on which to compute $V_1$, which can be a theoretical field or a data field.
301        
302    us : np.array
303        The thresholds where $V_1$ is computed. For data fields, they must be increasing.
304        
305    edges : bool, optional
306        If False (default), the given `us` is assumed to be an array of uniformly distributed thresholds, which are taken as the central values of the bins.
307        If True, input `us` is assumed to be a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform distributions of thresholds. 
308        In the latter case, the effective thresholds are the central value of the given bins.
309        
310    verbose : bool, optional
311        If True (default), progress bars are shown for the computations on data fields that support them (currently, the $SO(3)$ fields).
312
313    threads : int or None, optional
314        Number of threads used for the computation on data fields. Only used by the general computation (i.e., not by fields with their own method, such as the $SO(3)$ fields).
315        Default: None, i.e., one thread per CPU available to the process, limited by the environment variables `OMP_NUM_THREADS` and `SLURM_CPUS_PER_TASK` if they are set.
316
317    chunk_voxels : int, optional
318        Number of pixels processed at once by each thread in the computation on data fields. Lower values reduce the memory usage.
319        The peak memory grows as `threads*chunk_voxels`. Only used by the general computation.
320        Default: 2**17.
321
322    Returns
323    -------
324    V1 : np.array
325        The values of the second Minkowski Functional at the given thresholds.
326    
327    """
328    us = np.atleast_1d(us)
329    us, dus = define_ubins(us, edges)
330    
331    if isinstance(field, TheoryField):
332        us = subsample_us(us, dus)
333        try:
334            return np.nanmean(field.V1(us), axis=1)
335        except AttributeError:
336            raise NotImplementedError(f"The theoretical expectation of V1 for {field.name} fields is not implemented. If you know an expression, please get in touch.") from None
337        
338    elif isinstance(field, DataField):
339        if hasattr(field, '_V1'):
340            return field._V1(us, dus, verbose=verbose)
341        return _Vj_data(field, 1, us, dus, threads, chunk_voxels)
342        
343    else:
344        raise TypeError(f"The field must be either TheoryField or DataField (or a subclass).")

Compute the second Minkowski Functional, $V_1$, normalized by the volume of the space.

Parameters
  • field (DataField or TheoryField): Field on which to compute $V_1$, which can be a theoretical field or a data field.
  • us (np.array): The thresholds where $V_1$ is computed. For data fields, they must be increasing.
  • edges (bool, optional): If False (default), the given us is assumed to be an array of uniformly distributed thresholds, which are taken as the central values of the bins. If True, input us is assumed to be a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform distributions of thresholds. In the latter case, the effective thresholds are the central value of the given bins.
  • verbose (bool, optional): If True (default), progress bars are shown for the computations on data fields that support them (currently, the $SO(3)$ fields).
  • threads (int or None, optional): Number of threads used for the computation on data fields. Only used by the general computation (i.e., not by fields with their own method, such as the $SO(3)$ fields). Default: None, i.e., one thread per CPU available to the process, limited by the environment variables OMP_NUM_THREADS and SLURM_CPUS_PER_TASK if they are set.
  • chunk_voxels (int, optional): Number of pixels processed at once by each thread in the computation on data fields. Lower values reduce the memory usage. The peak memory grows as threads*chunk_voxels. Only used by the general computation. Default: 2**17.
Returns
  • V1 (np.array): The values of the second Minkowski Functional at the given thresholds.
def V2( field, us, edges=False, verbose=True, threads=None, chunk_voxels=131072):
347def V2(field, us, edges=False, verbose=True, threads=None, chunk_voxels=1 << 17):
348    """Compute the third Minkowski Functional, $V_2$, normalized by the volume of the space.
349
350    Parameters
351    ----------
352    field : DataField or TheoryField
353        Field on which to compute $V_2$, which can be a theoretical field or a data field. Its dimension must be at least 2.
354        
355    us : np.array
356        The thresholds where $V_2$ is computed. For data fields, they must be increasing.
357        
358    edges : bool, optional
359        If False (default), the given `us` is assumed to be an array of uniformly distributed thresholds, which are taken as the central values of the bins.
360        If True, input `us` is assumed to be a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform distributions of thresholds. 
361        In the latter case, the effective thresholds are the central value of the given bins.
362        
363    verbose : bool, optional
364        If True (default), progress bars are shown for the computations on data fields that support them (currently, the $SO(3)$ fields).
365
366    threads : int or None, optional
367        Number of threads used for the computation on data fields. Only used by the general computation (i.e., not by fields with their own method, such as the $SO(3)$ fields).
368        Default: None, i.e., one thread per CPU available to the process, limited by the environment variables `OMP_NUM_THREADS` and `SLURM_CPUS_PER_TASK` if they are set.
369
370    chunk_voxels : int, optional
371        Number of pixels processed at once by each thread in the computation on data fields. Lower values reduce the memory usage.
372        The peak memory grows as `threads*chunk_voxels`. Only used by the general computation.
373        Default: 2**17.
374
375    Returns
376    -------
377    V2 : np.array
378        The values of the second Minkowski Functional at the given thresholds.
379    
380    """
381    if field.dim<2:
382        raise ValueError(f"V2 is defined for fields with at least 2 dimensions, but this field is {field.dim}D.")
383        
384    us = np.atleast_1d(us)
385    us, dus = define_ubins(us, edges)
386    
387    if isinstance(field, TheoryField):
388        us = subsample_us(us, dus)
389        try:
390            return np.nanmean(field.V2(us), axis=1)
391        except AttributeError:
392            raise NotImplementedError(f"The theoretical expectation of V2 for {field.name} fields is not implemented. If you know an expression, please get in touch.") from None
393        
394    elif isinstance(field, DataField):
395        if hasattr(field, '_V2'):
396            return field._V2(us, dus, verbose=verbose)
397        return _Vj_data(field, 2, us, dus, threads, chunk_voxels)
398        
399    else:
400        raise TypeError(f"The field must be either TheoryField or DataField (or a subclass).")

Compute the third Minkowski Functional, $V_2$, normalized by the volume of the space.

Parameters
  • field (DataField or TheoryField): Field on which to compute $V_2$, which can be a theoretical field or a data field. Its dimension must be at least 2.
  • us (np.array): The thresholds where $V_2$ is computed. For data fields, they must be increasing.
  • edges (bool, optional): If False (default), the given us is assumed to be an array of uniformly distributed thresholds, which are taken as the central values of the bins. If True, input us is assumed to be a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform distributions of thresholds. In the latter case, the effective thresholds are the central value of the given bins.
  • verbose (bool, optional): If True (default), progress bars are shown for the computations on data fields that support them (currently, the $SO(3)$ fields).
  • threads (int or None, optional): Number of threads used for the computation on data fields. Only used by the general computation (i.e., not by fields with their own method, such as the $SO(3)$ fields). Default: None, i.e., one thread per CPU available to the process, limited by the environment variables OMP_NUM_THREADS and SLURM_CPUS_PER_TASK if they are set.
  • chunk_voxels (int, optional): Number of pixels processed at once by each thread in the computation on data fields. Lower values reduce the memory usage. The peak memory grows as threads*chunk_voxels. Only used by the general computation. Default: 2**17.
Returns
  • V2 (np.array): The values of the second Minkowski Functional at the given thresholds.
def V3( field, us, edges=False, verbose=True, threads=None, chunk_voxels=131072):
403def V3(field, us, edges=False, verbose=True, threads=None, chunk_voxels=1 << 17):
404    """Compute the fourth Minkowski Functional, $V_3$, normalized by the volume of the space.
405
406    Parameters
407    ----------
408    field : DataField or TheoryField
409        Field on which to compute $V_3$, which can be a theoretical field or a data field. Its dimension must be at least 3.
410        
411    us : np.array
412        The thresholds where $V_3$ is computed. For data fields, they must be increasing.
413        
414    edges : bool, optional
415        If False (default), the given `us` is assumed to be an array of uniformly distributed thresholds, which are taken as the central values of the bins.
416        If True, input `us` is assumed to be a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform distributions of thresholds. 
417        In the latter case, the effective thresholds are the central value of the given bins.
418        
419    verbose : bool, optional
420        If True (default), progress bars are shown for the computations on data fields that support them (currently, the $SO(3)$ fields).
421
422    threads : int or None, optional
423        Number of threads used for the computation on data fields. Only used by the general computation (i.e., not by fields with their own method, such as the $SO(3)$ fields).
424        Default: None, i.e., one thread per CPU available to the process, limited by the environment variables `OMP_NUM_THREADS` and `SLURM_CPUS_PER_TASK` if they are set.
425
426    chunk_voxels : int, optional
427        Number of pixels processed at once by each thread in the computation on data fields. Lower values reduce the memory usage.
428        The peak memory grows as `threads*chunk_voxels`. Only used by the general computation.
429        Default: 2**17.
430
431    Returns
432    -------
433    V3 : np.array()
434        The values of the fourth Minkowski Functional at the given thresholds.
435    
436    """
437    if field.dim<3:
438        raise ValueError(f"V3 is defined for fields with at least 3 dimensions, but this field is {field.dim}D.")
439        
440    us = np.atleast_1d(us)
441    us, dus = define_ubins(us, edges)
442    
443    if isinstance(field, TheoryField):
444        us = subsample_us(us, dus)
445        try:
446            return np.nanmean(field.V3(us), axis=1)
447        except AttributeError:
448            raise NotImplementedError(f"The theoretical expectation of V3 for {field.name} fields is not implemented. If you know an expression, please get in touch.") from None
449        
450    elif isinstance(field, DataField):
451        if hasattr(field, '_V3'):
452            return field._V3(us, dus, verbose=verbose)
453        return _Vj_data(field, 3, us, dus, threads, chunk_voxels)
454        
455    else:
456        raise TypeError(f"The field must be either TheoryField or DataField (or a subclass).")

Compute the fourth Minkowski Functional, $V_3$, normalized by the volume of the space.

Parameters
  • field (DataField or TheoryField): Field on which to compute $V_3$, which can be a theoretical field or a data field. Its dimension must be at least 3.
  • us (np.array): The thresholds where $V_3$ is computed. For data fields, they must be increasing.
  • edges (bool, optional): If False (default), the given us is assumed to be an array of uniformly distributed thresholds, which are taken as the central values of the bins. If True, input us is assumed to be a monotonically increasing array of bin edges, including the rightmost edge, allowing for non-uniform distributions of thresholds. In the latter case, the effective thresholds are the central value of the given bins.
  • verbose (bool, optional): If True (default), progress bars are shown for the computations on data fields that support them (currently, the $SO(3)$ fields).
  • threads (int or None, optional): Number of threads used for the computation on data fields. Only used by the general computation (i.e., not by fields with their own method, such as the $SO(3)$ fields). Default: None, i.e., one thread per CPU available to the process, limited by the environment variables OMP_NUM_THREADS and SLURM_CPUS_PER_TASK if they are set.
  • chunk_voxels (int, optional): Number of pixels processed at once by each thread in the computation on data fields. Lower values reduce the memory usage. The peak memory grows as threads*chunk_voxels. Only used by the general computation. Default: 2**17.
Returns
  • V3 (np.array()): The values of the fourth Minkowski Functional at the given thresholds.
def general_curvature(field, order):
 87def general_curvature(field, order):
 88    """Computes the symmetrised polynomial of the principal curvatures of order `order`, multiplied by the modulus of the gradient, at every pixel.
 89
 90    Parameters
 91    ----------
 92    field : DataField
 93        Field on which to compute the general curvatures. Its derivatives must have been computed.
 94
 95    order : int
 96        Order of the polynomial of the curvatures.
 97
 98    Returns
 99    -------
100    curvature : np.array
101        The value of the polynomial at each pixel.
102
103        For example:
104        `field.dim = 2`, `order=1` : geodesic curvature $\\kappa$
105        `field.dim = 3`, `order=1` : mean curvature (H = ($\\kappa_1$ + $\\kappa_2$)/2 )
106        `field.dim = 3`, `order=2` : Gaussian curvature (K = $\\kappa_1 \\cdot \\kappa_2$)
107    
108    """
109    assert isinstance(field, DataField), "The field must be a DataField (or subclass)"
110    assert field.dim > 1, "The field must be at least 2D"
111    if order >= field.dim:
112        raise ValueError("The order of the polynomial has to be less than the dimension of the field.")
113    return _curvature(order, list(field.first_der), None if order == 0 else list(field.second_der))

Computes the symmetrised polynomial of the principal curvatures of order order, multiplied by the modulus of the gradient, at every pixel.

Parameters
  • field (DataField): Field on which to compute the general curvatures. Its derivatives must have been computed.
  • order (int): Order of the polynomial of the curvatures.
Returns
  • curvature (np.array): The value of the polynomial at each pixel.

    For example: field.dim = 2, order=1 : geodesic curvature $\kappa$ field.dim = 3, order=1 : mean curvature (H = ($\kappa_1$ + $\kappa_2$)/2 ) field.dim = 3, order=2 : Gaussian curvature (K = $\kappa_1 \cdot \kappa_2$)