snapanalysis package

Submodules

snapanalysis.orbit module

class snapanalysis.orbit.Orbit(t: ndarray[Quantity], pos: ndarray[Quantity], vel: ndarray[Quantity], ids: dict, source_dir: str | None = None)

Bases: object

Stores orbits of particles throughout a simulation. TODO: allow adding of orbits

t

Times the orbit is recorded at

Type:

np.array of astropy.Quantity

pos

Orbit xyz positions, shape is (N_times, 3, N_particles)

Type:

np.array of astropy.Quantity

vel

Orbit xyz positions, shape is (N_times, 3, N_particles)

Type:

np.array of astropy.Quantity

ids

Keys are particle IDs, values are the index of the particles in the last dimension of the position and velocity arrays

Type:

dict

source

The directory of the simulation the orbit was extracted from

Type:

str, optional

ids: dict
pos: ndarray[Quantity]
save(filename: str)

Saves the Orbit object to a pickle binary file

Parameters:

filename (str) – name of the file

source_dir: str | None = None
t: ndarray[Quantity]
vel: ndarray[Quantity]
snapanalysis.orbit.read_orbit_from_file(filename: str) Orbit

Reads an Orbit object from a pickle binary file

Parameters:

filename (str) – name of the file

Returns:

Loaded Orbit object

Return type:

snapanalysis.orbit.Orbit

snapanalysis.sim module

snapanalysis.sim.get_alignment_rotations(sim_dir: str, part_type: int, r_max: Quantity | None = None, out_file: None | str = None, select_IDs: None | tuple = None, use_centers: None | str = None) ndarray

Generates the rotation matrices needed to align the angular momentum vector of the specified particle type to the z-axis for every snapshot in a simulation.

Parameters:
  • sim_dir (str) – Directory in which the simualtion snapshots are stored

  • part_type (int) – Particle type with which to compute angular momentum vectors

  • r_max (u.Quantity | None, optional) – If not None, computes angular momenta using only particles inside this radius, by default None

  • out_file (None | str, optional) – If given as a string, saves the rotation matrices to a numpy binary file of this name, by default None

  • select_IDs (None or tuple, optional) – min. and max. particle IDs for selection if desired, otherwise uses all particles of the specified type.

  • use_centers (None or str, optional) – Uses COM positions and velocities stored in the specified text file. If None, snapshots will be auto-centered before rotations are calculated

Returns:

N_snapsx3x3 array containting the rotation matrices needed to align each snapshot’s angular momentum to the z-axis

Return type:

np.ndarray

snapanalysis.sim.get_particle_orbit(sim_dir: str, part_type: int, ids: list, use_centers: None | str = None, use_rotations: None | str = None, verbose: bool = False) Orbit

Stores the orbit of a particle or particles throughout a simulation.

Parameters:
  • sim_dir (str) – Directory containing simulation snapshots

  • part_type (int) – Type of particle

  • ids (list) – List of IDs of desired particles

  • use_centers (None or str, optional) – Uses COM positions and velocities stored in the specified text file. If None, snapshots will be auto-centered

  • use_rotations (None or str, optional) – Uses rotation matrices stored in the specified numpy binary file. If None, snapshots will be auto-aligned

  • verbose (bool, optional) – print progress, by default False

Returns:

Orbit – Orbit object containing the orbits of the specified particles

Return type:

snapanalysis.orbit.Orbit

snapanalysis.sim.orbit_com(sim_dir: str, part_type: int, out_file: None | str = None, select_IDs: None | tuple = None, use_guess: None | str = None, com_kwargs: dict = {}, vel_kwargs: dict = {}, verbose: bool = False) ndarray

orbit_com stores the center-of-mass position and velocity of the specified

Parameters:
  • sim_dir (str) – Directory containing simulation snapshots

  • part_type (int) – particle type to use for center-finding

  • out_file (None or str, optional) – if not None, saves the orbit file under this name

  • select_IDs (None or tuple, optional) – min. and max. particle IDs for selection if desired, otherwise uses all particles of the specified type.

  • use_guess (None or str ('previous')) – specifies where the intial sphere is centered. None uses the com of every particle, ‘previous’ uses the previous snapshot’s com.

  • com_kwargs (dict, optional) – kwargs for snap.find_position_center, by default {}

  • vel_kwargs (dict, optional) – kwargs for snap.find_velocity_center, by default {}

  • verbose (bool, optional) – print progress, by default False

Returns:

Nx7 array with [t,x,y,z,vx,vy,vz] at each timestep

Return type:

np.ndarray

snapanalysis.snap module

class snapanalysis.snap.snapshot(filename: str, ptype: int)

Bases: object

The main class of snapAnalysis, which reads and stores a single particle type from a single gagdet/arepo format hdf5 snapshot. Methods provide common analysis routines such as computing density fields, centering, rotations, etc.

