Debian Codegraph @

dask_image/ndfourier/_utils.py

raw
1 # -*- coding: utf-8 -*-
2
3 import numbers
4
5 import dask.array as da
6 import numpy as np
7
8
9 def _get_freq_grid(shape, chunks, axis, n, dtype=float):
10 assert len(shape) == len(chunks)
11
12 shape = tuple(shape)
13 dtype = np.dtype(dtype).type
14
15 assert (issubclass(dtype, numbers.Real) and
16 not issubclass(dtype, numbers.Integral))
17
18 axis = axis % len(shape)
19
20 freq_grid = []
21 for ax, (s, c) in enumerate(zip(shape, chunks)):
22 if axis == ax and n > 0:
23 f = da.fft.rfftfreq(n, chunks=c).astype(dtype)
24 else:
25 f = da.fft.fftfreq(s, chunks=c).astype(dtype)
26 freq_grid.append(f)
27
28 freq_grid = da.meshgrid(*freq_grid, indexing="ij", sparse=True)
29
30 return freq_grid
31
32
33 def _get_ang_freq_grid(shape, chunks, axis, n, dtype=float):
34 dtype = np.dtype(dtype).type
35
36 assert (issubclass(dtype, numbers.Real) and
37 not issubclass(dtype, numbers.Integral))
38
39 pi = dtype(np.pi)
40
41 freq_grid = _get_freq_grid(shape, chunks, axis, n, dtype=dtype)
42 ang_freq_grid = tuple((2 * pi) * f for f in freq_grid)
43
44 return ang_freq_grid
45
46
47 def _norm_args(a, s, n=-1, axis=-1):
48 if issubclass(a.dtype.type, numbers.Integral):
49 a = a.astype(float)
50
51 if isinstance(s, numbers.Number):
52 s = np.array(a.ndim * [s])
53 elif not isinstance(s, da.Array):
54 s = np.array(s)
55
56 if issubclass(s.dtype.type, numbers.Integral):
57 s = s.astype(a.real.dtype)
58 elif not issubclass(s.dtype.type, numbers.Real):
59 raise TypeError("The `s` must contain real value(s).")
60 if s.shape != (a.ndim,):
61 raise RuntimeError(
62 "Shape of `s` must be 1-D and equal to the input's rank."
63 )
64
65 if n != -1 and a.shape[axis] != (n // 2 + 1):
66 raise NotImplementedError(
67 "In the case of real-valued images, it is required that "
68 "(n // 2 + 1) == image.shape[axis]."
69 )
70
71 return (a, s, n, axis)
72
73
74 def _reshape_nd(arr, ndim, axis):
75 """Promote a 1d array to ndim with non-singleton size along axis."""
76 nd_shape = (1,) * axis + (arr.size,) + (1,) * (ndim - axis - 1)
77 return arr.reshape(nd_shape)