pynbody.snapshot.gadget.GadgetSnap

pynbody.snapshot.gadget.GadgetSnap#

class pynbody.snapshot.gadget.GadgetSnap(filename: Path, only_header=False, must_have_paramfile=False, ignore_cosmo=False)[source]#

Bases: SimSnap

Class for reading Gadget-1 and Gadget-2 old-style (i.e. pre-HDF5) snapshots.

Attributes:
ancestor

The original SimSnap from which this view is derived (potentially self)

filename

The filename of the snapshot, if it was loaded from disk.

Methods

all_keys()

Returns a list of all arrays that can be either lazy-evaluated or lazy loaded from an auxiliary file.

bridge(other)

Tries to construct a bridge function between this SimSnap and another one.

build_tree([num_threads, shared_mem])

Build a kdtree for SPH operations and for accelerating geometrical filters

check_headers(head1, head2)

Check two headers for consistency

conversion_context()

Return a dictionary containing a (scalefactor) and h (Hubble constant in canonical units) for this snapshot, ready for passing into unit conversion functions.

decorator(fn)

Register a decorator to be applied to all instances of a given class.

derivable_keys()

Returns a list of arrays which can be lazy-evaluated.

derived_array(fn)

Function decorator to register a derivable quantity for all SimSnaps, or for a specific subclass.

derived_quantity()

Deprecated alias for derived_array()

families()

Return the particle families which have representitives in this SimSnap.

family_keys([fam])

Return list of arrays which are not accessible from this view, but can be accessed from family-specific sub-views.

get(key[, alternative])

Standard python get method, returns self[key] if key in self else alternative

get_block_list()

Get list of unique blocks in snapshot, with the types they refer to

get_block_parts(name, family)

Get the number of particles present in a block, of a given type

get_copy_on_access_simsnap()

Return a new SimSnap that copies data out of this one when accessed

get_index_list(relative_to[, of_particles])

Get a list specifying the index of the particles in this view relative to the ancestor relative_to

halos(*args, **kwargs)

Tries to instantiate a halo catalogue object for the given snapshot.

has_family_key(name)

Returns True if the array name is accessible (in memory) for at least one family

has_key(name)

Returns True if the array name is accessible (in memory)

import_tree(serialized_tree[, num_threads])

Import a precomputed kdtree from a serialized form.

infer_original_units(dimensions)

Given a unit (or string) dimensions, returns a unit with the same physical dimensions which is in the unit schema of the current file.

intersect(other[, op])

Returns the set intersection of this simulation view with another view of the same simulation

is_ancestor(other)

Returns true if other is a subview of self

is_derived_array(name[, fam])

Returns True if the array or family array of given name is auto-derived (and therefore read-only).

is_descendant(other)

Returns true if self is a subview of other

items()

Returns a list of tuples describing the array names and their contents in memory

iter_subclasses()

Iterate over all subclasses of this class, recursively.

iter_subclasses_with_priority(priority)

Iterate over all subclasses, starting with the given priorities

iteritems()

Iterator over the array names and their contents in memory

iterkeys()

Iterator over the array names in memory

itervalues()

Iterator over the arrays in memory

keys()

Return the directly accessible array names (in memory)

load_copy()

Tries to load a copy of this snapshot, using partial loading to select only a subset of particles corresponding to a given SubSnap

loadable_family_keys([fam])

Return list of arrays which are loadable for specific families, but not for all families.

loadable_keys([fam])

Returns a list of arrays which can be lazy-loaded from an auxiliary file.

mean_by_mass(name)

Calculate the mean by mass of the specified array.

offset_velocity(offset)

Shift the velocity by the given offset.

original_units()

Converts all arrays'units to be consistent with the units of the original file.

physical_units([distance, velocity, mass, ...])

Converts all arrays' units to be consistent with the distance, velocity, mass basis units specified.

rotate(matrix[, description])

Rotates using a specified matrix.

rotate_x(angle)

Rotates about the current x-axis by 'angle' degrees.

rotate_y(angle)

Rotates about the current y-axis by 'angle' degrees.

rotate_z(angle)

Rotates about the current z-axis by 'angle' degrees.

set_units_system([velocity, distance, mass, ...])

Set the unit system for the snapshot by specifying any or all of velocity, distance, mass and temperature units.

setdiff(other)

Returns the set difference of this simulation view with another view of the same simulation

stable_derived_array(fn)

Function decorator to register a stable derivable quantity for all SimSnaps, or for a specific subclass.

