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.
@@ -0,0 +1,169 @@
1
+ """Vector field that switches randomly between its fields as it is called."""
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
+ from flowfields.vector_fields.sum import FieldSum
9
+
10
+
11
+ class FieldSelect(FlowField):
12
+ """
13
+ Stateful probabilistic field selector with optional smooth transitions.
14
+
15
+ At each call this field may stochastically switch to a new active sub-field
16
+ (or blend of sub-fields). The selection is governed by a softmax-like
17
+ distribution over the weights:
18
+
19
+ p_i(x) ∝ w_i(x)^(1 / (1 + T))
20
+
21
+ where T = ``temperature``. T = 0 keeps the raw weight ratios; larger T
22
+ flattens the distribution toward uniform, making all fields equally likely.
23
+
24
+ ``select_n`` fields are drawn without replacement from this distribution and
25
+ combined via ``FieldSum`` to form the active field.
26
+
27
+ **Switching**: with probability ``change_id_prob`` at each call a new set of
28
+ ``select_n`` fields is sampled (using weights evaluated at the current x).
29
+ The first set is sampled on the first call, with the weights at that
30
+ point.
31
+
32
+ **Interpolation**: when ``lerp_len > 0`` a transition between the outgoing
33
+ and incoming active field is linearly interpolated over ``lerp_len`` calls:
34
+
35
+ v(x) = (1 - t) * v_current(x) + t * v_next(x), t = step / lerp_len
36
+
37
+ After ``lerp_len`` steps the new field becomes the current field.
38
+
39
+ If ``normalize=True`` (default) the final vector is divided by its L2 norm.
40
+
41
+ Args:
42
+ fields: List of candidate ``FlowField`` instances.
43
+ weights: Per-field scalar or ``ScalarField`` weights used as selection
44
+ probabilities. ``None`` makes all fields equally likely.
45
+ select_n: Number of fields to blend at each active selection. Fewer
46
+ are used if fewer fields have a non-zero weight at that point.
47
+ change_id_prob: Probability of resampling the active field on each call.
48
+ temperature: Controls distribution flatness; 0 = proportional to weight,
49
+ higher values = more uniform.
50
+ normalize: Whether to L2-normalise the output vector. The active
51
+ fields are always normalised, so ``False`` only keeps the length
52
+ of vectors interpolated during a transition.
53
+ lerp_len: Number of steps over which to interpolate between field
54
+ transitions. 0 = instantaneous switch.
55
+ rng: Random generator, or a seed for one. ``None`` takes a fresh
56
+ seed from the operating system.
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ fields: list[FlowField],
62
+ weights: None | list[float] | list[ScalarField] = None,
63
+ select_n: int = 1,
64
+ change_id_prob: float = 0.1,
65
+ temperature: float = 0.0,
66
+ normalize: bool = True,
67
+ lerp_len: int = 0,
68
+ rng: np.random.Generator | int | None = None,
69
+ **kwargs,
70
+ ):
71
+ warn_unused_arguments(self, kwargs)
72
+ self.list_of_fields = fields
73
+ self.weights = weights
74
+ self.change_id_prob = change_id_prob
75
+ self.normalize = normalize
76
+ self.select_n = select_n
77
+ self.temperature = temperature
78
+ self.lerp_len = lerp_len
79
+ self.lerp_count = 0
80
+ self.rng = np.random.default_rng(rng)
81
+
82
+ # The first fields are drawn on the first call, where the weights can
83
+ # be evaluated
84
+ self.last_idx = None
85
+ self.current_field = None
86
+ self.next_field = None
87
+
88
+ def select_index(self, x: np.ndarray | None = None) -> np.ndarray:
89
+ """
90
+ Draws the indices of the fields to activate.
91
+
92
+ Args:
93
+ x: Point where the weights are evaluated. If None, or if the field
94
+ has no weights, all fields are equally likely. The same happens
95
+ if every weight is zero at x.
96
+
97
+ Returns:
98
+ Array with the drawn indices, without repetition.
99
+ """
100
+ magnitudes = []
101
+
102
+ for idx, _ in enumerate(self.list_of_fields):
103
+
104
+ if self.weights is not None and x is not None:
105
+ if isinstance(self.weights[idx], ScalarField):
106
+ weight_value = self.weights[idx](x)
107
+ else:
108
+ weight_value = self.weights[idx]
109
+
110
+ magnitudes.append(weight_value)
111
+ else:
112
+ magnitudes.append(1.0)
113
+
114
+ magnitudes = np.array(magnitudes, dtype=float)
115
+ total = np.sum(magnitudes)
116
+ # If every weight is zero here, fall back to a uniform choice
117
+ p = magnitudes / total if total > 0 else np.full(len(magnitudes), 1.0 / len(magnitudes))
118
+ # Apply temperature to p, where higher temperature makes distribution more uniform
119
+ if self.temperature > 0:
120
+ p = p**(1.0 / (1.0 + self.temperature))
121
+ p = p / np.sum(p)
122
+
123
+ idx = self.rng.choice(
124
+ len(self.list_of_fields),
125
+ p=p,
126
+ # Fields with zero probability are never drawn, even if that means
127
+ # blending fewer than select_n fields
128
+ size=min(self.select_n, np.count_nonzero(p)),
129
+ replace=False,
130
+ )
131
+ return idx
132
+
133
+ def __call__(
134
+ self,
135
+ x: np.ndarray,
136
+ ) -> np.ndarray:
137
+ """
138
+ Returns the flowfield vector at point x.
139
+ """
140
+ if (self.last_idx is None\
141
+ or self.rng.random() < self.change_id_prob)\
142
+ and self.lerp_count == 0:
143
+ self.last_idx = self.select_index(x).tolist()
144
+ fields = [self.list_of_fields[i] for i in self.last_idx]
145
+ weights = [self.weights[i] for i in self.last_idx] if self.weights is not None else None
146
+ self.next_field = FieldSum(
147
+ fields=fields,
148
+ weights=weights,
149
+ )
150
+ self.lerp_count = 0
151
+ if self.current_field is None: # first call: no transition
152
+ self.current_field = self.next_field
153
+
154
+ if self.current_field is self.next_field:
155
+ y = self.current_field(x)
156
+ elif self.lerp_count < self.lerp_len:
157
+ t = self.lerp_count / self.lerp_len
158
+ y = (1 - t) * self.current_field(x) + t * self.next_field(x)
159
+ self.lerp_count += 1
160
+ else:
161
+ # The transition is over: the new field is used from this call on
162
+ self.current_field = self.next_field
163
+ self.lerp_count = 0
164
+ y = self.current_field(x)
165
+
166
+ if self.normalize:
167
+ y = normalize_vector(y)
168
+
169
+ return y
@@ -0,0 +1,66 @@
1
+ """Vector field that adds its fields with weights."""
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 FieldSum(FlowField):
11
+ """
12
+ Weighted linear combination of multiple flow fields.
13
+
14
+ At each point x the output is the sum of all constituent field vectors,
15
+ each scaled by its corresponding weight:
16
+
17
+ v(x) = sum_i w_i(x) * F_i(x)
18
+
19
+ Each weight ``w_i`` can be:
20
+ - ``float`` — a fixed scalar multiplier.
21
+ - ``ScalarField`` — a position-dependent multiplier evaluated at x,
22
+ allowing spatially-varying blending.
23
+
24
+ If ``normalize=True`` (default) the summed vector is divided by its L2
25
+ norm so that ||v(x)|| = 1.
26
+
27
+ Args:
28
+ fields: The ``FlowField`` instances to add.
29
+ weights: One weight per field. ``None`` gives all fields weight 1.
30
+ normalize: Whether to L2-normalise the output vector.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ fields: list[FlowField],
36
+ weights: None | list[float] | list[ScalarField] = None,
37
+ normalize: bool = True,
38
+ **kwargs,
39
+ ):
40
+ warn_unused_arguments(self, kwargs)
41
+ self.list_of_fields = fields
42
+ self.weights = weights
43
+ self.normalize = normalize
44
+
45
+ def __call__(
46
+ self,
47
+ x: np.ndarray,
48
+ ) -> np.ndarray:
49
+ """
50
+ Returns the flowfield vector at point x.
51
+ """
52
+ y = np.zeros_like(x, dtype=float)
53
+ for idx, field in enumerate(self.list_of_fields):
54
+ y_ = field(x) * 1.0
55
+ if self.weights is not None:
56
+ if isinstance(self.weights[idx], ScalarField):
57
+ weight_value = self.weights[idx](x)
58
+ else:
59
+ weight_value = self.weights[idx]
60
+ y_ *= weight_value
61
+
62
+ y += y_
63
+ if self.normalize:
64
+ y = normalize_vector(y)
65
+
66
+ return y
@@ -0,0 +1,187 @@
1
+ Metadata-Version: 2.4
2
+ Name: flowfields
3
+ Version: 0.2.0
4
+ Summary: Tools for artwork by composing flow fields
5
+ Author: Tiago Tavares
6
+ License-Expression: AGPL-3.0-or-later
7
+ Project-URL: Homepage, https://github.com/tiagoft/flowfields
8
+ Project-URL: Source, https://github.com/tiagoft/flowfields
9
+ Project-URL: Issues, https://github.com/tiagoft/flowfields/issues
10
+ Project-URL: Demos, https://github.com/tiagoft/flowfields/blob/main/demos/README.md
11
+ Project-URL: Author, https://github.com/tiagoft
12
+ Keywords: generative art,flow field,vector field,creative coding,p5.js
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Other Audience
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Artistic Software
24
+ Classifier: Topic :: Multimedia :: Graphics
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: numpy>=1.24
30
+ Requires-Dist: pillow>=10.0
31
+ Provides-Extra: plot
32
+ Requires-Dist: matplotlib>=3.7; extra == "plot"
33
+ Dynamic: license-file
34
+
35
+ # flowfields
36
+
37
+ [![tests](https://github.com/tiagoft/flowfields/actions/workflows/tests.yml/badge.svg)](https://github.com/tiagoft/flowfields/actions/workflows/tests.yml)
38
+ [![coverage](https://raw.githubusercontent.com/tiagoft/flowfields/badges/coverage.svg)](https://github.com/tiagoft/flowfields/actions/workflows/tests.yml)
39
+
40
+ ![An image of the Eiffel tower drawn with colored lines that follow a tree of fields](https://raw.githubusercontent.com/tiagoft/flowfields/main/demos/outputs/16-field_tree.png)
41
+
42
+ A generative-art toolkit built around composable **vector fields** and **scalar fields**. Fields form trees (similar to syntax trees): leaf nodes are primitives and internal nodes are combinators. It comes in Python and as a [p5.js](https://p5js.org) library.
43
+
44
+ See the [demos](https://github.com/tiagoft/flowfields/blob/main/demos/README.md) for a small script and a figure for each feature.
45
+
46
+ ## Installation
47
+
48
+ ### Python
49
+
50
+ ```bash
51
+ pip install flowfields
52
+ # or
53
+ uv add flowfields
54
+ ```
55
+
56
+ The library needs only numpy and Pillow. `MatrixField.plot_figure` also needs
57
+ matplotlib, which comes with the `plot` extra:
58
+
59
+ ```bash
60
+ pip install "flowfields[plot]"
61
+ ```
62
+
63
+ To get the latest version from GitHub instead:
64
+
65
+ ```bash
66
+ pip install git+https://github.com/tiagoft/flowfields.git
67
+ ```
68
+
69
+ ### p5.js
70
+
71
+ `flowfields.js` needs p5.js 2.x. Load it after p5:
72
+
73
+ ```html
74
+ <script src="https://cdn.jsdelivr.net/npm/p5@2.4.0/lib/p5.min.js"></script>
75
+ <script src="https://cdn.jsdelivr.net/gh/tiagoft/flowfields@main/js/flowfields.js"></script>
76
+ ```
77
+
78
+ Build fields inside `setup()` or later. The [JS README](https://github.com/tiagoft/flowfields/blob/main/js/README.md) shows how
79
+ the Python API maps to JS, and [`js/examples/`](https://github.com/tiagoft/flowfields/tree/main/js/examples) has sketches.
80
+
81
+ ### Running the demos
82
+
83
+ ```bash
84
+ git clone https://github.com/tiagoft/flowfields.git
85
+ cd flowfields
86
+ uv run python demos/16-field_tree.py
87
+ ```
88
+
89
+ ---
90
+
91
+ ## Concepts
92
+
93
+ ### Scalar fields — `flowfields.scalar_fields`
94
+
95
+ A scalar field maps a 2-D point to a single float: `f(x) → float`. They are used as spatial weights inside composite vector fields.
96
+
97
+ | Class | Equation |
98
+ | --- | --- |
99
+ | `GaussianField(center, sigma, scale)` | `f(x) = scale · exp(−‖x − center‖² / 2σ²)` |
100
+ | `ConstantField(value)` | `f(x) = value` |
101
+ | `BoxField(min_corner, max_corner, inside_value, outside_value)` | `inside_value` if `x` is inside the box, else `outside_value` |
102
+
103
+ ### Vector fields — `flowfields.vector_fields`
104
+
105
+ A vector field maps a 2-D point to a 2-D vector: `F(x) → np.ndarray`. Most fields accept `normalize=True` (default) to return a unit vector.
106
+
107
+ #### Primitive fields
108
+
109
+ | Class | Equation |
110
+ | --- | --- |
111
+ | `RotationField(center, direction)` | `v(x) = direction · [−rᵧ, rₓ]` where `r = x − center` |
112
+ | `ExpansionField(center, direction)` | `v(x) = direction · (x − center)` |
113
+ | `NoiseField(distribution)` | `v ~ Normal(0, 1)ⁿ` by default, or `v ~ Uniform(−1, 1)ⁿ` with `distribution="uniform"` (fresh sample every call) |
114
+
115
+ #### Composite fields — combine other fields into a tree
116
+
117
+ | Class | Behaviour |
118
+ | --- | --- |
119
+ | `FieldSum(fields, weights)` | `v(x) = Σᵢ wᵢ(x) · Fᵢ(x)` — weighted linear blend |
120
+ | `FieldMax(fields, weights)` | `v(x) = F_{argmax wᵢ(x)}(x)` — hard winner-take-all |
121
+ | `FieldSelect(fields, weights, ...)` | probabilistic selection; switches fields over time with optional linear interpolation |
122
+
123
+ Weights can be a plain `float`, a `ScalarField` instance (position-dependent), or `None` (equal weights).
124
+
125
+ ---
126
+
127
+ ## Basic usage
128
+
129
+ ```python
130
+ import numpy as np
131
+ import flowfields.scalar_fields as sf
132
+ import flowfields.vector_fields as vf
133
+
134
+ field = vf.FieldSum(
135
+ fields=[
136
+ vf.RotationField(np.array([2.0, 0.0])),
137
+ vf.RotationField(np.array([-5.0, 0.0]), direction=-1),
138
+ vf.ExpansionField(np.array([2.0, -6.0])),
139
+ ],
140
+ weights=[
141
+ sf.GaussianField(np.array([1.0, 0.0]), sigma=3.0),
142
+ sf.ConstantField(0.2),
143
+ sf.ConstantField(0.5),
144
+ ],
145
+ )
146
+
147
+ x = np.array([1.0, 0.5])
148
+ v = field(x) # unit vector at point x
149
+ ```
150
+
151
+ ### Swapping fields
152
+
153
+ Fields accept keyword arguments they do not use, so one field type can
154
+ replace another with a slightly different API. Each unused argument gives an
155
+ `UnusedArgumentWarning`, which also catches typos:
156
+
157
+ ```python
158
+ vf.RotationField(center, normalise=False)
159
+ # UnusedArgumentWarning: RotationField ignores the argument 'normalise' (did you mean 'normalize'?)
160
+ ```
161
+
162
+ To swap fields on purpose without the warning:
163
+
164
+ ```python
165
+ import warnings
166
+ import flowfields
167
+
168
+ warnings.simplefilter("ignore", flowfields.UnusedArgumentWarning)
169
+ ```
170
+
171
+ ## Gallery
172
+
173
+ Pieces made with flowfields for [Genuary 2026](https://genuary.art). Click an image to see its code.
174
+
175
+ | | | |
176
+ | --- | --- | --- |
177
+ | [![Genuary 03](https://raw.githubusercontent.com/tiagoft/flowfields/main/artwork/genuary2026/images/genuary03.jpg)](https://github.com/tiagoft/flowfields/blob/main/artwork/genuary2026/genuary03.py) | [![Genuary 08](https://raw.githubusercontent.com/tiagoft/flowfields/main/artwork/genuary2026/images/genuary08.jpg)](https://github.com/tiagoft/flowfields/blob/main/artwork/genuary2026/genuary08.py) | [![Genuary 12](https://raw.githubusercontent.com/tiagoft/flowfields/main/artwork/genuary2026/images/genuary12.jpg)](https://github.com/tiagoft/flowfields/blob/main/artwork/genuary2026/genuary12.py) |
178
+ | [![Genuary 16](https://raw.githubusercontent.com/tiagoft/flowfields/main/artwork/genuary2026/images/genuary16.jpg)](https://github.com/tiagoft/flowfields/blob/main/artwork/genuary2026/genuary16.py) | [![Genuary 19](https://raw.githubusercontent.com/tiagoft/flowfields/main/artwork/genuary2026/images/genuary19.jpg)](https://github.com/tiagoft/flowfields/blob/main/artwork/genuary2026/genuary19.py) | [![Genuary 25](https://raw.githubusercontent.com/tiagoft/flowfields/main/artwork/genuary2026/images/genuary25.jpg)](https://github.com/tiagoft/flowfields/blob/main/artwork/genuary2026/genuary25.py) |
179
+
180
+ All pieces are in [`artwork/genuary2026`](https://github.com/tiagoft/flowfields/tree/main/artwork/genuary2026).
181
+
182
+ ## License
183
+
184
+ flowfields is free software, released under the
185
+ [GNU Affero General Public License v3.0 or later](https://github.com/tiagoft/flowfields/blob/main/LICENSE). Images and other
186
+ works you make with it are yours; programs that use or modify the library,
187
+ including sketches served on the web, must be shared under the same license.
@@ -0,0 +1,25 @@
1
+ flowfields/__init__.py,sha256=7abBZM2ZCfqSmuhJdl7ZjsJYvXGpV1cUJWXOwX-vDb0,1681
2
+ flowfields/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ flowfields/utils.py,sha256=EJOQMy8fzR6BnT69O3pglYeDYo-HYCSlq1XWTDzUKqM,9071
4
+ flowfields/color_fields/__init__.py,sha256=aCkO3BXQykBQcvAK8IjwwG4PvbQRD6_XYaHm2kfYnBo,257
5
+ flowfields/color_fields/base.py,sha256=A7xT90tyi_N5Joro-0MF0Xw2B1F-5FRyokcIioDEF8c,611
6
+ flowfields/color_fields/matrixcolorfield.py,sha256=NejM9aOI8PYjsLtoKq9qGoxOAGPm7GorwVUMBMiHx1E,5312
7
+ flowfields/scalar_fields/__init__.py,sha256=56x0yyRAak7sGbK5p8W1lLLjhtXWSZPWjnM5FG8x-oI,541
8
+ flowfields/scalar_fields/base.py,sha256=byyQoje3KXRT9jiVwk1r_zI5fFmHzyJ_59-Efd_8aVc,696
9
+ flowfields/scalar_fields/box.py,sha256=kQJQzK5LiqLy4Rlr4yMojZcCRTmW4rk66k4q13TJOvA,1822
10
+ flowfields/scalar_fields/constant.py,sha256=PEca9pIUUHXgtiX72H-T9WJdpuMrKwWVuIYb0AiLXWc,805
11
+ flowfields/scalar_fields/gaussian.py,sha256=OqwbJhz2llvImg8cli2HI_iU4ChGl5xtCHHsZxDc564,1273
12
+ flowfields/scalar_fields/matrix.py,sha256=n1xYHio1q30zG2Wr_0QNQs9zfFdyKKTSaQcP-N0lS9E,5990
13
+ flowfields/vector_fields/__init__.py,sha256=M3GmeeA8f6mLc025LdnfnVXRzBqwytmSXHCTUSS73wY,608
14
+ flowfields/vector_fields/base.py,sha256=1phS_MLytKbGF-Z1DLtYVOvwspv36tjAy1pm2ohzL64,730
15
+ flowfields/vector_fields/expansion.py,sha256=wbWdBqOsUFE-pLUaCxI5P8skGLI4AYPv8Oot22kJc-E,1615
16
+ flowfields/vector_fields/max.py,sha256=mZgjz-8iYGLiEjkdqgKLR-VnhhwZlFaLe2KUQaMGQyQ,2233
17
+ flowfields/vector_fields/noise.py,sha256=H4f93ncf8dCyJayA13mIEKxPXHxijp8Fo6fBo-ZYDzw,2157
18
+ flowfields/vector_fields/rotation.py,sha256=v0CAHV4Wd6Niw7fmSxeDBCKWct2QXFbMZa44FsvRfjs,1681
19
+ flowfields/vector_fields/select.py,sha256=vs83yzjAJGnECS7r1eE7230i72rd9DxdlQoPw0m89bg,6622
20
+ flowfields/vector_fields/sum.py,sha256=YSSjJu5S_hkB6aYUeF8TjtteXF9_P3heTmgEqlBZFdc,2025
21
+ flowfields-0.2.0.dist-info/licenses/LICENSE,sha256=DZak_2itbUtvHzD3E7GNUYSRK6jdOJ-GqncQ2weavLA,34523
22
+ flowfields-0.2.0.dist-info/METADATA,sha256=pMoeNQhTDuIn20aOkKhLQzFbu4AzRZzXqrJ1NtGljjs,7804
23
+ flowfields-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
24
+ flowfields-0.2.0.dist-info/top_level.txt,sha256=RdNPsPkRofvH6U16Mq1q6zghvuq4nIiYIwsBM1Knn3Q,11
25
+ flowfields-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+