vicflow 0.1.0__tar.gz → 0.2.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: vicflow
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: GPU-accelerated 2D vortex-in-cell fluid simulator for generative art
5
5
  Keywords: fluid simulation,vortex-in-cell,generative art,cfd,gpu,pytorch,metal,triton
6
6
  Author: Quentin
@@ -34,6 +34,14 @@ Description-Content-Type: text/markdown
34
34
 
35
35
  # vicflow
36
36
 
37
+ [![PyPI](https://img.shields.io/pypi/v/vicflow)](https://pypi.org/project/vicflow/)
38
+ [![Python](https://img.shields.io/pypi/pyversions/vicflow)](https://pypi.org/project/vicflow/)
39
+ [![Downloads per month](https://static.pepy.tech/badge/vicflow/month)](https://pepy.tech/projects/vicflow)
40
+ [![Total downloads](https://static.pepy.tech/badge/vicflow)](https://pepy.tech/projects/vicflow)
41
+ [![CI](https://github.com/petitquentin/vicflow/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/petitquentin/vicflow/actions/workflows/ci.yml?query=branch%3Amain)
42
+ [![License](https://img.shields.io/pypi/l/vicflow)](https://github.com/petitquentin/vicflow/blob/main/LICENSE)
43
+ [![GitHub stars](https://img.shields.io/github/stars/petitquentin/vicflow)](https://github.com/petitquentin/vicflow/stargazers)
44
+
37
45
  GPU-accelerated 2D vortex-in-cell fluid simulator for generative art. High-Reynolds flows on CUDA, ROCm and Apple Silicon. Based on Mark J. Stock's [vic2d](https://github.com/markstock/vic2d).
38
46
 
39
47
  > **Status: early development.** What exists today is the solver on
@@ -147,6 +155,64 @@ sim.run(500)
147
155
  write_image("frame.png", sim.color, bits=16)
148
156
  ```
149
157
 
158
+ The time step can follow the flow: with `courant`, `dt` becomes the largest
159
+ step, and each step is shortened so that the fastest fluid moves at most
160
+ `courant` cells. This suits runs that start at rest and speed up, such as
161
+ Rayleigh-Taylor. `run_until` shortens the last steps to land exactly on a
162
+ time, for frames evenly spaced in time:
163
+
164
+ ```python
165
+ sim = Simulation(
166
+ grid,
167
+ np.zeros(grid.shape),
168
+ viscosity=1e-5,
169
+ dt=0.01, # the largest step
170
+ density=density,
171
+ courant=2.0, # at most 2 cells per step
172
+ )
173
+ for frame in range(1, 101):
174
+ sim.run_until(0.05 * frame)
175
+ write_image(f"frame{frame:03d}.png", sim.density, vmin=-1, vmax=1)
176
+ print(sim.step_count, sim.last_dt)
177
+ ```
178
+
179
+ ## Scenes, palettes and recipes
180
+
181
+ *Experimental: these modules may still change between minor versions, and
182
+ with them the images they make.*
183
+
184
+ `vicflow.recipes` holds complete scenes with tested parameters. Each recipe
185
+ returns the arguments of `Simulation`, grid included, so any of them can be
186
+ overridden:
187
+
188
+ ```python
189
+ from vicflow import Simulation, recipes
190
+
191
+ scene = recipes.rayleigh_taylor(1024, palette="ink", seed=3)
192
+ sim = Simulation(**scene, backend="torch")
193
+ sim.run(round(recipes.DURATIONS["rayleigh_taylor"] / sim.dt))
194
+ ```
195
+
196
+ The recipes are `stripes` (thin buoyant color stripes, after Mark J. Stock's
197
+ run19 and run27 images), `rayleigh_taylor` and `turbulence`; the
198
+ [`examples/`](https://github.com/petitquentin/vicflow/tree/main/examples)
199
+ scripts render them.
200
+
201
+ `vicflow.scenes` has the building blocks: color `bands` and `stripes`,
202
+ wavy `interface`s and `layers`, `vortex`, `dipole`, `shear_layer`, random
203
+ `turbulence` and smooth `noise`, and `density_from_luminance`. They return
204
+ NumPy arrays to combine freely. Lengths are in domain units and random
205
+ patterns depend on the seed only, so a scene starts the same at 256 cells as
206
+ at 4096: the coarse run is a quick preview of the fine one while the flow is
207
+ young, before turbulence makes them drift apart.
208
+
209
+ `vicflow.palettes` has the color lists they paint with: built-in palettes
210
+ (`palettes.names()`), your own (`["#15161d", "#23356b", ...]` or RGB
211
+ triples), or a matplotlib colormap (`Palette.from_matplotlib("magma")`).
212
+ Colors are interpolated in Oklab, so gradients look even.
213
+
214
+ ## GPU
215
+
150
216
  On a GPU, install the `torch` extra (`pip install "vicflow[torch]"`) and pick
151
217
  the PyTorch backend; it uses CUDA or Apple's MPS when available, in float32,
152
218
  with a fused advection kernel (Triton on NVIDIA, Metal on Apple Silicon; AMD/ROCm
@@ -177,12 +243,17 @@ sim = Simulation(
177
243
  )
178
244
  ```
179
245
 
246
+ vic2d's `-cn` is a fixed `dt = cn / n` on an `n`-cell grid. Its `-constcn` uses
247
+ the same units as `courant` (cells per step) but another rule to pick the
248
+ step, so adaptive steps are not reproduced exactly.
249
+
180
250
  `time_order=1` is about 20 % faster, but its kinetic energy drifts upwards at
181
251
  large time steps and it can blow up next to walls.
182
252
 
183
253
  ## Public API
184
254
 
185
- `Grid`, `Simulation` and the `vicflow.image` module. The other modules
255
+ `Grid`, `Simulation` and the `vicflow.image` module; `vicflow.scenes`,
256
+ `vicflow.palettes` and `vicflow.recipes` are public but experimental. The other modules
186
257
  (`vicflow.poisson`, `vicflow.advect`, `vicflow.backends`, ...) are internal and
187
258
  may change between versions.
188
259
 
@@ -1,5 +1,13 @@
1
1
  # vicflow
2
2
 
3
+ [![PyPI](https://img.shields.io/pypi/v/vicflow)](https://pypi.org/project/vicflow/)
4
+ [![Python](https://img.shields.io/pypi/pyversions/vicflow)](https://pypi.org/project/vicflow/)
5
+ [![Downloads per month](https://static.pepy.tech/badge/vicflow/month)](https://pepy.tech/projects/vicflow)
6
+ [![Total downloads](https://static.pepy.tech/badge/vicflow)](https://pepy.tech/projects/vicflow)
7
+ [![CI](https://github.com/petitquentin/vicflow/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/petitquentin/vicflow/actions/workflows/ci.yml?query=branch%3Amain)
8
+ [![License](https://img.shields.io/pypi/l/vicflow)](https://github.com/petitquentin/vicflow/blob/main/LICENSE)
9
+ [![GitHub stars](https://img.shields.io/github/stars/petitquentin/vicflow)](https://github.com/petitquentin/vicflow/stargazers)
10
+
3
11
  GPU-accelerated 2D vortex-in-cell fluid simulator for generative art. High-Reynolds flows on CUDA, ROCm and Apple Silicon. Based on Mark J. Stock's [vic2d](https://github.com/markstock/vic2d).
4
12
 
5
13
  > **Status: early development.** What exists today is the solver on
@@ -113,6 +121,64 @@ sim.run(500)
113
121
  write_image("frame.png", sim.color, bits=16)
114
122
  ```
115
123
 
124
+ The time step can follow the flow: with `courant`, `dt` becomes the largest
125
+ step, and each step is shortened so that the fastest fluid moves at most
126
+ `courant` cells. This suits runs that start at rest and speed up, such as
127
+ Rayleigh-Taylor. `run_until` shortens the last steps to land exactly on a
128
+ time, for frames evenly spaced in time:
129
+
130
+ ```python
131
+ sim = Simulation(
132
+ grid,
133
+ np.zeros(grid.shape),
134
+ viscosity=1e-5,
135
+ dt=0.01, # the largest step
136
+ density=density,
137
+ courant=2.0, # at most 2 cells per step
138
+ )
139
+ for frame in range(1, 101):
140
+ sim.run_until(0.05 * frame)
141
+ write_image(f"frame{frame:03d}.png", sim.density, vmin=-1, vmax=1)
142
+ print(sim.step_count, sim.last_dt)
143
+ ```
144
+
145
+ ## Scenes, palettes and recipes
146
+
147
+ *Experimental: these modules may still change between minor versions, and
148
+ with them the images they make.*
149
+
150
+ `vicflow.recipes` holds complete scenes with tested parameters. Each recipe
151
+ returns the arguments of `Simulation`, grid included, so any of them can be
152
+ overridden:
153
+
154
+ ```python
155
+ from vicflow import Simulation, recipes
156
+
157
+ scene = recipes.rayleigh_taylor(1024, palette="ink", seed=3)
158
+ sim = Simulation(**scene, backend="torch")
159
+ sim.run(round(recipes.DURATIONS["rayleigh_taylor"] / sim.dt))
160
+ ```
161
+
162
+ The recipes are `stripes` (thin buoyant color stripes, after Mark J. Stock's
163
+ run19 and run27 images), `rayleigh_taylor` and `turbulence`; the
164
+ [`examples/`](https://github.com/petitquentin/vicflow/tree/main/examples)
165
+ scripts render them.
166
+
167
+ `vicflow.scenes` has the building blocks: color `bands` and `stripes`,
168
+ wavy `interface`s and `layers`, `vortex`, `dipole`, `shear_layer`, random
169
+ `turbulence` and smooth `noise`, and `density_from_luminance`. They return
170
+ NumPy arrays to combine freely. Lengths are in domain units and random
171
+ patterns depend on the seed only, so a scene starts the same at 256 cells as
172
+ at 4096: the coarse run is a quick preview of the fine one while the flow is
173
+ young, before turbulence makes them drift apart.
174
+
175
+ `vicflow.palettes` has the color lists they paint with: built-in palettes
176
+ (`palettes.names()`), your own (`["#15161d", "#23356b", ...]` or RGB
177
+ triples), or a matplotlib colormap (`Palette.from_matplotlib("magma")`).
178
+ Colors are interpolated in Oklab, so gradients look even.
179
+
180
+ ## GPU
181
+
116
182
  On a GPU, install the `torch` extra (`pip install "vicflow[torch]"`) and pick
117
183
  the PyTorch backend; it uses CUDA or Apple's MPS when available, in float32,
118
184
  with a fused advection kernel (Triton on NVIDIA, Metal on Apple Silicon; AMD/ROCm
@@ -143,12 +209,17 @@ sim = Simulation(
143
209
  )
144
210
  ```
145
211
 
212
+ vic2d's `-cn` is a fixed `dt = cn / n` on an `n`-cell grid. Its `-constcn` uses
213
+ the same units as `courant` (cells per step) but another rule to pick the
214
+ step, so adaptive steps are not reproduced exactly.
215
+
146
216
  `time_order=1` is about 20 % faster, but its kinetic energy drifts upwards at
147
217
  large time steps and it can blow up next to walls.
148
218
 
149
219
  ## Public API
150
220
 
151
- `Grid`, `Simulation` and the `vicflow.image` module. The other modules
221
+ `Grid`, `Simulation` and the `vicflow.image` module; `vicflow.scenes`,
222
+ `vicflow.palettes` and `vicflow.recipes` are public but experimental. The other modules
152
223
  (`vicflow.poisson`, `vicflow.advect`, `vicflow.backends`, ...) are internal and
153
224
  may change between versions.
154
225
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "vicflow"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "GPU-accelerated 2D vortex-in-cell fluid simulator for generative art"
5
5
  readme = "README.md"
6
6
  license = "GPL-3.0-or-later"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "vicflow"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "GPU-accelerated 2D vortex-in-cell fluid simulator for generative art"
5
5
  readme = "README.md"
6
6
  license = "GPL-3.0-or-later"
@@ -2,11 +2,11 @@
2
2
 
3
3
  from importlib.metadata import PackageNotFoundError, version
4
4
 
5
- from . import image
5
+ from . import image, palettes, recipes, scenes
6
6
  from .grid import Grid
7
7
  from .solver import Simulation
8
8
 
9
- __all__ = ["Grid", "Simulation", "image"]
9
+ __all__ = ["Grid", "Simulation", "image", "palettes", "recipes", "scenes"]
10
10
  try:
11
11
  __version__ = version("vicflow")
12
12
  except PackageNotFoundError: # running from a source tree that is not installed
@@ -112,6 +112,19 @@ def interpolate(
112
112
  return out
113
113
 
114
114
 
115
+ def extrapolate(now, prev, dt: float, dt_prev: float | None = None):
116
+ """Velocity extrapolated linearly in time to ``t + dt/2`` and ``t + dt``.
117
+
118
+ ``now`` is the velocity at ``t``, ``prev`` the one at ``t - dt_prev``
119
+ (``dt_prev`` defaults to ``dt``). Works on NumPy arrays and torch tensors.
120
+ """
121
+ if dt_prev is None or dt_prev == dt:
122
+ return 1.5 * now - 0.5 * prev, 2 * now - prev # the same, rounded as before
123
+ r = dt / dt_prev
124
+ slope = now - prev
125
+ return now + (0.5 * r) * slope, now + r * slope
126
+
127
+
115
128
  def backtrace_rk4(
116
129
  u: np.ndarray,
117
130
  v: np.ndarray,
@@ -120,6 +133,7 @@ def backtrace_rk4(
120
133
  u_prev: np.ndarray | None = None,
121
134
  v_prev: np.ndarray | None = None,
122
135
  walls: tuple[bool, bool] = (False, False),
136
+ dt_prev: float | None = None,
123
137
  ) -> tuple[np.ndarray, np.ndarray]:
124
138
  """Departure points of every node after one RK4 step backwards in time.
125
139
 
@@ -128,8 +142,8 @@ def backtrace_rk4(
128
142
 
129
143
  Without ``u_prev, v_prev`` the velocity is frozen at ``(u, v)`` over the
130
144
  step, as in vic2d (first order in time). With the velocities of the
131
- previous step, at ``t - dt``, it is extrapolated linearly in time to
132
- ``t + dt/2`` and ``t + dt`` (second order).
145
+ previous step, at ``t - dt_prev`` (``dt_prev`` defaults to ``dt``), it is
146
+ extrapolated linearly in time to ``t + dt/2`` and ``t + dt`` (second order).
133
147
 
134
148
  Returns the departure positions in grid-index units.
135
149
  """
@@ -140,9 +154,7 @@ def backtrace_rk4(
140
154
  if u_prev is None or v_prev is None:
141
155
  vel_end = vel_mid = vel_now
142
156
  else:
143
- vel_prev = np.stack([u_prev, v_prev])
144
- vel_end = 2 * vel_now - vel_prev # at t + dt
145
- vel_mid = 1.5 * vel_now - 0.5 * vel_prev # at t + dt/2
157
+ vel_mid, vel_end = extrapolate(vel_now, np.stack([u_prev, v_prev]), dt, dt_prev)
146
158
 
147
159
  k1 = vel_end # the nodes themselves: no interpolation needed
148
160
  k2 = interpolate(vel_mid, x - 0.5 * s * k1[0], y - 0.5 * s * k1[1], walls)
@@ -163,11 +175,12 @@ def advect(
163
175
  v_prev: np.ndarray | None = None,
164
176
  walls: tuple[bool, bool] = (False, False),
165
177
  limit_from: int | None = None,
178
+ dt_prev: float | None = None,
166
179
  ) -> np.ndarray:
167
180
  """Advect fields of shape ``(k, nx, ny)`` by one time step.
168
181
 
169
- See ``backtrace_rk4`` for the meaning of ``u_prev, v_prev``, and
182
+ See ``backtrace_rk4`` for the meaning of ``u_prev, v_prev, dt_prev``, and
170
183
  ``interpolate`` for ``limit_from``. The velocity is never limited.
171
184
  """
172
- px, py = backtrace_rk4(u, v, dt, h, u_prev, v_prev, walls)
185
+ px, py = backtrace_rk4(u, v, dt, h, u_prev, v_prev, walls, dt_prev)
173
186
  return interpolate(fields, px, py, walls, limit_from)
@@ -38,6 +38,6 @@ class NumpyBackend:
38
38
  def diffuse(self, field, nu, dt, h):
39
39
  return _diffusion.diffuse(field, nu, dt, h, self.grid.walls)
40
40
 
41
- def advect(self, fields, u, v, dt, h, u_prev=None, v_prev=None, limit_from=None):
41
+ def advect(self, fields, u, v, dt, h, u_prev=None, v_prev=None, limit_from=None, dt_prev=None):
42
42
  walls = self.grid.walls
43
- return _advect.advect(fields, u, v, dt, h, u_prev, v_prev, walls, limit_from)
43
+ return _advect.advect(fields, u, v, dt, h, u_prev, v_prev, walls, limit_from, dt_prev)
@@ -29,6 +29,7 @@ import warnings
29
29
  import numpy as np
30
30
  import torch
31
31
 
32
+ from ..advect import extrapolate
32
33
  from ..diffusion import MAX_DIFFUSION_NUMBER
33
34
  from ..grid import Grid
34
35
  from ..poisson import Poisson, Scheme
@@ -332,13 +333,14 @@ class TorchBackend:
332
333
  dy = -s * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1]) / 6
333
334
  return interpolate(fields, dx, dy, ix, iy, walls, limit_from)
334
335
 
335
- def advect(self, fields, u, v, dt, h, u_prev=None, v_prev=None, limit_from=None):
336
+ def advect(self, fields, u, v, dt, h, u_prev=None, v_prev=None, limit_from=None, dt_prev=None):
336
337
  vel_now = (u, v)
337
338
  if u_prev is None or v_prev is None:
338
339
  vel_mid = vel_end = vel_now
339
340
  else:
340
- vel_end = (2 * u - u_prev, 2 * v - v_prev)
341
- vel_mid = (1.5 * u - 0.5 * u_prev, 1.5 * v - 0.5 * v_prev)
341
+ u_mid, u_end = extrapolate(u, u_prev, dt, dt_prev)
342
+ v_mid, v_end = extrapolate(v, v_prev, dt, dt_prev)
343
+ vel_mid, vel_end = (u_mid, v_mid), (u_end, v_end)
342
344
  if self._use_fused and self._on_device_float32(fields, u, v, u_prev, v_prev):
343
345
  s, walls = dt / h, self.grid.walls
344
346
  return self._fused_advect(fields, vel_now, vel_mid, vel_end, s, walls, limit_from)
@@ -0,0 +1,226 @@
1
+ """Color palettes: ordered lists of colors to paint initial color fields.
2
+
3
+ A :class:`Palette` is a list of colors, given as hex strings (``"#1f2a5a"``)
4
+ or RGB triples in ``[0, 1]``. Calling it with positions ``t`` in ``[0, 1]``
5
+ interpolates between them, by default in Oklab (Björn Ottosson, 2020), where
6
+ equal steps look like equal changes of color and a gradient between two
7
+ saturated colors does not go through gray. Colors are sRGB values, the
8
+ values ``vicflow.image`` reads from and writes to PNG files.
9
+
10
+ Painting functions (``vicflow.scenes``) take a palette or the name of one of
11
+ the palettes listed by :func:`names`. Their colors go from the bottom (or the
12
+ left) of the domain, ``t = 0``, to the top (or the right), ``t = 1``.
13
+
14
+ This module is experimental: named palettes may still be adjusted between
15
+ minor versions, which changes the images made with them.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Sequence
21
+ from typing import Literal, TypeAlias
22
+
23
+ import numpy as np
24
+
25
+ Color: TypeAlias = str | Sequence[float]
26
+ Space = Literal["oklab", "srgb"]
27
+
28
+ # sRGB colors, from t = 0 (bottom) to t = 1 (top)
29
+ PALETTES: dict[str, tuple[Color, ...]] = {
30
+ # dark and bright reds of thin buoyant stripes (Mark Stock's run19/run27 images)
31
+ "ember": (
32
+ (0.45, 0.30, 0.32),
33
+ (0.16, 0.08, 0.08),
34
+ (0.60, 0.06, 0.10),
35
+ (0.85, 0.15, 0.18),
36
+ (0.30, 0.08, 0.10),
37
+ (0.55, 0.42, 0.36),
38
+ ),
39
+ # night blue, teal, cream, orange and crimson
40
+ "dusk": (
41
+ (0.06, 0.09, 0.25),
42
+ (0.10, 0.35, 0.55),
43
+ (0.35, 0.70, 0.75),
44
+ (0.98, 0.85, 0.55),
45
+ (0.95, 0.55, 0.30),
46
+ (0.70, 0.20, 0.25),
47
+ ),
48
+ # deep reds, rust and sand, for thick strata
49
+ "garnet": (
50
+ (0.45, 0.30, 0.32),
51
+ (0.20, 0.08, 0.08),
52
+ (0.55, 0.05, 0.10),
53
+ (0.90, 0.15, 0.20),
54
+ (0.85, 0.30, 0.12),
55
+ (0.40, 0.08, 0.14),
56
+ (0.72, 0.45, 0.32),
57
+ ),
58
+ # marbling inks on paper: black, indigo, blue, paper, ochre, rust
59
+ "ink": ("#15161d", "#23356b", "#5b7fa8", "#efe6d2", "#c99a3e", "#8e3b24"),
60
+ # gray ink washes, from black to paper
61
+ "sumi": ("#0e0e10", "#38383c", "#76736d", "#bdb7aa", "#f3efe4"),
62
+ # abyss to foam
63
+ "ocean": ("#03122b", "#0b3a5c", "#14708a", "#3fb0b0", "#a6e3d4", "#f2f7f2"),
64
+ # soil, clay, sand and moss
65
+ "earth": ("#2b1d14", "#5c3a21", "#8f6436", "#c49a5a", "#e3cf9f", "#6b7a4b"),
66
+ # light, soft tints
67
+ "pastel": ("#f7cfc8", "#f2a593", "#f1d58e", "#a9d8b8", "#93bfe3", "#bba3dd"),
68
+ # bright colors separated by near-black, so that filaments glow
69
+ "neon": ("#07060d", "#ff2d95", "#120a24", "#16f2d0", "#0b0a12", "#f9f871"),
70
+ }
71
+
72
+
73
+ def _parse(color: Color) -> np.ndarray:
74
+ if isinstance(color, str):
75
+ h = color.removeprefix("#")
76
+ if len(h) == 3:
77
+ h = "".join(c * 2 for c in h)
78
+ if len(h) != 6:
79
+ raise ValueError(f"expected a color like '#1f2a5a' or '#fa0', got {color!r}")
80
+ try:
81
+ return np.array([int(h[i : i + 2], 16) for i in (0, 2, 4)]) / 255.0
82
+ except ValueError:
83
+ raise ValueError(f"not a hex color: {color!r}") from None
84
+ rgb = np.asarray(color, dtype=np.float64)
85
+ if rgb.shape != (3,):
86
+ raise ValueError(f"expected an RGB triple, got {color!r}")
87
+ if not np.all((rgb >= 0) & (rgb <= 1)):
88
+ raise ValueError(f"RGB values must be in [0, 1], got {color!r}")
89
+ return rgb
90
+
91
+
92
+ def _srgb_to_linear(c: np.ndarray) -> np.ndarray:
93
+ return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
94
+
95
+
96
+ def _linear_to_srgb(c: np.ndarray) -> np.ndarray:
97
+ c = np.clip(c, 0.0, 1.0)
98
+ return np.where(c <= 0.0031308, 12.92 * c, 1.055 * c ** (1 / 2.4) - 0.055)
99
+
100
+
101
+ _RGB_TO_LMS = np.array(
102
+ [
103
+ [0.4122214708, 0.5363325363, 0.0514459929],
104
+ [0.2119034982, 0.6806995451, 0.1073969566],
105
+ [0.0883024619, 0.2817188376, 0.6299787005],
106
+ ]
107
+ )
108
+ _LMS_TO_LAB = np.array(
109
+ [
110
+ [0.2104542553, 0.7936177850, -0.0040720468],
111
+ [1.9779984951, -2.4285922050, 0.4505937099],
112
+ [0.0259040371, 0.7827717662, -0.8086757660],
113
+ ]
114
+ )
115
+ _LAB_TO_LMS = np.linalg.inv(_LMS_TO_LAB)
116
+ _LMS_TO_RGB = np.linalg.inv(_RGB_TO_LMS)
117
+
118
+
119
+ def srgb_to_oklab(rgb) -> np.ndarray:
120
+ """Oklab ``(L, a, b)`` of sRGB colors; the last axis holds the 3 components."""
121
+ lms = _srgb_to_linear(np.asarray(rgb, dtype=np.float64)) @ _RGB_TO_LMS.T
122
+ return np.cbrt(lms) @ _LMS_TO_LAB.T
123
+
124
+
125
+ def oklab_to_srgb(lab) -> np.ndarray:
126
+ """sRGB colors of Oklab ``(L, a, b)`` values, clipped to ``[0, 1]``."""
127
+ lms = (np.asarray(lab, dtype=np.float64) @ _LAB_TO_LMS.T) ** 3
128
+ return _linear_to_srgb(lms @ _LMS_TO_RGB.T)
129
+
130
+
131
+ class Palette:
132
+ """An ordered list of colors, interpolated between them.
133
+
134
+ ``colors`` are hex strings or RGB triples in ``[0, 1]``; ``space`` is
135
+ where the interpolation happens: ``"oklab"`` (perceptually even) or
136
+ ``"srgb"`` (straight lines between the sRGB values).
137
+
138
+ ``palette(t)`` gives the color at positions ``t`` (clipped to
139
+ ``[0, 1]``, the colors evenly spaced along it) as a color field of
140
+ shape ``(3, *t.shape)``, the layout of ``Simulation.color``.
141
+ """
142
+
143
+ def __init__(
144
+ self, colors: Sequence[Color], *, space: Space = "oklab", name: str | None = None
145
+ ) -> None:
146
+ if isinstance(colors, str) or len(colors) == 0:
147
+ raise ValueError("a palette needs a list of at least one color")
148
+ if space not in ("oklab", "srgb"):
149
+ raise ValueError(f"space must be 'oklab' or 'srgb', got {space!r}")
150
+ self._colors = np.array([_parse(c) for c in colors])
151
+ self._colors.flags.writeable = False
152
+ self.space = space
153
+ self.name = name
154
+
155
+ @property
156
+ def colors(self) -> np.ndarray:
157
+ """The colors, an array ``(len(self), 3)`` of RGB values in ``[0, 1]``."""
158
+ return self._colors
159
+
160
+ def __len__(self) -> int:
161
+ return len(self._colors)
162
+
163
+ def __repr__(self) -> str:
164
+ label = repr(self.name) if self.name else "unnamed"
165
+ return f"<Palette {label}, {len(self)} colors, {self.space}>"
166
+
167
+ def __call__(self, t) -> np.ndarray:
168
+ t = np.clip(np.asarray(t, dtype=np.float64), 0.0, 1.0)
169
+ k = len(self._colors)
170
+ if k == 1:
171
+ rgb = np.broadcast_to(self._colors[0], (*t.shape, 3))
172
+ else:
173
+ s = t * (k - 1)
174
+ i = np.minimum(s.astype(np.int64), k - 2)
175
+ f = (s - i)[..., None]
176
+ anchors = srgb_to_oklab(self._colors) if self.space == "oklab" else self._colors
177
+ mixed = anchors[i] + f * (anchors[i + 1] - anchors[i])
178
+ rgb = oklab_to_srgb(mixed) if self.space == "oklab" else mixed
179
+ return np.ascontiguousarray(np.moveaxis(rgb, -1, 0))
180
+
181
+ def sample(self, count: int) -> np.ndarray:
182
+ """``count`` colors evenly spaced from the first to the last, ``(count, 3)``."""
183
+ if count < 1:
184
+ raise ValueError(f"count must be at least 1, got {count}")
185
+ return self(np.linspace(0.0, 1.0, count)).T.copy()
186
+
187
+ def reversed(self) -> Palette:
188
+ """The same colors in the opposite order."""
189
+ name = None if self.name is None else f"{self.name}_r"
190
+ return Palette(self._colors[::-1], space=self.space, name=name)
191
+
192
+ @classmethod
193
+ def from_matplotlib(cls, cmap, count: int = 16) -> Palette:
194
+ """``count`` colors sampled from a matplotlib colormap or its name.
195
+
196
+ Needs matplotlib. The colors are interpolated in sRGB, like the
197
+ colormap itself.
198
+ """
199
+ try:
200
+ from matplotlib import colormaps
201
+ except ImportError:
202
+ raise ImportError("Palette.from_matplotlib needs matplotlib") from None
203
+ cm = colormaps[cmap] if isinstance(cmap, str) else cmap
204
+ rgb = np.asarray(cm(np.linspace(0.0, 1.0, count)))[:, :3]
205
+ return cls(np.clip(rgb, 0.0, 1.0), space="srgb", name=getattr(cm, "name", None))
206
+
207
+
208
+ def names() -> list[str]:
209
+ """The names of the built-in palettes."""
210
+ return list(PALETTES)
211
+
212
+
213
+ def get(palette: str | Palette | Sequence[Color]) -> Palette:
214
+ """A palette from its name, a list of colors, or a palette (returned as is).
215
+
216
+ A name ending in ``_r`` gives the reversed palette.
217
+ """
218
+ if isinstance(palette, Palette):
219
+ return palette
220
+ if isinstance(palette, str):
221
+ base = palette.removesuffix("_r")
222
+ if base not in PALETTES:
223
+ raise ValueError(f"unknown palette {palette!r}; built-in palettes: {names()}")
224
+ p = Palette(PALETTES[base], name=base)
225
+ return p.reversed() if palette.endswith("_r") else p
226
+ return Palette(palette)