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,FluidEnvLikeAbstract 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=Ethe 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]),terminatedandtruncatedbool tensors[E]and info values[E]. With the defaultn_envs=Noneit 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 = 1for 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:
RuntimeError – If CUDA is not available.
ValueError – If ndims is not 2 or 3.
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 adjoint_rtol: float | None
Relative residual every adjoint (backward) linear solve is held to.
Each adjoint solve stops on
||r|| < rtol * ||g||, withgits incoming gradient. The tolerance is proportional tog, 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 thertolof its forward solve, e.g.pressure_tol, and a forward solve with an absolute tolerance tophipict.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
/tmpand/dev/shmare 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_gradduring the rollout and replayed underenable_gradin 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).
- 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 default_bptt_segment_size: int
The
bptt_segment_sizethis env starts at, as it resolves it.0for an env that leaves its step whole; otherwise a divisor ofn_sim_steps.
- 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:
- 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:
- 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:
- init(domain_idxs: list[int] | None = None) None[source]
Generate and save the initial domain if it does not already exist.
- 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 mode: EnvMode
The current mode of the environment (‘train’, ‘val’, or ‘test’).
- 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.
- 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.
- 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 singleenv_idsindex), 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_shapescaled byrender_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:
- 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 callreset()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].