### Verify ΦFlow Installation (from source)
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Installation_Instructions.md
Executes the 'verify.py' script located in the tests directory of the cloned ΦFlow source to check the installation and configuration.
```bash
python <Φ-Flow directory>/tests/verify.py
```
--------------------------------
### Install Pytest for Unit Tests
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Installation_Instructions.md
Installs Pytest, a framework used for running unit tests within the ΦFlow project. This is a prerequisite for executing the test suites.
```bash
pip install pytest
```
--------------------------------
### Install Latest Developer ΦFlow using pip
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Installation_Instructions.md
Installs the bleeding-edge developer version of ΦFlow directly from the GitHub repository using pip.
```bash
pip install --upgrade git+https://github.com/tum-pbs/PhiFlow@develop
```
--------------------------------
### Install Dash for Web UI
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Installation_Instructions.md
Installs the 'dash' library, which is required to enable the web UI for ΦFlow. This is not needed if running ΦFlow exclusively within Jupyter notebooks.
```bash
pip install dash
```
--------------------------------
### Install Latest Stable ΦFlow using pip
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Installation_Instructions.md
Installs the most recent stable release of the ΦFlow library, including GUI support, via pip.
```bash
pip install phiflow
```
--------------------------------
### Install and Import PhiFlow Libraries
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Smoke_Plume.ipynb
Installs the phiflow library and imports necessary modules for JAX-based fluid simulation and progress tracking. This code is essential for running the example.
```python
%pip install phiflow
from phi.jax.flow import *
from tqdm.notebook import trange
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
```
--------------------------------
### Install and Import PhiFlow for SPH
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/particles/SPH.ipynb
Installs the PhiFlow library and imports necessary modules from phi.torch.flow and phi.physics.sph for setting up and running the SPH simulation. tqdm.notebook is used for progress bars.
```python
%pip install --quiet phiflow
from phi.torch.flow import *
from phi.physics import sph
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from tqdm.notebook import trange
```
--------------------------------
### Install PhiFlow and Import Modules (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/optim/Gradient_Descent.ipynb
Installs the PhiFlow library quietly and imports necessary modules from phi.torch.flow. It also provides a commented-out alternative for users without JAX installed.
```python
%pip install --quiet phiflow
from phi.torch.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
```
--------------------------------
### Clone ΦFlow Git Repository
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Installation_Instructions.md
Clones the ΦFlow source code from its GitHub repository into a specified target directory. This is the first step for installing from source.
```bash
git clone https://github.com/tum-pbs/PhiFlow.git
```
--------------------------------
### Install Dependencies and Import Libraries
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/mesh/FVM_Cylinder_GMsh.ipynb
Installs necessary libraries (phiflow, meshio) and imports core components from PhiFlow for PyTorch backend. It also imports `trange` for progress bars.
```python
# %pip install --quiet phiflow meshio
from phi.torch.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from tqdm.notebook import trange
```
--------------------------------
### Install and Import PhiFlow Libraries
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/optim/Close_Packing.ipynb
Installs the PhiFlow library and imports necessary modules from phi.jax.flow. This sets up the environment for using PhiFlow with JAX. Alternative imports for other backends like PyTorch or TensorFlow are commented out.
```python
# %pip install --quiet phiflow
from phi.jax.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
```
--------------------------------
### Setup and Import Libraries for ΦFlow FLIP Simulation
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/FLIP.ipynb
Imports necessary libraries and modules from ΦFlow and other packages to set up and run FLIP simulations. This includes JAX, notebook progress bars, and specific ΦFlow components for fields and particle distribution.
```python
# !pip install git+https://github.com/tum-pbs/PhiFlow@3.0
from phi.jax.flow import *
from phi.field._point_cloud import distribute_points
from tqdm.notebook import trange
```
--------------------------------
### Install and Import PhiFlow Libraries (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Taylor_Green.ipynb
Installs the PhiFlow library and imports necessary modules for JAX-based simulations. It also includes commented-out alternatives for different backends and progress bar utilities.
```python
%pip install phiflow
from phi.jax.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from tqdm.notebook import trange
from functools import partial
```
--------------------------------
### Install PhiFlow and Import Libraries
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/mesh/FVM_Heat.ipynb
Installs the PhiFlow library quietly and imports necessary modules from phi.torch.flow and tqdm for use in the simulation. It also provides an alternative import for JAX users.
```python
# %pip install --quiet phiflow
from phi.torch.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from tqdm.notebook import trange
```
--------------------------------
### Install ΦFlow and Import Modules
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Variable_Boundaries.ipynb
Installs the ΦFlow Python package from GitHub and imports necessary modules for use. This is a prerequisite for running the subsequent examples.
```Python
%pip install phiflow
from phi.flow import *
```
--------------------------------
### Install and Import PhiFlow Libraries (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Wake_Flow.ipynb
Installs the necessary PhiFlow library and imports core components for PyTorch-based fluid simulations. It also imports `trange` for progress bars in notebooks.
```python
%pip install phiflow
from phi.torch.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from tqdm.notebook import trange
```
--------------------------------
### Verify ΦFlow Installation (pip)
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Installation_Instructions.md
Verifies a ΦFlow installation made via pip by running the 'phi.verify()' function within a Python script or command line.
```python
import phi; phi.verify()
```
```bash
python3 -c "import phi; phi.verify()"
```
--------------------------------
### Install PhiFlow and Import Modules (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Reaction_Diffusion.ipynb
Installs the PhiFlow library quietly and imports necessary modules for PyTorch-based flow operations, along with `trange` for progress bars in notebooks. This snippet is essential for setting up the environment to run the reaction-diffusion simulation.
```python
%pip install --quiet phiflow
from phi.torch.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from tqdm.notebook import trange
```
--------------------------------
### Initialize and Run Wave Simulation (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Waves.ipynb
Initializes a 2D `CenteredGrid` for the wave simulation and then runs the simulation using the `iterate` function with the `step` function. The simulation runs for 300 time steps with 16 substeps per frame, starting from an initial state.
```python
h_initial = CenteredGrid(x=128, y=128, bounds=Box(x=12.8, y=12.8), boundary=ZERO_GRADIENT)
h_trj, *_ = iterate(step, batch(time=300), h_initial, h_initial, 0, substeps=16, range=trange)
```
--------------------------------
### Install PhiFlow and Import Modules (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Julia_Set.ipynb
Installs the phiflow library quietly and imports necessary modules from phi.jax.flow. It also includes a commented-out alternative for users without JAX.
```python
%pip install --quiet phiflow
from phi.jax.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
```
--------------------------------
### Initialize Simulation: Ropes Example (PhiFlow/JAX)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/particles/Ropes.ipynb
Sets up the initial state for the rope simulation. It involves creating a grid, scattering nodes, defining fixed points, and plotting the initial point cloud. Dependencies include phiflow, jax, and tqdm.
```python
# %pip install --quiet phiflow
from phi.jax.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from tqdm.notebook import trange
grid = CenteredGrid(0, x=20, y=20, bounds=Box(x=1, y=1))
x = pack_dims(grid.points, 'x,y', instance('nodes'))
x += math.random_uniform(x.shape) * .01
fixed_indices = vec(nodes=[399, 19, 199, 239, 0])
fixed = math.scatter(expand(False, instance(x)), fixed_indices, True)
plot(PointCloud(x, fixed), size=(4, 3))
```
--------------------------------
### Install and Import PhiFlow
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/SDF.ipynb
Installs the PhiFlow library using pip and imports necessary components for using the library. This is a prerequisite for running other PhiFlow code examples.
```python
# %pip install phiflow
from phi.flow import *
```
--------------------------------
### Run Additional ΦFlow Unit Tests
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Installation_Instructions.md
Executes specialized unit tests for ΦFlow, including tests for GPU functionality and release configurations, using Pytest.
```bash
pytest /tests/gpu
```
```bash
pytest /tests/release
```
--------------------------------
### Install and Import PhiFlow Libraries
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Higher_order_Kolmogorov.ipynb
Installs the PhiFlow library and imports necessary modules from phi.jax.flow and tqdm for visualization. Sets global precision for calculations to 64-bit.
```python
%pip install phiflow
from phi.jax.flow import *
from tqdm.notebook import trange
math.set_global_precision(64)
```
--------------------------------
### Install and Import PhiFlow Libraries (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Fluid_Logo.ipynb
Installs the PhiFlow library and imports necessary modules for fluid simulation, specifically for JAX. If JAX is not available, alternative imports for PyTorch or TensorFlow are commented out.
```python
%pip install phiflow
from phi.jax.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
```
--------------------------------
### Setup and Initialization for Differentiable Pressure in PhiFlow (JAX)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/optim/Differentiable_Pressure.ipynb
Initializes the PhiFlow environment using JAX and sets up the simulation resolution, control areas, and target flow fields. It also defines the target flow pattern based on a Gaussian distribution.
```python
# %pip install --quiet phiflow
from phi.jax.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from tqdm.notebook import trange
res = dict(x=80, y=64)
control_area = union(Sphere(x=20, y=15, radius=10), Sphere(x=20, y=50, radius=10))
control_mask = StaggeredGrid(control_area, 0, **res)
target_mask = StaggeredGrid(Box(x=(40, INF), y=None), 0, **res)
target = target_mask * StaggeredGrid(lambda x: math.exp(-0.5 * math.vec_squared(x - (50, 10), 'vector') / 32**2), 0, **res) * (0, 2)
plot(control_mask['x'], target, overlay='args', size=(4, 3), title='Control areas (left) and target flow (right)')
```
--------------------------------
### Setup PhiFlow Environment and Import Libraries
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Heat_Flow.ipynb
This snippet installs the PhiFlow library and imports necessary components from phi.jax.flow. It also imports trange for progress bars in notebooks. An alternative import for non-JAX environments is commented out.
```python
%pip --quiet install phiflow
from phi.jax.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from tqdm.notebook import trange
```
--------------------------------
### Install ΦFlow
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Billiards.ipynb
Installs the ΦFlow library. This is a prerequisite for running the billiards simulation.
```python
# !pip install phiflow
```
--------------------------------
### Initialize Fluid Field and Particles (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/optim/PIV.ipynb
Creates an initial divergence-free velocity field using noise and scatters marker particles across the domain. This setup is used to observe scaling behavior with varying particle counts.
```python
v0 = StaggeredGrid(Noise(batch(seed=2)), x=64, y=64, bounds=Box(x=20, y=20))
v0, _ = fluid.make_incompressible(v0)
marker_count = vec(batch('count'), 128, 256, 512, 1024, 2048, 4096)
initial_markers = v0.bounds.sample_uniform(instance(markers=marker_count))
plot([Sphere(initial_markers.count['128'], radius=.4), v0], overlay='list', color=['orange', None], size=(5, 3))
```
--------------------------------
### Install PhiFlow and Import Libraries
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/particles/FLIP.ipynb
Installs the PhiFlow library quietly and imports necessary components for the simulation. It also provides commented-out alternatives for different backends if JAX is not available.
```python
%pip install --quiet phiflow
from phi.jax.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from phi.field._point_cloud import distribute_points
from tqdm.notebook import trange
```
--------------------------------
### Run ΦFlow Unit Tests
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Installation_Instructions.md
Executes the standard unit tests for ΦFlow using Pytest. This command should be run from the root of the cloned repository.
```bash
pytest /tests/commit
```
--------------------------------
### Install and Verify PhiFlow
Source: https://context7.com/tum-pbs/phiflow/llms.txt
Installs the PhiFlow library using pip and provides a command to verify the installation by importing and running a verification function. This is the first step to using the library.
```bash
# Install PhiFlow
pip install phiflow
# Verify installation
python3 -c "import phi; phi.verify()"
```
--------------------------------
### Install PhiFlow and Import Modules
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/optim/Learn_Throw.ipynb
Installs the phiflow library and imports necessary modules for PyTorch-based simulations. It also provides an option to import from phi.flow if JAX is not available.
```python
%pip install --quiet phiflow
from phi.torch.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.jax or phi.tf as well.
```
--------------------------------
### Initialize Grid and Plot Initial State (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Reaction_Diffusion.ipynb
Initializes the grid states `u` and `v` for the reaction-diffusion simulation. It demonstrates creating initial conditions using noise and a Gaussian-like function, then stacking them and plotting the initial configuration. This sets up the starting point for the simulation.
```python
u0 = [
CenteredGrid(Noise(scale=20, smoothness=1.3), x=100, y=100) * .2 + .1,
CenteredGrid(lambda x: math.exp(-0.5 * math.sum((x - 50)**2) / 3**2), x=100, y=100),
CenteredGrid(lambda x: math.cos(math.vec_length(x-50)/3), x=100, y=100) * .5,
]
u0 = stack(u0, batch('initialization'))
plot(u0)
```
--------------------------------
### Install PhiFlow and Import Libraries (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/mesh/Build_Mesh.ipynb
Installs the PhiFlow library and imports necessary components for flow simulations and visualization. This is typically the first step in using PhiFlow.
```python
%pip install --quiet phiflow
from phi.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from tqdm.notebook import trange
```
--------------------------------
### Example Array Filenames - Bash
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Scene_Format_Specification.md
Provides concrete examples of how array files are named according to the specified convention, demonstrating the uppercase property name and zero-padded frame index.
```bash
Density_000000.npz
Velocity_000042.npz
```
--------------------------------
### Install and Import PhiFlow with JAX
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Burgers.ipynb
Installs the PhiFlow library using pip and imports necessary components from phi.jax.flow. This snippet is essential for setting up the environment for JAX-based simulations. It assumes JAX is installed or will be handled by the installation.
```python
%pip install --quiet phiflow
from phi.jax.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from tqdm.notebook import trange
```
--------------------------------
### Python Docstring Example with Markdown
Source: https://github.com/tum-pbs/phiflow/blob/master/CONTRIBUTING.md
This snippet demonstrates the Google style docstring format with Markdown used for API documentation generation in ΦFlow. It includes sections for function description, notes, examples, arguments, and return values.
```python
"""
Function description.
*Note in italic.*
Example:
```python
def python_example()
```
Args:
arg1: Description.
Indentation for multi-line description.
Returns:
Single output. For multi-output use same format as for args.
"""
```
--------------------------------
### Install and Import ΦFlow
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Unstructured.ipynb
Installs the necessary ΦFlow library from GitHub and imports core components. This is a prerequisite for using the library's functionalities.
```python
# !pip install --upgrade --quiet git+https://github.com/tum-pbs/PhiFlow@2.5-develop
from phi.flow import *
```
--------------------------------
### Build Unstructured Mesh for Simulation
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/mesh/FVM_BackStep.ipynb
Defines an obstacle and constructs an unstructured mesh using predefined vertical coordinates and the obstacle. The mesh is then plotted to visualize its structure.
```python
obstacle = Box(x=.5, y=.5)
vert_x = concat([
math.linspace(0, .4, spatial(x=20))[:-1],
math.linspace(.4, .6, spatial(x=20))[:-1],
math.linspace(.6, 1, spatial(x=20)),
], 'x')
vert_y = math.linspace(0, 1, spatial(y=31))
mesh = geom.build_mesh(x=vert_x, y=vert_y, obstacles=obstacle)
plot(mesh)
```
--------------------------------
### Record and Visualize Optimization Trajectory
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/optim/Close_Packing.ipynb
Records the intermediate states of the optimization process using `math.SolveTape`. This allows for visualization of how the spheres move and arrange during optimization. The recorded trajectories are then plotted as an animation.
```python
with math.SolveTape(record_trajectories=True) as solves:
minimize(loss, Solve('L-BFGS-B', x0=x0))
x_trj = solves[0].x % size
plot(Sphere(x_trj, R), size=(8, 4), animate='trajectory', frame_time=40)
```
--------------------------------
### Run and Animate Simulation: Ropes Example (PhiFlow)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/particles/Ropes.ipynb
Executes the simulation for a specified number of steps and stores the trajectory. It then animates the resulting graph trajectory over time to visualize the rope's movement. Dependencies include PhiFlow's iterate and plot functions.
```python
v0 = math.zeros_like(x)
graph_trj, v_trj = iterate(step, batch(time=50), graph, v0, substeps=2)
plot(graph_trj, animate='time')
```
--------------------------------
### Trace Multiple Streamlines
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/particles/Streamlines.ipynb
Generates multiple streamlines by initializing starting points `x0` on a grid. It then iterates the `move_along_field` function for each starting point to obtain trajectories `x_trj`.
```python
x0 = pack_dims(CenteredGrid(0, 0, domain, x=8, y=8).points, spatial, instance('start_point'))
x_trj = iterate(move_along_field, spatial(iter=50), x0)
```
--------------------------------
### Configure Colorbar in show()
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Web_Interface.md
This example shows how to configure the colormap and colorbar behavior using the `phi.vis.show()` function. It includes options for selecting a colormap and for keeping the colorbar consistent between frames.
```python
from phi.vis import show
show(data,
colormap='OrWhBl',
slow_colorbar=True)
```
--------------------------------
### Domain and Particle Initialization for FLIP Simulation
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/FLIP.ipynb
Defines the simulation domain, creates a ground obstacle using a heightmap, and initializes fluid particles in a specified region. Accessible cells for pressure computation are also defined.
```python
domain = Box(x=64, y=64)
ground = geom.Heightmap(wrap([15, 10, 0, 0, 3, 8, 20, 60], spatial('x')), domain, max_dist=10)
accessible_cells = CenteredGrid(~ground, 0, domain, x=64, y=64)
particles = distribute_points(union(Box(x=(30, 55), y=(40, 62))), x=64, y=64, bounds=domain) * (0, 0)
plot(accessible_cells, particles, overlay='args')
```
--------------------------------
### Trace Single Streamline
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/particles/Streamlines.ipynb
Traces a single streamline starting from `x0` by repeatedly applying the `move_along_field` function for a specified number of iterations. The resulting trajectory `x_trj` and the vector field `v` are then plotted.
```python
x0 = vec(x=5, y=5)
x_trj = iterate(move_along_field, spatial(iter=50), x0)
plot([v, x_trj], overlay='list', alpha=[.1, 1])
```
--------------------------------
### Compile CUDA Kernels for TensorFlow
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Installation_Instructions.md
Compiles custom CUDA kernels for ΦFlow to accelerate TensorFlow operations. This requires a TensorFlow-compatible CUDA SDK and a C++ compiler.
```bash
python /setup.py tf_cuda
```
--------------------------------
### Set Up Domain and Time Parameters (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/prerendered/Taylor_Green_Comparison.ipynb
Configures the simulation domain with periodic boundary conditions and a specified grid resolution. It also defines the time points for the simulation and initializes the analytical velocity and pressure fields.
```python
DOMAIN = dict(x=25, y=25, extrapolation=extrapolation.PERIODIC, bounds=Box(x=2*PI, y=2*PI))
TIME = math.linspace(0, 10., batch(time=200))
analytic_v = StaggeredGrid(partial(taylor_green_velocity, t=TIME), **DOMAIN)
analytic_p = CenteredGrid(partial(taylor_green_pressure, t=TIME), **DOMAIN)
plot({"Velocity": analytic_v, "Pressure": analytic_p}, animate='time')
```
--------------------------------
### Select GPU or CPU Device for Computation
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Cookbook.ipynb
Demonstrates how to list available devices (GPU or CPU) and set the default computational device for the ΦFlow backend. This is crucial for optimizing performance based on hardware availability.
```python
backend.default_backend().list_devices('GPU')
```
```python
backend.default_backend().list_devices('CPU')
```
```python
assert backend.default_backend().set_default_device('CPU')
```
--------------------------------
### Set Boundary Conditions and Run Simulation
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/mesh/FVM_Cylinder_GMsh.ipynb
Sets up the boundary conditions for the fluid simulation (e.g., inflow, no-slip) and initializes the velocity field based on the mesh. It then runs the simulation for a specified number of time steps using `math.iterate`.
```python
boundary = {'x-': vec(x=1, y=0), 'x+': ZERO_GRADIENT, 'y': 0, 'cyl': 0}
velocity = Field(mesh, tensor(vec(x=0, y=0)), boundary)
v_trj = math.iterate(implicit_time_step, batch(time=100), velocity, dt=0.001, range=trange)
```
--------------------------------
### Implement Gradient Descent Step and Trajectory (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/optim/Gradient_Descent.ipynb
Defines a single gradient descent step with a fixed step size and then iteratively applies this step to trace an optimization trajectory starting from a specific point. The trajectory is then plotted.
```python
def gradient_descent_step(x):
return x - .1 * pot_grad(x)
x0 = vec(x=1, y=0)
opt_trj = iterate(gradient_descent_step, batch(iter=50), x0)
plot(opt_trj.iter.as_spatial(), size=(5, 2))
```
--------------------------------
### Reference Existing Scenes with ΦFlow
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Reading_and_Writing_Data.md
Demonstrates how to reference existing simulation scenes using their full path or directory and ID. It also shows how to list all available scenes in a given directory. This functionality is crucial for accessing previously saved simulation data.
```python
from phi.flow import *
scene = Scene.at('~/data/sim_000000') # reference an existing scene by full path
scene = Scene.at('~/data', 0) # reference an existing scene by directory and id
scenes = Scene.list('~/data') # list all scenes in directory
```
--------------------------------
### Define Domain and Fluid Settings for SPH
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/particles/SPH.ipynb
Sets up the simulation domain, smoothing length, initial particle positions, and physical parameters like particle mass, time step, viscosity, gravity, and normalization constants for pressure and viscosity forces. It also visualizes the domain and initial particle distribution.
```python
domain = Box(x=80, y=80, z=80)
smoothing_length = 0.8 # copied from warp, we would usually set desired_neighbors instead.
initial_positions = pack_dims(math.meshgrid(x=25, y=100, z=25), spatial, instance('particles')) * smoothing_length
initial_positions += 0.001 * smoothing_length * math.random_normal(initial_positions.shape)
particles = Sphere(initial_positions, volume=smoothing_length**3, radius_variable=False)
desired_neighbors = sph.expected_neighbors(particles.volume, smoothing_length, 3)
particle_mass = 0.01 * math.mean(particles.volume)
dt = 0.01 * smoothing_length
dynamic_visc = 0.025
damping_coef = -0.95
gravity = vec(x=0, y=0, z=-0.1)
pressure_normalization = -(45.0 * particle_mass) / (PI * smoothing_length**6)
viscous_normalization = (45.0 * dynamic_visc * particle_mass) / (PI * smoothing_length**6)
plot([domain, initial_positions], overlay='list', alpha=[.1, .4], size=(3, 3))
```
--------------------------------
### Create and List Scenes
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/IO_with_Scenes.ipynb
Demonstrates how to create a new scene for storing data and how to list existing scenes in a directory. A scene appends an index suffix to the provided name.
```python
scene = Scene.create('./data', name='sim')
print(scene)
scenes = Scene.list('./data')
print(scenes)
```
--------------------------------
### Set Up Boundary Conditions and Run Simulation
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Lid_Driven_Cavity.ipynb
Initializes the fluid simulation domain with specified boundary conditions and runs the simulation for a set number of time steps using the defined 'step' function.
```python
boundary = {'x': 0, 'y-': 0, 'y+': vec(x=1, y=0)}
v0 = StaggeredGrid(0, boundary, x=50, y=32)
v_trj, p_trj = iterate(step, batch(time=300), v0, None)
```
--------------------------------
### Verify PhiFlow Installation
Source: https://github.com/tum-pbs/phiflow/blob/master/README.md
Verifies the PhiFlow installation and checks for compatible PyTorch, Jax, and TensorFlow installations.
```python
$
python3 -c "import phi; phi.verify()"
```
--------------------------------
### Initialize Velocity Field and Run Simulation
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/mesh/FVM_BackStep.ipynb
Sets up boundary conditions for the velocity field on the mesh and initializes it to zero. It then runs the simulation for a specified number of time steps using the implicit_time_step function and visualizes the trajectory.
```python
boundary = {'x-': vec(x=.1, y=0), 'obstacle': 0, 'y': 0, 'x+': ZERO_GRADIENT}
velocity = Field(mesh, tensor(vec(x=0, y=0)), boundary)
v_trj = math.iterate(implicit_time_step, batch(time=100), velocity, dt=0.01, range=trange)
```
--------------------------------
### Create and Visualize Different Types of Grids in ΦFlow
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Cookbook.ipynb
Demonstrates the creation of various grid types in ΦFlow, including `CenteredGrid` and `StaggeredGrid`, with different initializations (zero, predefined values, noise, functions) and boundary conditions. It also shows how to visualize these grids using `vis.plot`.
```python
zero_grid = CenteredGrid(0, 0, x=32, y=32, bounds=Box(x=1, y=1))
y_grid = CenteredGrid((0, 1), extrapolation.BOUNDARY, x=32, y=32)
noise_grid = CenteredGrid(Noise(), extrapolation.PERIODIC, x=32, y=32)
sin_curve = CenteredGrid(lambda x: math.sin(x), extrapolation.PERIODIC, x=100, bounds=Box(x=2 * PI))
vis.plot(zero_grid, y_grid, noise_grid, sin_curve, size=(12, 3))
```
```python
zero_grid = StaggeredGrid(0, 0, x=32, y=32, bounds=Box(x=1, y=1))
y_grid = StaggeredGrid((0, 1), extrapolation.BOUNDARY, x=32, y=32)
noise_grid = StaggeredGrid(Noise(), extrapolation.PERIODIC, x=32, y=32)
sin_curve = StaggeredGrid(lambda x: math.sin(x), extrapolation.PERIODIC, x=100, bounds=Box(x=2 * PI))
vis.plot(zero_grid, y_grid, noise_grid, sin_curve, size=(12, 3))
```
--------------------------------
### Install PhiFlow using pip
Source: https://github.com/tum-pbs/phiflow/blob/master/README.md
Installs the PhiFlow library using pip. This command requires Python 3.6 or higher.
```bash
$
pip install phiflow
```
--------------------------------
### Import ΦFlow and Backend Tensors
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Math_Introduction.ipynb
This code snippet demonstrates how to import the main ΦFlow library and optionally import specific backend tensor integrations like PyTorch or TensorFlow. This is typically the first step when working with ΦFlow tensors.
```python
from phi.flow import *
# from phi.torch.flow import *
# from phi.tf.flow import *
```
--------------------------------
### Install PhiFlow and Import
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Heightmaps.ipynb
Installs the PhiFlow library from GitHub and imports necessary modules for flow operations. This is a prerequisite for using PhiFlow functionalities.
```python
# !pip install git+https://github.com/tum-pbs/PhiFlow@3.0
from phi.flow import *
```
--------------------------------
### Install and Import ΦFlow Package
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Fluids_Tutorial.ipynb
Installs the ΦFlow Python package from GitHub and imports necessary components for fluid simulations. This is a prerequisite for using the library's functionalities.
```python
# !pip install --quiet phiflow
from phi.flow import *
```
--------------------------------
### Define Domain, Obstacles, and Initial Particles
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/particles/FLIP.ipynb
Sets up the simulation environment by defining the bounding box for the domain, creating a simple rectangular obstacle, and distributing initial fluid particles within specified regions.
```python
domain = Box(x=64, y=64)
obstacle = Box(x=(1, 25), y=(30, 33)).rotated(-20)
initial_particles = distribute_points(union(Box(x=(15, 30), y=(50, 60)), Box(x=None, y=(-INF, 5))), x=64, y=64) * (0, 0)
plot(initial_particles.geometry, obstacle, overlay='args')
```
--------------------------------
### Install PhiFlow and Import Libraries
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/particles/Terrain.ipynb
Installs the PhiFlow library and imports necessary modules from phi.torch.flow, tqdm, and PIL for image processing. It also includes commented-out imports for alternative backends like JAX.
```python
%pip install --quiet phiflow
from phi.torch.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from tqdm.notebook import trange
from PIL import Image
# %matplotlib widget
```
--------------------------------
### Complete Fluid Simulation Example
Source: https://context7.com/tum-pbs/phiflow/llms.txt
Provides a comprehensive example of a smoke simulation. It integrates various components like advection, buoyancy, inflow, obstacles, and incompressible projection using `fluid.make_incompressible` to create a divergence-free velocity field.
```python
from phi.flow import *
# Domain setup
DOMAIN = Box(x=100, y=100)
RESOLUTION = dict(x=64, y=64)
# Initial conditions
smoke = CenteredGrid(0, extrapolation.BOUNDARY, **RESOLUTION, bounds=DOMAIN)
velocity = StaggeredGrid(0, extrapolation.ZERO, **RESOLUTION, bounds=DOMAIN)
# Inflow region
INFLOW = CenteredGrid(Sphere(center=(50, 10), radius=5), extrapolation.BOUNDARY, **RESOLUTION, bounds=DOMAIN)
# Obstacle
obstacle = Obstacle(Box(x=(45, 55), y=(40, 60)))
# Simulation parameters
dt = 1.0
buoyancy_factor = (0, 0.5) # Upward buoyancy
# Run simulation
trajectory = [smoke]
for step in range(100):
# Add smoke from inflow
smoke = smoke + INFLOW
# Compute buoyancy force
buoyancy = smoke * buoyancy_factor @ velocity
# Advect quantities
smoke = advect.mac_cormack(smoke, velocity, dt=dt)
velocity = advect.semi_lagrangian(velocity, velocity, dt=dt)
# Apply forces
velocity = velocity + buoyancy * dt
# Make velocity divergence-free
velocity, pressure = fluid.make_incompressible(velocity, obstacles=[obstacle])
trajectory.append(smoke)
# Visualize
trajectory = field.stack(trajectory, batch('time'))
vis.plot(trajectory, animate='time')
```
--------------------------------
### Configure Displayed Fields in show()
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Web_Interface.md
This example illustrates how to configure which fields are initially displayed when using the `phi.vis.show()` function. The `display` parameter can accept a single field name or a tuple of field names.
```python
from phi.vis import show
# Display a single field named 'Density'
show(data, display='Density')
# Display multiple fields: 'Density' and 'Velocity'
show(data, display=('Density', 'Velocity'))
```
--------------------------------
### Running and Visualizing FLIP Simulation Results
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/FLIP.ipynb
Executes the FLIP simulation for a specified number of time steps and visualizes the final state of the fluid particles and obstacles. This code iterates the `step` function and plots the result.
```python
particle_trj, p_trj = iterate(step, batch(t=100), particles, None, range=trange)
plot(field.mask(particle_trj).t[-1], ground, overlay='args')
```
--------------------------------
### Install PhiFlow and Import Libraries (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/prerendered/Taylor_Green_Comparison.ipynb
Installs the PhiFlow library if not already present and imports necessary modules for fluid simulations. It also sets the global precision to double for enhanced accuracy.
```python
# !pip install --upgrade --quiet git+https://github.com/tum-pbs/PhiFlow@2.3-develop
import time
from functools import partial
from tqdm.notebook import trange
from phi.jax.flow import *
math.set_global_precision(64) # double precision for all following operations
```
--------------------------------
### Define Rope Connections: Ropes Example (PhiFlow)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/particles/Ropes.ipynb
Represents the rope system as a graph, where edges define the lengths of the sticks connecting nodes. It calculates pairwise differences and distances to construct the graph. The output is a visual representation of the graph.
```python
deltas = math.pairwise_differences(x, max_distance=grid.dx.mean * 1.1, format='coo')
distances = math.vec_length(deltas)
graph = geom.Graph(x, distances, {}, deltas, distances)
plot(graph)
```
--------------------------------
### Create a Batched Tensor with Batch Dimension (Python)
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Math_Introduction.ipynb
Generates a tensor with a batch dimension, which is used for parallel computation. Slices along batch dimensions are independent. This example creates a 2D grid with multiple examples in the batch and visualizes them.
```python
from phi.jax.flow import *
plot(math.random_uniform(batch(examples=4), spatial(x=10, y=8)), show_color_bar=False)
```
--------------------------------
### Simulation Step Function: Ropes Example (PhiFlow/JAX)
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/particles/Ropes.ipynb
Defines a single simulation step for the rope system. It incorporates gravity, velocity updates, and multiple relaxation steps to adjust node positions, minimizing stick stretching. The function is compiled using jit_compile for performance.
```python
@jit_compile
def step(graph: geom.Graph, v, dt=1., gravity=vec(x=0, y=-0.01), relaxation_steps=50):
v += gravity * dt
x = graph.center + math.where(fixed, 0, dt * v)
for _ in range(relaxation_steps):
deltas = math.pairwise_differences(x, format=graph.edges)
stick_centers = x + .5 * deltas
stick_directions = math.vec_normalize(deltas, epsilon=1e-5)
next_x = stick_centers - stick_directions * .5 * graph.edges
next_x = math.mean(next_x, dual)
x = math.where(fixed, x, next_x)
v = (x - graph.center) / dt
return geom.Graph(x, graph.edges, {}), v
```
--------------------------------
### Configure Arrow Drawing in show()
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Web_Interface.md
This snippet demonstrates various parameters for configuring how arrows are drawn in the web interface using `phi.vis.show()`. Options include centering, resolution, length, and whether to draw arrow tips.
```python
from phi.vis import show
show(data,
arrow_origin='center',
max_arrow_resolution=30,
min_arrow_length=0.01,
max_arrows=1000,
draw_full_arrows=True)
```
--------------------------------
### Performing Gradient Descent Optimization
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/Fluids_Tutorial.ipynb
Demonstrates basic gradient descent. It first calculates the initial loss, then updates the initial velocity by subtracting a fraction of the calculated gradient. The process is repeated to show how the loss decreases with optimization steps.
```python
print(f"Initial loss: {simulate(initial_smoke, initial_velocity)[0]}")
initial_velocity -= 0.01 * velocity_grad
print(f"Next loss: {simulate(initial_smoke, initial_velocity)[0]}")
```
--------------------------------
### Install and Import PhiFlow Libraries
Source: https://github.com/tum-pbs/phiflow/blob/master/examples/grids/Multi_Grid_Fluid.ipynb
Installs the PhiFlow library and imports necessary modules for JAX-based fluid simulations. It also imports `trange` for creating progress bars in Jupyter notebooks. Note that alternative backends like PyTorch or TensorFlow can be used if JAX is not available.
```python
%pip install phiflow
from phi.jax.flow import *
# from phi.flow import * # If JAX is not installed. You can use phi.torch or phi.tf as well.
from tqdm.notebook import trange
```
--------------------------------
### Install and Import ΦFlow Libraries
Source: https://github.com/tum-pbs/phiflow/blob/master/docs/prerendered/HigherOrder_Demo.ipynb
Installs the latest version of the phiflow library and imports necessary modules from phi.jax.flow. It also sets the global precision for mathematical operations to 64-bit floating point.
```python
# !pip install --upgrade phiflow
from phi.jax.flow import *
from tqdm.notebook import trange
math.set_global_precision(64)
```