FluidEnv

class fluidgym.envs.fluid_env.FluidEnv(adaptive_cfl: float, dt: float, step_length: float, episode_length: int, ndims: int, use_marl: bool, dtype: dtype = torch.float32, cuda_device: device | None = None, cpu_device: device | None = None, load_initial_domain: bool = True, load_domain_statistics: bool = True, randomize_initial_state: bool = True, enable_actions: bool = True, differentiable: bool = False, advection_tol: phipict.solvers.tolerance.SolverTolerance = None, pressure_tol: phipict.solvers.tolerance.SolverTolerance = None, pressure_tol_intermediate: phipict.solvers.tolerance.SolverTolerance = None, pressure_warm_start: bool = False, linear_solve_max_iter: int | None = None, exclude_advection_solve_gradients: bool | None = None, exclude_pressure_solve_gradients: bool | None = None, exclude_pressure_gradient_adjoint: bool | None = None, n_envs: int | None = None)[source]

Bases: ABC, FluidEnvLike

Abstract base class for FluidGym environments.

It provides common functionality for all FluidGym environments, such as managing the simulation, rendering, and saving/loading initial domains.

Batched environments. With n_envs=E the environment runs E copies of itself in one batched simulation on its GPU: same grid, boundaries and sparsity patterns, own states, actions, observations and rewards. The API then carries a leading env dim everywhere: actions [E, *action] ([E, A, *action] in MARL), observations [E, *obs], rewards [E] ([E, A]), terminated and truncated bool tensors [E] and info values [E]. With the default n_envs=None it is a single environment without that dim, exactly as before. All environments share the episode length and, with adaptive substepping, the time step (set by the fastest environment).

Internally, every environment works with the leading env dim regardless of n_envs (E = 1 for a single environment): block fields are [E, ...] and _apply_action(), _get_global_obs(), _advance_impl() and _finish_step() take and return per-environment tensors. The base class removes the env dim for a single environment.

Raises:

Notes

The environment must be reset before calling step(). The initial domain must be generated by calling init() before using the environment for training or evaluation. The initial domain is saved to disk when init() is called, and loaded when reset() is called.

property action_space: Box

The action space of the environment.

property adjoint_rtol: float | None

Relative residual every adjoint (backward) linear solve is held to.

Each adjoint solve stops on ||r|| < rtol * ||g||, with g its incoming gradient. The tolerance is proportional to g, so the gradient does not depend on the scale of the loss: the reward scale, the natural magnitude of the reward or the adjoint decaying along the rollout. None (the default) holds each adjoint solve to the rtol of its forward solve, e.g. pressure_tol, and a forward solve with an absolute tolerance to phipict.solvers.tolerance.ADJOINT_RTOL_FALLBACK. A float overrides this for every solve.

This is a process-wide solver setting (phipict.solvers.tolerance.set_adjoint_rtol()), shared by every env in the process; the last one set wins.

property bptt_carry_spill_dir: str | None

Directory to write checkpoint carries into, instead of host RAM.

At a long horizon the carry is what host memory runs out of: it is one state snapshot per step. Note /tmp and /dev/shm are usually tmpfs, i.e. RAM.

property bptt_checkpoint: bool

Run each env step as an activation checkpoint (differentiable BPTT).

The step is run under no_grad during the rollout and replayed under enable_grad in backward, so only one step’s activations are ever live. This is what makes GPU peak independent of the rollout length; offloading the tape alone leaves a residue per PISO step that caps the horizon.

Costs one extra forward per step, plus one carry per step (see bptt_offload_device / bptt_carry_spill_dir). Only meaningful on a differentiable environment.

property bptt_offload_device: device | None

Where checkpoint carries are parked (None = keep on the GPU).

property bptt_segment_size: int

PISO steps per checkpoint segment (0 = one segment per env step).

close() → None[source]

Release what this env holds outside Python: the carry spill directory.

Also runs on garbage collection and at interpreter exit via the finalizer, so a run that never calls this still cleans up after itself; only a killed process leaves files behind, and the next run sweeps those.

property cuda_device: device

The CUDA device used by the environment.

property default_bptt_segment_size: int

The bptt_segment_size this env starts at, as it resolves it.

0 for an env that leaves its step whole; otherwise a divisor of n_sim_steps.

detach() → None[source]

Detach all tensors in the simulation from the computation graph.

property differentiable: bool

Whether the environment is differentiable.

property dt: float

The simulation time step.

property episode_length: int

The number of steps per episode.

get_pressure() → Tensor[source]

Get the pressure field of the fluid.

Returns:

The pressure field as a tensor of shape (H, W) for 2D or (D, H, W) for 3D, with a leading env dim for a vectorized environment.

Return type:

torch.Tensor

get_state() → EnvState[source]

Get the current state of the environment.

Returns:

The current state of the environment.

Return type:

EnvState

get_uncontrolled_episode_metrics() → DataFrame | list[DataFrame | None] | None[source]

Get the uncontrolled episode metrics for the current domain.

Note: This method returns the metrics for the currently loaded (non-randomized) initial domain. If the environment has been reset with randomization, the metrics may not correspond to the current state.

Returns:

The uncontrolled episode metrics, or None if not available. One entry per environment for a vectorized environment.

Return type:

pd.DataFrame | list[pd.DataFrame | None] | None

get_velocity() → Tensor[source]

Get the velocity field of the fluid.

Returns:

The velocity field as a tensor, with a leading env dim for a vectorized environment.

Return type:

torch.Tensor

get_vorticity() → Tensor[source]

Get the vorticity field of the fluid.

Returns:

The vorticity field as a tensor, with a leading env dim for a vectorized environment.

Return type:

torch.Tensor

