fargopy package
Submodules
Module contents
fargopy.fields module
- class fargopy.fields.Field(data=None, coordinates='cartesian', domains=None, type='scalar', **kwargs)[source]
Bases:
FargobjRepresents a simulation field (scalar or vector) with coordinate system and domain information.
The
Fieldobject encapsulates the data arrays and associated coordinate meshes for a specific simulation variable. It supports slicing, coordinate transformation and simple visualization helpers.- data
Numpy array containing the physical data.
- Type:
np.ndarray
- coordinates
Coordinate system type (‘cartesian’, ‘cylindrical’, ‘spherical’).
- Type:
str
- domains
Object containing domain-specific geometry (e.g., mesh arrays).
- Type:
object
- type
Field type (‘scalar’ or ‘vector’).
- Type:
str
Examples
Load a field from a simulation object (returns a Field instance if interpolation is disabled or a FieldInterpolator otherwise):
>>> fp.Simulation.load_field(fields='gasdens', snapshot=0, interpolate=False)
Access data and mesh:
>>> rho = field.data >>> xmesh = field.mesh.x
- get_size()[source]
Return the size of the field data in megabytes (MB).
- Returns:
Size in MB.
- Return type:
float
- meshslice(slice=None, component=0, verbose=False)[source]
Perform a slice on a field and produce the corresponding field slice and associated coordinate matrices for plotting.
- Parameters:
slice (str) – Slice definition string (e.g., ‘z=0’).
component (int, optional) – Component index for vector fields (default: 0).
verbose (bool, optional) – If True, print debug information.
- Returns:
(sliced field, mesh dictionary with coordinates). The mesh dictionary contains coordinate arrays (x, y, z, r, phi, theta) corresponding to the slice.
- Return type:
tuple
Examples
Slice a field at z=0:
>>> field_slice, mesh = field.meshslice(slice='z=0')
Plot the slice:
>>> plt.pcolormesh(mesh.x, mesh.y, field_slice)
- to_cartesian()[source]
Convert the field to cartesian coordinates.
- Returns:
The field in cartesian coordinates. For scalar fields, returns the field itself. For vector fields, returns a tuple (vx, vy, vz).
- Return type:
Examples
>>> v = sim.load_field('gasv', snapshot=0) >>> vx, vy, vz = v.to_cartesian()
- class fargopy.fields.FieldInterpolator(sim, df=None)[source]
Bases:
FargobjLoads and interpolates fields from a FARGO3D simulation.
The
FieldInterpolatorfacilitates loading, slicing, and interpolating simulation data across multiple snapshots and fields. It handles coordinate transformations and dimensionality reduction based on slice definitions.Attributesde
- simSimulation
The simulation object.
- dfpd.DataFrame or None
DataFrame containing loaded field data organized by snapshot and time.
- snapshot_time_tablepd.DataFrame or None
Table mapping snapshots to normalized time.
- snapshotlist or None
List of loaded snapshots.
- slicestr or None
Slice definition string used to load the data.
- dimint or None
Dimensionality of the loaded data (e.g., 2 for a 2D slice).
Examples
Load multiple fields from a snapshot with interpolation enabled:
>>> data = sim.load_field(fields=['gasdens', 'gasv'], snapshot=4)
Load a specific slice:
>>> dens = sim.load_field(fields='gasdens', slice='r=[0.8,1.2],phi=[-25 deg,25 deg],theta=1.56', snapshot=4)
- create_mesh(slice=None, nr=50, ntheta=50, nphi=50, nz=50)[source]
Create a mesh grid based on the slice definition provided by the user. If no slice is provided, create a full 3D mesh within the simulation domain. Supports both spherical and cylindrical coordinate systems.
- Parameters:
slice (str, optional) – The slice definition string (e.g., “r=[0.8,1.2],phi=0,theta=[0 deg,90 deg]” for spherical or “r=[0.8,1.2],phi=0,z=[0,0.5]” for cylindrical).
nr (int) – Number of divisions in r.
ntheta (int) – Number of divisions in theta (spherical only).
nphi (int) – Number of divisions in phi.
nz (int) – Number of divisions in z (cylindrical only).
- Returns:
Mesh grid (x, y, z) based on the slice definition or the full domain.
- Return type:
tuple
- cut_sector(xc, yc, zc, rc, hc, dataframe=None)[source]
Filter the DataFrame to keep only data inside a cylinder of radius rc and height hc centered at (xc, yc, zc). Returns a new filtered DataFrame.
- Parameters:
xc (float) – Center coordinates of the cylinder.
yc (float) – Center coordinates of the cylinder.
zc (float) – Center coordinates of the cylinder.
rc (float) – Cylinder radius.
hc (float) – Cylinder height.
dataframe (pd.DataFrame, optional) – DataFrame to filter (default: self.df).
- Returns:
Filtered DataFrame with only points inside the cylinder.
- Return type:
pd.DataFrame
- evaluate(var1, snapshot=None, time=None, var2=None, var3=None, dataframe=None, interpolator='griddata', method='linear', rbf_kwargs=None, griddata_kwargs=None, idw_kwargs=None, sigma_smooth=None, field=None, reflect=False, coords=None)[source]
Evaluate the selected field at arbitrary spatial coordinates using multi-snapshot interpolation. Supports scalar and vector fields, 1D/2D/3D geometry, time interpolation, and several interpolation backends. Designed for unified DataFrames (gasdens + gasv + others).
- Parameters:
time (float or int) – Normalized time in [0,1] or snapshot index.
var1 (array-like or float) – Evaluation coordinates. For 3D: typically (x, y, z) if coords=’cartesian’, (phi, r, theta) if coords=’spherical’, or (phi, r, z) if coords=’cylindrical’. The coordinate system is determined by the ‘coords’ parameter. Scalars are accepted.
var2 (array-like or float) – Evaluation coordinates. For 3D: typically (x, y, z) if coords=’cartesian’, (phi, r, theta) if coords=’spherical’, or (phi, r, z) if coords=’cylindrical’. The coordinate system is determined by the ‘coords’ parameter. Scalars are accepted.
var3 (array-like or float) – Evaluation coordinates. For 3D: typically (x, y, z) if coords=’cartesian’, (phi, r, theta) if coords=’spherical’, or (phi, r, z) if coords=’cylindrical’. The coordinate system is determined by the ‘coords’ parameter. Scalars are accepted.
dataframe (pandas.DataFrame, optional) – Custom DataFrame. If omitted, self.df is used.
interpolator ({"griddata", "rbf", "linearnd", "idw", "regular_grid"}, default "griddata") –
Backend used for spatial interpolation: - “griddata”: scipy.interpolate.griddata (default, works for irregular grids) - “rbf”: Radial Basis Function interpolation - “linearnd”: LinearNDInterpolator - “idw”: Inverse Distance Weighting - “regular_grid”: scipy.interpolate.RegularGridInterpolator (automatic for
3D regular grids, fastest option when applicable)
Note: For 3D data with regular grid structure, RegularGridInterpolator is automatically used by default regardless of the interpolator setting, with automatic fallback to griddata if the grid is irregular.
method (str, default "linear") – Kernel/method used by backend (e.g., ‘linear’, ‘cubic’ for griddata).
sigma_smooth (float or None) – Optional Gaussian smoothing parameter.
field ({"gasdens", "gasv", "gasenergy"} or None) – Field to evaluate. If None and DF has exactly one field, it is auto-selected. If multiple fields exist, explicit selection is required.
reflect (bool, default False) –
If True, enable symmetry-based reflection for interpolation. When interpolating at points outside the loaded domain, the method attempts to evaluate at the corresponding reflected point and uses that value.
The reflection is performed in the coordinate system specified by the ‘coords’ parameter used in load_field(): - Cartesian: reflects across z=0 (z -> -z) - Spherical: reflects across equatorial plane (theta -> π - theta) - Cylindrical: reflects across z=0 (z -> -z)
This is useful for enforcing symmetry in simulations that are symmetric about the equatorial/midplane. Works efficiently with RegularGridInterpolator by only reflecting points that fall outside the domain (NaN values).
coords ({"cartesian", "spherical", "cylindrical", None}, default None) –
Target coordinate system for the evaluation points (var1, var2, var3). If None (default), uses the original coordinate system from load_data.
”cartesian”: var1=x, var2=y, var3=z
”spherical”: var1=phi, var2=r, var3=theta
”cylindrical”: var1=phi, var2=r, var3=z
The method automatically converts between coordinate systems as needed. This allows querying data in any coordinate system regardless of how it was originally loaded.
- Returns:
Interpolated value(s). Vector fields return shape (3, N) or (3, …).
- Return type:
ndarray or float
Examples
Evaluate density at Cartesian coordinates:
>>> loader.evaluate(var1=x_points, var2=y_points, var3=z_points, ... field='gasdens', time=0.5, coords='cartesian')
Evaluate in spherical coordinates:
>>> loader.evaluate(var1=phi_vals, var2=r_vals, var3=theta_vals, ... field='gasdens', time=0.5, coords='spherical')
Notes
For 3D regular grids (uniform spacing in each dimension), the method automatically uses RegularGridInterpolator for optimal performance, regardless of the ‘interpolator’ parameter. This provides significant speedup (often 10-100x) compared to griddata for large datasets.
The coordinate transformation feature allows seamless querying in different coordinate systems. The original simulation data coordinate system is preserved internally, and transformations are applied automatically.
- load_data(fields=None, slice=None, snapshots=1, cut=None, coords='cartesian')[source]
Load one or multiple fields into a unified DataFrame.
This method loads simulation data for the specified fields and snapshots, potentially applying a spatial slice or cut. The data is stored in an internal DataFrame (self.df) for further processing or interpolation.
- Parameters:
fields (str or list of str) – Name(s) of the fields to load (e.g., ‘gasdens’, ‘gasv’).
slice (str, optional) – Slice definition (e.g., ‘z=0’, ‘theta=1.57’).
snapshots (int or list of int, optional) – Snapshot number(s) to load. Can be a single integer or a range [start, end].
cut (list, optional) – Geometric cut parameters (sphere or cylinder mask).
coords (str, optional) – Coordinate system for vector transformation (‘cartesian’ by default).
- Returns:
The DataFrame containing the loaded data.
- Return type:
pd.DataFrame
Examples
Load density and velocity for snapshot 10:
>>> loader = fp.FieldInterpolator(sim) >>> df = loader.load_data(fields=['gasdens', 'gasv'], snapshot=10)
Load a 2D slice at z=0 (midplane):
>>> df_slice = loader.load_data(fields='gasdens', slice='z=0', snapshot=10)
- plot(t=0, contour_levels=10, component='vz', smoothing_sigma=None, field=None)[source]
Automatically determines the plane (XY, XZ, or 3D) and plots the field data.
- Parameters:
t (int, optional) – Index of the snapshot/time to plot.
contour_levels (int, optional) – Number of contour levels for 2D plots.
component (str, optional) – Component to plot for vector fields (‘vx’, ‘vy’, ‘vz’).
field (str or None, optional) – Which field to plot when multiple fields were loaded (e.g. ‘gasdens’, ‘gasv’, ‘gasenergy’). If None and exactly one field is present, that field is plotted. If None and multiple candidate fields exist, a ValueError is raised instructing the user to pick one.
fargopy.flux module
- class fargopy.flux.Surface(type='sphere', radius=1.0, height=None, subdivisions=1, center=(0.0, 0.0, 0.0), z_cut=None, x_axis=1, y_axis=0, z_axis=0, width=None, length=None, coords='cartesian')[source]
Bases:
objectAnalytic surface tessellation and helpers for flux and mass analysis.
The
Surfaceclass provides tools to define analytic control surfaces (sphere, cylinder, plane) and tessellate them into small patches. These surfaces are used to calculate physical quantities like mass flux (accretion rates) and enclosed mass by integrating simulation fields.- type
Surface type (‘sphere’, ‘cylinder’, ‘plane’).
- Type:
str
- radius
Radius or characteristic dimension (e.g., hill radius factor).
- Type:
float
- centers
(N, 3) array of patch centroids.
- Type:
np.ndarray
- normals
(N, 3) array of outward-facing unit normals for each patch.
- Type:
np.ndarray
- areas
(N,) array of patch areas.
- Type:
np.ndarray
Examples
Define a spherical surface around a planet:
>>> surface = fp.Flux.Surface(type='sphere', radius=0.5, subdivisions=2)
Calculate mass flux through the surface:
>>> flux = surface.mass_flux(sim, field_density='gasdens', field_velocity='gasv')
- property centers
Get surface centers in the coordinate system specified by self.coords.
This property automatically returns coordinates in the system specified during Surface initialization. For Cartesian, returns shape (N, 3) array. For cylindrical/spherical, returns shape (N, 3) array with columns representing (phi, r, z/theta).
- Returns:
Array of shape (N, 3) where N is the number of surface patches. - If coords=’cartesian’: columns are (x, y, z) - If coords=’cylindrical’: columns are (phi, r, z) - If coords=’spherical’: columns are (phi, r, theta)
- Return type:
np.ndarray
Examples
>>> sphere = fp.flux.Surface(type='sphere', radius=1.0, subdivisions=2, coords='spherical') >>> centers = sphere.centers # Returns (N, 3) array with (phi, r, theta) columns >>> phi = centers[:, 0] >>> r = centers[:, 1] >>> theta = centers[:, 2]
Notes
Internally, coordinates are always stored in Cartesian form. This property performs the coordinate transformation on-the-fly based on self.coords.
- property centers_in_coords
Get surface centers in the default coordinate system specified by self.coords.
This property provides a convenient way to access surface centers without manually calling get_centers_in_coords(). The coordinate system is determined by the
coordsattribute set during initialization or modified later.- Returns:
Coordinates in the system specified by self.coords: - Cartesian: (x, y, z) - Spherical: (phi, r, theta) - Cylindrical: (phi, r, z)
- Return type:
tuple of np.ndarray
Examples
>>> surface = fp.Flux.Surface(type='sphere', radius=1.0, subdivisions=2, coords='spherical') >>> phi, r, theta = surface.centers_in_coords >>> # Use directly for interpolation >>> rho = fields.evaluate(var1=phi, var2=r, var3=theta, field='gasdens')
Notes
This is equivalent to calling get_centers_in_coords(self.coords) but more concise. Change self.coords to switch the output coordinate system dynamically.
- generate_dataframe()[source]
Return tessellation metadata as a pandas
DataFrame.The returned DataFrame contains one row per surface patch with columns
'Center','Normal'and'Area'. Coordinates are represented as Python lists to ensure JSON-serializable cell values.
- get_centers_in_coords(coords_system='cartesian')[source]
Get surface centers in the specified coordinate system.
This method converts the tessellation centers from Cartesian coordinates to the requested coordinate system. This is essential for fast interpolation when the simulation data is stored in spherical or cylindrical coordinates, as it allows using RegularGridInterpolator instead of slow unstructured methods.
- Parameters:
coords_system (str, optional) – Target coordinate system: ‘cartesian’, ‘spherical’, or ‘cylindrical’. Default is ‘cartesian’.
- Returns:
For cartesian: (x, y, z) For spherical: (phi, r, theta) For cylindrical: (phi, r, z) Each array has shape (n_points,) corresponding to surface centers.
- Return type:
tuple of np.ndarray
Notes
The coordinate transformations are: - Spherical: phi = arctan2(y, x), r = sqrt(x² + y² + z²), theta = arccos(z/r) - Cylindrical: phi = arctan2(y, x), r = sqrt(x² + y²), z = z
Examples
>>> surface = Surface(type='sphere', radius=1.0, subdivisions=2) >>> phi, r, theta = surface.get_centers_in_coords('spherical') >>> # Use these for fast interpolation with spherical simulation data
- get_normals_in_coords(coords_system='cartesian')[source]
Get surface normals in the specified coordinate system.
Transforms the unit normal vectors from Cartesian to the requested coordinate system. This is useful for flux calculations when working in native simulation coordinates.
- Parameters:
coords_system (str, optional) – Target coordinate system: ‘cartesian’, ‘spherical’, or ‘cylindrical’.
- Returns:
For cartesian: (nx, ny, nz) For spherical: (n_phi, n_r, n_theta) For cylindrical: (n_phi, n_r, n_z) Each array has shape (n_points,).
- Return type:
tuple of np.ndarray
Notes
The transformation uses Jacobian matrices for the coordinate change. For spherical: [n_phi, n_r, n_theta]^T = J^T [nx, ny, nz]^T For cylindrical: [n_phi, n_r, n_z]^T = J^T [nx, ny, nz]^T
- mass_flux(sim, field_density='gasdens', field_velocity='gasv', snapshot=[0, 1], interpolator='regular_grid', method='linear', follow_planet=True, planet_index=0, correct_normals=True, relative_velocity=False, coords=None)[source]
Compute mass flux through the surface patches.
The instantaneous mass flux for each patch is computed as:
dΦ = ρ * (v_rel · n_out) * dA
and the returned value is the sum over all patches. Velocities can optionally be converted to the planet rest frame by enabling
relative_velocity.- Parameters:
sim (object) – Simulation object exposing
load_fieldandload_planets.field_density (str, optional) – Density field name (default
'gasdens').field_velocity (str, optional) – Velocity field name (default
'gasv').snapshot ([start, end], optional) – Inclusive snapshot range to evaluate.
interpolator (str, optional) – Passed to the field evaluator for interpolation.
method (str, optional) – Passed to the field evaluator for interpolation.
follow_planet (bool, optional) – If True follow the planet position and scale the surface (useful for Hill-sphere analysis).
planet_index (int, optional) – Index of the planet to follow.
correct_normals (bool, optional) – If True ensure per-patch normals point outward from the surface center before computing the flux.
relative_velocity (bool, optional) – If True subtract the planet velocity from the interpolated fluid velocity prior to flux computation.
coords (str, optional) – Coordinate system to use for field loading and interpolation. If None, uses
self.coords(default coordinate system set during initialization). Options are ‘cartesian’, ‘cylindrical’, or ‘spherical’. Using the simulation’s native coordinate system enables faster RegularGridInterpolator instead of unstructured griddata.
- Returns:
Array of flux values, one per requested snapshot.
- Return type:
numpy.ndarray
Examples
Compute accretion rate (mass flux) onto a planet:
>>> surface = fp.Flux.Surface(type='sphere', radius=0.5, subdivisions=3, coords='spherical') >>> mdot = surface.mass_flux(sim, field_density='gasdens', field_velocity='gasv', follow_planet=True) >>> plt.plot(mdot)
- property normals
Get surface normals in the coordinate system specified by self.coords.
This property automatically returns normal vectors in the system specified during Surface initialization. For Cartesian, returns shape (N, 3) array. For cylindrical/spherical, returns shape (N, 3) array with columns representing (n_phi, n_r, n_z/n_theta).
- Returns:
Array of shape (N, 3) where N is the number of surface patches. - If coords=’cartesian’: columns are (nx, ny, nz) - If coords=’cylindrical’: columns are (n_phi, n_r, n_z) - If coords=’spherical’: columns are (n_phi, n_r, n_theta)
- Return type:
np.ndarray
Examples
>>> sphere = fp.flux.Surface(type='sphere', radius=1.0, coords='spherical') >>> normals = sphere.normals # Returns (N, 3) array with (n_phi, n_r, n_theta) columns >>> n_r = normals[:, 1] # Radial component (should be ~1 for sphere)
Notes
Internally, normals are always stored in Cartesian form. This property performs the coordinate transformation on-the-fly based on self.coords. Normals are always unit vectors regardless of coordinate system.
- property normals_in_coords
Get surface normals in the default coordinate system specified by self.coords.
This property provides a convenient way to access surface normals without manually calling get_normals_in_coords(). The coordinate system is determined by the
coordsattribute.- Returns:
Normal vector components in the system specified by self.coords: - Cartesian: (nx, ny, nz) - Spherical: (n_phi, n_r, n_theta) - Cylindrical: (n_phi, n_r, n_z)
- Return type:
tuple of np.ndarray
Examples
>>> surface = fp.Flux.Surface(type='sphere', radius=1.0, coords='cylindrical') >>> n_phi, n_r, n_z = surface.normals_in_coords
Notes
This is equivalent to calling get_normals_in_coords(self.coords) but more concise. Normals are always unit vectors regardless of coordinate system.
- tessellate()[source]
Recompute the tessellation from current instance parameters.
This method is a convenience wrapper that dispatches to the appropriate internal tessellation implementation depending on
self.type.
- total_mass(sim, field='gasdens', snapshot=[0, 1], follow_planet=True, planet_index=0, return_resolution=False)[source]
Compute enclosed mass by direct grid integration.
The method integrates the requested density field on the simulation grid accounting for the region geometry defined by this Surface instance. Supports both spherical and cylindrical coordinate systems.
self.typemust be either'sphere'or'cylinder'; the integration mask is constructed accordingly.- Parameters:
sim (object) – Simulation object providing access to the raw grid and fields.
field (str, optional) – Density field name (default
'gasdens').snapshot (int or [start, end], optional) – Snapshot index or inclusive snapshot range to integrate.
follow_planet (bool, optional) – If True update the integration center and radius from the specified planet’s position/hill radius.
planet_index (int, optional) – Planet index to follow when
follow_planetis True.return_resolution (bool, optional) – If True return detailed resolution metadata for each snapshot alongside the integrated mass.
- Returns:
If
return_resolutionis False and a single snapshot is requested, returns a float. If multiple snapshots are requested, returns a numpy array of masses. Ifreturn_resolutionis True a list of dictionaries with per-snapshot metadata is returned.- Return type:
float or numpy.ndarray or list
Examples
Compute total mass inside a Hill sphere:
>>> surface = fp.Flux.Surface(type='sphere', radius=1.0) # radius is factor of Hill radius >>> mass = surface.total_mass(sim, field='gasdens', follow_planet=True)
- total_mass_mtc(sim, field='gasdens', n_samples=10000, snapshot=[0, 1], interpolator='regular_grid', method='linear', cut_r=None, follow_planet=True, planet_index=0, random_seed=None, coords=None)[source]
Estimate enclosed mass using Monte Carlo sampling.
The method samples
n_samplespoints uniformly within the spherical region defined by this surface (accounting forz_cutwhen present), interpolates the requested density field at the sample points and returns an estimate of the enclosed mass.- Parameters:
sim (object) – Simulation object providing
load_fieldandload_planetsmethods (FARGOpy simulation API).field (str, optional) – Density field name to sample (default
'gasdens').n_samples (int, optional) – Number of Monte Carlo samples per snapshot.
snapshot (int or [start, end], optional) – Snapshot index or inclusive snapshot range.
interpolator (str, optional) – Interpolator backend passed to the field evaluator.
method (str, optional) – Interpolation method passed to the field evaluator.
cut_r (float, optional) – Radial cut passed to
sim.load_fieldto limit data transfer.follow_planet (bool, optional) – If True follow the planet position when sampling (useful for Hill-sphere based regions).
planet_index (int, optional) – Index of the planet to follow when
follow_planetis True.random_seed (int, optional) – Random seed for reproducibility of Monte Carlo sampling. If None (default), results will vary between runs. Set to a fixed integer for reproducible results.
coords (str, optional) – Coordinate system to use for field loading and interpolation. If None, uses
self.coords. Options are ‘cartesian’, ‘cylindrical’, or ‘spherical’. Using the simulation’s native coordinate system enables faster RegularGridInterpolator.
- Returns:
Estimated enclosed mass. Returns a single float if a single snapshot is requested, otherwise an array of estimates.
- Return type:
float or numpy.ndarray
fargopy.plot module
- class fargopy.plot.Plot[source]
Bases:
objectPlotting utilities and visualization helpers for FARGO3D data.
The
Plotclass encapsulates static methods for common plotting tasks, such as adding watermarks to figures and creating standardized heatmaps for simulation fields.- static fargopy_mark(ax, frac=0.16666666666666666, alpha=0.5)[source]
Add a watermark to a 2D or 3D plot.
Places a rotated “FARGOpy {version}” watermark in the top-right corner of the specified axes.
- Parameters:
ax (matplotlib.axes.Axes) – The axes object where the watermark will be added.
- Returns:
The created text object.
- Return type:
matplotlib.text.Text
Examples
Add watermark to a plot:
>>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3], [1, 2, 3]) >>> fp.Plot.fargopy_mark(ax)
- static mesh(sim, snapshot=0, slice='theta=1.56', planet=0, draw_hill=True, hill_frac=1.0, figsize=(8, 8), point_size=1, line_alpha=0.5, cmap='viridis', show=True)[source]
Plot the simulation mesh in the XY plane and (optionally) the planet Hill circle.
- Parameters:
sim (Simulation) – The simulation object.
snapshot (int, optional) – Snapshot to plot, by default 0.
slice (str, optional) – Slice definition, by default ‘theta=1.56’.
planet (int or str, optional) – Planet index or name to focus, by default 0.
draw_hill (bool, optional) – Whether to draw the Hill sphere, by default True.
hill_frac (float, optional) – Fraction of Hill radius to draw, by default 1.0.
figsize (tuple, optional) – Figure size, by default (8,8).
point_size (int, optional) – Size of mesh points, by default 1.
line_alpha (float, optional) – Alpha transparency of mesh lines, by default 0.5.
cmap (str, optional) – Colormap for points, by default ‘viridis’.
show (bool, optional) – Whether to show the plot, by default True.
- Returns:
(fig, ax, nr_celdas_radial, nr_celdas_azimutal, n_inside) Matplotlib figure and axes, max contiguous radial cells, max contiguous azimuthal cells, and the number of mesh cells inside the hill_frac * Hill radius.
- Return type:
tuple
Examples
>>> fp.Plot.mesh(sim, snapshot=0)
fargopy.simulation module
- class fargopy.simulation.Planet(name, pos, vel, mass, posi, mstar)[source]
Bases:
objectRepresents a planet in the simulation, holding its physical state and properties.
- name
Name or label of the planet.
- Type:
str
- mass
Planet mass (in Msun or simulation units).
- Type:
float
- pos
Current cartesian position (x, y, z) in AU.
- Type:
Planet.Vector
- vel
Current cartesian velocity (vx, vy, vz) in AU/UT.
- Type:
Planet.Vector
- posi
Initial cartesian position (x, y, z) in AU.
- Type:
Planet.Vector
- mstar
Stellar mass (in Msun or simulation units).
- Type:
float
- Properties
- ----------
- hill_radius
The Hill radius of the planet (in AU), computed from its current position and mass.
- Type:
float
Example
>>> jupiter = planets[0] >>> print(jupiter.pos.x, jupiter.vel.y, jupiter.hill_radius)
- property hill_radius
no-index:
Returns the Hill radius in AU, using the current position and mass.
- Returns:
Hill radius in AU.
- Return type:
float
- Type:
- class fargopy.simulation.Simulation(**kwargs)[source]
Bases:
FargobjManage a FARGO3D simulation and its filesystem, execution and I/O.
The
Simulationobject centralizes configuration, units, setup discovery, compilation and runtime control for a FARGO3D case. It stores derived paths (setup directory, output directory), unit conversion factors and exposes convenience methods to compile, launch and inspect simulation outputs.- fargo3d_dir
Base directory of FARGO3D installation.
- Type:
str
- outputs_dir
Directory where outputs are stored.
- Type:
str
- setups_dir
Directory where setups are located.
- Type:
str
- setup
Active setup name.
- Type:
str
- fargo3d_binary
Path to the compiled binary.
- Type:
str
- units_system
Unit system (‘CGS’ or ‘MKS’).
- Type:
str
- Parameters:
**kwargs (dict) – Configuration keywords. Typical keys include
setup,fargo3d_dir,output_dirandload. Whenload=Truethe object attempts to read serialized metadata from the specified setup directory.
Examples
Create a simulation object:
>>> import fargopy as fp >>> sim = fp.Simulation()
Select a setup:
>>> sim.set_setup('fargo')
Compile the simulation:
>>> sim.compile(parallel=0, gpu=0)
Run the simulation (clean run):
>>> sim.run(cleanrun=True)
Check status:
>>> sim.status()
Stop simulation:
>>> sim.stop()
- compile(setup=None, parallel=0, gpu=0, options='', force=False)[source]
Compile the FARGO3D executable for the active setup.
- Parameters:
setup (str, optional) – Setup name to compile. When provided the method will try to set the setup before compiling.
parallel (int, optional) – Parallel compilation flag (default: 0).
gpu (int, optional) – GPU-enabled compilation flag (default: 0).
options (str, optional) – Additional make options passed to the build system.
force (bool, optional) – If
Trueperform a clean before building.
Examples
>>> sim.compile(parallel=1, gpu=0)
- static download_precomputed(setup=None, download_dir=None, quiet=False, clean=True)[source]
Download and extract a precomputed output archive from the public repository.
- Parameters:
setup (str, optional) – Name of the entry in
PRECOMPUTED_SIMULATIONS.download_dir (str, optional) – Destination directory for the compressed file and extracted output.
quiet (bool, optional) – When True, suppress download progress indicators.
clean (bool, optional) – Remove the downloaded archive after extraction when set to True.
- Returns:
Absolute path to the extracted output directory, or an empty string on failure.
- Return type:
str
- list_fields(quiet=False)[source]
Return a list of data file names present in the output directory.
- Parameters:
quiet (bool, optional) – When
Trueavoid printing the detailed file list.- Returns:
Filenames found in the output directory.
- Return type:
list
- static list_precomputed()[source]
Display the catalog of downloadable precomputed simulations with descriptions and sizes.
- Returns:
The listing is printed to stdout.
- Return type:
None
- static list_setups()[source]
Print all valid setup directories detected under
FP_FARGO3D_DIR.- Returns:
The setups are printed to stdout; nothing is returned.
- Return type:
None
- load_field(fields, slice=None, snapshot=None, type=None, coords='cartesian', cut=None)[source]
Load a field or multiple fields from the simulation.
This method initializes a
FieldInterpolatorto handle the loading and interpolation of simulation fields. It supports loading single or multiple fields, taking slices, and specifying the coordinate system for vector fields.- Parameters:
fields (str or list of str) – Name or list of names of the fields to load (e.g., ‘gasdens’, ‘gasv’).
slice (str, optional) – Slice definition string (e.g., ‘phi=0’, ‘theta=1.57’). Used to load a specific subset of the data.
snapshot (int or list of int, optional) – Snapshot number(s) to load. Can be a single integer or a range [start, end]. Default is None (which usually implies snapshot 0 or all, depending on context, but here it is passed to FieldInterpolator).
type (str, optional) – Field type (‘scalar’ or ‘vector’). If None, it is inferred from the field name.
coords (str, optional) – Coordinate system for vector transformation (‘cartesian’, ‘cylindrical’, ‘spherical’). Default is ‘cartesian’.
cut (list, optional) – Geometric cut parameters (sphere or cylinder mask) to apply to the data.
- Returns:
An object capable of interpolating and managing the loaded field data.
- Return type:
fargopy.FieldInterpolator
Examples
Load density and velocity for snapshot 10:
>>> loader = sim.load_field(fields=['gasdens', 'gasv'], snapshot=10)
Load a 2D slice at phi=0:
>>> df_slice = sim.load_field(fields='gasdens', slice='phi=0', snapshot=10)
- load_macros(summaryfile='summary0.dat')[source]
Parse the PREPROCESSOR MACROS SECTION from a summary file.
- Parameters:
summaryfile (str, optional) – Summary filename relative to the output directory (default
'summary0.dat').- Returns:
Mapping of macro names to parsed values. Returns an empty dict when the file is missing or parsing fails.
- Return type:
dict
- load_planets(snapshot=0, summaryfile=None)[source]
Load planet data from a summary file.
- Parameters:
snapshot (int, optional) – Snapshot index to load.
summaryfile (str, optional) – Name of the summary file.
- Returns:
List of Planet objects for the given snapshot.
- Return type:
list of Planet
- load_properties(quiet=False, varfile='variables.par', domain_prefix='domain_', dimsfile='dims.dat', summaryfile='summary0.dat')[source]
Load and print simulation properties, including variables, domains, dimensions, and planets.
- Parameters:
quiet (bool, optional) – If True, suppress output.
varfile (str, optional) – Name of the variables file.
domain_prefix (str, optional) – Prefix for domain files.
dimsfile (str, optional) – Name of the dimensions file.
summaryfile (str, optional) – Name of the summary file.
- Returns:
Summary information string.
- Return type:
str
- resume(snapshot=-1, mpioptions='-np 1')[source]
Resume an interrupted simulation from the specified snapshot.
- Parameters:
snapshot (int, optional) – Snapshot index to resume from. Use
-1to resume from the most recent resumable snapshot.mpioptions (str, optional) – MPI launch options for parallel executions.
- run(mode='async', options='-m', mpioptions='-np 1', resume=False, cleanrun=False, test=False, unlock=True)[source]
Run the FARGO3D simulation.
- Parameters:
mode (str, optional) – ‘async’ for asynchronous or ‘sync’ for synchronous execution.
options (str, optional) – Command-line options for FARGO3D.
mpioptions (str, optional) – MPI options for parallel runs.
resume (bool, optional) – Resume from previous run.
cleanrun (bool, optional) – Clean output directory before running.
test (bool, optional) – If True, do not actually run the simulation.
unlock (bool, optional) – If True, unlock the simulation if locked.
Examples
Run asynchronously:
>>> sim.run(cleanrun=True)
Run synchronously:
>>> sim.run(mode='sync', cleanrun=True)
- set_fargo3d_dir(dir=None)[source]
Set the base FARGO3D installation directory.
- Parameters:
dir (str or None) – Path to the FARGO3D installation. When
Nonethe method is a no-op.- Returns:
The method does not return meaningful data; it updates internal path attributes and prints diagnostics.
- Return type:
None
- set_output_dir(dir)[source]
Set the output directory where FARGO3D stores run results.
- Parameters:
dir (str or None) – Output directory path. When present the method attempts to load simulation properties from a
variables.parfile.
- set_setup(setup)[source]
Associate the simulation with a named setup directory.
- Parameters:
setup (str or None) – Setup name present under the configured
setups_dir. IfNonethe setup association is cleared.- Returns:
The assigned setup name on success, otherwise
None.- Return type:
str or None
- set_setup_dir(dir)[source]
Set the absolute path to a setup directory and validate it.
- Parameters:
dir (str) – Filesystem path to the setup directory.
- Returns:
Truewhen the directory exists and is accepted, otherwiseFalse.- Return type:
bool
- set_units(UM=1.9891e+33, UL=14959800000000.0, G=1, mu=2.35)[source]
Define simulation base units and derived unit scales.
- Parameters:
UM (float) – Mass unit (default: MSUN).
UL (float) – Length unit (default: AU).
G (float) – Dimensionless gravitational constant (default: 1).
mu (float) – Mean molecular weight used to compute temperature units.
- status(mode='isrunning', verbose=True, **kwargs)[source]
Report process, logfile and output status for the simulation.
- Parameters:
mode ({'isrunning','logfile','outputs','progress','summary','locking','all'}, optional) – Which status block to display.
'all'prints every section.verbose (bool, optional) – When
Trueprint human-readable diagnostics to stdout.**kwargs (dict) – Backend-specific options used by certain modes (for instance
numstatusfor the'progress'mode).
- stop(verbose=False)[source]
Stop a running FARGO3D process and release the lock on the setup.
If a process is associated with the simulation the method attempts to terminate it and then unlock the setup directory. If no process handler is available the method simply tries to remove any filesystem lock.
- time_scale(scale='orbits')[source]
Calculates the time scale of the simulation in different units.
- Parameters:
scale (str, optional) – ‘orbits’ to calculate the number of orbits completed by the planet, ‘duration’ for the total simulation time in simulation units.
- Returns:
Number of orbits or total simulation time, depending on scale.
- Return type:
float
- to_paraview(snapshot=0, dir='.', basename=None)[source]
Export a snapshot to a VTU (UnstructuredGrid) file with physical XYZ coordinates and point data arrays for density and Cartesian velocity. Supports both spherical and cylindrical coordinate systems.
- Parameters:
snapshot (int) – Snapshot index to export (default: 0).
dir (str) – Output directory where the .vtu file will be written (default: current directory).
basename (str or None) – Base name for the output file (without extension). If None, a default name using the simulation setup and snapshot is created.
Notes
Requires the ‘vtk’ Python package (and vtk.util.numpy_support).
Expects self.load_field(‘gasdens’) and self.load_field(‘gasv’) to return fargopy.Field-like objects where .data is a numpy array with shapes:
For spherical: rho: (ntheta, nr, nphi), vel: (3, ntheta, nr, nphi) or (ntheta, nr, nphi, 3) For cylindrical: rho: (nz, nr, nphi), vel: (3, nz, nr, nphi) or (nz, nr, nphi, 3)
Domains expected in self.domains as theta/z, r, phi arrays.
- Output is a single .vtu unstructured grid with VTK_VOXEL cells and point data arrays:
“rho” (scalar)
“vel_cart” (3-component vector)
- units(system)[source]
Switch the simulation unit system between
'CGS'and'MKS'.- Parameters:
system ({'CGS','MKS'}) – Unit system identifier.
- unlock_simulation(lock_info=None, force=True, verbose=False)[source]
Remove a simulation lock and optionally kill the owning PID.
- Parameters:
lock_info (dict or None) – Lock metadata as returned by
fargopy.Sys.is_locked. IfNonethe method will attempt to discover the lock for the active setup directory.force (bool, optional) – When
Trueattempt to forcibly terminate the process owning the lock (kill -9) before releasing the lock.
fargopy.sys module
- class fargopy.sys.Sys[source]
Bases:
objectSystem utilities for command execution, directory locking, and resource monitoring.
The
Sysclass provides a collection of static methods to interact with the operating system. It handles shell command execution with output capturing, directory locking mechanisms for concurrent safety, and system pause functionalities.- OUT = ''
- QERROR = True
- STDERR = ''
- STDOUT = ''
- static lock(dir, content={})[source]
Create a lock file in a directory.
Creates a
fargopy.lockfile containing the provided content to signal that the directory is in use or processing.- Parameters:
dir (str) – Path to the directory to lock.
content (dict, optional) – Dictionary of metadata to store in the lock file.
- static run(cmd, quiet=True)[source]
Run a system shell command.
Executes a command string in the shell and captures its stdout and stderr. Useful for running FARGO3D executables or other system tools.
- Parameters:
cmd (str) – The command string to execute.
quiet (bool, optional) – If True, suppress printing output to stdout (default: True).
- Returns:
(error_code, output_list) - error_code (int): 0 for success, non-zero for error. - output_list (list): List of output lines (strings).
- Return type:
tuple
Examples
Run a simple shell command:
>>> err, out = fp.Sys.run("ls -l")
- static sleep_timeout(timeout=5, msg=None)[source]
Sleep for a specified duration, interruptible by user input.
Sleeps for
timeoutseconds. Checks for keyboard interrupt (Enter or Ctrl+C) during the sleep period.- Parameters:
timeout (int, optional) – Sleep duration in seconds (default: 5).
msg (str, optional) – Message to display before sleeping.
- Returns:
True if interrupted, False if timeout completed.
- Return type:
bool
Examples
Sleep for 10 seconds or until user interrupt:
>>> if fp.Sys.sleep_timeout(10, "Press Enter to skip"): ... print("Skipped")