Debian Codegraph @

dask_image/ndfilters/_utils.py

raw
1 # -*- coding: utf-8 -*-
2 import collections
3 import inspect
4 import numbers
5 import re
6
7 import numpy as np
8
9
10 def _get_docstring(func):
11 # Drop the output parameter from the docstring.
12 split_doc_params = lambda s: re.subn( # noqa: E731
13 "( [A-Za-z]+ : )", "\0\\1", s)[0].split("\0")
14 drop_doc_param = lambda s: not s.startswith(" output : ") # noqa: E731
15 func_doc = "" if func.__doc__ is None else func.__doc__
16 cleaned_docstring = "".join([
17 l for l in split_doc_params(func_doc) if drop_doc_param(l) # noqa: E741, E501
18 ])
19 cleaned_docstring = cleaned_docstring.replace('input', 'image')
20 cleaned_docstring = cleaned_docstring.replace('labels', 'label_image')
21 cleaned_docstring = cleaned_docstring.split('Examples')[0].strip()
22
23 docstring = """
24 Wrapped copy of "{mod_name}.{func_name}"
25
26
27 Excludes the output parameter as it would not work with Dask arrays.
28
29
30 Original docstring:
31
32 {doc}
33 """.format(
34 mod_name=inspect.getmodule(func).__name__,
35 func_name=func.__name__,
36 doc=cleaned_docstring,
37 )
38
39 return docstring
40
41
42 def _update_wrapper(func):
43 def _updater(wrapper):
44 wrapper.__name__ = func.__name__
45 wrapper.__doc__ = _get_docstring(func)
46 return wrapper
47
48 return _updater
49
50
51 def _get_depth_boundary(ndim, depth, boundary=None):
52 strlike = (bytes, str)
53
54 if not isinstance(ndim, numbers.Integral):
55 raise TypeError("Expected integer value for `ndim`.")
56 if ndim <= 0:
57 raise ValueError("Expected positive value for `ndim`.")
58
59 if isinstance(depth, numbers.Number):
60 depth = ndim * (depth,)
61 if not isinstance(depth, collections.abc.Sized):
62 raise TypeError("Unexpected type for `depth`.")
63 if len(depth) != ndim:
64 raise ValueError("Expected `depth` to have a length equal to `ndim`.")
65 if isinstance(depth, collections.abc.Sequence):
66 depth = dict(zip(range(ndim), depth))
67 if not isinstance(depth, collections.abc.Mapping):
68 raise TypeError("Unexpected type for `depth`.")
69
70 if not all(map(lambda d: isinstance(d, numbers.Integral), depth.values())):
71 raise TypeError("Expected integer values for `depth`.")
72 if not all(map(lambda d: d >= 0, depth.values())):
73 raise ValueError("Expected positive semidefinite values for `depth`.")
74
75 depth = dict([(a, int(d)) for a, d in depth.items()])
76
77 if (boundary is None) or isinstance(boundary, strlike):
78 boundary = ndim * (boundary,)
79 if not isinstance(boundary, collections.abc.Sized):
80 raise TypeError("Unexpected type for `boundary`.")
81 if len(boundary) != ndim:
82 raise ValueError(
83 "Expected `boundary` to have a length equal to `ndim`."
84 )
85 if isinstance(boundary, collections.abc.Sequence):
86 boundary = dict(zip(range(ndim), boundary))
87 if not isinstance(boundary, collections.abc.Mapping):
88 raise TypeError("Unexpected type for `boundary`.")
89
90 type_check = lambda b: (b is None) or isinstance(b, strlike) # noqa: E731
91 if not all(map(type_check, boundary.values())):
92 raise TypeError("Expected string-like values for `boundary`.")
93
94 return depth, boundary
95
96
97 def _get_size(ndim, size):
98 if not isinstance(ndim, numbers.Integral):
99 raise TypeError("The ndim must be of integral type.")
100
101 if isinstance(size, numbers.Number):
102 size = ndim * (size,)
103 size = np.array(size)
104
105 if size.ndim != 1:
106 raise RuntimeError("The size must have only one dimension.")
107 if len(size) != ndim:
108 raise RuntimeError(
109 "The size must have a length equal to the number of dimensions."
110 )
111 if not issubclass(size.dtype.type, numbers.Integral):
112 raise TypeError("The size must be of integral type.")
113
114 size = tuple(size)
115
116 return size
117
118
119 def _get_origin(size, origin=0):
120 size = np.array(size)
121 ndim = len(size)
122
123 if isinstance(origin, numbers.Number):
124 origin = ndim * (origin,)
125
126 origin = np.array(origin)
127
128 if not issubclass(origin.dtype.type, numbers.Integral):
129 raise TypeError("The origin must be of integral type.")
130
131 # Validate dimensions.
132 if origin.ndim != 1:
133 raise RuntimeError("The origin must have only one dimension.")
134 if len(origin) != ndim:
135 raise RuntimeError(
136 "The origin must have the same length as the number of dimensions"
137 " as the array being filtered."
138 )
139
140 # Validate origin is bounded.
141 if not (origin < ((size + 1) // 2)).all():
142 raise ValueError("The origin must be within the footprint.")
143
144 origin = tuple(origin)
145
146 return origin
147
148
149 def _get_depth(size, origin=0):
150 origin = np.array(_get_origin(size, origin))
151 size = np.array(size)
152
153 half_size = size // 2
154 depth = half_size + abs(origin)
155
156 depth = tuple(depth)
157
158 return depth
159
160
161 def _get_footprint(ndim, size=None, footprint=None):
162 # Verify that we only got size or footprint.
163 if size is None and footprint is None:
164 raise RuntimeError("Must provide either size or footprint.")
165 if size is not None and footprint is not None:
166 raise RuntimeError("Provide either size or footprint, but not both.")
167
168 # Get a footprint based on the size.
169 if size is not None:
170 size = _get_size(ndim, size)
171 footprint = np.ones(size, dtype=bool)
172
173 # Validate the footprint.
174 if footprint.ndim != ndim:
175 raise RuntimeError(
176 "The footprint must have the same number of dimensions as"
177 " the array being filtered."
178 )
179 if footprint.size == 0:
180 raise RuntimeError("The footprint must have only non-zero dimensions.")
181
182 # Convert to Boolean.
183 footprint = (footprint != 0)
184
185 return footprint