align_angular_momentum(**kwargs) None

align_angular_momentum rotates the particle data such that the average angular momentum vector is aligned with the z-axis.

Parameters:

snapshot.find_angular_momentum_directon() (**kwargs are passed to)

apply_center(pos_center: ndarray, vel_center: ndarray | None = None) None

center_particles centers particles on a specified center in position and velocity

Parameters:
  • pos_center (np.ndarray) – [x, y, z] Position center

  • vel_center (None or np.ndarray, optional) – [vx, vy, vz] Velocity center

apply_rotation(rot_mat: ndarray) None

apply_rotation applies a rotation matrix to particle positions and velocities

Parameters:

rot_mat (np.ndarray) – rotation matrix

arrange_fields(indices: ndarray) None

arrange_fields re-arranges all existing data fields according to the input indices. Useful for sorting the simulation by particle ID, for instance.

Parameters:

indices (np.ndarray) – array of sorting indices, e.g., from numpy.argsort()

check_if_field_read(field: str) bool

check_if_field_read checks to see whether a data field has already been stored

Parameters:

field (str) – field name

Returns:

True if field has already been read, False otherwise

Return type:

bool

density_points(points: ndarray, k_max: int = 1000) ndarray

density_points computes the local density field at a specified collection of points using the k_max-th nearest particles to the point.

In practice, the density at a local point is calculated as the mass of k_max particles, divided by the volume of a sphere with radius equal to the distance to the k_max-th nearest-neighbor.

Parameters:
  • points (np.ndarray) – Nx3 array of points at which to compute the density

  • k_max (int, optional) – maximum nearest neighbor to use in density calculation, i.e. the defualt of 1000 uses the 1000 nearest-neighbors.

Returns:

Array of length N containing the value of the density field at the input points

Return type:

np.ndarray

find_and_apply_center(com_kwargs: dict = {}, vel_kwargs: dict = {}) None

find_and_apply_center Calculates the positions and velocity center of the snapshot and centers the particle data on the COM location in phase-space.

Parameters:
  • com_kwargs (dict, optional) – kwargs for snap.find_position_center

  • vel_kwargs (dict, optional) – kwargs for snap.find_velocity_center

find_angular_momentum_direction(r_max: Quantity | None = None) ndarray

find_angular_momentum_direction Returns the normalized average specific angular momentum vector of the loaded particles.

Parameters:

r_max (u.Quantity | None, optional) – max. radius within which to consider particles. None uses entire box. By default None

Returns:

[x,y,z] components of the average angular momentum unit vector

Return type:

np.ndarray

find_position_center(guess: None | ndarray = None, r_start: None | float = None, vol_dec: float = 3.0, delta: float = 0.01, N_min: int = 1000, verbose: bool = False) ndarray

find_position_center finds the center of mass of the snapshot via the shrinking-spheres method.

Parameters:
  • guess (None or np.ndarray, optional) – Initial [x,y,z] guess for COM position. If None, uses the com of every active particle in the box.

  • r_start (None or float, optional) – Initial sphere radius, default (none) uses furthest particle from box origin

  • vol_dec (float, optional) – Factor by which the sphere radius is reduced during an iteration, by default 3.

  • delta (float, optional) – Tolerance, stop when change in COM is less than delta, by default 0.01

  • Nmin (int, optional) – Minimum number of particles allowed within the sphere, by default 1000

  • verbose (bool, optional) – Prints extra information, by default False

Returns:

[x, y, z] center of mass

Return type:

np.ndarray

find_velocity_center(pos_center: ndarray, r_max: Quantity = <Quantity 15. kpc>) ndarray

find_velocity_center finds the COM velocity using particles within r_max.

Parameters:
  • pos_center (np.ndarray) – [x, y, z] center of mass position

  • r_max (u.Quantity, optional) – max distance from COM to use particles for the calculation, by default 15.0*u.kpc

Returns:

[vx, vy, vz] COM velocity

Return type:

np.ndarray

get_FDM_velocities() ndarray

Calculates the FDM velocity field based on the wavefunction outputs, via the phase gradient method: v = hbar/m gradient(phase) Based on code from Philip Mocz

Returns:

FDM cell velocities

Return type:

np.ndarray

load_particle_data(fields: list) None

load_particle_data reads particle data for a field if it doesn’t already exist.

Parameters:

fields (list) – list containing desired data fields, e.g. [‘Coordinates’, ‘Velocities’, ‘ParticleIDs’, ‘Masses’, ‘Potential’, ‘Acceleration’, ‘PsiRe’, ‘PsiIm’]

principal_axes() tuple[ndarray, ndarray]

principal_axes calculates the length and direction of the principal axes of the particle distribution by diagonalizing the inertia tensor.

