Metadata-Version: 2.4
Name: vicflow
Version: 0.2.0
Summary: GPU-accelerated 2D vortex-in-cell fluid simulator for generative art
Keywords: fluid simulation,vortex-in-cell,generative art,cfd,gpu,pytorch,metal,triton
Author: Quentin
Author-email: Quentin <petitquentin41@gmail.com>
License-Expression: GPL-3.0-or-later
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Topic :: Scientific/Engineering :: Physics
Classifier: Topic :: Multimedia :: Graphics
Classifier: Topic :: Artistic Software
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Environment :: GPU
Classifier: Environment :: GPU :: NVIDIA CUDA
Requires-Dist: numpy>=2.0
Requires-Dist: pypng>=0.20220715.0
Requires-Dist: torch>=2.14 ; extra == 'torch'
Requires-Python: >=3.11
Project-URL: Homepage, https://github.com/petitquentin/vicflow
Project-URL: Source, https://github.com/petitquentin/vicflow
Project-URL: Issues, https://github.com/petitquentin/vicflow/issues
Project-URL: Changelog, https://github.com/petitquentin/vicflow/blob/main/CHANGELOG.md
Provides-Extra: torch
Description-Content-Type: text/markdown

# vicflow

[![PyPI](https://img.shields.io/pypi/v/vicflow)](https://pypi.org/project/vicflow/)
[![Python](https://img.shields.io/pypi/pyversions/vicflow)](https://pypi.org/project/vicflow/)
[![Downloads per month](https://static.pepy.tech/badge/vicflow/month)](https://pepy.tech/projects/vicflow)
[![Total downloads](https://static.pepy.tech/badge/vicflow)](https://pepy.tech/projects/vicflow)
[![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)
[![License](https://img.shields.io/pypi/l/vicflow)](https://github.com/petitquentin/vicflow/blob/main/LICENSE)
[![GitHub stars](https://img.shields.io/github/stars/petitquentin/vicflow)](https://github.com/petitquentin/vicflow/stargazers)

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).

> **Status: early development.** What exists today is the solver on
> periodic domains and between no-slip walls, with density, buoyancy and
> color, validated against vic2d, with a NumPy reference backend and a PyTorch
> backend (CUDA, Apple Silicon, CPU) whose advection runs as a fused native
> kernel on GPUs (Triton, Metal). Obstacles, open boundaries and scene files
> come next.

## Installation

```bash
pip install vicflow            # NumPy backend (CPU)
pip install "vicflow[torch]"   # adds the PyTorch backend: CUDA, Apple Silicon (MPS), CPU
```

vicflow needs Python 3.11 or later. With an NVIDIA driver older than 580
(CUDA 12.x), install PyTorch from https://download.pytorch.org/whl/cu126
before vicflow: the PyTorch wheels on PyPI need CUDA 13.

## Method

The flow is described by its vorticity ω. Each time step:

1. diffuses ω (explicit 5-point scheme),
2. advects it semi-Lagrangially: every grid node traces its fluid back with
   RK4 and interpolates ω there with the 4th-order M4′ kernel,
3. recovers the velocity by solving ∇²ψ = −ω with FFTs, u = ∂ψ/∂y, v = −∂ψ/∂x.

Each axis is periodic or bounded by no-slip walls. Walls carry ψ = 0 (a sine
transform, done as an FFT of the odd extension), and create vorticity: at
every step the wall vorticity is set from the slip velocity next to it, then
diffuses into the fluid.

This is vic2d's scheme; its low numerical diffusion is what makes
Reynolds numbers in the millions possible.

## Example

```python
import numpy as np
from vicflow import Grid, Simulation

grid = Grid.square(256)
x, y = grid.coords()
vorticity = np.sin(2 * np.pi * x) * np.sin(2 * np.pi * y)

sim = Simulation(grid, vorticity, viscosity=1e-4, dt=0.01)
sim.run(100)
print(sim.time, sim.kinetic_energy())
```

Fields have shape `(nx, ny)` and are indexed `[ix, iy]`, with y pointing up,
like vic2d. Images and matplotlib put rows (y) first and y down, so plot a
field transposed: `plt.imshow(sim.vorticity.T, origin="lower")`. The domain's
longest side has length 1.

Fields can be replaced between steps, e.g. to add a vortex in the middle of a
run: `sim.vorticity = sim.vorticity + extra`. The velocity is recomputed from
the new vorticity. Changing a field in place (`sim.vorticity[...] += ...`)
does not update the velocity: assign the whole field.

A box with walls all round, or a channel periodic in x:

```python
box = Grid.square(256, "wall")  # 257 x 257 nodes, wall nodes included
channel = Grid(512, 128, "periodic", "wall")  # 512 x 129 nodes
```

A density field is carried by the flow and drives it through buoyancy
(Boussinesq); with the default gravity, pointing down, heavy fluid sinks
(vic2d's points up).
At a sharp interface the M4′ interpolation overshoots and leaves grid-scale
ripples; the default `limiter="scalars"` clips the advected density and color
to their local range, and leaves the vorticity alone.
Rayleigh-Taylor instability, heavy fluid over light:

```python
grid = Grid(512, 256, "periodic", "wall")
x, y = grid.coords()
density = np.tanh((y - 0.25 - 0.01 * np.cos(2 * np.pi * 4 * x)) / 0.01)
sim = Simulation(
    grid,
    np.zeros(grid.shape),
    viscosity=1e-5,
    dt=0.002,
    density=density,
    diffusivity=1e-5,
    buoyancy=1.0,
)
```

Color is a stack of passive scalars of shape `(channels, nx, ny)`, usually
RGB, carried and diffused (`color_diffusivity`) in the same advection pass.
`vicflow.image` reads and writes PNGs (8 or 16 bits per channel) with y
pointing up, like vic2d; the image needs one pixel per node:

```python
from vicflow.image import read_color, write_image

color = read_color("start.png")  # (3, width, height), values in [0, 1]
sim = Simulation(
    grid,
    vorticity,
    viscosity=1e-5,
    dt=0.002,
    color=color,
    color_diffusivity=1e-6,
)
sim.run(500)
write_image("frame.png", sim.color, bits=16)
```

The time step can follow the flow: with `courant`, `dt` becomes the largest
step, and each step is shortened so that the fastest fluid moves at most
`courant` cells. This suits runs that start at rest and speed up, such as
Rayleigh-Taylor. `run_until` shortens the last steps to land exactly on a
time, for frames evenly spaced in time:

```python
sim = Simulation(
    grid,
    np.zeros(grid.shape),
    viscosity=1e-5,
    dt=0.01,  # the largest step
    density=density,
    courant=2.0,  # at most 2 cells per step
)
for frame in range(1, 101):
    sim.run_until(0.05 * frame)
    write_image(f"frame{frame:03d}.png", sim.density, vmin=-1, vmax=1)
print(sim.step_count, sim.last_dt)
```

## Scenes, palettes and recipes

*Experimental: these modules may still change between minor versions, and
with them the images they make.*

`vicflow.recipes` holds complete scenes with tested parameters. Each recipe
returns the arguments of `Simulation`, grid included, so any of them can be
overridden:

```python
from vicflow import Simulation, recipes

scene = recipes.rayleigh_taylor(1024, palette="ink", seed=3)
sim = Simulation(**scene, backend="torch")
sim.run(round(recipes.DURATIONS["rayleigh_taylor"] / sim.dt))
```

The recipes are `stripes` (thin buoyant color stripes, after Mark J. Stock's
run19 and run27 images), `rayleigh_taylor` and `turbulence`; the
[`examples/`](https://github.com/petitquentin/vicflow/tree/main/examples)
scripts render them.

`vicflow.scenes` has the building blocks: color `bands` and `stripes`,
wavy `interface`s and `layers`, `vortex`, `dipole`, `shear_layer`, random
`turbulence` and smooth `noise`, and `density_from_luminance`. They return
NumPy arrays to combine freely. Lengths are in domain units and random
patterns depend on the seed only, so a scene starts the same at 256 cells as
at 4096: the coarse run is a quick preview of the fine one while the flow is
young, before turbulence makes them drift apart.

`vicflow.palettes` has the color lists they paint with: built-in palettes
(`palettes.names()`), your own (`["#15161d", "#23356b", ...]` or RGB
triples), or a matplotlib colormap (`Palette.from_matplotlib("magma")`).
Colors are interpolated in Oklab, so gradients look even.

## GPU

On a GPU, install the `torch` extra (`pip install "vicflow[torch]"`) and pick
the PyTorch backend; it uses CUDA or Apple's MPS when available, in float32,
with a fused advection kernel (Triton on NVIDIA, Metal on Apple Silicon; AMD/ROCm
should work through Triton but is untested).

```python
sim = Simulation(grid, vorticity, viscosity=1e-4, dt=0.01, backend="torch")
sim.run(100)
w = sim.to_numpy(sim.vorticity)
```

## Replaying a vic2d run

vicflow's defaults favour stable, artefact-free runs over matching vic2d
bit for bit. To reproduce a vic2d run, pass its conventions explicitly:

```python
sim = Simulation(
    grid,
    vorticity,
    viscosity=1e-4,
    dt=0.01,
    density=density,
    gravity=(0, 1),  # vic2d's gravity points up (only with a density field)
    vic2d_mean_flow=True,  # its mean-velocity convention, which depends on the grid origin
    time_order=1,  # velocity frozen during the backtrace (default 2: extrapolated)
    limiter="none",  # no limiter (default "scalars")
)
```

vic2d's `-cn` is a fixed `dt = cn / n` on an `n`-cell grid. Its `-constcn` uses
the same units as `courant` (cells per step) but another rule to pick the
step, so adaptive steps are not reproduced exactly.

`time_order=1` is about 20 % faster, but its kinetic energy drifts upwards at
large time steps and it can blow up next to walls.

## Public API

`Grid`, `Simulation` and the `vicflow.image` module; `vicflow.scenes`,
`vicflow.palettes` and `vicflow.recipes` are public but experimental. The other modules
(`vicflow.poisson`, `vicflow.advect`, `vicflow.backends`, ...) are internal and
may change between versions.

## Development

Needs [uv](https://docs.astral.sh/uv/).

```bash
uv sync                 # create the environment
uv run pytest           # tests, including the comparison with vic2d
uv run ruff check .     # lint
uv run ruff format .    # format
uv run python benchmarks/step_time.py   # ms per step for every available backend
```

Work happens on `dev`; `main` only receives stable, tagged versions.

[`tests/reference/`](https://github.com/petitquentin/vicflow/tree/main/tests/reference)
holds the vic2d runs used as an oracle and the scripts that regenerate them.
[`validation/turbulence_vs_legacy.py`](https://github.com/petitquentin/vicflow/blob/main/validation/turbulence_vs_legacy.py) runs a larger
case (decaying turbulence, 1024²) with both codes and draws them side by side.

## Citing

If you use vicflow in your work, please cite it:

```bibtex
@misc{vicflow2026,
  author       = {Quentin Petit},
  title        = {vicflow: a {GPU}-accelerated {2D} vortex-in-cell fluid simulator for generative art},
  howpublished = {\url{https://github.com/petitquentin/vicflow}},
  year         = {2026}
}
```

## Credits

The numerical method comes from vic2d by Mark J. Stock. If you use vicflow,
please also cite it:

```bibtex
@Misc{vic2d2004,
  author =       {Mark J.~Stock},
  title =        {vic2d:  A command-line two-dimensional fluid simulator using a novel semi-Lagrangian advection technique},
  howpublished = {\url{https://github.com/markstock/vic2d}},
  year =         {2004}
}
```

## License

GPL-3.0-or-later, like vic2d. See [`LICENSE`](https://github.com/petitquentin/vicflow/blob/main/LICENSE).