abstract property id: str

Unique identifier for the environment.

init(domain_idxs: list[int] | None = None) → None[source]

Generate and save the initial domain if it does not already exist.

Parameters:

domain_idxs (list[int]) – List of domain indices to initialize. If empty, initializes all domains. Defaults to None.

abstract property initial_domain_id: str

Unique identifier for the initial domain.

load_domain(path: Path) → None[source]

Load a domain from disk given a path and set it as the environment’s current domain.

Parameters:

path (Path) – Path to the domain.

load_initial_domain(idx: int, mode: EnvMode | None = None) → None[source]

Load an initial domain from disk and set it as the environments current domain.

Parameters:
  • idx (int) – Index of the initial domain to load.

  • mode (EnvMode | None) – Environment mode (‘train’, ‘val’, ‘test’). If None, uses the current mode. Defaults to None.

metadata = {'render_fps': 24, 'render_modes': ['rbg_array']}
property metrics: list[str]

The list of metrics tracked by the environment.

property mode: EnvMode

The current mode of the environment (‘train’, ‘val’, or ‘test’).

abstract property n_agents: int

The number of agents in the environment.

property n_envs: int

Number of environments simulated together (1 for a single one).

property n_sim_steps: int

The number of simulation steps per environment step.

property ndims: int

The number of spatial dimensions (2 or 3).

property num_envs: int

Alias of n_envs, the name vectorized-env libraries use.

abstract property obs_resampling_shape: tuple[int, ...]

The shape of the uniform grid the observations are resampled onto.

This is a property of the environment and does not change: the observations, and the sensor and mask indices that go with them, are defined on this grid. To render at a higher resolution, set render_resolution.

property observation_space: Dict

The observation space of the environment.

abstractmethod plot(output_path: Path | None = None) → None[source]

Plot the environments configuration.

Parameters:

output_path (Path | None) – Path to save the plot. If None, the current directory is used. Defaults to None.

plot_grid() → None[source]

Plot the simulation grid.

render(save: bool = False, render_3d: bool = False, filename: str | None = None, output_path: Path | None = None, env_ids: int | Sequence[int] | None = None) → ndarray[source]

Render the current state of the environment.

Parameters:
  • save (bool) – Whether to save the rendered frame as a PNG file. Defaults to False.

  • render_3d (bool) – Whether to enable 3d rendering. Defaults to False.

  • filename (str | None) – The filename of the saved PNG files. If None, a default name is used. Defaults to None.

  • output_path (Path | None) – The output path to save the rendered files. If None, saves to the current directory. Defaults to None.

  • env_ids (int | Sequence[int] | None) – The environments of a vectorized environment to render: one index for a single frame, a sequence for a stack of frames, None (the default) for all environments. Must be None for a single environment.

Returns:

The rendered frame [H, W, 3] for a single environment (or a single env_ids index), else the frames [len(env_ids), H, W, 3] of the requested environments matching the layout of vectorized-env video recorders.

Return type:

np.ndarray

property render_resolution: int

How much finer the render grid is than obs_resampling_shape.

A multiplier of 1, the default, renders on the observation grid. Raising it only affects rendering, never the observations.

property render_shape: tuple[int, ...]

The shape of the rendered domain.

This is obs_resampling_shape scaled by render_resolution, and is used for rendering only.

reset(seed: int | None = None, randomize: bool | None = None, domain_idx: int | Sequence[int] | None = None) → tuple[dict[str, Tensor], dict[str, Tensor]][source]

Resets the environment to an initial internal state, returning an initial observation and info.

Parameters:
  • seed (int | None) – The seed to use for random number generation. If None, the current seed is used.

  • randomize (bool | None) – Whether to randomize the initial state. If None, the default behavior is used.

  • domain_idx (int | Sequence[int] | None) – Index of the initial domain to load, one for all environments or one per environment. Takes precedence over the random draw, so a randomized initial state can still start from a fixed domain. If None, every environment draws a random index when randomizing, and all start from the first initial domain otherwise. Defaults to None.

Returns:

A tuple containing the initial observation and an info dictionary. The observation has a leading env dim for a vectorized environment.

Return type:

tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]

sample_action() → Tensor[source]

Sample a random action uniformly from the action space.

Returns:

A random action.

Return type:

torch.Tensor

seed(seed: int) → None[source]

Update the random seeds and seed the random number generators.

Parameters:

seed (int) – The seed to set. If None, the current seed is used.

set_state(state: EnvState) → None[source]

Set the current state of the environment.

Parameters:

state (EnvState) – The state to set the environment to.

step(action: Tensor) → tuple[dict[str, Tensor], Tensor, bool | Tensor, bool | Tensor, dict[str, Tensor]][source]

Run one timestep of the environment’s dynamics using the agent actions.

When the end of an episode is reached (terminated or truncated), it is necessary to call reset() to reset this environment’s state for the next episode.

Parameters:

action (torch.Tensor) – The action to take, [n_envs, ...] for a vectorized environment.

Returns:

  • tuple[

  • dict[str, torch.Tensor], torch.Tensor, bool, bool, dict[str, torch.Tensor]] – A tuple containing the observation, reward, terminated flag, truncated flag, and info dictionary. For a vectorized environment everything has a leading env dim, and the flags are bool tensors of shape [n_envs].

property step_length: float

The length of each environment step in non-dimensional time units.

test() → None[source]

Set the environment to test mode.

property time_passed: float

The total time passed in the current episode.

train() → None[source]

Set the environment to training mode.

property use_marl: bool

Whether the environment is in multi-agent reinforcement learning mode.

val() → None[source]

Set the environment to evaluation mode.

property vectorized: bool

Whether the API carries a leading env dim (n_envs was given).