Returns:

  • np.ndarray – Principal axes lengths (eigenvalues of inertia tensor)

  • np.ndarray – Principal axes directions (eigenvectors of inertia tensor)

print_header()

Displays all info contained in the header of the snapshot.

print_structure()

Displays the file structure of the snapshot.

read_all() None

read_all wrapper to load all “standard” fields (IDs, pos, vel, mass)

read_field(field: str) ndarray

read_field returns one data field of one particle type

Parameters:

field (str) – data field

Returns:

data field

Return type:

np.ndarray

read_masstable() Quantity

read_masstable returns the masstable

Returns:

masstable

Return type:

astropy Quantity

select_particles(selection: tuple | ndarray) None

select_particles selects the desired ID range

Parameters:

selection (tuple or np.ndarray) – Tuple of min and max ID values to keep (inclusive), or a boolean array to be used as a mask for the particles

snapanalysis.utils module

snapanalysis.utils.cartesian_to_cylindrical(coords: ndarray) ndarray

cartesian_to_cylindrical transforms a set of Cartesian coordinates to cylindrical coordinates, while preserving the input shape.

Parameters:

coords (np.array) – Nx3 array of x,y,z coordinates

Returns:

(rho, phi (azimuth), z) coordinates

Return type:

np.array

snapanalysis.utils.cartesian_to_spherical(coords: ndarray) ndarray

cartesian_to_spherical transforms a set of Cartesian coordinates to spherical coordinates, while preserving the shape of the input.

Parameters:

coords (np.array) – Nx3 array of x,y,z coordinates

Returns:

(r, theta (polar), phi (azimuth)) coordinates

Return type:

np.array

snapanalysis.utils.com_define(m: ndarray, pos: ndarray) ndarray

com_define basic center-of-mass calculation

Parameters:
  • m (np.ndarray) – particle masses

  • pos (np.ndarray) – particle positions

Returns:

[x, y, z] center of mass

Return type:

np.ndarray

snapanalysis.utils.find_alignment_rotation(vec: ndarray) ndarray

find_alignment_rotation returns the rotation matrix needed to align the input vector with the positive z-axis

Parameters:

vec (np.ndarray) – [x,y,z] vector

Returns:

rotation matrix

Return type:

np.ndarray

snapanalysis.utils.get_snaps(dir: str, ext: str = '.hdf5', prefix: str = 'snap_') ndarray

get_snaps returns an ordered list of all snapshots in a directory. Original code by Himansh Rathore

Parameters:
  • dir (str) – directory where snapshots are stored

  • ext (str, optional) – snapshot file extension, by default ‘.hdf5’

  • prefix (str, optional) – snapshot name prefix, by default ‘snap_

Returns:

Ordered list of snapshots

Return type:

np.ndarray

snapanalysis.utils.get_vslice_indices(pos: ndarray, slice: float, axis: int) ndarray

get_vslice_indices returns particle indices within a vertical slice about the box midplane

Parameters:
  • pos (np.ndarray) – paticle positions

  • slice (float) – slice width in simulation units

  • axis (int) – axis index along which the slice is taken

Returns:

array of indices to pos that specify which particles are in the slice

Return type:

np.ndarray

snapanalysis.utils.inertia_tensor(m: ndarray, pos: ndarray) ndarray

inertia_tensor Calculates the inertia tensor for a collection of point masses of mass m at positions pos

Parameters:
  • m (np.ndarray) – Nx1 array of masses

  • pos (np.ndarray) – Nx3 array of positions

Returns:

3x3 symmetric inertia tensor

Return type:

np.ndarray

snapanalysis.utils.rotation_matrix(alpha: float, beta: float, gamma: float) ndarray

rotation_matrix returns the rotation matrix for a general intrinsic rotation of yaw, pitch, roll (Tait-Bryan angles about z,y,x) alpha, beta, gamma, respectively.

Parameters:
  • alpha (float) – yaw angle (about z axis)

  • beta (float) – pitch angle (about y axis)

  • gamma (float) – roll angle (about x axis)

Returns:

rotation matrix

Return type:

np.ndarray

snapanalysis.utils.set_axes(ax: int) tuple[int, int]

set_axes returns x and y axes for a plot based on the projection axis

Parameters:

ax (int) – projection axis index

Returns:

  • int – plot x-axis index

  • int – plot y-axis index

snapanalysis.utils.vector_cartesian_to_cylindrical(coords: ndarray, vecs: ndarray) ndarray

vector_cartesian_to_cylindrical transforms a vector field defined in cartesian coordinates at coords with vectors vecs into cylindrical coordinates.

Parameters:
  • coords (np.ndarray) – Points at which the vector field is defined in Cartesian coordinates

  • vecs (np.ndarray) – Cartesian vector values of the field

Returns:

(rho, phi (azimuth), z) vectors

