flowfields 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
flowfields/utils.py ADDED
@@ -0,0 +1,282 @@
1
+ """Helpers for opening images and for working with 2D vectors."""
2
+
3
+ import difflib
4
+ import inspect
5
+ import warnings
6
+
7
+ import numpy as np
8
+ from PIL import Image
9
+
10
+
11
+ class UnusedArgumentWarning(UserWarning):
12
+ """A field was given keyword arguments that it does not use
13
+
14
+ Fields accept and ignore unknown keyword arguments, so one field type can
15
+ replace another with a slightly different API. This warning catches
16
+ typos such as ``normalise=False``. To swap fields on purpose without it:
17
+
18
+ warnings.simplefilter("ignore", flowfields.UnusedArgumentWarning)
19
+ """
20
+
21
+
22
+ def warn_unused_arguments(field: object, kwargs: dict) -> None:
23
+ """Warn that a field ignores the keyword arguments in kwargs
24
+
25
+ Fields call it from ``__init__`` with their ``**kwargs``. The warning
26
+ names each argument and, when one is close to a parameter of the field,
27
+ suggests it. It points to the line that created the field.
28
+
29
+ Args:
30
+ field (object): The field being created
31
+ kwargs (dict): The keyword arguments the field does not use
32
+ """
33
+ if not kwargs:
34
+ return
35
+ cls = type(field)
36
+ parameters = [
37
+ name for name in inspect.signature(cls.__init__).parameters
38
+ if name not in ("self", "kwargs")
39
+ ]
40
+ names = []
41
+ for name in kwargs:
42
+ close = difflib.get_close_matches(name, parameters, n=1)
43
+ hint = f" (did you mean '{close[0]}'?)" if close else ""
44
+ names.append(f"'{name}'{hint}")
45
+ plural = "s" if len(names) > 1 else ""
46
+ # stacklevel 3: this function, the field's __init__, the caller
47
+ warnings.warn(
48
+ f"{cls.__name__} ignores the argument{plural} {', '.join(names)}",
49
+ UnusedArgumentWarning,
50
+ stacklevel=3,
51
+ )
52
+
53
+
54
+ def open_image(filename: str, mode: str = "RGB") -> np.ndarray:
55
+ """Open an image file as an array of pixels
56
+
57
+ Args:
58
+ filename (str): Path to the image file
59
+ mode (str): Pillow color mode. Use "RGB" for color and "L" for
60
+ grayscale.
61
+
62
+ Returns:
63
+ np.ndarray: Pixels as floats in [0, 1], with shape (H, W, 3) for "RGB"
64
+ and (H, W) for "L"
65
+ """
66
+ with Image.open(filename) as img:
67
+ return np.array(img.convert(mode), dtype=float) / 255.0
68
+
69
+
70
+ def kmeans(
71
+ data: np.ndarray,
72
+ n_clusters: int,
73
+ rng: np.random.Generator | int | None = None,
74
+ max_iter: int = 100,
75
+ tol: float = 1e-4,
76
+ ) -> tuple[np.ndarray, np.ndarray]:
77
+ """Group points into n_clusters clusters with k-means
78
+
79
+ The first centers are chosen with k-means++: each new center is a data
80
+ point drawn with probability proportional to its squared distance to the
81
+ nearest center so far. Then each point goes to its nearest center and
82
+ each center moves to the mean of its points (Lloyd's algorithm). It
83
+ stops when no point changes cluster, when the centers move less than
84
+ ``tol`` times the variance of the data (the sum of the squared moves,
85
+ over the mean variance of the dimensions, as in scikit-learn), or after
86
+ max_iter rounds. A cluster that loses all its points keeps its previous
87
+ center.
88
+
89
+ Args:
90
+ data (np.ndarray): Points with shape (n_points, n_dims), such as the
91
+ pixels of an image reshaped to (H * W, 3)
92
+ n_clusters (int): Number of clusters, from 1 to n_points
93
+ rng (np.random.Generator | int | None): Random generator for the
94
+ first centers, or a seed for one. None takes a fresh seed from
95
+ the operating system.
96
+ max_iter (int): Maximum number of rounds
97
+ tol (float): Relative tolerance on the moves of the centers
98
+
99
+ Returns:
100
+ tuple[np.ndarray, np.ndarray]: The centers, with shape
101
+ (n_clusters, n_dims), and the cluster of each point, with shape
102
+ (n_points,)
103
+ """
104
+ rng = np.random.default_rng(rng)
105
+ data = np.asarray(data, dtype=float)
106
+ n_points = data.shape[0]
107
+ if not 1 <= n_clusters <= n_points:
108
+ raise ValueError(
109
+ f"n_clusters must be between 1 and {n_points}, got {n_clusters}")
110
+
111
+ # k-means++ initialization
112
+ centers = np.empty((n_clusters, data.shape[1]))
113
+ centers[0] = data[rng.integers(n_points)]
114
+ distances = np.sum((data - centers[0])**2, axis=1)
115
+ for k in range(1, n_clusters):
116
+ total = np.sum(distances)
117
+ if total > 0:
118
+ idx = rng.choice(n_points, p=distances / total)
119
+ else: # every point is already on a center
120
+ idx = rng.integers(n_points)
121
+ centers[k] = data[idx]
122
+ distances = np.minimum(distances, np.sum((data - centers[k])**2, axis=1))
123
+
124
+ # Lloyd's algorithm
125
+ threshold = tol * np.mean(np.var(data, axis=0))
126
+ labels = _nearest_center(data, centers)
127
+ for _ in range(max_iter):
128
+ moved = 0.0
129
+ for k in range(n_clusters):
130
+ members = data[labels == k]
131
+ if len(members) > 0:
132
+ new_center = np.mean(members, axis=0)
133
+ moved += np.sum((new_center - centers[k])**2)
134
+ centers[k] = new_center
135
+ new_labels = _nearest_center(data, centers)
136
+ if np.array_equal(new_labels, labels):
137
+ break
138
+ labels = new_labels
139
+ if moved <= threshold:
140
+ break
141
+
142
+ return centers, labels
143
+
144
+
145
+ def _nearest_center(data: np.ndarray, centers: np.ndarray) -> np.ndarray:
146
+ """Index of the nearest center to each point; ties go to the first one"""
147
+ best = np.full(data.shape[0], np.inf)
148
+ labels = np.zeros(data.shape[0], dtype=int)
149
+ for k in range(centers.shape[0]):
150
+ distances = np.sum((data - centers[k])**2, axis=1)
151
+ closer = distances < best
152
+ best[closer] = distances[closer]
153
+ labels[closer] = k
154
+ return labels
155
+
156
+
157
+ def normalize_vector(v: np.ndarray) -> np.ndarray:
158
+ """Normalize a vector in cartesian form
159
+
160
+ Args:
161
+ v (np.ndarray): Input vector
162
+
163
+ Returns:
164
+ np.ndarray: Normalized vector
165
+ """
166
+ norm = np.linalg.norm(v)
167
+ if norm == 0:
168
+ return v
169
+ return v / norm
170
+
171
+
172
+ def clamp_vector(
173
+ v: np.ndarray,
174
+ min_length: float,
175
+ max_length: float,
176
+ ) -> np.ndarray:
177
+ """Clamp a vector's length between a minimum and maximum value
178
+
179
+ Args:
180
+ v (np.ndarray): Input vector
181
+ min_length (float): Minimum length
182
+ max_length (float): Maximum length
183
+
184
+ Returns:
185
+ np.ndarray: Clamped vector
186
+ """
187
+ norm = np.linalg.norm(v)
188
+ if norm == 0:
189
+ return v
190
+ clamped_norm = clamp(norm, min_length, max_length)
191
+ return v / norm * clamped_norm
192
+
193
+
194
+ def lerp(a: np.ndarray, b: np.ndarray, t: float) -> np.ndarray:
195
+ """Linear interpolation between two vectors
196
+
197
+ Args:
198
+ a (np.ndarray): First vector
199
+ b (np.ndarray): Second vector
200
+ t (float): Interpolation factor (0 <= t <= 1)
201
+
202
+ Returns:
203
+ np.ndarray: Interpolated vector
204
+ """
205
+ return (1 - t) * a + t * b
206
+
207
+
208
+ def clamp(value: float, min_value: float, max_value: float) -> float:
209
+ """Clamp a value between a minimum and maximum value
210
+
211
+ Args:
212
+ value (float): Input value
213
+ min_value (float): Minimum value
214
+ max_value (float): Maximum value
215
+
216
+ Returns:
217
+ float: Clamped value
218
+ """
219
+ return max(min_value, min(value, max_value))
220
+
221
+
222
+ def cartesian_to_polar(v: np.ndarray) -> tuple[float, float]:
223
+ """Convert a 2D vector from cartesian to polar coordinates
224
+
225
+ Args:
226
+ v (np.ndarray): Input vector in cartesian coordinates
227
+ Returns:
228
+ tuple[float, float]: (radius, angle) in polar coordinates
229
+ """
230
+ radius = np.linalg.norm(v)
231
+ angle = np.arctan2(v[1], v[0])
232
+ return radius, angle
233
+
234
+
235
+ def polar_to_cartesian(radius: float, angle: float) -> np.ndarray:
236
+ """Convert polar coordinates to a 2D cartesian vector
237
+
238
+ Args:
239
+ radius (float): Radius in polar coordinates
240
+ angle (float): Angle in polar coordinates
241
+
242
+ Returns:
243
+ np.ndarray: Vector in cartesian coordinates
244
+ """
245
+ x = radius * np.cos(angle)
246
+ y = radius * np.sin(angle)
247
+ return np.array([x, y])
248
+
249
+
250
+ def rotate_vector(v: np.ndarray, angle: float) -> np.ndarray:
251
+ """Rotate a 2D vector by a given angle
252
+
253
+ Args:
254
+ v (np.ndarray): Input vector
255
+ angle (float): Rotation angle in radians
256
+
257
+ Returns:
258
+ np.ndarray: Rotated vector
259
+ """
260
+ rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)],
261
+ [np.sin(angle), np.cos(angle)]])
262
+ return rotation_matrix @ v
263
+
264
+
265
+ def quantize_vector(v: np.ndarray, n_levels: int) -> np.ndarray:
266
+ """Round the angle of a 2D vector to one of n_levels directions
267
+
268
+ The directions are evenly spaced, starting at angle 0. The length of the
269
+ vector does not change.
270
+
271
+ Args:
272
+ v (np.ndarray): Input vector
273
+ n_levels (int): Number of allowed directions
274
+
275
+ Returns:
276
+ np.ndarray: Quantized vector
277
+ """
278
+ radius, angle = cartesian_to_polar(v)
279
+ #quantized_radius = round(radius * n_levels) / n_levels
280
+ quantized_angle = round(angle /
281
+ (2 * np.pi) * n_levels) * (2 * np.pi / n_levels)
282
+ return polar_to_cartesian(radius, quantized_angle)
@@ -0,0 +1,19 @@
1
+ """Vector fields: functions that give a vector for each point in the plane."""
2
+
3
+ from flowfields.vector_fields.base import FlowField
4
+ from flowfields.vector_fields.rotation import RotationField
5
+ from flowfields.vector_fields.expansion import ExpansionField
6
+ from flowfields.vector_fields.noise import NoiseField
7
+ from flowfields.vector_fields.sum import FieldSum
8
+ from flowfields.vector_fields.max import FieldMax
9
+ from flowfields.vector_fields.select import FieldSelect
10
+
11
+ __all__ = [
12
+ "FlowField",
13
+ "RotationField",
14
+ "ExpansionField",
15
+ "NoiseField",
16
+ "FieldSum",
17
+ "FieldMax",
18
+ "FieldSelect",
19
+ ]
@@ -0,0 +1,25 @@
1
+ """Abstract base class for vector fields."""
2
+
3
+ import numpy as np
4
+ from flowfields.utils import warn_unused_arguments
5
+
6
+ class FlowField():
7
+ """
8
+ Abstract base class for 2D vector fields.
9
+
10
+ Subclasses implement ``__call__`` to return a flow vector v(x) at any
11
+ point x in the plane. The optional ``normalize`` flag (supported by most
12
+ subclasses) divides the result by its L2 norm so that ||v(x)|| = 1.
13
+ """
14
+
15
+ def __init__(
16
+ self,
17
+ **kwargs,
18
+ ):
19
+ warn_unused_arguments(self, kwargs)
20
+
21
+ def __call__(self, x: np.ndarray) -> np.ndarray:
22
+ """
23
+ Returns the flowfield vector at point x.
24
+ """
25
+ raise NotImplementedError("Subclasses should implement this method.")
@@ -0,0 +1,51 @@
1
+ """Vector field that points away from or toward a center."""
2
+
3
+ import numpy as np
4
+
5
+ from flowfields.utils import normalize_vector, warn_unused_arguments
6
+ from flowfields.vector_fields.base import FlowField
7
+
8
+
9
+ class ExpansionField(FlowField):
10
+ """
11
+ Radial expansion / contraction field centred at a fixed point.
12
+
13
+ At each point x the vector points directly away from (or toward) the centre:
14
+
15
+ v(x) = direction * (x - center)
16
+
17
+ ``direction = +1`` produces an outward (source / expansion) field;
18
+ ``direction = -1`` produces an inward (sink / contraction) field.
19
+
20
+ If ``normalize=True`` (default) the output is divided by its L2 norm,
21
+ giving a pure radial direction independent of distance from the centre.
22
+ Otherwise the vector length equals the distance from the centre.
23
+
24
+ Args:
25
+ center: Point the flow moves away from or toward.
26
+ direction: +1 for outward, -1 for inward.
27
+ normalize: Whether to L2-normalise the output vector.
28
+ **kwargs: Not used; each one gives an ``UnusedArgumentWarning``.
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ center: np.ndarray,
34
+ direction: int = 1,
35
+ normalize: bool = True,
36
+ **kwargs,
37
+ ):
38
+ warn_unused_arguments(self, kwargs)
39
+ self.center = center
40
+ self.direction = direction
41
+ self.normalize = normalize
42
+
43
+ def __call__(self, x: np.ndarray) -> np.ndarray:
44
+ """
45
+ Returns the flowfield vector at point x.
46
+ """
47
+ y = x - self.center
48
+ y = y * self.direction
49
+ if self.normalize:
50
+ y = normalize_vector(y)
51
+ return y
@@ -0,0 +1,72 @@
1
+ """Vector field that uses only the highest-weighted of its fields at each point."""
2
+
3
+ import numpy as np
4
+
5
+ from flowfields.scalar_fields import ScalarField
6
+ from flowfields.utils import normalize_vector, warn_unused_arguments
7
+ from flowfields.vector_fields.base import FlowField
8
+
9
+
10
+ class FieldMax(FlowField):
11
+ """
12
+ Hard-selection field that returns the vector of the highest-weighted field.
13
+
14
+ At each point x the weights are evaluated and the winning field is chosen:
15
+
16
+ i* = argmax_i w_i(x)
17
+ v(x) = F_{i*}(x)
18
+
19
+ Weights can be fixed scalars or ``ScalarField`` instances evaluated at x,
20
+ so the dominant field can change continuously across space. This produces
21
+ sharp, discontinuous transitions at boundaries where two weights are equal.
22
+ With ``weights=None`` all weights are equal, so the first field always wins.
23
+
24
+ If ``normalize=True`` (default) the selected vector is divided by its L2
25
+ norm.
26
+
27
+ Args:
28
+ fields: The candidate ``FlowField`` instances.
29
+ weights: One weight per field. ``None`` gives all fields the same
30
+ weight.
31
+ normalize: Whether to L2-normalise the output vector.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ fields: list[FlowField],
37
+ weights: None | list[float] | list[ScalarField] = None,
38
+ normalize: bool = True,
39
+ **kwargs,
40
+ ):
41
+ warn_unused_arguments(self, kwargs)
42
+ self.list_of_fields = fields
43
+ self.weights = weights
44
+ self.normalize = normalize
45
+
46
+ def __call__(
47
+ self,
48
+ x: np.ndarray,
49
+ ) -> np.ndarray:
50
+ """
51
+ Returns the flowfield vector at point x.
52
+ """
53
+ magnitudes = []
54
+
55
+ for idx, field in enumerate(self.list_of_fields):
56
+
57
+ if self.weights is not None:
58
+ if isinstance(self.weights[idx], ScalarField):
59
+ weight_value = self.weights[idx](x)
60
+ else:
61
+ weight_value = self.weights[idx]
62
+ magnitudes.append(weight_value)
63
+ else:
64
+ magnitudes.append(1.0)
65
+
66
+ idx = np.argmax(magnitudes)
67
+ y = self.list_of_fields[idx](x)
68
+
69
+ if self.normalize:
70
+ y = normalize_vector(y)
71
+
72
+ return y
@@ -0,0 +1,59 @@
1
+ """Vector field that returns random vectors."""
2
+
3
+ import numpy as np
4
+
5
+ from flowfields.utils import normalize_vector, warn_unused_arguments
6
+ from flowfields.vector_fields.base import FlowField
7
+
8
+
9
+ class NoiseField(FlowField):
10
+ """
11
+ Spatially-uncorrelated random vector field.
12
+
13
+ Each call samples a fresh vector independently of position:
14
+
15
+ v ~ Normal(0, 1)^n if ``distribution="gaussian"`` (default)
16
+ v ~ Uniform(-1, 1)^n if ``distribution="uniform"``
17
+
18
+ where n is the dimensionality of the input x. Because each evaluation is
19
+ independent, this field is non-deterministic and has no spatial coherence.
20
+
21
+ If ``normalize=True`` (default) the random vector is divided by its L2
22
+ norm, producing a random unit direction. All directions are equally likely
23
+ with ``"gaussian"``, while ``"uniform"`` samples from a square, which
24
+ favours the diagonals.
25
+
26
+ Args:
27
+ normalize: Whether to L2-normalise the output vector.
28
+ distribution: Distribution of each coordinate, either ``"gaussian"`` or
29
+ ``"uniform"``.
30
+ rng: Random generator, or a seed for one. ``None`` takes a fresh
31
+ seed from the operating system.
32
+ **kwargs: Not used; each one gives an ``UnusedArgumentWarning``.
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ normalize: bool = True,
38
+ distribution: str = "gaussian",
39
+ rng: np.random.Generator | int | None = None,
40
+ **kwargs,
41
+ ):
42
+ warn_unused_arguments(self, kwargs)
43
+ if distribution not in ("gaussian", "uniform"):
44
+ raise ValueError(f"Unknown distribution: {distribution}")
45
+ self.normalize = normalize
46
+ self.distribution = distribution
47
+ self.rng = np.random.default_rng(rng)
48
+
49
+ def __call__(self, x: np.ndarray) -> np.ndarray:
50
+ """
51
+ Returns a new random vector with the same shape as x.
52
+ """
53
+ if self.distribution == "gaussian":
54
+ noise = self.rng.normal(size=x.shape)
55
+ else:
56
+ noise = self.rng.uniform(low=-1.0, high=1.0, size=x.shape)
57
+ if self.normalize:
58
+ noise = normalize_vector(noise)
59
+ return noise
@@ -0,0 +1,54 @@
1
+ """Vector field that circles around a center."""
2
+
3
+ import numpy as np
4
+
5
+ from flowfields.utils import normalize_vector, warn_unused_arguments
6
+ from flowfields.vector_fields.base import FlowField
7
+
8
+
9
+ class RotationField(FlowField):
10
+ """
11
+ Curl / rotation field centred at a fixed point.
12
+
13
+ At each point x the vector is the radius vector rotated 90° in the plane:
14
+
15
+ r = x - center
16
+ v(x) = direction * [-r_y, r_x]
17
+
18
+ This produces circular streamlines around ``center``.
19
+ ``direction = +1`` gives counter-clockwise rotation;
20
+ ``direction = -1`` gives clockwise rotation.
21
+
22
+ If ``normalize=True`` (default) the output is divided by its L2 norm,
23
+ giving unit-speed circular flow regardless of distance from the centre.
24
+ Otherwise the vector length equals the distance from the centre.
25
+
26
+ Args:
27
+ center: Point the flow rotates around.
28
+ direction: +1 for counter-clockwise, -1 for clockwise.
29
+ normalize: Whether to L2-normalise the output vector.
30
+ **kwargs: Not used; each one gives an ``UnusedArgumentWarning``.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ center: np.ndarray,
36
+ direction: int = 1,
37
+ normalize: bool = True,
38
+ **kwargs,
39
+ ):
40
+ warn_unused_arguments(self, kwargs)
41
+ self.center = center
42
+ self.direction = direction
43
+ self.normalize = normalize
44
+
45
+ def __call__(self, x: np.ndarray) -> np.ndarray:
46
+ """
47
+ Returns the flowfield vector at point x.
48
+ """
49
+ r = x - self.center
50
+ y = np.array([-r[1], r[0]], dtype=float)
51
+ y = y * self.direction
52
+ if self.normalize:
53
+ y = normalize_vector(y)
54
+ return y