stable_derived_quantity()

Deprecated alias for stable_derived_array()

transform(matrix)

Deprecated alias for rotate().

translate(offset)

Translate by the given offset.

union(other)

Returns the set union of this simulation view with another view of the same simulation

unlink_array(name)

If the named array is auto-derived, this destroys the link so that the array becomes editable but no longer auto-updates.

values()

Returns a list of the actual arrays in memory

wrap([boxsize, convention])

Wraps the positions of the particles in the box to lie in a chosen fundamental domain.

write([fmt, filename])

write_array(array_name[, fam, overwrite])

Write out the array with the specified name.

__init__(filename: Path, only_header=False, must_have_paramfile=False, ignore_cosmo=False)[source]#

Initialize an empty, zero-length SimSnap.

For most purposes SimSnaps should instead be initialized through load() or new().

all_keys() list[str]#

Returns a list of all arrays that can be either lazy-evaluated or lazy loaded from an auxiliary file.

property ancestor: SimSnap#

The original SimSnap from which this view is derived (potentially self)

bridge(other) bridge.AbstractBridge#

Tries to construct a bridge function between this SimSnap and another one.

This function calls pynbody.bridge.bridge_factory(). For more information see bridge-tutorial, or the reference documentation for pynbody.bridge.

build_tree(num_threads=None, shared_mem=None) None#

Build a kdtree for SPH operations and for accelerating geometrical filters

Parameters:
  • num_threads (int, optional) – Number of threads to use for building and most operations on the tree. If None, the default number of threads is used.

  • shared_mem (bool, optional) – Whether to use shared memory for the tree. This is used by the tangos library to share a kdtree between different processes. It is not recommended for general use, and defaults to False.

check_headers(head1, head2)[source]#

Check two headers for consistency

conversion_context() dict[str, float]#

Return a dictionary containing a (scalefactor) and h (Hubble constant in canonical units) for this snapshot, ready for passing into unit conversion functions.

classmethod decorator(fn)#

Register a decorator to be applied to all instances of a given class.

Decorators are called when a new instance of the class is created, and are passed the new instance as an argument.

derivable_keys() list[str]#

Returns a list of arrays which can be lazy-evaluated.

classmethod derived_array(fn)#

Function decorator to register a derivable quantity for all SimSnaps, or for a specific subclass.

Example usage:

>>> @pynbody.derived_array
... def radius_squared(sim):
...     return sim['x']**2 + sim['y']**2 + sim['z']**2

When a user tries to access the radius_squared array from any snapshot, the function will be called and the result will be stored then returned. The function should take a single argument, the simulation object, and return a numpy array or SimArray of the same length as the simulation.

The array will be automatically updated whenever arrays it relies upon for derivation are changed.

If instead of pynbody.derived_array, a derived array associated with a specific subclass of SimSnap is desired, one may use the following syntax:

>>> @MySimSnapSubclass.derived_array
... def radius_squared(sim):
...     return sim['x']**2 + sim['y']**2 + sim['z']**2

If the function has a docstring, it will be prepended with “Derived: “ to indicate that it is a derived quantity. If the derived array is being added for a specific subclass, a list of subclasses is also included in the automatic modifications to the docstring.

Changed in version 2.0: The function name has been changed from derived_quantity to derived_array. The old name is still available but will be removed in a future version.

See also

For introductory information about derived quantities see Automatically Derived Arrays.

derived_quantity()#

Deprecated alias for derived_array()

families() list[Family]#

Return the particle families which have representitives in this SimSnap. The families are ordered by their appearance in the snapshot.

family_keys(fam=None) list[str]#

Return list of arrays which are not accessible from this view, but can be accessed from family-specific sub-views.

If fam is not None, only those keys applying to the specific family will be returned (equivalent to self.fam.keys()).

property filename#

The filename of the snapshot, if it was loaded from disk.

get(key, alternative=None) SimArray | None#

Standard python get method, returns self[key] if key in self else alternative

get_block_list()[source]#

Get list of unique blocks in snapshot, with the types they refer to

get_block_parts(name, family)[source]#

Get the number of particles present in a block, of a given type

get_copy_on_access_simsnap() SimSnap#

Return a new SimSnap that copies data out of this one when accessed

This provides a degree of isolation (e.g. modifications made to the arrays in the copy-on-access view are not reflected back into the original snapshot). It is intended for advanced use, e.g. by tangos.

