### FluidSim NS2D Bouss Solver - Simulation Setup Example Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/solvers/ns2d/bouss/solver.html This example demonstrates how to set up and run a simulation using the FluidSim NS2D Bouss solver. It configures simulation parameters, including grid size, time stepping, forcing, and output settings, and then starts the simulation. ```python if __name__ == "__main__": from math import pi import fluiddyn as fld params = Simul.create_default_params() params.short_name_type_run = "test" params.oper.nx = nx = 64 params.oper.ny = nx // 2 params.oper.Lx = Lx = 2 * pi params.oper.Ly = Lx / 2 params.oper.coef_dealiasing = 0.5 delta_x = Lx / nx params.nu_2 = 1.0 * 10e-6 # params.nu_8 = 2.*10e-1*params.forcing.forcing_rate**(1./3)*delta_x**8 params.time_stepping.USE_CFL = True params.time_stepping.USE_T_END = True # params.time_stepping.deltat0 = 0.1 # Period of time of the simulation params.time_stepping.t_end = 5.0 # params.time_stepping.it_end = 50 params.init_fields.type = "noise" params.forcing.enable = True # params.forcing.type = 'tcrandom_anisotropic' params.forcing.type = "user_defined" # params.forcing.nkmax_forcing = 12 # params.forcing.nkmin_forcing = 4 # params.forcing.tcrandom_anisotropic.angle = '45' # 'Proportional' # params.forcing.type_normalize params.output.sub_directory = "tests" params.output.periods_print.print_stdout = 0.01 params.output.periods_save.phys_fields = 2.0 params.output.periods_save.spectra = 0.5 params.output.periods_save.spatial_means = 0.05 params.output.periods_save.spect_energy_budg = 1.0 params.output.periods_save.increments = 1.0 params.output.periods_plot.phys_fields = 5.0 params.output.ONLINE_PLOT_OK = True params.output.spectra.HAS_TO_PLOT_SAVED = True params.output.spatial_means.HAS_TO_PLOT_SAVED = True params.output.spect_energy_budg.HAS_TO_PLOT_SAVED = False params.output.increments.HAS_TO_PLOT_SAVED = False params.output.phys_fields.field_to_plot = "rot" sim = Simul(params) # monkey-patching for forcing import numpy as np forcing_maker = sim.forcing.forcing_maker oper = forcing_maker.oper_coarse forcing0 = np.cos(2 * np.pi * oper.Y / oper.ly) omega = 2 * np.pi def compute_forcingc_each_time(self): return forcing0 * np.sin(omega * sim.time_stepping.t) forcing_maker.monkeypatch_compute_forcingc_each_time( compute_forcingc_each_time ) # sim.output.phys_fields.plot() sim.time_stepping.start() sim.output.phys_fields.plot() fld.show() ``` -------------------------------- ### Example: Setting up and Running a 2D Waves Simulation Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/solvers/waves2d/solver.html Demonstrates how to create default parameters, configure simulation settings (grid size, time stepping, initial conditions, output), instantiate the Simul class, and start the simulation. This example requires the 'fluiddyn' library. ```python if __name__ == "__main__": import fluiddyn as fld params = Simul.create_default_params() params.short_name_type_run = "test" nh = 32 Lh = 2 * np.pi params.oper.nx = nh params.oper.ny = nh params.oper.Lx = Lh params.oper.Ly = Lh # params.oper.type_fft = 'FFTWPY' delta_x = params.oper.Lx / params.oper.nx params.nu_8 = ( 2.0 * 10e-1 * params.forcing.forcing_rate ** (1 / 3) * delta_x**8 ) params.time_stepping.t_end = 1.0 params.time_stepping.USE_CFL = False params.init_fields.type = "noise" # params.forcing.enable = True # params.forcing.type = 'tcrandom' # 'Proportional' # params.forcing.type_normalize # params.output.periods_print.print_stdout = 0.25 params.output.periods_save.phys_fields = 0.5 params.output.periods_plot.phys_fields = 0.0 params.output.ONLINE_PLOT_OK = True # params.output.spectra.HAS_TO_PLOT_SAVED = True # params.output.spatial_means.HAS_TO_PLOT_SAVED = True # params.output.spect_energy_budg.HAS_TO_PLOT_SAVED = True # params.output.increments.HAS_TO_PLOT_SAVED = True params.output.phys_fields.field_to_plot = "f" sim = Simul(params) # sim.output.phys_fields.plot() sim.time_stepping.start() # sim.output.phys_fields.plot() fld.show() ``` -------------------------------- ### Simulation Setup Example Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/solvers/ns3d/strat/solver.html Demonstrates how to set up and initialize a simulation using the Simul class with default parameters, configuring grid, time stepping, initial conditions, and output settings. ```python if __name__ == "__main__": import numpy as np import fluiddyn as fld params = Simul.create_default_params() params.short_name_type_run = "test" n = 16 L = 2 * np.pi params.oper.nx = n params.oper.ny = n params.oper.nz = n params.oper.Lx = L params.oper.Ly = L params.oper.Lz = L params.oper.type_fft = "fluidfft.fft3d.mpi_with_fftwmpi3d" # params.oper.type_fft = 'fluidfft.fft3d.with_pyfftw' # params.oper.type_fft = 'fluidfft.fft3d.with_cufft' delta_x = params.oper.Lx / params.oper.nx # params.nu_8 = 2.*10e-1*params.forcing.forcing_rate**(1./3)*delta_x**8 params.nu_8 = 2.0 * 10e-1 * delta_x**8 params.time_stepping.USE_T_END = True params.time_stepping.t_end = 6.0 params.time_stepping.it_end = 2 params.init_fields.type = "noise" params.init_fields.noise.velo_max = 1.0 params.init_fields.noise.length = 1.0 # params.forcing.enable = False # params.forcing.type = 'random' # 'Proportional' # params.forcing.type_normalize params.output.periods_print.print_stdout = 0.00000000001 params.output.periods_save.phys_fields = 1.0 # params.output.periods_save.spectra = 0.5 # params.output.periods_save.spatial_means = 0.05 # params.output.periods_save.spect_energy_budg = 0.5 # params.output.periods_plot.phys_fields = 0.0 params.output.ONLINE_PLOT_OK = True # params.output.spectra.HAS_TO_PLOT_SAVED = True # params.output.spatial_means.HAS_TO_PLOT_SAVED = True # params.output.spect_energy_budg.HAS_TO_PLOT_SAVED = True # params.output.phys_fields.field_to_plot = 'rot' sim = Simul(params) ``` -------------------------------- ### Example Simulation Setup and Run Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/base/solvers/pseudo_spect.html Demonstrates how to create default parameters, configure simulation settings (grid size, viscosity, time-stepping, output), initialize a pseudo-spectral simulation, and run it. ```python if __name__ == "__main__": import fluiddyn as fld params = Simul.create_default_params() params.short_name_type_run = "test" nh = 16 Lh = 2 * np.pi params.oper.nx = nh params.oper.ny = nh params.oper.Lx = Lh params.oper.Ly = Lh delta_x = params.oper.Lx / params.oper.nx params.nu_8 = ( 2.0 * 10e-1 * params.forcing.forcing_rate ** (1.0 / 3) * delta_x**8 ) params.time_stepping.t_end = 5.0 params.init_fields.type = "noise" params.output.periods_plot.phys_fields = 0.0 params.output.periods_print.print_stdout = 0.25 params.output.periods_save.phys_fields = 2.0 sim = Simul(params) sim.output.phys_fields.plot() sim.time_stepping.start() sim.output.phys_fields.plot() fld.show() ``` -------------------------------- ### Simulation Setup and Execution Example Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/solvers/ns2d/strat/solver.html Demonstrates how to set up and run a simulation using the 2D stratified Navier-Stokes solver. Includes parameter configuration, custom forcing, and simulation execution. ```python if __name__ == "__main__": from math import pi import fluiddyn as fld params = Simul.create_default_params() params.short_name_type_run = "test" params.oper.nx = nx = 64 params.oper.ny = nx // 2 params.oper.Lx = Lx = 2 * pi params.oper.Ly = Lx / 2 params.oper.coef_dealiasing = 0.5 delta_x = Lx / nx params.nu_2 = 1.0 * 10e-6 # params.nu_8 = 2.*10e-1*params.forcing.forcing_rate**(1./3)*delta_x**8 params.N = 1.0 # Brunt Vaisala frequency params.time_stepping.USE_CFL = True params.time_stepping.USE_T_END = True # params.time_stepping.deltat0 = 0.1 # Period of time of the simulation params.time_stepping.t_end = 5.0 # params.time_stepping.it_end = 50 params.init_fields.type = "noise" params.forcing.enable = True # params.forcing.type = 'tcrandom_anisotropic' params.forcing.type = "user_defined" params.forcing.nkmax_forcing = 12 params.forcing.nkmin_forcing = 4 params.forcing.tcrandom_anisotropic.angle = "45" # 'Proportional' # params.forcing.type_normalize params.output.sub_directory = "tests" params.output.periods_print.print_stdout = 0.01 params.output.periods_save.phys_fields = 2.0 params.output.periods_save.spectra = 0.5 params.output.periods_save.spatial_means = 0.05 params.output.periods_save.spect_energy_budg = 1.0 params.output.periods_save.increments = 1.0 params.output.periods_plot.phys_fields = 5.0 params.output.ONLINE_PLOT_OK = True params.output.spectra.HAS_TO_PLOT_SAVED = True params.output.spatial_means.HAS_TO_PLOT_SAVED = True params.output.spect_energy_budg.HAS_TO_PLOT_SAVED = False params.output.increments.HAS_TO_PLOT_SAVED = False params.output.phys_fields.field_to_plot = "rot" sim = Simul(params) # monkey-patching for forcing import numpy as np forcing_maker = sim.forcing.forcing_maker oper = forcing_maker.oper_coarse forcing0 = np.cos(2 * np.pi * oper.Y / oper.ly) omega = 2 * np.pi def compute_forcingc_each_time(self): return forcing0 * np.sin(omega * sim.time_stepping.t) forcing_maker.monkeypatch_compute_forcingc_each_time( compute_forcingc_each_time ) # sim.output.phys_fields.plot() sim.time_stepping.start() sim.output.phys_fields.plot() fld.show() ``` -------------------------------- ### Example: Running a Predator-Prey Simulation Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/solvers/models0d/predaprey/solver.html Demonstrates how to set up and run a predator-prey simulation using the Simul class. It includes setting simulation parameters, initial conditions, and starting the time stepping. ```python if __name__ == "__main__": import fluiddyn as fld params = Simul.create_default_params() params.time_stepping.deltat0 = 0.1 params.time_stepping.t_end = 20 params.output.periods_print.print_stdout = 0.01 sim = Simul(params) sim.state.state_phys.set_var("X", 2) sim.state.state_phys.set_var("Y", 1.1) # sim.output.phys_fields.plot() sim.time_stepping.start() fld.show() ``` -------------------------------- ### Example Simulation Setup with ForcingMilestone3D Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/solvers/ns3d/forcing/milestone.html Sets up parameters for a 3D Navier-Stokes simulation using the Simul class, enabling and configuring the 'milestone' forcing type. This example demonstrates how to set physical dimensions, grid resolution, and forcing parameters. ```python from time import perf_counter import matplotlib.pyplot as plt from fluidsim.solvers.ns3d.solver import Simul params = Simul.create_default_params() diameter = 0.5 number_cylinders = 3 speed = 0.1 ny = params.oper.ny = 96 // 2 nx = params.oper.nx = 4 * ny / 3 ly = params.oper.Ly = 3 * diameter * number_cylinders lx = params.oper.Lx = ly / ny * nx * 4 / number_cylinders params.oper.nz = 8 params.oper.Lz = 1.0 params.forcing.enable = True params.forcing.type = "milestone" params.forcing.milestone.nx_max = 48 objects = params.forcing.milestone.objects ``` -------------------------------- ### Shallow Water Simulation Setup and Execution Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/solvers/sw1l/solver.html Demonstrates how to set up and run a simulation using the one-layer shallow water solver. This includes parameter configuration, initialization, and starting the time-stepping process. ```python if __name__ == "__main__": import numpy as np import fluiddyn as fld params = Simul.create_default_params() params.short_name_type_run = "test" nh = 32 Lh = 2 * np.pi params.oper.nx = nh params.oper.ny = nh params.oper.Lx = Lh params.oper.Ly = Lh delta_x = params.oper.Lx / params.oper.nx params.nu_8 = ( 2.0 * 10e-1 * params.forcing.forcing_rate ** (1.0 / 3) * delta_x**8 ) params.time_stepping.t_end = 1.0 # params.time_stepping.USE_CFL = False # params.time_stepping.deltat0 = 0.01 params.init_fields.type = "noise" params.forcing.enable = True params.forcing.type = "waves" params.output.periods_print.print_stdout = 0.25 params.output.periods_save.phys_fields = 0.5 params.output.periods_save.spectra = 0.5 params.output.periods_save.spectra_energy_budg = 0.5 params.output.periods_save.increments = 0.5 params.output.periods_save.pdf = 0.5 params.output.periods_save.time_signals_fft = True params.output.periods_plot.phys_fields = 0.0 params.output.phys_fields.field_to_plot = "eta" sim = Simul(params) sim.output.phys_fields.plot(key_field="eta") sim.time_stepping.start() sim.output.phys_fields.plot(key_field="eta") fld.show() ``` -------------------------------- ### Simulation Setup and Execution Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/solvers/ns2d/solver.html Configures simulation parameters, initializes the simulation object, and starts the time-stepping process. This snippet demonstrates a typical workflow for running a simulation. ```python from math import pi import fluiddyn as fld params = Simul.create_default_params() params.short_name_type_run = "test" params.oper.nx = params.oper.ny = nh = 32 params.oper.Lx = params.oper.Ly = Lh = 2 * pi # params.oper.coef_dealiasing = 1. delta_x = Lh / nh params.nu_8 = ( 2.0 * 10e-1 * params.forcing.forcing_rate ** (1.0 / 3) * delta_x**8 ) params.time_stepping.t_end = 10.0 params.init_fields.type = "dipole" params.forcing.enable = False params.forcing.type = "random" # 'Proportional' # params.forcing.type_normalize params.output.sub_directory = "tests" # params.output.periods_print.print_stdout = 0.25 params.output.periods_save.phys_fields = 1.0 params.output.periods_save.spectra = 0.5 params.output.periods_save.spatial_means = 0.05 # params.output.periods_save.spect_energy_budg = 0.5 # params.output.periods_save.increments = 0.5 # params.output.periods_plot.phys_fields = 2.0 params.output.ONLINE_PLOT_OK = True # params.output.spectra.HAS_TO_PLOT_SAVED = True # params.output.spatial_means.HAS_TO_PLOT_SAVED = True # params.output.spect_energy_budg.HAS_TO_PLOT_SAVED = True # params.output.increments.HAS_TO_PLOT_SAVED = True params.output.phys_fields.field_to_plot = "rot" sim = Simul(params) # sim.output.phys_fields.plot() sim.time_stepping.start() # sim.output.phys_fields.plot() fld.show() ``` -------------------------------- ### Run Simulation Examples Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/util/scripts/turb_trandom_anisotropic.html Examples of how to run the simulation script with different options, including printing parameters and plotting forcing. ```bash ./run_simul.py --only-print-params ``` ```bash ./run_simul.py --only-print-params-as-code ``` ```bash ./run_simul.py -F 0.3 --delta-F 0.1 --ratio-kfmin-kf 0.8 --ratio-kfmax-kf 0.5 -opf ``` ```bash ./run_simul.py -F 1.0 --delta-F 0.1 --ratio-kfmin-kf 0.8 --ratio-kfmax-kf 0.5 -opf ``` ```bash mpirun -np 2 ./run_simul.py ``` -------------------------------- ### Fluidsim Simulation Execution Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/base/solvers/base.html Example of creating default parameters, configuring simulation settings, instantiating the Simul class, and starting the time stepping process. ```python if __name__ == "__main__": params = Simul.create_default_params() params.short_name_type_run = "test" params.time_stepping.USE_CFL = False params.time_stepping.t_end = 2.0 params.time_stepping.deltat0 = 0.1 sim = Simul(params) sim.time_stepping.start() ``` -------------------------------- ### start() Source: https://fluidsim.readthedocs.io/en/latest/genindex.html Starts the time stepping process for a simulation. ```APIDOC ## method fluidsim.base.time_stepping.base.TimeSteppingBase0.start() ### Description Initiates the time evolution of the simulation according to the defined time-stepping scheme. ### Usage Call this method to begin the simulation run after all parameters and initial conditions have been set. ``` -------------------------------- ### Setup Fluidsim Python Environment and Install Source: https://fluidsim.readthedocs.io/en/latest/_sources/examples/clusters/adastra/README.md.txt Configures the Adastra environment modules, sets necessary environment variables for FFTW and PYFFTW, creates a Python virtual environment, and installs the Fluidsim stack from source. ```shell module purge module load cpe/23.12 module load craype-x86-genoa module load PrgEnv-gnu module load gcc/13.2.0 module load cray-hdf5-parallel cray-fftw module load cray-python export LIBRARY_PATH=/opt/cray/pe/fftw/3.3.10.6/x86_genoa/lib export CFLAGS="-I/opt/cray/pe/fftw/3.3.10.6/x86_genoa/include" export PYFFTW_LIB_DIR="/opt/cray/pe/fftw/3.3.10.6/x86_genoa/lib" export PYFFTW_INCLUDE="/opt/cray/pe/fftw/3.3.10.6/x86_genoa/include" python -m venv ~/venv-fluidsim . ~/venv-fluidsim/bin/activate pip install pip -U python ~/dev/fluidsim/scripts/install-fluidsim-stack-from-source.py --fftw-openmp -v ``` -------------------------------- ### Run Fluidsim Apptainer Container and Install Source: https://fluidsim.readthedocs.io/en/latest/_sources/apptainer/README.md.txt Enters the Apptainer container and proceeds to install Fluidsim from source, including setting up a virtual environment, installing dependencies like h5py and pytest, cloning the Fluidsim repository, and running tests. ```sh cd ~/apptainer apptainer shell --no-home image-fluidsim.sif ``` ```sh python -m venv venv-fluidsim . venv-fluidsim/bin/activate HDF5_MPI="ON" pip install --no-binary=h5py h5py pytest pytest-mpi python -c 'import h5py; h5py.run_tests()' hg clone https://foss.heptapod.net/fluiddyn/fluidsim cd fluidsim/ pip install ".[test,mpi,fft]" pytest --pyargs fluidsim pip install fluidfft-fftw fluidfft-fftwmpi fluidfft-mpi_with_fftw mpirun -np 2 pytest --pyargs fluidsim pip install fluidfft-p3dfft pip install fluidfft-pfft ``` -------------------------------- ### Pythran Configuration Example Source: https://fluidsim.readthedocs.io/en/latest/build-from-source.html Example configuration for a ~/.pythranrc file to enable complex hooks and specify C++ compilers. ```ini [pythran] complex_hook = True [compiler] CXX=clang++ CC=clang ``` -------------------------------- ### Start Simulation and Print Duration Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/solvers/ns3d/forcing/milestone.html Record the start time, initiate the simulation's time stepping, and print the total execution time. ```python t_start = perf_counter() sim.time_stepping.start() mpi.printby0(f"Done in {perf_counter() - t_start} s") ``` -------------------------------- ### Abstract Method for Starting Simulation Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim_core/scripts/restart.html Abstract method to be implemented by subclasses. It starts the new simulation execution. ```python @abstractmethod def _start_sim(self, sim, args): """Start the new simulation""" ``` -------------------------------- ### Build and Install Fluidsim from Source Source: https://fluidsim.readthedocs.io/en/latest/_sources/examples/clusters/gricad_guix/README.md.txt Builds and installs Fluidsim using the specified manifest and package definition. This process is time-intensive. ```sh source /applis/site/guix-start.sh # This will take a while guix package -f $DIR_SCM_FILES/python-fluidsim.scm --manifest=$DIR_SCM_FILES/manifest.scm --profile=$HOME/guix-profile-fluidsim ``` -------------------------------- ### Build and Install Fluidsim from Source Source: https://fluidsim.readthedocs.io/en/latest/examples/clusters/gricad_guix/README.html Installs Fluidsim and its dependencies from source using the specified manifest and package definition files. This is a time-intensive process. ```bash source /applis/site/guix-start.sh # This will take a while guix package -f $DIR_SCM_FILES/python-fluidsim.scm --manifest=$DIR_SCM_FILES/manifest.scm \ --profile=$HOME/guix-profile-fluidsim ``` -------------------------------- ### RestarterABC: __start_sim() Source: https://fluidsim.readthedocs.io/en/latest/generated/fluidsim_core.scripts.restart.html Abstract method to start the new simulation. Subclasses need to implement the specific simulation start logic. ```python @abstractmethod def __start_sim(sim, args): """Start the new simulation""" pass ``` -------------------------------- ### Pythran Configuration Example Source: https://fluidsim.readthedocs.io/en/latest/_sources/build-from-source.md.txt Example configuration for a ~/.pythranrc file to customize Pythran compilation settings. Note that Fluidsim build does not use this file directly. ```sh [pythran ] complex_hook = True [compiler ] CXX=clang++ CC=clang ``` -------------------------------- ### Install and Setup Mercurial Source: https://fluidsim.readthedocs.io/en/latest/_sources/examples/clusters/gricad_guix/README.md.txt Installs Mercurial with the `hg-evolve` and `hg-git` extensions, then initializes Mercurial setup. ```bash uv tool install -p 3.13 mercurial --with hg-evolve --with hg-git uvx hg-setup init -f ``` -------------------------------- ### Install and Setup Mercurial Source: https://fluidsim.readthedocs.io/en/latest/_sources/examples/clusters/adastra/README.md.txt Installs Mercurial with specific extensions and initializes it for use. ```shell uv tool install mercurial --with hg-git --with hg-evolve uvx hg-setup init ``` -------------------------------- ### Install UV and Environment Setup Source: https://fluidsim.readthedocs.io/en/latest/examples/clusters/adastra/README.html Install the UV package manager and source its environment script to use installed applications. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```bash . $HOME/.local/bin/env ``` -------------------------------- ### Main Execution Block Source: https://fluidsim.readthedocs.io/en/latest/_sources/ipynb/executed/parametric_study_ns3dstrat/0_run_simulations.ipynb.txt Parses command-line arguments and initiates the main simulation setup function. Prints the parsed arguments for verification. ```python if __name__ == "__main__": args = parser.parse_args() mpi.printby0(args) params, sim = main(args) ``` -------------------------------- ### Install Mercurial with Extensions using UV Source: https://fluidsim.readthedocs.io/en/latest/examples/clusters/gricad_guix/README.html Installs Mercurial version 3.13 with hg-evolve and hg-git extensions using UV, then initializes Mercurial setup. ```bash uv tool install -p 3.13 mercurial --with hg-evolve --with hg-git uvx hg-setup init -f ``` -------------------------------- ### Setup Simulation Directory Source: https://fluidsim.readthedocs.io/en/latest/ipynb/restart_modif_resol.html Initializes the simulation directory by removing any existing data and setting up the base path. ```python from pathlib import Path import shutil path_fls = "/tmp/sim_data" path_base = Path(path_fls) / "doc_aniso" shutil.rmtree(path_base, ignore_errors=True) ``` -------------------------------- ### Install Fluidsim with Custom Backend Source: https://fluidsim.readthedocs.io/en/latest/_sources/build-from-source.md.txt Install Fluidsim using pip, specifying a custom backend for the build configuration. This example sets the 'transonic-backend' to 'python'. ```sh pip install . -v --config-settings=setup-args=-Dtransonic-backend=python ``` -------------------------------- ### Install Fluidsim with Multiple Config Settings Source: https://fluidsim.readthedocs.io/en/latest/_sources/build-from-source.md.txt Install Fluidsim using pip, specifying multiple configuration settings. This example disables 'xsimd' and sets the 'transonic-backend'. ```sh pip install . -v \ -C setup-args=-Dtransonic-backend=python \ -C setup-args=-Duse-xsimd=false ``` -------------------------------- ### Setup Conda-based Environment and Install Source: https://fluidsim.readthedocs.io/en/latest/_sources/build-from-source.md.txt Clones the Transonic repository (if necessary) and then uses Pixi to perform an editable installation of Fluidsim and run tests within a conda-forge environment. ```sh # TODO: remove this clone after Transonic release hg clone https://foss.heptapod.net/fluiddyn/transonic/ ../transonic pixi run install-editable pixi run fluidsim-test -v ``` -------------------------------- ### Get Start and Last Times from Path Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/base/output/print_stdout.html Retrieves the start and last times from a simulation run path. This is a utility function for accessing timing information stored in the simulation output. ```python def get_times_start_last(self): return times_start_last_from_path(self.sim.output.path_run) ``` -------------------------------- ### Setup Simulation Environment Source: https://fluidsim.readthedocs.io/en/latest/_sources/ipynb/restart_modif_resol.ipynb.txt Initializes the simulation environment by removing existing data, setting the FLUIDSIM_PATH, and specifying the TRANSONIC_BACKEND. ```python from pathlib import Path import shutil path_fls = "/tmp/sim_data" path_base = Path(path_fls) / "doc_aniso" shutil.rmtree(path_base, ignore_errors=True) ``` ```python import os os.environ["FLUIDSIM_PATH"] = path_fls os.environ["TRANSONIC_BACKEND"] = "python" ``` -------------------------------- ### Setup and Cleanup for Tutorial Data Source: https://fluidsim.readthedocs.io/en/latest/_sources/ipynb/executed/parametric_study_ns3dstrat/0_run_simulations.ipynb.txt This snippet imports the fluidsim library and removes any existing tutorial data directory to ensure a clean state before running new simulations. ```Python import fluidsim as fls path_dir_data = Path(fls.FLUIDSIM_PATH) / "tutorial_parametric_study" shutil.rmtree(path_dir_data, ignore_errors=True) ``` -------------------------------- ### Run Fluidsim Apptainer Shell Source: https://fluidsim.readthedocs.io/en/latest/apptainer/README.html Starts an Apptainer shell with no home directory access. This is the entry point to the container for installation. ```bash cd ~/apptainer apptainer shell --no-home image-fluidsim.sif ``` -------------------------------- ### Example Help Message Source: https://fluidsim.readthedocs.io/en/latest/generated/fluidsim.util.scripts.turb_trandom_anisotropic.html Displays the help message for the run_simul.py script, outlining available arguments and options for setting up simulations. ```bash usage: run_simul.py [-h] [-oppac] [-opp] [-opf] [-nz NZ] [--ratio-nh-nz RATIO_NH_NZ] [--t_end T_END] [-N N] [-nu NU] [--nu4 NU4] [-Rb RB] [--Rb4 RB4] [--coef-nu4 COEF_NU4] [--forced-field FORCED_FIELD] [--init-velo-max INIT_VELO_MAX] [--nh-forcing NH_FORCING] [--ratio-kfmin-kf RATIO_KFMIN_KF] [--ratio-kfmax-kf RATIO_KFMAX_KF] [-F F] [--delta-F DELTA_F] [--spatiotemporal-spectra] [--projection PROJECTION] [--disable-no-vz-kz0] [--disable-NO-SHEAR-MODES] [--max-elapsed MAX_ELAPSED] [--coef-dealiasing COEF_DEALIASING] [--periods_save-phys_fields PERIODS_SAVE_PHYS_FIELDS] [--sub-directory SUB_DIRECTORY] [--modify-params MODIFY_PARAMS] Launcher for simulations with the solver ns3d.strat and the forcing tcrandom_anisotropic. Examples -------- ./run_simul.py --only-print-params ./run_simul.py --only-print-params-as-code ./run_simul.py -F 0.3 --delta-F 0.1 --ratio-kfmin-kf 0.8 --ratio-kfmax-kf 1.5 -opf ./run_simul.py -F 1.0 --delta-F 0.1 --ratio-kfmin-kf 0.8 --ratio-kfmax-kf 1.5 -opf ``` -------------------------------- ### Set Optimization Level Source: https://fluidsim.readthedocs.io/en/latest/_sources/build-from-source.md.txt Install Fluidsim with pip, specifying a custom optimization level for the build. This example sets the optimization level to '2'. ```sh pip install . -v -C setup-args=-Doptimization=2 ``` -------------------------------- ### Taylor Green Integration Setup Source: https://fluidsim.readthedocs.io/en/latest/_sources/ipynb/executed/taylor-green.ipynb.txt Initializes the parameters and arrays required for the Taylor Green integration. This includes setting up the grid, initial conditions, and physical constants. ```python import numpy as np import matplotlib.pyplot as plt from matplotlib import animation # Grid parameters N = 128 x = np.linspace(0, 2*np.pi, N, endpoint=False) dx = x[1] - x[0] # Physical parameters nu = 1e-3 # Time parameters t_max = 10 dt = 0.001 # Initial conditions psi = np.sin(x) # Arrays for storing results psi_history = [psi] t_history = [0] ``` -------------------------------- ### Get Averaged Dimensionless Numbers Source: https://fluidsim.readthedocs.io/en/latest/_sources/ipynb/executed/parametric_study_ns3dstrat/1_analyze_1_simul.ipynb.txt Retrieves spatially averaged dimensionless numbers from the simulation output. Specify 'tmin' to set the start time for averaging. ```python period = info_forcing["period"] ``` ```python dimless_numbers = sim.output.spatial_means.get_dimless_numbers_averaged( tmin=period ) dimless_numbers ``` -------------------------------- ### Example Usage Source: https://fluidsim.readthedocs.io/en/latest/_sources/ipynb/executed/taylor-green.ipynb.txt Demonstrates how to run the simulation with specific parameters and visualize the energy decay. ```python if __name__ == '__main__': nx, ny = 64, 64 Lx, Ly = 2 * np.pi, 2 * np.pi nt = 100 dt = 0.01 nu = 0.01 energy_history = run_simulation(nx, ny, Lx, Ly, nt, dt, nu) plot_energy_decay(energy_history) ``` -------------------------------- ### Create Initial Simulation Directory Source: https://fluidsim.readthedocs.io/en/latest/_sources/ipynb/restart_modif_resol.ipynb.txt Generates an initial simulation directory with specified parameters, including output periods for standard output and energy budget spectrography. ```python from fluidsim.util.scripts.turb_trandom_anisotropic import main params, sim = main( args=( '--sub-directory "doc_aniso" -nz 12 --ratio-nh-nz 2 --t_end 1 ' '--modify-params "params.output.periods_print.print_stdout = 0.25; ' 'params.output.periods_save.spect_energy_budg = 0"' ) ) ``` -------------------------------- ### Define Grid and Initial Conditions Source: https://fluidsim.readthedocs.io/en/latest/_sources/ipynb/executed/parametric_study_ns3dstrat/1_analyze_1_simul.ipynb.txt Defines the spatial grid and initializes velocity and pressure fields for the simulation. This setup is crucial for the simulation's starting state. ```python x = np.linspace(0, 1, Nx) y = np.linspace(0, 1, Ny) X, Y = np.meshgrid(x, y) # Example: Initial vortex center_x, center_y = 0.5, 0.5 radius = 0.1 initial_velocity[:, :, 0] = -np.sin(np.pi * (Y - center_y)) * np.exp(-((X - center_x)**2 + (Y - center_y)**2) / radius**2) initial_velocity[:, :, 1] = np.sin(np.pi * (X - center_x)) * np.exp(-((X - center_x)**2 + (Y - center_y)**2) / radius**2) ``` -------------------------------- ### Set Up a 2D Simulation Source: https://fluidsim.readthedocs.io/en/latest/_sources/ipynb/executed/taylor-green.ipynb.txt Initializes a 2D simulation with specified parameters. This is a foundational step for many simulation types. ```python from fluidsim import Base2D sim_2d = Base2D(grid_size=32, Re=10.0, dt=0.01, T=0.5) sim_2d.run() ``` -------------------------------- ### Fluidsim Dataframe Maker Initialization Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/util/util.html Initializes a specialized DataframeMaker for Fluidsim, providing methods to get simulation start and last times, and load simulation data. ```python class _DataframeMakerFluidsim(DataframeMaker): def get_time_start_from_path(self, path): """ """Get first time""" t_start, _ = times_start_last_from_path(path) return t_start def get_time_last_from_path(self, path): """ """Get last saved time""" return get_last_time_spatial_means_from_path(path) def load_sim(self, path): """Load a simulation object""" return load_sim_for_plot(path, hide_stdout=True) def get_dataframe_from_paths( self, paths, tmin=None, tmax=None, use_cache=True, customize=None, ): df = super().get_dataframe_from_paths( paths, tmin, tmax, use_cache, customize ) if "R2" in df.columns and "R4" in df.columns: df["min_R"] = np.array([df.R2, df.R4]).min(axis=0) return df _dataframe_maker = _DataframeMakerFluidsim() get_mean_values_from_path = _dataframe_maker.get_mean_values_from_path get_dataframe_from_paths = _dataframe_maker.get_dataframe_from_paths ``` -------------------------------- ### Initialize 3D Simulation Source: https://fluidsim.readthedocs.io/en/latest/_sources/ipynb/executed/taylor-green.ipynb.txt Sets up a 3D simulation environment with specified grid size, Reynolds number, time step, and total simulation time. ```python from fluidsim import Base3D sim_3d = Base3D(grid_size=32, Re=10.0, dt=0.01, T=0.5) ``` -------------------------------- ### Taylor-Green Vortex Simulation Setup Source: https://fluidsim.readthedocs.io/en/latest/_sources/ipynb/executed/taylor-green.ipynb.txt Initializes the Taylor-Green vortex problem by setting up the grid, initial velocity, and pressure fields. This is a common starting point for CFD simulations. ```python import numpy as np def taylor_green_vortex(nx, ny, Lx, Ly, nu, t): """Computes the initial velocity and pressure fields for the Taylor-Green vortex. Args: nx (int): Number of grid points in the x-direction. ny (int): Number of grid points in the y-direction. Lx (float): Domain size in the x-direction. Ly (float): Domain size in the y-direction. nu (float): Kinematic viscosity. t (float): Time. Returns: tuple: A tuple containing: - u (np.ndarray): Velocity in the x-direction. - v (np.ndarray): Velocity in the y-direction. - p (np.ndarray): Pressure. """ x = np.linspace(0, Lx, nx, endpoint=False) y = np.linspace(0, Ly, ny, endpoint=False) X, Y = np.meshgrid(x, y) u = -np.exp(-t / (2.0 * (Lx / (2.0 * np.pi))**2 / nu)) * np.sin(X) * np.cos(Y) v = np.exp(-t / (2.0 * (Lx / (2.0 * np.pi))**2 / nu)) * np.cos(X) * np.sin(Y) p = 0.25 * (np.exp(-t / (2.0 * (Lx / (2.0 * np.pi))**2 / nu)) * (np.cos(2*X) + np.cos(2*Y)) + 2.0) return u, v, p ``` -------------------------------- ### OperatorFiniteDiff2DPeriodic Initialization and Description Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/operators/op_finitediff2d.html Demonstrates how to initialize the `OperatorFiniteDiff2DPeriodic` with grid dimensions and physical domain sizes, and how to obtain a descriptive string of the operator's configuration. This is useful for verifying operator setup. ```python if __name__ == "__main__": nx = 3 ny = 3 oper = OperatorFiniteDiff2DPeriodic([ny, nx], [nx / 2.0, ny / 2.0]) a = np.arange(nx * ny).reshape([ny, nx]) ``` -------------------------------- ### Initialize from Existing Files or Parameters Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/base/output/spatiotemporal_spectra.html Checks for existing output files and initializes simulation state from them if found. If no files exist, it initializes based on the provided simulation parameters. ```python # check for existing files paths = sort_files_tmin(self.path_dir.glob("rank*.h5")) if paths: # check values in files with open_patient(paths[0], "r") as file: if file.attrs["nb_proc"] != mpi.nb_proc: raise ValueError( f"process number ({mpi.nb_proc}) is different from " f"process number in file ({file.attrs['nb_proc']})" ) if (file.attrs["dims_order"] != self.dims_order).any(): raise ValueError("dimensions order is different from files") if (file.attrs["probes_region"] != self.probes_region).any(): raise ValueError("probes region is different from files") # init from files INIT_FROM_PARAMS = False paths_rank = [ p for p in paths if p.name.startswith(f"rank{mpi.rank:05}") ] if paths_rank: self.path_file = paths_rank[-1] with open_patient(self.path_file, "r") as file: self.index_file = file.attrs["index_file"] self.probes_k0adim_loc = file["probes_k0adim_loc"][:] self.probes_ik0_loc = file["probes_ik0_loc"][:] self.probes_k1adim_loc = file["probes_k1adim_loc"][:] self.probes_ik1_loc = file["probes_ik1_loc"][:] if self.nb_dim == 3: self.probes_k2adim_loc = file["probes_k2adim_loc"][:] self.probes_ik2_loc = file["probes_ik2_loc"][:] self.probes_nb_loc = self.probes_ik0_loc.size self.number_times_in_file = file["times"].size self.t_last_save = file["times"][-1] else: # no probes in proc self.path_file = None self.index_file = 0 self.number_times_in_file = 0 self.probes_nb_loc = 0 self.probes_ik0_loc = [] self.probes_ik1_loc = [] self.probes_ik2_loc = [] with open_patient(paths[-1], "r") as file: self.t_last_save = file["times"][-1] else: # no files were found : initialize from params INIT_FROM_PARAMS = True if self.nb_dim == 3: # pair kx,ky,kz with k0,k1,k2 iksmax = np.array([ikzmax, ikymax, ikxmax]) iksmin = np.array([1 - ikzmax, 1 - ikymax, 0]) ik0max, ik1max, ik2max = iksmax[self.dims_order] ik0min, ik1min, ik2min = iksmin[self.dims_order] ``` -------------------------------- ### Restarter Class for Simulation Restart Source: https://fluidsim.readthedocs.io/en/latest/generated/fluidsim.util.scripts.restart.html A class that encapsulates the logic for restarting a FluidSim simulation. It inherits from `RestarterABC` and provides methods for argument parsing, parameter setup, and starting the new simulation. ```python class fluidsim.util.scripts.restart.Restarter[source]: Bases: RestarterABC ``` -------------------------------- ### Set up Grid and Initial Conditions Source: https://fluidsim.readthedocs.io/en/latest/_sources/ipynb/executed/taylor-green.ipynb.txt Configures the computational grid and applies the initial velocity and pressure fields for the simulation. This snippet demonstrates setting up a 3D grid and calling the initial condition function. ```python x = np.linspace(0, 2 * np.pi, nx, endpoint=False) y = np.linspace(0, 2 * np.pi, ny, endpoint=False) z = np.linspace(0, 2 * np.pi, nz, endpoint=False) X, Y, Z = np.meshgrid(x, y, z, indexing='ij') u0, v0, w0, p0 = taylor_green_vortex(X, Y, Z, 0.0, Re) # Set initial velocity and pressure velocity_component_x.fill(u0) velocity_component_y.fill(v0) velocity_component_z.fill(w0) pressure.fill(p0) ``` -------------------------------- ### AD1D Solver Example Usage Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/solvers/ad1d/solver.html Demonstrates how to set up and run a simulation using the AD1D solver, including parameter configuration, initialization, and time stepping. ```python if __name__ == "__main__": import fluiddyn as fld params = Simul.create_default_params() params.U = 1.0 params.short_name_type_run = "test" params.oper.nx = 200 params.oper.Lx = 1.0 # params.oper.type_fft = 'FFTWPY' params.time_stepping.type_time_scheme = "RK2" # delta_x = params.oper.Lx/params.oper.nx params.nu_2 = 0.01 params.time_stepping.t_end = 0.4 params.time_stepping.USE_CFL = True # params.time_stepping.deltat0 = 0.1 params.init_fields.type = "gaussian" params.output.periods_print.print_stdout = 0.25 params.output.periods_save.phys_fields = 0.5 params.output.periods_plot.phys_fields = 0.0 params.output.phys_fields.field_to_plot = "s" # params.output.spectra.has_to_plot = 1 # False # params.output.spatial_means.has_to_plot = 1 # False # params.output.spect_energy_budg.has_to_plot = 1 # False # params.output.increments.has_to_plot = 1 # False sim = Simul(params) # sim.output.phys_fields.plot() sim.time_stepping.start() print("x of s_max: ", sim.oper.xs[sim.state.state_phys.argmax()]) sim.output.phys_fields.plot() fld.show() ``` -------------------------------- ### Get Array Range by Time Min/Max Source: https://fluidsim.readthedocs.io/en/latest/_modules/fluidsim/base/output/spatiotemporal_spectra.html Calculates the start and stop indices for a given time range (tmin, tmax) within a sorted array of times. This function is optimized using the 'boost' decorator. ```python from transonic import boost, Array, Type import numpy as np Uf32f64 = Type(np.float32, np.float64) A = Array[Uf32f64, "1d"] @boost def get_arange_minmax(times: A, tmin: Uf32f64, tmax: Uf32f64): """get a range of index for which `tmin <= times[i] <= tmax` This assumes that `times` is sorted. """ if tmin <= times[0]: start = 0 else: start = find_index_first_geq(times, tmin) if tmax >= times[-1]: stop = len(times) else: stop = find_index_first_g(times, tmax) return np.arange(start, stop) ```