### Load data for projection backend example Source: https://swiftsimio.readthedocs.io/en/latest/_sources/visualisation/projection.rst.txt Loads a SWIFT snapshot and imports project_gas, the starting point for using any projection backend. This snippet is the setup for the backend example that follows. ```python from swiftsimio import load from swiftsimio.visualisation.projection import project_gas data = load("cosmo_volume_example.hdf5") ``` -------------------------------- ### Install swiftsimio via pip Source: https://swiftsimio.readthedocs.io/en/latest/getting_started/index.html Use the pip package manager to install the swiftsimio toolkit. ```bash pip install swiftsimio ``` -------------------------------- ### Install swiftsimio with dev and docs dependencies Source: https://swiftsimio.readthedocs.io/en/latest/_sources/getting_started/index.rst.txt Installs swiftsimio in editable mode with optional dependencies for development and building documentation. Run from the cloned repository directory. ```bash cd swiftsimio pip install -e .[dev,docs] ``` -------------------------------- ### swiftsnap example output Source: https://swiftsimio.readthedocs.io/en/latest/command_line/index.html Example output produced by the swiftsnap command, showing metadata such as simulation state, cosmology parameters, and code version. ```text Untitled SWIFT simulation Written at: 2020-06-01 08:44:51 Active policies: cosmological integration, hydro, keep, self gravity, steal Output type: Snapshot, Output selection: Snapshot LLVM/Clang (11.0.0) Non-MPI version of SWIFT SWIFT (io_selection_changes) v0.8.5-725-g10d7d5b3-dirty 2020-05-29 18:00:58 +0100 Simulation state: z=0.8889, a=0.5294, t=6.421 Gyr H_0=70.3 km/(Mpc*s), ρ_crit=1.433e-05 cm**(-3) Ω_b=0.0455, Ω_k=0, Ω_lambda=0.724, Ω_m=0.276, Ω_r=0 ω=-1, ω_0=-1, ω_a=0 Gravity scheme: With per-particle softening Hydrodynamics scheme: Gadget-2 version of SPH (Springel 2005) Chemistry model: None Cooling model: None Entropy floor: None Feedback model: None Tracers: None ``` -------------------------------- ### Initialize structured array for view examples Source: https://swiftsimio.readthedocs.io/en/latest/modules/swiftsimio.objects.html Sets up a structured array to demonstrate view operations. ```python >>> import numpy as np >>> x = np.array([(-1, 2)], dtype=[('a', np.int8), ('b', np.int8)]) ``` -------------------------------- ### Output of load_statistics example Source: https://swiftsimio.readthedocs.io/en/latest/_sources/statistics/index.rst.txt Expected output from the load_statistics example, showing the statistics file fields and the name of the total_mass field. ```bash Statistics file: energy.txt, containing fields: #, step, time, a, z, total_mass, gas_mass, dm_mass, sink_mass, star_mass, bh_mass, gas_z_mass, star_z_mass, bh_z_mass, kin_energy, int_energy, pot_energy, rad_energy, gas_entropy, com_x, com_y, com_z, mom_x, mom_y, mom_z, ang_mom_x, ang_mom_y, ang_mom_z 'Total mass in the simulation' ``` -------------------------------- ### Setting Up Visualization Region Source: https://swiftsimio.readthedocs.io/en/latest/_sources/visualisation/volume_render.rst.txt Example of loading data and defining a spatial region for subsequent visualization. ```python import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import LogNorm from swiftsimio import load from swiftsimio.visualisation import volume_render # Load the data data = load("eagle_6.hdf5") # Rough location of an interesting galaxy in the volume. region = [ 0.225 * data.metadata.boxsize[0], 0.275 * data.metadata.boxsize[0], 0.12 * data.metadata.boxsize[1], 0.17 * data.metadata.boxsize[1], 0.45 * data.metadata.boxsize[2], 0.5 * data.metadata.boxsize[2], ] ``` -------------------------------- ### Initialize __SWIFTNamedColumnDataset Source: https://swiftsimio.readthedocs.io/en/latest/_modules/swiftsimio/reader.html Example of initializing a named column dataset for gas particle element mass fractions. ```python data.gas = __SWIFTNamedColumnDataset( "/PartType0/ElementMassFractions", ["hydrogen", "helium"], "element_mass_fraction", handle ) ``` ```python data.gas.element_mass_fraction.hydrogen data.gas.element_mass_fraction.helium ``` -------------------------------- ### ranges_from_array example Source: https://swiftsimio.readthedocs.io/en/latest/modules/swiftsimio.accelerated.html Demonstrates the input array and the corresponding output of contiguous ranges. ```python [0, 1, 2, 3, 5, 6, 7, 9, 11, 12, 13] ``` ```python [[0, 4], [5, 8], [9, 10], [11, 14]] ``` -------------------------------- ### Invoke the fast projection backend Source: https://swiftsimio.readthedocs.io/en/latest/_sources/visualisation/projection.rst.txt Demonstrates how to import the fast backend from swiftsimio and generate a 2D projection grid using particle positions, smoothing lengths, and mass. ```python from swiftsimio.visualisation.projection_backends import backends scatter = backends["fast"] # Using the variable names from above out = scatter(x=x, y=y, h=h, m=m, res=res) ``` -------------------------------- ### compiler_info (property) Source: https://swiftsimio.readthedocs.io/en/latest/modules/swiftsimio.html Gets and formats information about the compiler. ```APIDOC ## compiler_info (property) ### Description Get and format information about the compiler. Formatting is as: Compiler Name (Compiler Version) MPI library ### Method Property ### Signature `compiler_info: str` ### Returns - **str** - The compiler information. ``` -------------------------------- ### Populate gas dataset with required fields Source: https://swiftsimio.readthedocs.io/en/latest/_modules/swiftsimio/snapshot_writer.html A complete example showing how to initialize the Writer object and populate all required fields for the gas dataset before writing to an HDF5 file. ```python import numpy as np import unyt as u from swiftsimio import Writer, cosmo_array from swiftsimio.metadata.writer.unit_systems import cosmo_unit_system # number of gas particles n_p = 1000 # scale factor of 1.0 a = 1.0 # Box is 100 Mpc lbox = 100 boxsize = cosmo_array( [lbox, lbox, lbox], u.Mpc, comoving=True, scale_factor=a, scale_exponent=1, ) # Create the Writer object. cosmo_unit_system corresponds to default Gadget-like # units of 10^10 Msun, Mpc, and km/s w = Writer(unit_system=cosmo_unit_system, boxsize=boxsize, scale_factor=a) # Randomly spaced coordinates from 0 to lbox Mpc in each direction w.gas.coordinates = cosmo_array( np.random.rand(n_p, 3) * lbox, u.Mpc, comoving=True, scale_factor=w.scale_factor, scale_exponent=1, ) # Random velocities from 0 to 1 km/s w.gas.velocities = cosmo_array( np.random.rand(n_p, 3), u.km / u.s, comoving=True, scale_factor=w.scale_factor, scale_exponent=1, ) # Generate uniform masses as 10^6 solar masses for each particle w.gas.masses = cosmo_array( np.ones(n_p, dtype=float) * 1e6, u.solMass, comoving=True, scale_factor=w.scale_factor, scale_exponent=0, ) # Generate internal energy corresponding to 10^4 K w.gas.internal_energy = cosmo_array( np.ones(n_p, dtype=float) * 1e4 / 1e6, u.kb * u.K / u.solMass, comoving=True, scale_factor=w.scale_factor, scale_exponent=-2, ) # Generate initial guess for smoothing lengths based on mean inter-particle spacing w.gas.generate_smoothing_lengths() # w.gas.particle_ids can optionally be set, otherwise they are auto-generated # write the initial conditions out to a file w.write("ics.hdf5") ``` -------------------------------- ### diffusion_info (property) Source: https://swiftsimio.readthedocs.io/en/latest/modules/swiftsimio.html Gets and formats information about the diffusion scheme. ```APIDOC ## diffusion_info (property) ### Description Get and format information about the diffusion scheme. Formatting is as: alpha_D,0 = Diffusion alpha, beta_D = Diffusion beta Diffusion alpha (min) < alpha_D < Diffusion alpha (max) ### Method Property ### Signature `diffusion_info: str` ### Returns - **str** - Formatted diffusion scheme information. ``` -------------------------------- ### viscosity_info (property) Source: https://swiftsimio.readthedocs.io/en/latest/modules/swiftsimio.html Gets and formats information about the viscosity scheme. ```APIDOC ## viscosity_info (property) ### Description Get and format information about the viscosity scheme. Formatting is as: Viscosity Model alpha_V,0 = Alpha viscosity, ell_V = Viscosity decay length [internal units], beta_V = Beta viscosity Alpha viscosity (min) < alpha_V < Alpha viscosity (max) ### Method Property ### Signature `viscosity_info: str` ### Returns - **str** - Viscosity scheme information. ``` -------------------------------- ### hydro_info (property) Source: https://swiftsimio.readthedocs.io/en/latest/modules/swiftsimio.html Gets and formats information about the hydro scheme. ```APIDOC ## hydro_info (property) ### Description Get and format information about the hydro scheme. Formatting is as: Scheme Kernel function in DimensionD eta = Kernel eta (Kernel target N_ngb) C_CFL = CFL parameter ### Method Property ### Signature `hydro_info: str` ### Returns - **str** - Hydro scheme information. ``` -------------------------------- ### library_info (property) Source: https://swiftsimio.readthedocs.io/en/latest/modules/swiftsimio.html Gets and formats information about the libraries used. ```APIDOC ## library_info (property) ### Description Get and format information about the libraries used. Formatting is as: FFTW vFFTW library version GSL vGSL library version HDF5 vHDF5 library version ### Method Property ### Signature `library_info: str` ### Returns - **str** - The library information. ``` -------------------------------- ### Create a projected temperature cube Source: https://swiftsimio.readthedocs.io/en/latest/_sources/visualisation/volume_render.rst.txt Shows how to calculate a temperature cube by creating a mass-weighted temperature dataset and dividing it by the mass density cube. ```python from swiftsimio import load from swiftsimio.visualisation.volume_render import render_gas data = load("cosmo_volume_example.hdf5") # First create a mass-weighted temperature dataset data.gas.mass_weighted_temps = data.gas.masses * data.gas.temperatures # Map in msun / mpc^3 mass_cube = render_gas( data, resolution=256, project="masses", parallel=True, periodic=True, ) # Map in msun * K / mpc^3 mass_weighted_temp_cube = render_gas( data, resolution=256, project="mass_weighted_temps", parallel=True, periodic=True, ) # A 256 x 256 x 256 cube with dimensions of temperature temp_cube = mass_weighted_temp_cube / mass_cube ``` -------------------------------- ### present_group_names (property) Source: https://swiftsimio.readthedocs.io/en/latest/modules/swiftsimio.html Gets the names of the groups that we want to expose. ```APIDOC ## present_group_names (property) ### Description Get the names of the groups that we want to expose. ### Method Property ### Signature `present_group_names: list[str]` ### Returns - **list[str]** - List of names to expose. ``` -------------------------------- ### Create a projected temperature map Source: https://swiftsimio.readthedocs.io/en/latest/_sources/visualisation/slice.rst.txt Shows how to create a temperature map by calculating a mass-weighted temperature slice and dividing it by a mass density slice. ```python from swiftsimio import load from swiftsimio.visualisation.slice import slice_gas data = load("cosmo_volume_example.hdf5") # First create a mass-weighted temperature dataset data.gas.mass_weighted_temps = data.gas.masses * data.gas.temperatures # Map in msun / mpc^3 mass_map = slice_gas( data, z_slice=0.5 * data.metadata.boxsize[2], resolution=1024, project="masses", parallel=True, periodic=True, ) # Map in msun * K / mpc^3 mass_weighted_temp_map = slice_gas( data, z_slice=0.5 * data.metadata.boxsize[2], resolution=1024, project="mass_weighted_temps", parallel=True, periodic=True, ) temp_map = mass_weighted_temp_map / mass_map from unyt import K temp_map.convert_to_units(K) from matplotlib.pyplot import imsave from matplotlib.colors import LogNorm # Normalize and save imsave("temp_map.png", LogNorm()(temp_map.value), cmap="twilight") ``` -------------------------------- ### present_groups (property) Source: https://swiftsimio.readthedocs.io/en/latest/modules/swiftsimio.html Gets the groups containing datasets that are present in the file. ```APIDOC ## present_groups (property) ### Description Get the groups containing datasets that are present in the file. ### Method Property ### Signature `present_groups: list[str]` ### Returns - **list[str]** - List of present groups. ``` -------------------------------- ### Plot a density-temperature phase diagram Source: https://swiftsimio.readthedocs.io/en/latest/getting_started/index.html Load a SWIFT snapshot, convert gas densities and temperatures to CGS units, and generate a phase diagram plot. ```python import swiftsimio as sw # This loads all metadata but explicitly does _not_ read any particle data yet data = sw.load("/path/to/swift/output") import matplotlib.pyplot as plt data.gas.densities.convert_to_cgs() data.gas.temperatures.convert_to_cgs() plt.loglog() plt.scatter( data.gas.densities, data.gas.temperatures, s=1 ) plt.xlabel(fr"Gas density $\left[{data.gas.densities.units.latex_repr}\right]$") plt.ylabel(fr"Gas temperature $\left[{data.gas.temperatures.units.latex_repr}\right]$") plt.tight_layout() plt.savefig("test_plot.png", dpi=300) ``` -------------------------------- ### Create a gas mass density map Source: https://swiftsimio.readthedocs.io/en/latest/_sources/visualisation/slice.rst.txt Demonstrates how to use slice_gas to generate a mass density map from simulation data and save it as an image. ```python from swiftsimio import load from swiftsimio.visualisation.slice import slice_gas data = load("cosmo_volume_example.hdf5") # This creates a grid that has units msun / Mpc^3, and can be transformed like # any other unyt quantity. The position of the slice along the z axis is # provided in the z_slice argument. mass_map = slice_gas( data, z_slice=0.5 * data.metadata.boxsize[2], resolution=1024, project="masses", parallel=True, periodic=True, ) # Let's say we wish to save it as g / cm^2, from unyt import g, cm mass_map.convert_to_units(g / cm**3) from matplotlib.pyplot import imsave from matplotlib.colors import LogNorm # Normalize and save imsave("gas_slice_map.png", LogNorm()(mass_map.value), cmap="viridis") ``` -------------------------------- ### Import optional packages with fallbacks (swiftsimio.optional_packages) Source: https://swiftsimio.readthedocs.io/en/latest/_modules/swiftsimio/optional_packages.html Source code for the swiftsimio.optional_packages module. It attempts to import optional dependencies (tqdm, scipy.spatial.cKDTree, astropy, matplotlib.pyplot, numba, numba.cuda, and hdfstream) and provides mock fallbacks when they are unavailable. The module defines availability flags such as TQDM_AVAILABLE, TREE_AVAILABLE, ASTROPY_AVAILABLE, MATPLOTLIB_AVAILABLE, and CUDA_AVAILABLE, and mock functions like tqdm, jit, and cuda_jit that return the input unchanged or a trivial wrapper. When numba is missing, it prints a message suggesting 'pip install numba'. ```python from typing import Iterable, Callable, Any # TQDM try: from tqdm import tqdm TQDM_AVAILABLE = True except (ImportError, ModuleNotFoundError): [docs] def tqdm(x: Iterable, *args: tuple[Any], **kwargs: dict[str, Any]) -> Iterable: """ Mock the main tqdm function for use if it's unavailable. Parameters ---------- x : Iterable The iterable whose progress would be track by tqdm. *args : tuple[Any] Arbitrary additional arguments. **kwargs : dict[str, Any] Arbitrary additional kwargs. Returns ------- out : Iterable The input iterable is returned. """ return x TQDM_AVAILABLE = False try: from scipy.spatial import cKDTree as KDTree TREE_AVAILABLE = True except (ImportError, ModuleNotFoundError): KDTree = None TREE_AVAILABLE = False # Astropy try: import astropy ASTROPY_AVAILABLE = True except (ImportError, ModuleNotFoundError): astropy = None ASTROPY_AVAILABLE = False # matplotlib try: import matplotlib.pyplot as plt MATPLOTLIB_AVAILABLE = True except (ImportError, ModuleNotFoundError): plt = None MATPLOTLIB_AVAILABLE = False # numba try: from numba import jit, prange from numba.core.config import NUMBA_NUM_THREADS as NUM_THREADS except (ImportError, ModuleNotFoundError): try: from numba import jit, prange from numba.config import NUMBA_NUM_THREADS as NUM_THREADS except (ImportError, ModuleNotFoundError): print( "You do not have numba installed. Please consider installing " "if you are going to be doing visualisation or indexing large arrays " "(pip install numba)" ) def jit(*args: tuple[Any], **kwargs: dict[str, Any]) -> Callable: """ Mock the numba jit function for use if not available. Parameters ---------- *args : tuple[Any] Arbitrary arguments. **kwargs : dict[str, Any] Arbitrary kwargs. Returns ------- out : Callable The wrapper function (a trivial wrapper). """ return lambda func: func prange = range NUM_THREADS = 1 # Numba/CUDA try: from numba.cuda.cudadrv.error import CudaSupportError try: import numba.cuda.cudadrv.driver as drv from numba import cuda from numba.cuda import jit as cuda_jit try: CUDA_AVAILABLE = cuda.is_available() except AttributeError: # Backwards compatibility with older versions # Check for the driver d = drv.Driver() d.initialize() CUDA_AVAILABLE = True except CudaSupportError: CUDA_AVAILABLE = False except (ImportError, ModuleNotFoundError): # Mock the CudaSupportError so that we can raise it in cases # where we don't have numba installed. class CudaSupportError(Exception): """ Mock the CudaSupportError class for use if it's unavailable. Parameters ---------- message : str The error message. """ def __init__(self, message: str) -> None: self.message = message CUDA_AVAILABLE = False if not CUDA_AVAILABLE: # Mock cuda-jit to prevent crashes [docs] def cuda_jit(*args, **kwargs): # NOQA """ Mock the cuda_jit function for use if it's unavailable. Returns ------- out : Callable The wrapper function (a trivial wrapper). """ return lambda func: func # For additional CUDA API access cuda = None # hdfstream try: import hdfstream HDFSTREAM_AVAILABLE = True except (ImportError, ModuleNotFoundError): hdfstream = None HDFSTREAM_AVAILABLE = False ``` -------------------------------- ### code_info (property) Source: https://swiftsimio.readthedocs.io/en/latest/modules/swiftsimio.html Gets and formats a nicely printed set of code information. ```APIDOC ## code_info (property) ### Description Get and format a nicely printed set of code information. Formatting is as: Name (Git Branch) Git Revision Git Date ### Method Property ### Signature `code_info: str` ### Returns - **str** - The code information. ``` -------------------------------- ### Get mapping metadata Source: https://swiftsimio.readthedocs.io/en/latest/_modules/swiftsimio/metadata/objects.html Extracts mappings from SubgridScheme keys ending in 'Mapping'. ```python [docs] def get_mapping_metadata(self) -> None: """ Get the mappings based on the named columns (must have already been read). From the form: SubgridScheme/{X}To{Y}Mapping. Includes a hack of `Dust` -> `Grains` that will be deprecated. """ try: possible_keys = self.handle["SubgridScheme"].keys() available_keys = [key for key in possible_keys if key.endswith("Mapping")] available_data = [ self.handle[f"SubgridScheme/{key}"][:] for key in available_keys ] except KeyError: available_keys = [] available_data = [] # Keys have form {X}To{Y}Mapping regex = r"([a-zA-Z]*)To([a-zA-Z]*)Mapping" compiled = re.compile(regex) for key, data in zip(available_keys, available_data): matched = compiled.match(key) snake_case = _convert_snake_to_camel(key) if matched: x = matched.group(1) y = matched.group(2) ``` -------------------------------- ### Render gas volume quick view Source: https://swiftsimio.readthedocs.io/en/latest/visualisation/volume_render.html Loads data and renders a gas volume to create a density projection image. ```python import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import LogNorm from swiftsimio import load from swiftsimio.visualisation import volume_render # Load the data data = load("eagle_6.hdf5") # Rough location of an interesting galaxy in the volume. region = [ 0.225 * data.metadata.boxsize[0], 0.275 * data.metadata.boxsize[0], 0.12 * data.metadata.boxsize[1], 0.17 * data.metadata.boxsize[1], 0.45 * data.metadata.boxsize[2], 0.5 * data.metadata.boxsize[2], ] # Render the volume (note 1024 is reasonably high resolution so this won't complete # immediately; you should consider using 256, etc. for testing). rendered = volume_render.render_gas( data, resolution=1024, region=region, parallel=True ) # Quick view! By projecting along the final axis you can get # the projected density from the rendered image. plt.imsave("volume_render_quick_view.png", LogNorm()(rendered.sum(-1))) ``` -------------------------------- ### SWIFTFOFMetadata Source: https://swiftsimio.readthedocs.io/en/latest/modules/index.html Represents metadata for a friends-of-friends group. Provides methods to get a nice name. ```APIDOC ## SWIFTFOFMetadata ### Description Represents metadata for a friends-of-friends group. Provides methods to get a nice name. ### Properties - **homogeneous_arrays** - Whether arrays are homogeneous. - **present_groups** - The groups present. - **present_group_names** - The names of groups present. ### Methods - **get_nice_name()** - Returns a nice name. ``` -------------------------------- ### Create a mass density cube Source: https://swiftsimio.readthedocs.io/en/latest/_sources/visualisation/volume_render.rst.txt Demonstrates the basic usage of render_gas to create a mass density voxel grid from simulation data. ```python from swiftsimio import load from swiftsimio.visualisation.volume_render import render_gas data = load("cosmo_volume_example.hdf5") # This creates a grid that has units msun / Mpc^3, and can be transformed like # any other unyt quantity. mass_grid = render_gas( data, resolution=256, project="masses", parallel=True, periodic=True, ) ``` -------------------------------- ### Generate Initial Conditions with swiftsimio Source: https://swiftsimio.readthedocs.io/en/latest/_sources/creating_initial_conditions/index.rst.txt This script demonstrates how to initialize a Writer object, define particle properties using cosmo_array, and export the data to an HDF5 file. ```python import numpy as np import unyt as u from swiftsimio import Writer, cosmo_array from swiftsimio.metadata.writer.unit_systems import cosmo_unit_system # number of gas particles n_p = 1000 # scale factor of 1.0 a = 1.0 # Box is 100 Mpc lbox = 100 boxsize = cosmo_array( [lbox, lbox, lbox], u.Mpc, comoving=True, scale_factor=a, scale_exponent=1, ) # Create the Writer object. cosmo_unit_system corresponds to default Gadget-like units # of 10^10 Msun, Mpc, and km/s w = Writer(unit_system=cosmo_unit_system, boxsize=boxsize, scale_factor=a) # Randomly spaced coordinates from 0 to lbox Mpc in each direction w.gas.coordinates = cosmo_array( np.random.rand(n_p, 3) * lbox, u.Mpc, comoving=True, scale_factor=w.scale_factor, scale_exponent=1, ) # Random velocities from 0 to 1 km/s w.gas.velocities = cosmo_array( np.random.rand(n_p, 3), u.km / u.s, comoving=True, scale_factor=w.scale_factor, scale_exponent=1, ) # Generate uniform masses as 10^6 solar masses for each particle w.gas.masses = cosmo_array( np.ones(n_p, dtype=float) * 1e6, u.solMass, comoving=True, scale_factor=w.scale_factor, scale_exponent=0, ) # Generate internal energy corresponding to 10^4 K w.gas.internal_energy = cosmo_array( np.ones(n_p, dtype=float) * 1e4 / 1e6, u.kb * u.K / u.solMass, comoving=True, scale_factor=w.scale_factor, scale_exponent=-2, ) # Generate initial guess for smoothing lengths based on mean inter-particle spacing w.gas.generate_smoothing_lengths() # w.gas.particle_ids can optionally be set, otherwise they are auto-generated # write the initial conditions out to a file w.write("ics.hdf5") ```