get_index_list(relative_to, of_particles=None) ndarray#

Get a list specifying the index of the particles in this view relative to the ancestor relative_to

The returned index list satisfies relative_to[get_index_list(relative_to)]==self.

halos(*args, **kwargs) halo.HaloCatalogue#

Tries to instantiate a halo catalogue object for the given snapshot.

For introductory information about halo catalogues, see Halos in Pynbody, and the documentation for pynbody.halo.

Multiple catalogue classes are available in pynbody, and they are tried in turn until the first which accepted the request to load halos for this file.

The order of catalogue class priority is either defined in the configuration file or can be passed as a ‘priority’ keyword argument, which should be a list of either class names or classes.

For example

>>> h = snap.halos(priority = ["HOPCatalogue", "AHFCatalogue", pynbody.halo.subfind.SubfindCatalogue])

would try to load HOP halos, then AHF halos, then Subfind halos, before finally trying all other known halo classes in an arbitrary order.

Arguments and keyword arguments other than priority are passed onto the individual halo loaders. If a given catalogue class does not accept the args/kwargs that you pass in, by definition it cannot be used; this can lead to ‘silent’ failures. To understand why a given class is not being instantiated by this method, the best option is to try _directly_ instantiating that class to reveal the error explicitly.

has_family_key(name: str) bool#

Returns True if the array name is accessible (in memory) for at least one family

has_key(name: str) bool#

Returns True if the array name is accessible (in memory)

import_tree(serialized_tree, num_threads=None) None#

Import a precomputed kdtree from a serialized form.

Throws ValueError if the tree is not compatible with the snapshot (though does not protect against all possible incompatibilities, so use with care).

infer_original_units(dimensions)#

Given a unit (or string) dimensions, returns a unit with the same physical dimensions which is in the unit schema of the current file.

intersect(other, op=<function intersect1d>) SimSnap#

Returns the set intersection of this simulation view with another view of the same simulation

is_ancestor(other) bool#

Returns true if other is a subview of self

is_derived_array(name, fam=None) bool#

Returns True if the array or family array of given name is auto-derived (and therefore read-only).

is_descendant(other) bool#

Returns true if self is a subview of other

items() list[tuple[str, SimArray]]#

Returns a list of tuples describing the array names and their contents in memory

classmethod iter_subclasses() Iterable[type]#

Iterate over all subclasses of this class, recursively.

This is used by HaloCatalogue and SimSnap to find a suitable loader for a given file.

classmethod iter_subclasses_with_priority(priority: Iterable[str | type]) Iterable[type]#

Iterate over all subclasses, starting with the given priorities

The priorities can be provided either as a string or a class

iteritems() Iterator[tuple[str, SimArray]]#

Iterator over the array names and their contents in memory

iterkeys() Iterator[str]#

Iterator over the array names in memory

itervalues() Iterator[SimArray]#

Iterator over the arrays in memory

keys() list[str]#

Return the directly accessible array names (in memory)

load_copy() SimSnap#

Tries to load a copy of this snapshot, using partial loading to select only a subset of particles corresponding to a given SubSnap

loadable_family_keys(fam=None)[source]#

Return list of arrays which are loadable for specific families, but not for all families.

loadable_keys(fam=None)[source]#

Returns a list of arrays which can be lazy-loaded from an auxiliary file.

mean_by_mass(name) float | UnitBase#

Calculate the mean by mass of the specified array.

offset_velocity(offset)#

Shift the velocity by the given offset.

Returns a pynbody.transformation.GenericTranslation object which can be used as a context manager to ensure that the translation is undone.

For more information, see the pynbody.transformation documentation.

original_units()#

Converts all arrays’units to be consistent with the units of the original file.

physical_units(distance='kpc', velocity='km s^-1', mass='Msol', persistent=True, convert_parent=True)#

Converts all arrays’ units to be consistent with the distance, velocity, mass basis units specified.

Parameters:
  • distance (string (default = 'kpc')) – The distance unit to convert to.

  • velocity (string (default = 'km s^-1')) – The velocity unit to convert to.

  • mass (string (default = 'Msol')) – The mass unit to convert to.

  • persistent (boolean (default = True)) – Apply units change to future lazy-loaded arrays if True.

  • convert_parent (boolean (default = True)) – Propagate units change from a halo catalogue to a parent snapshot. See note below.

Note