Return type:

np.ndarray

snapanalysis.utils.vector_cartesian_to_spherical(coords: ndarray, vecs: ndarray) ndarray

vector_cartesian_to_spherical transforms a vector field defined in cartesian coordinates at coords with vectors vecs into spherical coordinates.

Parameters:
  • coords (np.ndarray) – Points at which the vector field is defined in Cartesian coordinates

  • vecs (np.ndarray) – Cartesian vector values of the field

Returns:

(r, theta (polar), phi (azimuth)) vectors

Return type:

np.ndarray

snapanalysis.vis module

snapanalysis.vis.anisotropy_profile(snap: snapshot, rmin: float = 0.0, rmax: float = 150.0, nbins: int = 100, log_bins: bool = False, plot: bool = True, plot_name: bool | str = False) tuple[ndarray, ndarray]

anisotropy_profile calculates the velocity anisotropy profile of a halo, given by Eqn 4.61 of Binney & Tremaine:

\(\beta(r) = 1 - \frac{\sigma_\theta^2 + \sigma_\phi^2}{2 \sigma_r^2}\)

Parameters:
  • rmin (float, optional) – min. radius, by default 0.

  • rmax (float, optional) – max. radius, by default 150.

  • nbins (int, optional) – number of radial bins, by default 100

  • log_bins (bool, optional) – If True, make logarithmically spaced bins instead of linearly spaced bins, by default False

  • plot (bool, optional) – show a plot of the computed profile, by default True

  • plot_name (bool | str, optional) – if a str, saves the plot with this filename, by default False

Returns:

  • np.ndarray – radial points / bin centers

  • np.ndarray – value of the anisotropy profile at the bin centers

snapanalysis.vis.density_profile(snap: snapshot, rmin: float = 0.0, rmax: float = 150.0, nbins: int = 100, log_bins: bool = False, plot: bool = True, plot_name: bool | str = False) tuple[ndarray, ndarray]

density_profile computes the density profile of a halo Note: snpshot must be centered (with e.g. snap.apply_center()) first!

Parameters:
  • rmin (float, optional) – min. radius, by default 0.

  • rmax (float, optional) – max. radius, by default 150.

  • nbins (int, optional) – number of radial bins, by default 100

  • log_bins (bool, optional) – use logarithmic bin spacing, by default False

  • plot (bool, optional) – creates a plot of the density profile, by default True

  • plotName (bool | str, optional) – if not False, saves the plot under this file name, by default False

Returns:

  • np.ndarray – Radial points / bin centers

  • np.ndarray – value of the density profile at the bin centers

snapanalysis.vis.density_projection(snap: snapshot, axis: int = 2, bins: int | list = [200, 200], mass_weight: bool = True, plot: bool = True, plot_name: bool | str = False, slice_width: None | float = None, normalization: bool = 'surface') tuple[ndarray, ndarray, ndarray]

density_projection generates a density histogram projected along the specified axis.

Parameters:
  • axis (int, optional) – Axis to project along (x=0, y=1, z=2), by default 2

  • bins (int or list, optional) – bin specification passed to np.histogram, by default [200,200]

  • mass_weight (bool, optional) – weight particles by their mass, by default True

  • plot (bool, optional) – create a plot of the density histogram, by default True

  • plot_name (bool or str, optional) – if not False, saves the plot under this file name, by default False

  • slice_width (None | float, optional) – A distance in the length units of the snapshot

  • include (from the midplane along the specified axis to)

  • None (by default)

  • normalization (str, optional) – “surface” (default) returns surface density, “overdensity” returns the density contrast, “volume” returns volume density, requires slice_width to be nonzero.

Returns:

  • np.ndarray – Density histogram

  • np.ndarray – x bin edges

  • np.ndarray – y bin edges

snapanalysis.vis.potential_projection(snap: snapshot, axis: int = 2, bins: int | list = [200, 200], plot: bool = True, plot_name: bool | str = False, slice_width: None | float = None) tuple[ndarray, ndarray, ndarray]

potential_projection bins the particles in the specified plane and finds the mean value of the potential within each bin.

Parameters:
  • axis (int, optional) – Axis to project along (x=0, y=1, z=2), by default 2

  • bins (int | list, optional) – bin specification passed to scipy’s binned_statistic_2d, by default [200,200]

  • plot (bool, optional) – create a plot of the potential, by default True

  • plot_name (bool | str, optional) – if not False, saves the plot under this file name, by default False

  • slice_width (None | float, optional) – Leave as None to use the whole box. Otherwise, provide a distance in the length units of the snapshot from the midplane along the specified axis to include, by default None

Returns:

  • np.ndarray – Binned potential field

  • np.ndarray – x bin edges

  • np.ndarray – y bin edges

Module contents

snapanalysis.main() None