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/__init__.py ADDED
@@ -0,0 +1,70 @@
1
+ """Generative-art toolkit built around composable vector, scalar and color fields.
2
+
3
+ Every field is available from the package itself::
4
+
5
+ import flowfields as ff
6
+
7
+ field = ff.FieldSum(
8
+ fields=[ff.RotationField(center), ff.NoiseField(rng=0)],
9
+ weights=[ff.GaussianField(center, sigma=2.0), 0.2],
10
+ )
11
+
12
+ The submodules ``vector_fields``, ``scalar_fields``, ``color_fields`` and
13
+ ``utils`` remain available as well.
14
+ """
15
+
16
+ from importlib.metadata import PackageNotFoundError, version
17
+
18
+ from flowfields import color_fields, scalar_fields, utils, vector_fields
19
+ from flowfields.color_fields import ColorField, MatrixColorField
20
+ from flowfields.scalar_fields import (
21
+ BoxField,
22
+ ConstantField,
23
+ GaussianField,
24
+ KernelProbabilisticMatrixField,
25
+ MatrixField,
26
+ ScalarField,
27
+ )
28
+ from flowfields.vector_fields import (
29
+ ExpansionField,
30
+ FieldMax,
31
+ FieldSelect,
32
+ FieldSum,
33
+ FlowField,
34
+ NoiseField,
35
+ RotationField,
36
+ )
37
+ from flowfields.utils import UnusedArgumentWarning
38
+
39
+ try:
40
+ __version__ = version("flowfields")
41
+ except PackageNotFoundError: # running from a source tree that is not installed
42
+ __version__ = "unknown"
43
+
44
+ __all__ = [
45
+ "__version__",
46
+ "UnusedArgumentWarning",
47
+ # submodules
48
+ "color_fields",
49
+ "scalar_fields",
50
+ "utils",
51
+ "vector_fields",
52
+ # scalar fields
53
+ "ScalarField",
54
+ "GaussianField",
55
+ "ConstantField",
56
+ "BoxField",
57
+ "MatrixField",
58
+ "KernelProbabilisticMatrixField",
59
+ # vector fields
60
+ "FlowField",
61
+ "RotationField",
62
+ "ExpansionField",
63
+ "NoiseField",
64
+ "FieldSum",
65
+ "FieldMax",
66
+ "FieldSelect",
67
+ # color fields
68
+ "ColorField",
69
+ "MatrixColorField",
70
+ ]
@@ -0,0 +1,9 @@
1
+ """Color fields: functions that give a color for each point in the plane."""
2
+
3
+ from flowfields.color_fields.base import ColorField
4
+ from flowfields.color_fields.matrixcolorfield import MatrixColorField
5
+
6
+ __all__ = [
7
+ "ColorField",
8
+ "MatrixColorField",
9
+ ]
@@ -0,0 +1,25 @@
1
+ """Abstract base class for color fields."""
2
+
3
+ import numpy as np
4
+ from flowfields.utils import warn_unused_arguments
5
+
6
+ class ColorField():
7
+ """
8
+ Abstract base class for color fields.
9
+
10
+ Subclasses implement ``__call__`` to return a color at any point x in the
11
+ plane.
12
+ """
13
+
14
+ def __init__(
15
+ self,
16
+ **kwargs,
17
+ ):
18
+ warn_unused_arguments(self, kwargs)
19
+
20
+ def __call__(self, x: np.ndarray) -> np.ndarray:
21
+ """
22
+ Returns the RGB color at point x.
23
+ """
24
+ raise NotImplementedError("ColorField is an abstract class and cannot be called directly.")
25
+
@@ -0,0 +1,137 @@
1
+ """Color field that draws colors from the local palette of an image."""
2
+
3
+ import numpy as np
4
+
5
+ from flowfields.color_fields.base import ColorField
6
+ from flowfields.utils import kmeans, warn_unused_arguments
7
+
8
+
9
+ class MatrixColorField(ColorField):
10
+ """
11
+ A color field that is defined by a matrix of colors.
12
+
13
+ The colors of the matrix are reduced to a palette of ``n_colors`` with
14
+ k-means. At each point x, a palette color is drawn according to how many
15
+ pixels of that color there are in a square window around x:
16
+
17
+ p_k(x) ∝ exp( z_k(x) / temperature )
18
+
19
+ where z_k(x) is the fraction of the window's pixels in color k. Unlike
20
+ ``MatrixField``, y grows from the top of the image: the first row of the
21
+ matrix is at the lowest y.
22
+
23
+ Args:
24
+ min_corner: Point that maps to the first row and column of the matrix.
25
+ max_corner: Point that maps to the last row and column of the matrix.
26
+ data: Array of RGB colors with shape (H, W, 3).
27
+ n_colors: Size of the palette.
28
+ random_state: Seed for k-means (``flowfields.utils.kmeans``). It
29
+ does not affect the color draws, which use ``rng``.
30
+ kernel_size: Side of the window, as a fraction of the largest side of
31
+ the matrix.
32
+ temperature: Lower values favour the most common color in the window,
33
+ and higher values approach a uniform draw from the whole palette,
34
+ including colors that are absent from the window.
35
+ rng: Random generator for the color draws, or a seed for one.
36
+ ``None`` takes a fresh seed from the operating system.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ min_corner: np.ndarray,
42
+ max_corner: np.ndarray,
43
+ data: np.ndarray,
44
+ n_colors: int,
45
+ random_state: int = 0,
46
+ kernel_size: float = 0.05,
47
+ temperature: float = 1.0,
48
+ rng: np.random.Generator | int | None = None,
49
+ **kwargs,
50
+ ):
51
+ warn_unused_arguments(self, kwargs)
52
+ self.min_corner = min_corner
53
+ self.max_corner = max_corner
54
+ self.data = data
55
+ self.n_colors = n_colors
56
+ self.random_state = random_state
57
+ self.kernel_size = kernel_size
58
+ self.temperature = temperature
59
+ self.rng = np.random.default_rng(rng)
60
+
61
+ # The palette: the n_colors centers of the image's pixels, and the
62
+ # palette color of every pixel
63
+ h, w, _ = self.data.shape
64
+ self.palette, labels = kmeans(
65
+ self.data.reshape(-1, 3),
66
+ self.n_colors,
67
+ rng=self.random_state,
68
+ )
69
+ labels = labels.reshape(h, w)
70
+
71
+ # One integral image (2D prefix sum) per palette color, so windowed
72
+ # pixel counts can be looked up in O(1) on every get_probs call.
73
+ self.integral_images = np.zeros((self.n_colors, h + 1, w + 1), dtype=np.int32)
74
+ for k in range(self.n_colors):
75
+ mask = labels == k
76
+ self.integral_images[k, 1:, 1:] = mask.cumsum(axis=0).cumsum(axis=1)
77
+
78
+ def get_probs(self, x: np.ndarray) -> np.ndarray:
79
+ """
80
+ Returns the probability of each palette color at point x.
81
+
82
+ Points outside the bounding box use the nearest point inside it.
83
+ """
84
+ # Get the normalized coordinates of x in the range [0, 1]
85
+ t = (x - self.min_corner) / (self.max_corner - self.min_corner)
86
+ t = np.clip(t, 0.0, 1.0)
87
+
88
+
89
+
90
+ # Select a window from the data matrix based on the kernel size
91
+ h, w, _ = self.data.shape
92
+ center_x = int(t[0] * (w-1))
93
+ center_y = int(t[1] * (h-1))
94
+ half_k = int(self.kernel_size * max(w, h) / 2)
95
+ x_min = max(center_x - half_k, 0)
96
+ x_max = min(center_x + half_k + 1, w)
97
+ y_min = max(center_y - half_k, 0)
98
+ y_max = min(center_y + half_k + 1, h)
99
+ #print(y_min, y_max, x_min, x_max)
100
+
101
+ # Count the number of pixels closest to each cluster center within the
102
+ # window via an O(1) integral-image box-sum lookup.
103
+ count = (
104
+ self.integral_images[:, y_max, x_max]
105
+ - self.integral_images[:, y_min, x_max]
106
+ - self.integral_images[:, y_max, x_min]
107
+ + self.integral_images[:, y_min, x_min]
108
+ ).astype(float)
109
+
110
+ z = count
111
+ z = z.clip(min=1)
112
+ z = z / z.sum() # Normalize to get probabilities
113
+ logits = z / self.temperature
114
+ logits -= logits.max() # Keeps np.exp from overflowing at low temperatures
115
+ probs = np.exp(logits)
116
+ probs /= probs.sum() # Normalize to get probabilities
117
+
118
+ # if probs contain NaN, print z and probs
119
+ if np.isnan(probs).any():
120
+ print("NaN values found in probabilities.")
121
+ print("Count:", count)
122
+ print("z:", z)
123
+ print("probs:", probs)
124
+ raise ValueError("NaN values found in probabilities.")
125
+
126
+ return probs
127
+
128
+
129
+ def __call__(self, x: np.ndarray, random_state: int = 0) -> np.ndarray:
130
+ """
131
+ Draws a palette color for point x and returns it as an RGB array.
132
+
133
+ The ``random_state`` argument is not used.
134
+ """
135
+ probs = self.get_probs(x)
136
+ sample = self.rng.choice(self.n_colors, p=probs.flatten())
137
+ return self.palette[sample]
flowfields/py.typed ADDED
File without changes
@@ -0,0 +1,16 @@
1
+ """Scalar fields: functions that give a number for each point in the plane."""
2
+
3
+ from flowfields.scalar_fields.base import ScalarField
4
+ from flowfields.scalar_fields.gaussian import GaussianField
5
+ from flowfields.scalar_fields.constant import ConstantField
6
+ from flowfields.scalar_fields.box import BoxField
7
+ from flowfields.scalar_fields.matrix import MatrixField, KernelProbabilisticMatrixField
8
+
9
+ __all__ = [
10
+ "ScalarField",
11
+ "GaussianField",
12
+ "ConstantField",
13
+ "BoxField",
14
+ "MatrixField",
15
+ "KernelProbabilisticMatrixField",
16
+ ]
@@ -0,0 +1,22 @@
1
+ """Abstract base class for scalar fields."""
2
+
3
+ import numpy as np
4
+ from flowfields.utils import warn_unused_arguments
5
+
6
+ class ScalarField():
7
+ """
8
+ Abstract base class for scalar fields.
9
+
10
+ Subclasses implement ``__call__`` to return a single float value f(x) at
11
+ any point x in the plane. Scalar fields are used as position-dependent
12
+ weights in ``FieldSum``, ``FieldMax``, and ``FieldSelect``.
13
+ """
14
+
15
+ def __init__(self, **kwargs):
16
+ warn_unused_arguments(self, kwargs)
17
+
18
+ def __call__(self, x: np.ndarray) -> float:
19
+ """
20
+ Returns the scalar field value at point x.
21
+ """
22
+ raise NotImplementedError("Subclasses should implement this method.")
@@ -0,0 +1,53 @@
1
+ """Scalar field with one value inside a rectangle and another outside of it."""
2
+
3
+ import numpy as np
4
+
5
+ from flowfields.scalar_fields.base import ScalarField
6
+ from flowfields.utils import warn_unused_arguments
7
+
8
+
9
+ class BoxField(ScalarField):
10
+ """
11
+ Axis-aligned rectangular indicator field.
12
+
13
+ Returns one of two constant values depending on whether x lies inside the
14
+ box defined by ``min_corner`` and ``max_corner``:
15
+
16
+ f(x) = inside_value if min_corner <= x <= max_corner (element-wise)
17
+ outside_value otherwise
18
+
19
+ The corners are automatically sorted at construction time, so passing them
20
+ in either order is safe. Useful for hard spatial masking or gating.
21
+
22
+ Args:
23
+ min_corner: Lower-left corner of the box.
24
+ max_corner: Upper-right corner of the box.
25
+ inside_value: Value returned for points inside the box, borders
26
+ included (default 1.0).
27
+ outside_value: Value returned for points outside the box (default 0.0).
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ min_corner: np.ndarray,
33
+ max_corner: np.ndarray,
34
+ inside_value: float = 1.0,
35
+ outside_value: float = 0.0,
36
+ **kwargs,
37
+ ):
38
+ warn_unused_arguments(self, kwargs)
39
+ min_corner_ = np.minimum(min_corner, max_corner)
40
+ max_corner_ = np.maximum(min_corner, max_corner)
41
+ self.min_corner = min_corner_
42
+ self.max_corner = max_corner_
43
+ self.inside_value = inside_value
44
+ self.outside_value = outside_value
45
+
46
+ def __call__(self, x: np.ndarray) -> float:
47
+ """
48
+ Returns the scalar field value at point x.
49
+ """
50
+ if np.all(x >= self.min_corner) and np.all(x <= self.max_corner):
51
+ return self.inside_value
52
+ else:
53
+ return self.outside_value
@@ -0,0 +1,30 @@
1
+ """Scalar field with the same value everywhere."""
2
+
3
+ import numpy as np
4
+
5
+ from flowfields.scalar_fields.base import ScalarField
6
+ from flowfields.utils import warn_unused_arguments
7
+
8
+
9
+ class ConstantField(ScalarField):
10
+ """
11
+ Uniform scalar field that returns the same value everywhere.
12
+
13
+ f(x) = value
14
+
15
+ Useful as a fixed-weight placeholder wherever a ``ScalarField`` is expected
16
+ but spatial variation is not needed.
17
+
18
+ Args:
19
+ value: The constant scalar value returned at every point (default 1.0).
20
+ """
21
+
22
+ def __init__(self, value: float = 1.0, **kwargs):
23
+ warn_unused_arguments(self, kwargs)
24
+ self.value = value
25
+
26
+ def __call__(self, x: np.ndarray) -> float:
27
+ """
28
+ Returns the scalar field value at point x.
29
+ """
30
+ return self.value
@@ -0,0 +1,42 @@
1
+ """Scalar field with the shape of a Gaussian bump."""
2
+
3
+ import numpy as np
4
+
5
+ from flowfields.scalar_fields.base import ScalarField
6
+ from flowfields.utils import warn_unused_arguments
7
+
8
+
9
+ class GaussianField(ScalarField):
10
+ """
11
+ Isotropic Gaussian (radial basis) scalar field.
12
+
13
+ Returns a bell-shaped value centred at a fixed point:
14
+
15
+ f(x) = scale * exp( -||x - center||^2 / (2 * sigma^2) )
16
+
17
+ The peak value is ``scale`` at x = ``center`` and decays symmetrically in
18
+ all directions with standard deviation ``sigma``. Useful as a
19
+ smooth, spatially-localised weight.
20
+
21
+ Args:
22
+ center: Peak location.
23
+ sigma: Spread of the Gaussian; larger values produce a wider bell.
24
+ scale: Peak amplitude (default 1.0).
25
+ """
26
+
27
+ def __init__(self,
28
+ center: np.ndarray,
29
+ sigma: float = 1.0,
30
+ scale: float = 1.0,
31
+ **kwargs):
32
+ warn_unused_arguments(self, kwargs)
33
+ self.center = center
34
+ self.sigma = sigma
35
+ self.scale = scale
36
+
37
+ def __call__(self, x: np.ndarray) -> float:
38
+ """
39
+ Returns the scalar field value at point x.
40
+ """
41
+ return self.scale * np.exp(-np.sum(
42
+ (x - self.center)**2) / (2 * self.sigma**2))
@@ -0,0 +1,179 @@
1
+ """Scalar fields that read their values from a 2D array, such as an image."""
2
+
3
+ import numpy as np
4
+
5
+ from flowfields.scalar_fields.base import ScalarField
6
+ from flowfields.utils import warn_unused_arguments
7
+
8
+
9
+ class MatrixField(ScalarField):
10
+ """
11
+ Matrix-based scalar field.
12
+
13
+ This field is defined by a 2D array of scalar values, and a spatial
14
+ bounding box that maps the array indices to a region in space. The field
15
+ value at any point is obtained by bilinear interpolation of the
16
+ array values. The first row of the array is at the top of the box (the
17
+ highest y), as in an image, and the field is 0 outside the box.
18
+
19
+ Args:
20
+ min_corner: One corner of the bounding box.
21
+ max_corner: The opposite corner of the bounding box.
22
+ data: 2D array of values.
23
+ normalize: Whether to rescale ``data`` to the range [0, 1].
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ min_corner: np.ndarray,
29
+ max_corner: np.ndarray,
30
+ data: np.ndarray,
31
+ normalize: bool = False,
32
+ **kwargs,
33
+ ):
34
+ warn_unused_arguments(self, kwargs)
35
+ min_corner_ = np.minimum(min_corner, max_corner)
36
+ max_corner_ = np.maximum(min_corner, max_corner)
37
+ self.min_corner = min_corner_
38
+ self.max_corner = max_corner_
39
+ self.data = data
40
+ self.normalize = normalize
41
+ if self.normalize:
42
+ self.data = self.data - np.min(self.data)
43
+ if np.max(self.data) > 0:
44
+ self.data = self.data / np.max(self.data)
45
+
46
+ def __call__(self, x: np.ndarray) -> float:
47
+ """
48
+ Returns the scalar field value at point x.
49
+ """
50
+ if np.all(x >= self.min_corner) and np.all(x <= self.max_corner):
51
+ # Perform bilinear interpolation
52
+ t = (x - self.min_corner) / (self.max_corner - self.min_corner)
53
+ t = np.clip(t, 0.0, 1.0)
54
+
55
+ # self.data is indexed [row, col]: row grows downward (cartesian y,
56
+ # flipped) and col grows rightward (cartesian x).
57
+ rc = np.array([1.0 - t[1], t[0]]) * (np.array(self.data.shape) - 1)
58
+ i0 = np.floor(rc).astype(int)
59
+ i1 = np.ceil(rc).astype(int)
60
+ w = rc - i0
61
+ v00 = self.data[i0[0], i0[1]]
62
+ v01 = self.data[i0[0], i1[1]]
63
+ v10 = self.data[i1[0], i0[1]]
64
+ v11 = self.data[i1[0], i1[1]]
65
+ zval = (
66
+ (1 - w[0]) * (1 - w[1]) * v00
67
+ + (1 - w[0]) * w[1] * v01
68
+ + w[0] * (1 - w[1]) * v10
69
+ + w[0] * w[1] * v11
70
+ )
71
+ return zval
72
+ else:
73
+ return 0.0
74
+
75
+ def plot_figure(
76
+ self,
77
+ output_filename,
78
+ figsize=(4, 4),
79
+ dpi=100,
80
+ cmap="gray",
81
+ vmin=0,
82
+ vmax=1,
83
+ ):
84
+ """
85
+ Saves an image of the matrix with a colorbar.
86
+
87
+ Args:
88
+ output_filename: Path of the file to write.
89
+ figsize: Figure size in inches.
90
+ dpi: Figure resolution.
91
+ cmap: Matplotlib colormap name.
92
+ vmin: Value at the bottom of the colormap.
93
+ vmax: Value at the top of the colormap.
94
+
95
+ Needs matplotlib, which comes with ``pip install "flowfields[plot]"``.
96
+ """
97
+ try:
98
+ import matplotlib.pyplot as plt
99
+ except ImportError as error:
100
+ raise ImportError(
101
+ "MatrixField.plot_figure needs matplotlib: "
102
+ 'pip install "flowfields[plot]"'
103
+ ) from error
104
+
105
+ plt.figure(figsize=figsize)
106
+ plt.imshow(self.data, cmap=cmap, vmin=vmin, vmax=vmax)
107
+ plt.colorbar()
108
+ # plt.axis("off")
109
+ plt.tight_layout()
110
+ plt.savefig(output_filename, dpi=dpi)
111
+ plt.close()
112
+
113
+
114
+ class KernelProbabilisticMatrixField(MatrixField):
115
+ """
116
+ A ``MatrixField`` multiplied by a Gaussian centred on its bounding box:
117
+
118
+ f(x) = exp( -||x - c||^2 / (2 * sigma^2) ) * m(x)
119
+
120
+ where c is the centre of the box and m(x) is the ``MatrixField`` value, so
121
+ the values fade toward the borders of the box.
122
+
123
+ Args:
124
+ min_corner: One corner of the bounding box.
125
+ max_corner: The opposite corner of the bounding box.
126
+ data: 2D array of values.
127
+ normalize: Whether to rescale ``data`` to the range [0, 1].
128
+ sigma: Spread of the Gaussian, in the same units as x.
129
+ """
130
+
131
+ def __init__(
132
+ self,
133
+ min_corner: np.ndarray,
134
+ max_corner: np.ndarray,
135
+ data: np.ndarray,
136
+ normalize: bool = False,
137
+ sigma: float = 1.0,
138
+ **kwargs,
139
+ ):
140
+ warn_unused_arguments(self, kwargs)
141
+ super().__init__(
142
+ min_corner,
143
+ max_corner,
144
+ data,
145
+ normalize,
146
+ )
147
+ self.sigma = sigma
148
+
149
+ def __call__(self, x: np.ndarray) -> float:
150
+ """
151
+ Returns the scalar field value at point x.
152
+ """
153
+ if np.all(x >= self.min_corner) and np.all(x <= self.max_corner):
154
+ # Apply Gaussian kernel
155
+ center = (self.min_corner + self.max_corner) / 2
156
+ distance = np.linalg.norm(x - center)
157
+ weight = np.exp(-0.5 * (distance / self.sigma) ** 2)
158
+
159
+ # Perform bilinear interpolation
160
+ t = (x - self.min_corner) / (self.max_corner - self.min_corner)
161
+ t = np.clip(t, 0.0, 1.0)
162
+
163
+ rc = np.array([1.0 - t[1], t[0]]) * (np.array(self.data.shape) - 1)
164
+ i0 = np.floor(rc).astype(int)
165
+ i1 = np.ceil(rc).astype(int)
166
+ w = rc - i0
167
+ v00 = self.data[i0[0], i0[1]]
168
+ v01 = self.data[i0[0], i1[1]]
169
+ v10 = self.data[i1[0], i0[1]]
170
+ v11 = self.data[i1[0], i1[1]]
171
+ zval = (
172
+ (1 - w[0]) * (1 - w[1]) * v00
173
+ + (1 - w[0]) * w[1] * v01
174
+ + w[0] * (1 - w[1]) * v10
175
+ + w[0] * w[1] * v11
176
+ )
177
+ return weight * zval
178
+ else:
179
+ return 0.0