The option convert_parent is only applicable to Halo objects. It is ignored by all other objects, including pynbody.snapshot.simsnap.SimSnap, pynbody.snapshot.subsnap.SubSnap, and pynbody.halo.HaloCatalogue objects.

When physical_units is called on a pynbody.halo.Halo and convert_parent is True, no immediate action is taken on the pynbody.halo.Halo itself; rather the request is passed upwards to the pynbody.halo.HaloCatalogue.

The catalogue object then calls physical_units on the parent snapshot and on all cached halos, setting convert_parent=False so that the units change is then applied to the pynbody.halo.Halo object itself.

This ensures that unit changes propagate through to properties of all halos. Most users will not need to worry about this subtlety; things should ‘just work’ if you ignore the convert_parent option.

rotate(matrix, description=None)#

Rotates using a specified matrix.

Returns a pynbody.transformation.GenericTranslation object which can be used as a context manager to ensure that the translation is undone.

For more information, see the pynbody.transformation documentation.

Parameters:
  • matrix (array_like) – The 3x3 orthogonal matrix to rotate by

  • description (str) – A description of the rotation to be returned from str() and repr()

rotate_x(angle)#

Rotates about the current x-axis by ‘angle’ degrees.

Returns a pynbody.transformation.GenericTranslation object which can be used as a context manager to ensure that the translation is undone.

For more information, see the pynbody.transformation documentation.

rotate_y(angle)#

Rotates about the current y-axis by ‘angle’ degrees.

Returns a pynbody.transformation.GenericTranslation object which can be used as a context manager to ensure that the translation is undone.

For more information, see the pynbody.transformation documentation.

rotate_z(angle)#

Rotates about the current z-axis by ‘angle’ degrees.

Returns a pynbody.transformation.GenericTranslation object which can be used as a context manager to ensure that the translation is undone.

For more information, see the pynbody.transformation documentation.

set_units_system(velocity=None, distance=None, mass=None, temperature=None)#

Set the unit system for the snapshot by specifying any or all of velocity, distance, mass and temperature units. The units can be given as strings or as pynbody Unit objects.

If any of the units are not specified and a previous file_units_system does not exist, the defaults are used.

setdiff(other) SimSnap#

Returns the set difference of this simulation view with another view of the same simulation

classmethod stable_derived_array(fn)#

Function decorator to register a stable derivable quantity for all SimSnaps, or for a specific subclass.

A stable derived array is one that is not expected to change over the course of a simulation, and so is only ever calculated once. Otherwise, it behaves just like a derived array; see derived_array().

If the function has a docstring, it will be prepended with “Derived: “ to indicate that it is a derived quantity. If the derived array is being added for a specific subclass, a list of subclasses is also included in the automatic modifications to the docstring.

For more information about derived quantities see derived-quantities, and specifically the subsection stable-derived-quantities.

Changed in version 2.0: The function name has been changed from stable_derived_quantity to stable_derived_array. The old name is still available but will be removed in a future version.

stable_derived_quantity()#

Deprecated alias for stable_derived_array()

transform(matrix)#

Deprecated alias for rotate().

translate(offset)#

Translate by the given offset.

Returns a pynbody.transformation.GenericTranslation object which can be used as a context manager to ensure that the translation is undone.

For more information, see the pynbody.transformation documentation.

union(other) SimSnap#

Returns the set union of this simulation view with another view of the same simulation

If the named array is auto-derived, this destroys the link so that the array becomes editable but no longer auto-updates.

values() list[SimArray]#

Returns a list of the actual arrays in memory

wrap(boxsize=None, convention='center')#

Wraps the positions of the particles in the box to lie in a chosen fundamental domain.

Parameters:
  • boxsize (float | units.UnitBase, optional) – The size of the box to wrap the particles in. If not specified, the boxsize is taken from the snapshot’s properties.

  • convention (str, optional) – The convention to use for wrapping the particles. The default is ‘center’, which wraps the particles to lie in the range [-boxsize/2, boxsize/2). Alternatively, ‘upper’ wraps the particles to lie in the range [0, boxsize).

write_array(array_name, fam=None, overwrite=False, **kwargs)#

Write out the array with the specified name.

Only a subset of SimSnap subclasses support this operation. If the subclass does not support it, an OSError will be raised.

Parameters:
  • array_name (str) – the name of the array to write

  • fam (str or list of str, optional) – Write out only one family; or provide a list to write out a set of families.

  • overwrite (bool, optional) – If True, overwrite the array on disk if it already exists. If False (default), an OSError will be raised if the array already exists.