Snap¶
- class plonk.Snap¶
Smoothed particle hydrodynamics Snap object.
Snapshot files contain the state of the simulation at a point in time. Typical minimum data from a smoothed particle hydrodynamics simulation include the particle positions and smoothing length, from which the density field can be reconstructed, as well as the particle type. In addition, the particle velocities are required to restart the simulation.
Other data stored in the snapshot file include equation of state, dust, and magnetic field information, as well as numerical quantities related to time-stepping.
Examples
Use load_snap to generate a Snap object.
>>> snap = plonk.load_snap('file_name.h5')
To access arrays on the particles.
>>> snap['position'] >>> snap['density']
To access sink arrays.
>>> snap.sinks['position'] >>> snap.sinks['spin']
To access a subset of particles as a SubSnap.
>>> subsnap = snap[:100] >>> subsnap = snap[snap['x'] > 0] >>> subsnap = snap['gas']
To set a new array directly.
>>> snap['my_r'] = np.sqrt(snap['x'] ** 2 + snap['y'] ** 2)
Alternatively, define a function.
>>> @snap.add_array() ... def my_radius(snap): ... return np.hypot(snap['x'], snap['y'])
Or, use an existing one function.
>>> @snap.add_array() ... def my_R(snap): ... return plonk.analysis.particles.radial_distance(snap)
- add_alias(name, alias)¶
Add alias to array.
- add_array(vector=False, dust=False)¶
Decorate function to add array to Snap.
This function decorates a function that returns an array. The name of the function is the string with which to reference the array.
The function being decorated should return a Pint Quantity array, not a unitless numpy array.
- Parameters
vector (bool) – A bool to represent if the array is a vector in space that should have rotations applied to it. If True the rotation should be applied. If False the rotation cannot be applied. Default is False.
dust (bool) – A bool to represent if the array is a dust array, in that it has one column per dust species. Default is False.
- Returns
The decorator which returns the array.
- Return type
Callable
- add_quantities(category='common')¶
Make extra quantities available on Snap.
- Parameters
snap – The Snap object to add extra quantities to.
category (str) –
The category from which to add extra quantities. Options include:
’common’: adds common quantities appropriate for most simulations, such as angular momentum.
’disc’: adds accretion disc quantities, such as eccentricity or Keplerian frequency.
Default is ‘common’.
- add_unit(name, unit)¶
Add missing code unit to array.
Add code units to an array from file that has not had units set automatically.
- Parameters
- Return type
- array(name, sinks=False)¶
Get a particle (or sink) array.
- array_code_unit(arr)¶
Get array code units.
- Parameters
arr (str) – The string representing the quantity.
- Returns
The Pint unit quantity, or the float 1.0 if no unit found.
- Return type
Quantity
- array_in_code_units(name)¶
Get array in code units.
- Parameters
snap – The Snap or SubSnap.
name (str) – The array name.
- Returns
The array on the particles in code units.
- Return type
ndarray
- available_arrays(verbose=False, aliases=False)¶
Return a list of available particle arrays.
- base_array_name(name)¶
Get the base array name from a string.
For example, ‘velocity_x’ returns ‘velocity’, ‘density’ returns ‘density’, ‘dust_fraction_001’ returns ‘dust_fraction’, ‘x’ returns ‘position’.
- bulk_load(arrays=None)¶
Load arrays into memory in bulk.
- Parameters
arrays (Optional[List[str]]) – A list of arrays to load as strings. If None, then load all available arrays.
- Return type
- bulk_unload(arrays=None)¶
Un-load arrays from memory in bulk.
- Parameters
arrays (Optional[List[str]]) – A list of arrays to load as strings. If None, then unload all loaded arrays.
- Return type
- close_file()¶
Close access to underlying file.
- context(cache=True)¶
Context manager for caching particle arrays on a Snap.
Caching arrays in memory improves performance by saving slow reads from disc. Caching arrays is turned on by default on a Snap. However, it can be useful to turn it off for low memory requirements, such as reading from many snapshots. In this case it may be useful to use this context manager to improve performance inside the context without then leaving those arrays in memory afterwards.
Examples
Temporarily turn on caching arrays.
# Caching off >>> snap.cache_arrays False
# No loaded arrays >>> snap.loaded_arrays() ()
# Produce an image which loads arrays >>> with snap.context(cache=True): … ax = snap.image(‘density’)
# No loaded arrays >>> snap.loaded_arrays() ()
- family(name, squeeze=False)¶
Get a SubSnap of a particle family by name.
- Parameters
- Returns
- Return type
- image(quantity, *, x='x', y='y', interp='projection', weighted=False, slice_normal=None, slice_offset=None, extent=None, units=None, ax=None, ax_kwargs={}, colorbar_kwargs={}, **kwargs)¶
Visualize scalar SPH data as an image.
Visualize scalar smoothed particle hydrodynamics data by interpolation to a pixel grid.
- Parameters
snap (SnapLike) – The Snap (or SubSnap) object to visualize.
quantity (str) – The quantity to visualize. Must be a string to pass to Snap.
x (str) – The x-coordinate for the visualization. Must be a string to pass to Snap. Default is ‘x’.
y (str) – The y-coordinate for the visualization. Must be a string to pass to Snap. Default is ‘y’.
interp (str) –
The interpolation type. Default is ‘projection’.
’projection’ : 2d interpolation via projection to xy-plane
’slice’ : 3d interpolation via cross-section slice.
weighted (bool) – Whether to density weight the interpolation or not. Default is False.
slice_normal (Tuple[float, float, float]) – The normal vector to the plane in which to take the cross-section slice as a tuple (x, y, z). Default is (0, 0, 1).
slice_offset (Union[Quantity, float]) – The offset of the cross-section slice. Default is 0.0.
extent (Quantity) – The range in the x and y-coord as (xmin, xmax, ymin, ymax) where xmin, etc. can be floats or quantities with units of length. The default is to set the extent to a box of size such that 99% of particles are contained within.
units (Dict[str, str]) – The units of the plot as a dictionary. The keys correspond to quantities such as ‘position’, ‘density’, ‘velocity’, and so on. The values are strings representing units, e.g. ‘g/cm^3’ for density. There is a special key ‘projection’ that corresponds to the length unit in the direction of projection for projected interpolation plots.
ax (Any) – A matplotlib Axes handle.
ax_kwargs – Keyword arguments to pass to matplotlib Axes.
colorbar_kwargs – Keyword arguments to pass to matplotlib Colorbar.
**kwargs – Additional keyword arguments to pass to interpolation and matplotlib functions.
- Returns
The matplotlib Axes object.
- Return type
ax
Notes
Additional parameters passed as keyword arguments will be passed to lower level functions as required. E.g. Plonk uses matplotlib’s imshow for a image plot, so additional arguments to imshow can be passed this way.
See below for additional parameters for interpolation, colorbars, etc. All other keyword arguments are passed to the appropriate matplotlib function.
- Parameters
num_pixels (tuple) – The number of pixels to interpolate particle quantities to as a tuple (nx, ny). Default is (512, 512).
show_colorbar (bool) – Whether or not to display a colorbar. Default is True.
snap (SnapLike) –
quantity (str) –
x (str) –
y (str) –
interp (str) –
weighted (bool) –
slice_offset (Union[Quantity, float]) –
extent (Quantity) –
ax (Any) –
- Return type
Any
Examples
Show an image of the surface density in xy-plane.
>>> plonk.image(snap=snap, quantity='density')
Alternatively, access the function as a method on the Snap object.
>>> snap.image(quantity='density')
Set units for the plot.
>>> units = {'position': 'au', 'density': 'g/cm^3', 'projection': 'cm'} >>> snap.image(quantity='density', units=units)
Show a slice image of the density in xy-plane at z=0.
>>> snap.image(quantity='density', interp='slice')
- load_snap(filename, data_source, config=None)¶
Load snapshot from file.
- Parameters
filename (Union[str, pathlib.Path]) – The path to the file.
data_source (optional) – The SPH software that produced the data. Default is ‘phantom’.
config (optional) – The path to a Plonk config.toml file.
- loaded_arrays()¶
Return a list of loaded arrays.
- Returns
A list of names of loaded particle arrays.
- Return type
List
- neighbours(indices)¶
Get neighbours of particles.
- Parameters
indices (Union[numpy.ndarray, List[int]]) – The particle indices.
- Returns
An array of neighbours lists.
- Return type
ndarray of list
- particle_indices(particle_type, squeeze=False)¶
Particle indices of a particular type.
- Parameters
- Returns
If particle has no subtypes then returns an array of indices of that type. Otherwise return a list of arrays of indices, one for each subtype. However, if squeeze is True, return a single array.
- Return type
ndarray or list of ndarray
- plot(*, x='x', y='y', c=None, s=None, units=None, xlim=None, ylim=None, ax=None, ax_kwargs={}, colorbar_kwargs={}, **kwargs)¶
Visualize SPH data as a particle plot.
Visualize SPH data by plotting the particles, or a subset of the particles, possibly with marker colors and different sizes.
- Parameters
snap (SnapLike) – The Snap (or SubSnap) object to visualize.
x (str) – The x-coordinate for the visualization. Must be a string to pass to Snap. Default is ‘x’.
y (str) – The y-coordinate for the visualization. Must be a string to pass to Snap. Default is ‘y’.
c (str) – The quantity to color the particles. Must be a string to pass to Snap.
s (str) – The quantity to set the particle size. Must be a string to pass to Snap.
units (Dict[str, str]) – The units of the plot as a dictionary. The keys correspond to quantities such as ‘position’, ‘density’, ‘velocity’, and so on. The values are strings representing units, e.g. ‘g/cm^3’ for density.
xlim (Quantity) – The range in the x-coord as (xmin, xmax) where xmin/xmax can be floats or quantities with units of length.
ylim (Quantity) – The range in the y-coord as (ymin, ymax) where ymin/ymax can be floats or quantities with units of length.
ax (Any) – A matplotlib Axes handle.
ax_kwargs – Keyword arguments to pass to matplotlib Axes.
colorbar_kwargs – Keyword arguments to pass to matplotlib Colorbar.
**kwargs – Additional keyword arguments to pass to matplotlib functions.
- Returns
The matplotlib Axes object.
- Return type
ax
Examples
Show the particles in xy-plane.
>>> plonk.plot(snap=snap)
Alternatively, access the function as a method on the Snap object.
>>> snap.plot()
Plot density against x.
>>> snap.plot(x='x', y='density')
Color particles by density.
>>> snap.plot(x='x', y='y', c='density')
Set units for the plot.
>>> units = {'position': 'au', 'density': 'g/cm^3'} >>> snap.plot(x='x', y='y', c='density', units=units)
- read_extra_arrays(filename=None)¶
Read extra arrays from file.
- Parameters
filename (optional) – A filename to read from.
- Returns
The Snap.
- Return type
- reopen_file()¶
Re-open access to the underlying file.
- reset(arrays=False, rotation=True, translation=True)¶
Reset Snap.
Reset rotation and translations transformations on the Snap to initial (on-file) values. In addition, unload cached arrays.
- Parameters
- Returns
The reset Snap. Note that the reset operation is in-place.
- Return type
- rotate(rotation=None, axis=None, angle=None)¶
Rotate snapshot.
The rotation can be defined by a scipy Rotation object, or a combination of a vector, specifying a rotation axis, and an angle, specifying the rotation in radians.
- Parameters
rotation (Optional[scipy.spatial.transform.rotation.Rotation]) – The rotation as a scipy.spatial.transform.Rotation object.
axis (Optional[Union[numpy.ndarray, List[float], Tuple[float, float, float]]]) – An array specifying a rotation axis, like (x, y, z).
angle (Optional[float]) – A float specifying the rotation in radians.
- Returns
The rotated Snap. Note that the rotation operation is in-place.
- Return type
Examples
Rotate a Snap by π/3 around [1, 1, 0].
>>> axis = (1, 1, 0) >>> angle = np.pi / 3 >>> snap.rotate(axis=axis, angle=angle)
- set_central_body(sink_idx)¶
Set the central body for orbital dynamics.
The central body can be a sink particle or multiple sink particles given by a sink index, or list of sink indices. This method sets snap.properties[‘central_body’] with the central body mass, barycenter position and velocity. This is required to calculate orbital quantities on the particles such as eccentricity.
- set_kernel(kernel)¶
Set kernel.
- set_molecular_weight(molecular_weight)¶
Set molecular weight.
Set the molecular weight of the gas in gram / mole in snap.properties[‘molecular_weight’]. This is required to calculate temperature.
- set_units(**kwargs)¶
Set default unit for arrays.
- Parameters
kwargs – Keyword arguments with keys as the array name, e.g. ‘pressure’, and with values as the unit as a string, e.g. ‘pascal’.
- Return type
Examples
Set multiple default units.
>>> snap.set_units(pressure='pascal', density='g/cm^3')
- property sinks: plonk.snap.snap.Sinks¶
Sink particle arrays.
- subsnaps_as_dict(squeeze=False)¶
Return particle-type subsnaps as a dict of SubSnaps.
- Parameters
squeeze (optional) – Squeeze sub-types. For each key, if False and the particle family has sub-types then return a list of SubSnaps of each sub-type. Otherwise return a SubSnap with all particle of that type.
- Returns
A dict of all SubSnaps.
- Return type
Dict
- subsnaps_as_list(squeeze=False)¶
Return particle-type subsnaps as a list of SubSnaps.
- Parameters
squeeze (optional) – Squeeze sub-types. If True then each particle sub-type of the same type will be treated the same.
- Returns
A list of all SubSnaps.
- Return type
List[SubSnap]
- to_dataframe(columns=None, units=None)¶
Convert Snap to DataFrame.
- Parameters
columns (optional) – A list of columns to add to the data frame. Default is None.
units (optional) – A list of units corresponding to columns add to the data frame. Units must be strings, and must be base units. I.e. ‘cm’ not ‘10 cm’. If None, use default, i.e. cgs. Default is None.
- Returns
- Return type
DataFrame
- translate(translation, unit=None)¶
Translate snapshot.
I.e. shift the snapshot origin.
- Parameters
translation (Union[pint.quantity.build_quantity_class.<locals>.Quantity, numpy.ndarray]) – The translation as an array like (x, y, z), optionally with units. If no units are specified you must specify the units parameter below.
unit (Optional[str]) – The length unit for the translation. E.g. ‘au’.
- Returns
The translated Snap. Note that the translation operation is in-place.
- Return type
- property tree: scipy.spatial.ckdtree.cKDTree¶
Particle neighbour kd-tree.
Trees are represented by scipy cKDTree objects.
- vector(quantity, *, x='x', y='y', interp='projection', weighted=False, slice_normal=None, slice_offset=None, extent=None, units=None, ax=None, ax_kwargs={}, **kwargs)¶
Visualize vector SPH data as a vector plot.
Visualize scalar smoothed particle hydrodynamics data by interpolation to a pixel grid of arrows.
- Parameters
snap (SnapLike) – The Snap (or SubSnap) object to visualize.
quantity (str) – The quantity to visualize. Must be a string to pass to Snap.
x (str) – The x-coordinate for the visualization. Must be a string to pass to Snap. Default is ‘x’.
y (str) – The y-coordinate for the visualization. Must be a string to pass to Snap. Default is ‘y’.
interp (str) –
The interpolation type. Default is ‘projection’.
’projection’ : 2d interpolation via projection to xy-plane
’slice’ : 3d interpolation via cross-section slice.
weighted (bool) – Whether to density weight the interpolation or not. Default is False.
slice_normal (Tuple[float, float, float]) – The normal vector to the plane in which to take the cross-section slice as a tuple (x, y, z). Default is (0, 0, 1).
slice_offset (Union[Quantity, float]) – The offset of the cross-section slice. Default is 0.0.
extent (Quantity) – The range in the x and y-coord as (xmin, xmax, ymin, ymax) where xmin, etc. can be floats or quantities with units of length. The default is to set the extent to a box of size such that 99% of particles are contained within.
units (Dict[str, str]) – The units of the plot as a dictionary. The keys correspond to quantities such as ‘position’, ‘density’, ‘velocity’, and so on. The values are strings representing units, e.g. ‘g/cm^3’ for density. There is a special key ‘projection’ that corresponds to the length unit in the direction of projection for projected interpolation plots.
ax (Any) – A matplotlib Axes handle.
ax_kwargs – Keyword arguments to pass to matplotlib Axes.
**kwargs – Additional keyword arguments to pass to interpolation and matplotlib functions.
- Returns
The matplotlib Axes object.
- Return type
ax
Notes
Additional parameters passed as keyword arguments will be passed to lower level functions as required.
See below for additional parameters for interpolation, vector properties, etc. All other keyword arguments are passed to the appropriate matplotlib function.
- Parameters
num_pixels (tuple) – The number of pixels to interpolate particle quantities to as a tuple (nx, ny). Default is (512, 512).
number_of_arrows (tuple) – The number of arrows to display by sub-sampling the interpolated data. Default is (25, 25).
normalize_vectors (bool) – Whether to normalize the arrows to all have the same length. Default is False.
snap (SnapLike) –
quantity (str) –
x (str) –
y (str) –
interp (str) –
weighted (bool) –
slice_offset (Union[Quantity, float]) –
extent (Quantity) –
ax (Any) –
- Return type
Any
Examples
Show a vector plot of velocity in xy-plane.
>>> plonk.vector(snap=snap, quantity='velocity')
Alternatively, access the function as a method on the Snap object.
>>> snap.vector(quantity='velocity')
Set units for the plot.
>>> units = {'position': 'au', 'velocity': 'km/s', 'projection': 'km'} >>> snap.vector(quantity='velocity', units=units)
Show a slice plot of the velocity in xy-plane at z=0.
>>> snap.vector(quantity='density', interp='slice')
- class plonk.SubSnap(base, indices)¶
A Snap subset of particles.
A SubSnap can be generated from a Snap via an index array, a particle mask, or a string. SubSnaps can be used like a Snap, including: accessing arrays, plotting, finding neighbours, etc.
- Parameters
Examples
Generate a SubSnap directly.
>>> subsnap = SubSnap(base=snap, indices=[0, 1, 2, 3])
You can generate a SubSnap from a Snap object. For example, generate a SubSnap of the gas particles on a Snap.
>>> subsnap = snap['gas']
Generate a SubSnap of particles with a mask.
>>> subsnap = snap[snap['x'] > 0]
Generate a SubSnap of particles from indices.
>>> subsnap = snap[:100] >>> subsnap = snap[[0, 9, 99]]
- property indices: numpy.ndarray¶
Particle indices.
- property sinks: plonk.snap.snap.Sinks¶
Sink particle arrays.
- class plonk.Sinks(base, indices=None)¶
Sink particles in a Snap.
A Sinks object is generated from a Snap.
- Parameters
base (Snap) – The base Snap.
indices (optional) – Indices to specify a subset of sink particles.
Examples
Generate a Sinks object directly.
>>> sinks = Sinks(base=snap)
Generate a Sinks object from a Snap object.
>>> sinks = snap.sinks
Choose a subset of sink particles.
>>> sinks = snap.sinks[[0, 1]] >>> star = snap.sinks[0] >>> planets = snap.sinks[1:4]
- array(name)¶
Get an array.
- Parameters
name (str) – A string representing the name of the particle array.
- Returns
- Return type
Quantity
- available_arrays(verbose=False, aliases=False)¶
Return a list of available sink arrays.
- property indices: numpy.ndarray¶
Sink particle indices.
- loaded_arrays()¶
Return a list of loaded arrays.
- Returns
A list of names of loaded sink arrays.
- Return type
List
- plot(*, x='x', y='y', c=None, s=None, units=None, xlim=None, ylim=None, ax=None, ax_kwargs={}, colorbar_kwargs={}, **kwargs)¶
Visualize SPH data as a particle plot.
Visualize SPH data by plotting the particles, or a subset of the particles, possibly with marker colors and different sizes.
- Parameters
snap (SnapLike) – The Snap (or SubSnap) object to visualize.
x (str) – The x-coordinate for the visualization. Must be a string to pass to Snap. Default is ‘x’.
y (str) – The y-coordinate for the visualization. Must be a string to pass to Snap. Default is ‘y’.
c (str) – The quantity to color the particles. Must be a string to pass to Snap.
s (str) – The quantity to set the particle size. Must be a string to pass to Snap.
units (Dict[str, str]) – The units of the plot as a dictionary. The keys correspond to quantities such as ‘position’, ‘density’, ‘velocity’, and so on. The values are strings representing units, e.g. ‘g/cm^3’ for density.
xlim (Quantity) – The range in the x-coord as (xmin, xmax) where xmin/xmax can be floats or quantities with units of length.
ylim (Quantity) – The range in the y-coord as (ymin, ymax) where ymin/ymax can be floats or quantities with units of length.
ax (Any) – A matplotlib Axes handle.
ax_kwargs – Keyword arguments to pass to matplotlib Axes.
colorbar_kwargs – Keyword arguments to pass to matplotlib Colorbar.
**kwargs – Additional keyword arguments to pass to matplotlib functions.
- Returns
The matplotlib Axes object.
- Return type
ax
Examples
Show the particles in xy-plane.
>>> plonk.plot(snap=snap)
Alternatively, access the function as a method on the Snap object.
>>> snap.plot()
Plot density against x.
>>> snap.plot(x='x', y='density')
Color particles by density.
>>> snap.plot(x='x', y='y', c='density')
Set units for the plot.
>>> units = {'position': 'au', 'density': 'g/cm^3'} >>> snap.plot(x='x', y='y', c='density', units=units)
- plonk.load_snap(filename, data_source='phantom', config=None)¶
Load snapshot from file.
- Parameters
filename (Union[str, pathlib.Path]) – The path to the file.
data_source (optional) – The SPH software that produced the data. Default is ‘phantom’.
config (optional) – The path to a Plonk config.toml file.