Computing physical quantities

pNbody offers two distinct pathways for accessing and computing physical quantities, depending on whether the user requires high-performance raw data or physically scaled quantities.

Raw / Brute Arrays

This approach provides direct access to data exactly as it is stored in the simulation snapshot, without any overhead from unit conversion or coordinate mapping.

  • Characteristics: No coordinate transformations are applied.

  • Coordinate System: Remains in the native simulation format (e.g., comoving coordinates for cosmological runs).

Proper Conversions

This approach automatically transforms raw data into physically meaningful quantities ready for analysis.

  • Characteristics: Includes the transition from comoving to physical (proper) coordinates and scales values into the desired unit system.

  • Coordinate System: Physical/Proper coordinates, accounting for the scale factor \(a(t)\) in cosmological simulations.

  • Use Case: Standard for generating plots, comparing with observational data, or performing physical diagnostics (e.g., calculating circular velocities in \(\text{km/s}\)).

Note

Each approach is implemented through its own set of methods to prevent the accidental mixing of units. Generally, methods prefixed with get_ or those located within the Proper mixin handle converted data, while direct attribute access (e.g., .pos, .vel) returns raw arrays.

The table below provides the list methods to compute basic quantities from both raw and converted arrays.

raw arrays

converted array

meaning

nb.pos

nb.Pos()

Coordinates

nb.x()

nb.X()

x-coordinates

nb.y()

nb.Z()

y-coordinates

nb.z()

nb.Z()

z-coordinates

nb.rxyz()

nb.Rxyz()

spherical radius

nb.phi_xyz()

spherical azimuthal angle

nb.theta_xyz()

spherical elevation angle

nb.rxy()

nb.Rxy()

cylindrical radius

nb.phi_xy()

cylindrical azimuthal angle

nb.cm()

nb.CM()

center of mass

nb.vel

nb.Vel()

Velocities

nb.vx()

nb.VX()

x-components of the velocity

nb.vy()

nb.VX()

y-components of the velocity

nb.vz()

nb.VZ()

z-components of the velocity

nb.Vx()

nb.VX()

x-components of the velocity

nb.Vy()

nb.VY()

y-components of the velocity

nb.Vz()

nb.VZ()

z-components of the velocity

nb.vn()

norm of the velocity

nb.vrxyz()

radial velocity in spherical coordinate

nb.Vr()

radial velocity in spherical coordinate

nb.Vt()

tengential velocity in spherical coordinate

nb.Vphi()

azimuthal velocity in spherical coordinate

nb.Vtheta()

polar velocity in spherical coordinate

nb.Vrxy()

radial velocity in cylindrical coordinate

nb.VR()

radial velocity in cylindrical coordinate

nb.Vtxy()

tangential velocity in cylindrical coordinate

nb.VT()

tangential velocity in cylindrical coordinate

nb.mass

nb.Mass()

masses

nb.get_mass_tot()

nb.TotalMass()

total mass

nb.totalmass()

nb.TotalMass()

total mass

Examples

To run the examples proposed hereafter, you need first to follow the instructions given in the section Generate examples .

We also suppose that the following model has been loaded, i.e, in your python interpreter you typed:

>>> from pNbody import Nbody
>>> nb = Nbody("MW_galaxy.hdf5")

From brute arrays

Any array attached to an Nbody object contains physical quantities. They corresponds precisely to the values stored in the snapshot without any conversion. In some cases working with those array can be useful. However, by default, no units are attached to those arrays. They can be used the following way:

# coordinates of particles
>>> nb.pos

array([[ 0.59459096, -6.849886  ,  0.83441144],
       [ 1.1637805 ,  9.026595  ,  0.10752326],
       [ 3.0834882 , -0.19680543, -0.28759104],
       ...,
       [ 4.139927  ,  1.5572525 ,  0.14975849],
       [-2.6131186 , -2.20977   , -0.05962646],
       [-3.0051165 , -5.1332235 ,  0.5773136 ]], dtype=float32)

# initial specific energy
>>> nb.u_init

array([1.0152912, 1.0152912, 1.0152912, ..., 0.       , 0.       ,
     0.       ], dtype=float32)

A large number of methods works directly on these brute arrays:

>>> nb.cm()

array([-0.3414196 ,  0.1023279 ,  0.59247654])

>>> nb.x()

array([ 0.59459096,  1.1637805 ,  3.0834882 , ...,  4.139927  ,
       -2.6131186 , -3.0051165 ], dtype=float32)

>>> nb.vx()

array([ 219.8732  , -206.42065 ,   11.346481, ...,  -13.726294,
        111.58997 ,  187.3271  ], dtype=float32)

By convention, the name of those methods stars with a lower case character.

With a proper conversion

If the Nbody object contains units or information if it comes from a cosmological simulation or not, a proper conversion can be performed using methods. By convention, the name of those methods stars with an upper case character. Those methods can be supplemented with units. How quantities are converted in different situations is described in section How to deal with comoving to proper units conversion ? .

For example, to get the position of particles in kpc:

>>> nb.Pos(units="kpc")

array([[ 0.59459096, -6.849886  ,  0.83441144],
       [ 1.1637805 ,  9.026595  ,  0.10752326],
       [ 3.0834882 , -0.19680543, -0.28759104],
       ...,
       [ 4.139927  ,  1.5572525 ,  0.14975849],
       [-2.6131186 , -2.20977   , -0.05962646],
       [-3.0051165 , -5.1332235 ,  0.5773136 ]], dtype=float32)

For example, to get the velocities of particles in km/s:

>>> nb.Vel(units="km/s")

array([[ 219.8732   ,    9.581228 ,   11.225813 ],
       [-206.42065  ,   22.783592 ,    1.2769856],
       [  11.346481 ,  182.89082  ,   20.033907 ],
       ...,
       [ -13.726294 ,  175.35052  ,    8.549284 ],
       [ 111.58997  , -112.51938  ,   63.499905 ],
       [ 187.3271   , -109.07539  ,  -16.536251 ]], dtype=float32)

The GEAR physical model

The following table profile a list of usefull methods specific to the GEAR physical model.

Hydrodynamical quantities

Hydrodynamical methods

method name

meaning

status

nb.Rho()

Gas density

ok

nb.Density()

Gas density

ok

nb.InternalEnergy()

Internal energy

ok

nb.SphRadius()

SPH smoothing value

ok

Thermochemistry quantities

Thermochemistry methods

method name

meaning

status

nb.T()

Gas temperature

ok

nb.Temperature()

Gas temperature

ok

nb.GasMeanWeight()

Gas mean molecular weight

ok

nb.FreeElectronNumberFraction()

Gas mean molecular weight

ok

nb.XHI

HI mass fraction (Grackle 1/2/3)

ok

nb.XHII

HII mass fraction (Grackle 1/2/3)

ok

nb.XHeI

HeI mass fraction (Grackle 1/2/3)

ok

nb.XHeII

HeII mass fraction (Grackle 1/2/3)

ok

nb.XHeIII

HeIII mass fraction (Grackle 1/2/3)

ok

nb.XH2I

H2I mass fraction (Grackle 2/3)

ok

nb.XH2II

H2II mass fraction (Grackle 2/3)

ok

nb.XHDI

HDI mass fraction (Grackle 3)

ok

nb.XHM

HM (H-) mass fraction (Grackle 3)

ok

nb.XDI

DI (deuterium) mass fraction (Grackle 3)

ok

nb.XDII

DII (deuterium) mass fraction (Grackle 3)

ok

nb.XHDI

HDI mass fraction mass fraction (Grackle 3)

ok

nb.Xe

Free electron mass fraction

ok

nb.XH()

Hydrogen mass fraction

ok

nb.XHe()

Helium mass fraction

ok

nb.XH2()

Molecular hydrogen mass fraction

ok

nb.HydrogenMass()

Hydrogen Mass

ok

nb.HeliumMass()

Helium Mass

ok

nb.H2Mass()

H2 Mass

ok

Stellar quantities

Stellar quantities

method name

meaning

status

nb.InitialMass()

Initial mass (before stellar mass loss)

ok

nb.StellarFormationTime()

Time at which a stellar particle formed

ok

nb.StellarAge()

Age of a stellar particle

ok

nb.FormationGasDensity()

Gas density at the formation of the stellar particle

ok

nb.LuminositySpec()

Specific luminosity of a stellar particle (Vazdekis)

ok

nb.Luminosity()

Luminosity of a stellar particle

ok

nb.TotalLuminosity()

Total luminosity of the stellar particles

ok

nb.Magnitudes()

Magnitude of a stellar particle

ok

nb.TotalMagnitude()

Total magnitude of a model

ok

nb.TotalMagnitudeV_EuclidVIS()

Total V-band magnitude derived from Euclid VIS

ok

Chemistry

Chemistry methods

method name

meaning

status

nb.MetalsH()

Metallicity [M/H]

ok

nb.Fe()

Iron abundance [Fe/H]

ok

nb.Mg()

Magnesium abundance [Mg/H]

ok

nb.O()

Oxygen abundance [O/H]

ok

nb.Ba()

Baryum abundance [Ba/H]

ok

nb.MgFe()

Magnesium over Iron ratio [Mg/Fe]

ok

nb.CaFe()

Calcium over Iron ratio [Mg/Fe]

ok

nb.BaFe()

Barium over Iron ratio [Mg/Fe]

ok

nb.SiFe()

Silicium over Iron ratio [Mg/Fe]

ok

nb.AbRatio()

Elt1 over Elt2 ratio [Elt1/Elt2]

ok

nb.ModeFeH()

Return the peak (mode) of the [Fe/H] distribution.

ok

nb.ModeFeHFit()

Return [Fe/H] mode using an analytical MDF fit.

ok

Others

Other methods

method name

meaning

status

nb.TotalKineticEnergy()

Total kinetic energy

?

nb.TotalPotentialEnergy()

Total potential energy

?

nb.TJeans()

Jeans temperature

?

nb.Tff()

Free-fall time

?

Module References

class pNbody.extensions.gear.base._NbodyBaseMixin

Bases: object

CM(a=None, h=None, units=None, ptype=None, r_max=None, center=array([0., 0., 0.]))

Calculate the center of mass of the model.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

  • ptype (int or list, optional) – Particle type(s) used to identify the center of mass minimum.

  • r_max (float, optional) – Maximum radius from the provided center to consider for the calculation in proper units.

  • center (array_like, optional) – The coordinate center in proper units.

Returns

A 3D array [x, y, z] representing the center of mass coordinates.

Return type

ndarray

Return the center of mass of the system in physical units.

Mass(a=None, h=None, units=None)

Return the particle masses in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

Returns

Physical masses.

Return type

ndarray

Pos(a=None, h=None, units=None)

Return the position of the particles in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units for the output.

Returns

Particle positions scaled to physical units.

Return type

ndarray

Rxy(a=None, h=None, units=None, center=None)

Return the 2D cylindrical radial distance in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

  • center (array_like, optional) – The coordinate center.

Returns

Physical 2D radii.

Return type

ndarray

Rxyz(a=None, h=None, units=None, center=None)

Return the 3D radial distance of particles in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

  • center (array_like, optional) – The coordinate center for radial calculation.

Returns

Physical radial distances.

Return type

ndarray

TotalMass(a=None, h=None, units=None)

Return the total mass of the system in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

Returns

Total physical mass.

Return type

float

VX(a=None, h=None, units=None)

Return the x coordinate of the particles velocity in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units for the output.

Returns

Particle x velocity scaled to physical units.

Return type

ndarray

VY(a=None, h=None, units=None)

Return the y coordinate of the particles velocity in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units for the output.

Returns

Particle y velocity scaled to physical units.

Return type

ndarray

VZ(a=None, h=None, units=None)

Return the z coordinate of the particles velocity in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units for the output.

Returns

Particle z velocity scaled to physical units.

Return type

ndarray

Vel(a=None, h=None, units=None)

Return the particle velocities in physical units.

This calculation removes the expansion contribution (peculiar velocity) and applies the requested unit conversion.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

Returns

Physical velocities.

Return type

ndarray

X(a=None, h=None, units=None)

Return the x coordinate of the particles in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units for the output.

Returns

Particle x coordinate scaled to physical units.

Return type

ndarray

Y(a=None, h=None, units=None)

Return the y coordinate of the particles in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units for the output.

Returns

Particle y coordinate scaled to physical units.

Return type

ndarray

Z(a=None, h=None, units=None)

Return the z coordinate of the particles in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units for the output.

Returns

Particle z coordinate scaled to physical units.

Return type

ndarray

class pNbody.extensions.gear.hydro._NbodyHydroMixin

Bases: object

Density(a=None, h=None, units=None)

Return the gas mass density in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

Returns

Physical densities.

Return type

ndarray

InternalEnergy(a=None, h=None, units=None)

Return the internal energy in physical units.

Checks for either self.u or self.u_init and applies the appropriate cosmological and unit conversion factors.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

Returns

Physical internal energy.

Return type

ndarray

Rho(a=None, h=None, units=None)

Return the gas mass density in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

Returns

Physical densities.

Return type

ndarray

SphRadius(a=None, h=None, units=None)

Return the SPH smoothing lengths in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

Returns

Physical smoothing lengths (Hsml).

Return type

ndarray

class pNbody.extensions.gear.thermochemistry._NbodyThermoChemistryMixin

Bases: object

Provide methods to calculate mass fractions and total masses of gas species.

This mixin handles the summation of different ionization states for Hydrogen, Helium, and Molecular Hydrogen, typically used in simulations involving cooling networks of Grackle.

FreeElectronNumberFraction()

Compute the free electron number fraction (xe).

This returns the number of free electrons per hydrogen nucleus:

xe = n_e / n_H

The computation converts mass fractions into number fractions using:

n_i / n_H = X_i / A_i

where: - X_i : mass fraction of species i - A_i : atomic/molecular mass (in units of hydrogen mass)

Each ion contributes according to its charge.

Returns

Free electron number fraction.

Return type

ndarray

GasMeanWeight(compute_free_electron=False)

Calculate the mean molecular weight ($mu$) of the gas.

This method identifies the appropriate Grackle cooling mode based on available species arrays. It computes the total number density by summing Hydrogen, Helium, and (if available) Molecular Hydrogen and Deuterium species, along with free electrons.

Note: Metal contributions are currently neglected in this calculation.

Returns

The dimensionless mean molecular weight $mu$ per particle.

Return type

ndarray

H2Mass(a=None, h=None, units=None)

Return the total molecular hydrogen mass for each particle.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

Returns

Molecular hydrogen mass in physical units.

Return type

ndarray

HeliumMass(a=None, h=None, units=None)

Return the total helium mass for each particle.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

Returns

Helium mass in physical units.

Return type

ndarray

HydrogenMass(a=None, h=None, units=None)

Return the total hydrogen mass for each particle.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

Returns

Hydrogen mass in physical units.

Return type

ndarray

T(a=None, h=None, units=None)

Calculate the gas temperature in Kelvin.

If Grackle species are available, the temperature is derived using a calculated mean molecular weight. Otherwise, it defaults to the standard thermodynamic relations provided in pNbody.thermodyn.

Parameters
  • a (float, optional) – Scale factor for internal energy conversion.

  • h (float, optional) – Hubble parameter for internal energy conversion.

  • units (str, optional) – Units for internal energy if conversion is required.

Returns

Gas temperature in Kelvin.

Return type

ndarray

Temperature(a=None, h=None, units=None)

Calculate the gas temperature in Kelvin.

If Grackle species are available, the temperature is derived using a calculated mean molecular weight. Otherwise, it defaults to the standard thermodynamic relations provided in pNbody.thermodyn.

Parameters
  • a (float, optional) – Scale factor for internal energy conversion.

  • h (float, optional) – Hubble parameter for internal energy conversion.

  • units (str, optional) – Units for internal energy if conversion is required.

Returns

Gas temperature in Kelvin.

Return type

ndarray

XDI()

Return the neutral deuterium (D I) mass fraction.

Returns

Neutral deuterium mass fraction.

Return type

ndarray

XDII()

Return the ionized deuterium (D II) mass fraction.

Returns

Ionized deuterium mass fraction.

Return type

ndarray

XH()

Return the total hydrogen mass fraction.

This sums the neutral (HI) and ionized (HII) components.

Returns

Total hydrogen mass fraction per particle.

Return type

ndarray

XH2()

Return the total molecular hydrogen mass fraction.

This sums the neutral (H2I) and ionized (H2II) molecular states.

Returns

Total H2 mass fraction per particle.

Return type

ndarray

XH2I()

Return the neutral molecular hydrogen (H₂) mass fraction.

Returns

Neutral molecular hydrogen mass fraction.

Return type

ndarray

XH2II()

Return the singly ionized molecular hydrogen (H₂⁺) mass fraction.

Returns

Singly ionized molecular hydrogen mass fraction.

Return type

ndarray

XHDI()

Return the hydrogen deuteride (HD) mass fraction.

Returns

Hydrogen deuteride mass fraction.

Return type

ndarray

XHI()

Return the neutral hydrogen mass fraction.

Returns

Neutral hydrogen mass fraction.

Return type

ndarray

XHII()

Return the ionized hydrogen mass fraction.

Returns

Ionized hydrogen mass fraction.

Return type

ndarray

XHM()

Return the negative hydrogen ion (H⁻) mass fraction.

Returns

Negative hydrogen ion mass fraction.

Return type

ndarray

XHe()

Return the total helium mass fraction.

This sums the neutral (HeI), singly ionized (HeII), and doubly ionized (HeIII) components.

Returns

Total helium mass fraction per particle.

Return type

ndarray

XHeI()

Return the neutral helium mass fraction.

Returns

Neutral helium mass fraction.

Return type

ndarray

XHeII()

Return the singly ionized helium mass fraction.

Returns

Singly ionized helium mass fraction.

Return type

ndarray

XHeIII()

Return the doubly ionized helium mass fraction.

Returns

Doubly ionized helium mass fraction.

Return type

ndarray

Xe()

Return the free electron mass fraction multiplied by the proton mass (Grackle convention).

Returns

Free electron mass fraction multiplied by the proton mass.

Return type

ndarray

class pNbody.extensions.gear.stars._NbodyStarsMixin

Bases: object

Mixin providing stellar analysis tools, luminosities, and magnitudes.

This mixin includes methods for calculating stellar ages, chemical evolution tracking, and photometric properties using Simple Stellar Population (SSP) models.

FormationGasDensity(a=None, h=None, units=None)

Calculate the gas density at the time of particle formation.

This is specifically used for stellar particles to retrieve the density of the parent gas particle at the birth redshift.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units for the output density.

Returns

Physical or comoving density at formation.

Return type

ndarray

InitialMass(a=None, h=None, units=None)

Return the initial stellar birth masses in physical units.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • units (str or pNbody.units.Unit, optional) – Target units.

Returns

Initial birth masses.

Return type

ndarray

Luminosity(tnow=None, band='V', model=None)

Calculate the luminosity per particle in solar units.

Parameters
  • tnow (float, optional) – The current scale factor.

  • band (str, optional) – The photometric band. Default is ‘V’.

  • model (str, optional) – The SSP model to use (e.g., ‘CMD’, ‘BastI’,’BPASS230_JKC_V’). If None, defaults to the Vazdekis specific luminosity calculation.

Returns

Total luminosity in solar mass for each particle.

Return type

ndarray

LuminositySpec(tnow=None, band='V')

Compute the specific luminosity per unit solar mass (L_sol / M_sol).

Uses the Vazdekis SSP models to interpolate luminosity based on stellar age and metallicity.

Parameters
  • tnow (float, optional) – The current scale factor for age calculation.

  • band (str, optional) – The photometric band (e.g., ‘U’, ‘B’, ‘V’, ‘R’, ‘I’). Default is ‘V’.

Returns

Specific luminosities for each particle.

Return type

ndarray

Magnitude(filter=None, tnow=None)

return the total magnitude of the system (alias for TotalMagnitude) tnow allows to shift the stellar ages

Magnitudes(filter=None, tnow=None)

Calculate the apparent or absolute magnitudes per particle.

Parameters
  • filter (str, optional) – The name of the filter to use. If None, uses the system default.

  • tnow (float, optional) – Current scale factor to determine stellar ages.

Returns

The magnitudes for each particle.

Return type

ndarray

StellarAge(a=None, t=None, units=None)

Calculate the current age of stellar particles.

The age is defined as the difference between the current cosmic time and the stellar formation time.

Parameters
  • a (float, optional) – Current scale factor. If None, uses the system’s current scale factor.

  • t (float, optional) – Current cosmic time.

  • units (str or pNbody.units.Unit, optional) – The output units for the age (e.g., ‘Gyr’).

Returns

The ages of stellar particles.

Return type

ndarray

StellarFormationTime(a=None, t=None, units=None)

Calculate the time at which stellar particles formed.

By default, this assumes the internal array tstar contains the scale factor or cosmic time of formation.

Parameters
  • a (float, optional) – Scale factor to override default behavior.

  • t (float, optional) – Cosmic time to override default behavior.

  • units (str or pNbody.units.Unit, optional) – The output units for the time.

Returns

The formation times of stellar particles.

Return type

ndarray

TotalLuminosity(tnow=None, band='V', model=None)

Calculate the total luminosity of the system.

Parameters
  • tnow (float, optional) – The current scale factor.

  • band (str, optional) – The photometric band. Default is ‘V’.

  • model (str, optional) – The SSP model to use.

Returns

The sum of luminosities of all particles in solar units.

Return type

float

TotalMagnitude(filter=None, tnow=None)

Calculate the total integrated magnitude of the system.

The total magnitude is derived by summing the fluxes of all individual stellar particles.

Parameters
  • filter (str, optional) – The name of the photometric filter. If None, uses the default.

  • tnow (float, optional) – The current scale factor for age calculation.

Returns

The total magnitude of the system.

Return type

float

TotalMagnitudeV_EuclidVIS(tnow=None)

Calculate the total integrated V-band magnitude derived from Euclid VIS.

This calculation applies the transformation from Marleau+2025 (Section 6.2), where the Euclid VIS filter (BPASS230_Euclid_VIS) is used as a proxy and shifted by a constant offset to estimate the V-band magnitude.

Parameters

tnow (float, optional) – The current scale factor for age calculation. If None, uses the current system scale factor.

Returns

The total estimated V-band magnitude of the system.

Return type

float

class pNbody.extensions.gear.chemistry._NbodyChemMixin

Bases: object

Provide chemical analysis tools for N-body simulation particles.

This mixin assumes the parent class possesses a ‘metals’ array and dictionaries for solar abundances and element indexing. It provides methods for calculating logarithmic abundance ratios [X/H] and [X/Y], as well as statistical descriptors of the Metallicity Distribution Function (MDF).

AbRatio(elt1, elt2)

Return the logarithmic abundance ratio [elt1/elt2].

Parameters
  • elt1 (str) – The first element symbol (e.g., ‘Fe’, ‘Mg’).

  • elt2 (str) – The second element symbol or ‘H’ for hydrogen.

Returns

The abundance ratio relative to solar.

Return type

ndarray

Ba()

Return the barium abundance [Ba/H] of each particle.

Returns

Logarithmic barium abundance relative to solar.

Return type

ndarray

BaFe()

Return the barium over iron ratio [Ba/Fe] of each particle.

Returns

Logarithmic Ba/Fe ratio relative to solar.

Return type

ndarray

CaFe()

Return the calcium over iron ratio [Ca/Fe] of each particle.

Returns

Logarithmic Ca/Fe ratio relative to solar.

Return type

ndarray

Fe()

Return the iron abundance [Fe/H] of each particle.

Returns

Logarithmic iron abundance relative to solar.

Return type

ndarray

MetalsH()

Return the metallicity [M/H] of each particle.

By default, this uses the internal ‘metals’ array. If the object possesses a format-specific ‘_MetalsH’ method, it will be used instead.

Returns

Logarithmic metallicity relative to solar.

Return type

ndarray

Mg()

Return the magnesium abundance [Mg/H] of each particle.

Returns

Logarithmic magnesium abundance relative to solar.

Return type

ndarray

MgFe()

Return the alpha-enhancement [Mg/Fe] of each particle.

Returns

Logarithmic Mg/Fe ratio relative to solar.

Return type

ndarray

ModeFeH(display=False)

Return the peak (mode) of the [Fe/H] distribution.

This computes a simple 1D histogram of the iron abundances and returns the value of the most populated bin.

Parameters

display (bool, optional) – If True, plots the [Fe/H] distribution and highlights the mode. Default is False.

Returns

The most frequent [Fe/H] value (the mode).

Return type

float

ModeFeHFit(display=False)

Return the [Fe/H] mode using an analytical MDF fit.

The peak is determined by fitting an instantaneous mixing model (Pagel 2009) to the metallicity distribution function.

Parameters

display (bool, optional) – If True, plots the histogram, the fitted analytical curve, and the resulting mode. Default is False.

Returns

A list containing [fitted_mode, error].

Return type

list

O()

Return the oxygen abundance [O/H] of each particle.

Returns

Logarithmic oxygen abundance relative to solar.

Return type

ndarray

SiFe()

Return the silicon over iron ratio [Si/Fe] of each particle.

Returns

Logarithmic Si/Fe ratio relative to solar.

Return type

ndarray

class pNbody.extensions.gear.units._NbodyUnitsMixin

Bases: object

Provide high-level unit transformation and conversion tools.

This mixin manages the tranition between comoving/proper units and facilitates bulk unit changes using Gadget parameter files.

ChangeUnits(GadgetParameterFile1=None, GadgetParameterFile2=None)

Convert all internal arrays from one unit system to another.

This requires two Gadget-style parameter files to define the source and target unit systems.

Parameters
  • GadgetParameterFile1 (str) – Path to the parameter file defining the CURRENT unit system.

  • GadgetParameterFile2 (str) – Path to the parameter file defining the TARGET unit system.

ComovingToProperConversionInfo()

Print comoving-to-proper conversion status to the message stream.

ComovingToProperConversionOff()

Disable conversion from comoving to proper coordinates.

ComovingToProperConversionOn()

Enable conversion from comoving to proper coordinates.

ConversionFactor(units, a=None, h=None, mode=None)

Return the total conversion factor including cosmology.

Combines unit conversion, scale factor conversion, and Hubble parameter correction into a single multiplier.

Parameters
  • units (str or pNbody.units.Unit) – Target units.

  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

  • mode (str, optional) – Physical quantity mode (e.g., ‘pos’, ‘vel’, ‘rho’).

Returns

The total conversion factor.

Return type

float

HubbleConversionFactor(h=None, mode=None)

Calculate the Hubble parameter ($h$) contribution to conversion.

Applies scaling for quantities typically stored in $h^{-1}$ units.

Parameters
  • h (float, optional) – The dimensionless Hubble parameter. Defaults to self.hubbleparam.

  • mode ({'pos', 'mass', 'rho', 'time', ...}, optional) – The physical quantity being converted.

Returns

The conversion factor to remove $h$ dependencies.

Return type

float

HubbleFactorCorrectionInfo()

Print Hubble factor correction status to the message stream.

HubbleFactorCorrectionOff()

Disable Hubble factor ($h$) correction.

HubbleFactorCorrectionOn()

Enable Hubble factor ($h$) correction.

ScaleFactorConversionFactor(a=None, mode=None)

Calculate the scale factor ($a$) contribution to coordinate conversion.

Applies the appropriate powers of $a$ based on the physical quantity type (position, density, velocity, etc.).

Parameters
  • a (float, optional) – The scale factor to use. Defaults to self.atime.

  • mode ({'pos', 'mass', 'rho', 'u', 'u_init', 'vel'}, optional) – The physical quantity being converted.

Returns

The conversion factor due to cosmic expansion.

Return type

float

UnitsConversionFactor(units, mode=None)

Return the base unit conversion factor.

This factor does not account for the Hubble parameter or the scaling factor.

Parameters
  • units (str or pNbody.units.Unit) – The target units for conversion.

  • mode (str, optional) – The physical quantity mode (not used in base conversion).

Returns

The conversion factor from internal system to target units.

Return type

float

doComovingToProperConversion()

Return True if conversion from comoving to proper coordinates is enabled.

Returns

Current status of coordinate conversion.

Return type

bool

doHubbleFactorCorrection()

Return True if $h$ factor correction is enabled.

Returns

Current status of Hubble correction.

Return type

bool

isCosmoRun()

Return True if the simulation is a cosmological run.

Returns

True if comoving-to-proper conversion is active.

Return type

bool

toPhysicalUnits(a=None, h=None)

Convert comoving units to physical units.

Deprecated since version 3.0: Use toProperUnits for a more consistent array-based conversion.

Parameters
  • a (float, optional) – Scale factor.

  • h (float, optional) – Hubble parameter.

toProperUnits(a=None, h=None)

Convert main arrays from comoving to proper (physical) units.

This method applies the scale factor and Hubble parameter corrections to positions, velocities, masses, and other fluid quantities, then disables further automatic conversions to prevent double-counting.

Parameters
  • a (float, optional) – The scale factor to use. Defaults to self.atime.

  • h (float, optional) – The Hubble parameter to use. Defaults to self.hubbleparam.

class pNbody.extensions.gear.time._NbodyTimeMixin

Bases: object

Provide cosmological time and scale factor transformation tools.

This mixin facilitates conversions between cosmic time, scale factor (a), and redshift (z), supporting both comoving integration and static physical coordinate snapshots.

Redshift(age=None)

Return the redshift of the current snapshot or a given age.

Parameters

age (float, optional) – The cosmic time or scale factor to convert to redshift. Defaults to self.tstar if not provided.

Returns

The redshift $z$.

Return type

float

ScaleFactor(units=None, t=None, params=None, mode=None)

Return the scale-factor (a) for the current state or a given time.

Parameters
  • units (str, optional) – The time units used if t is provided (e.g., ‘Gyr’).

  • t (float or array_like, optional) – The cosmic time at which to compute the scale factor.

  • params (dict, optional) – Cosmological parameters (OmegaLambda, Omega0, HubbleParam).

  • mode (str, optional) – Unit conversion mode.

Returns

The scale factor $a = 1/(1+z)$.

Return type

float or ndarray

Examples

>>> params = {'OmegaLambda': 0.685, 'Omega0': 0.315, 'HubbleParam': 0.673}
>>> # For a given t in Gyr:
>>> nb.ScaleFactor(t=t, units="Gyr", params=params)
>>> # If t is taken from the object:
>>> nb.ScaleFactor(params=params)
Time(units=None, a=None, t=None, params=None)

Return the cosmic time in specified units.

By default, the value is taken from the variable self.time. If comoving integration is off, cosmological parameters must be supplied to convert from scale factor to time.

Parameters
  • units (str, optional) – The target time units (e.g., ‘Gyr’, ‘Myr’).

  • a (float or array_like, optional) – Force the calculation for a specific scale factor.

  • t (float or array_like, optional) – Use as the unit time if comoving integration is off.

  • params (dict, optional) – Cosmological parameters dictionary.

Returns

The cosmic time in specified units (or code units if None).

Return type

float or ndarray

Examples

>>> nb.Time()                           # in code unit, using self.atime
>>> nb.Time(a=0.5)                      # in code unit, forcing self.atime=a
>>> nb.Time(units="Gyr")                # in Gyr
>>> nb.Time(units="Gyr", a=0.5)         # in Gyr, forcing self.atime=a
>>> nb.Time(units="Gyr", a=[0.1, 1])    # in Gyr, forcing self.atime=a
>>> # Using t as unit time (when ComovingIntegrationOff is True):
>>> nb.Time(units="Gyr", t=[1000])
>>> nb.Time(units="Gyr", t=[1000, 2000])
>>> # If integration is off and 'a' is provided, params are required:
>>> params = {'OmegaLambda': 0.685, 'Omega0': 0.315, 'HubbleParam': 0.673}
>>> nb.Time(a=0.5, params=params)
class pNbody.extensions.gear.info._NbodyInfoMixin

Bases: object

spec_info()

Compile a detailed summary of the simulation’s metadata and array states.

This method gathers cosmological parameters (redshift, omega, Hubble), simulation flags (SFR, cooling, feedback), and basic statistics (length, first and last elements) for internal arrays like energy, density, and particle IDs.

Returns

A list of formatted strings containing the simulation specifications.

Return type

list of str

class pNbody.extensions.gear.misc._NbodyMiscMixin

Bases: object

Mixin providing auxiliary utility methods for N-body snapshot management.

FevsLuminosityEvolution(tend=None, units=None)

Compute the evolution of total luminosity and metallicity over time.

This method bins particles by age and calculates the integrated luminosity and the mean/mode of the Iron abundance ([Fe/H]) for each time step up to tend.

Parameters
  • tend (float, optional) – The final scale factor/time to consider for the evolution.

  • units (str or pNbody.units.Unit, optional) – Units for the age calculation.

Returns

  • Ages (ndarray) – The time points (bins) at which evolution was calculated.

  • Lvs (ndarray) – Total luminosity at each time step.

  • FeHs (ndarray) – The mode of the metallicity distribution at each time step.

  • FeHms (ndarray) – The mean metallicity at each time step.

StarFormationvsTime(tmin=0, tmax=14, nt=500, unitsTime='Gyr', unitsMass='Msol')

Calculate the star formation rate (SFR) as a function of cosmic time.

Parameters
  • tmin (float, optional) – Start time for the history. Default is 0.

  • tmax (float, optional) – End time for the history. Default is 14.

  • nt (int, optional) – Number of time bins. Default is 500.

  • unitsTime (str, optional) – Units for the time axis. Default is ‘Gyr’.

  • unitsMass (str, optional) – Units for the mass. Default is ‘Msol’.

Returns

  • x (ndarray) – Time bins.

  • y (ndarray) – Star formation rate (dM/dt) in units of Mass/yr.

StellarMassvsTime(tmin=0, tmax=14, nt=500, unitsTime='Gyr', unitsMass='Msol')

Calculate the cumulative stellar mass as a function of cosmic time.

Parameters
  • tmin (float, optional) – Start time for the history. Default is 0.

  • tmax (float, optional) – End time for the history. Default is 14.

  • nt (int, optional) – Number of time bins. Default is 500.

  • unitsTime (str, optional) – Units for the time axis. Default is ‘Gyr’.

  • unitsMass (str, optional) – Units for the mass. Default is ‘Msol’.

Returns

  • x (ndarray) – Time bins in the requested units.

  • y (ndarray) – Cumulative stellar mass over time.

TJeans(a=None, h=None, units=None, Hsml=None, Softening=None, SofteningMaxPhys=None)

Calculate the Jeans temperature corresponding to the pressure floor.

The Jeans temperature ($T_J$) is the temperature required to support a region of a given density against gravitational collapse at the current resolution limit (defined by Hsml or Softening).

Parameters
  • a (float, optional) – Cosmological parameters for density and length scaling.

  • h (float, optional) – Cosmological parameters for density and length scaling.

  • units (str, optional) – Units for the density calculation.

  • Hsml (ndarray, optional) – Smoothing lengths. If None, uses self.SphRadius().

  • Softening (float, optional) – Gravity softening parameters used if Hsml is not provided.

  • SofteningMaxPhys (float, optional) – Gravity softening parameters used if Hsml is not provided.

Returns

The Jeans temperature in Kelvin.

Return type

ndarray

Tff(units=None)

Calculate the free-fall time ($t_{ff}$) of the gas.

The free-fall time represents the characteristic timescale for gravitational collapse in the absence of pressure support: $t_{ff} = sqrt{frac{3pi}{32Grho}}$.

Parameters

units (str or pNbody.units.Unit, optional) – Target time units (e.g., ‘Myr’).

Returns

Free-fall time per particle.

Return type

ndarray (float32)

TimeStepLevel()

Calculate the current timestep level in log2 representation.

This typically represents the refinement level or power-of-two sub-stepping used in the simulation integrator.

Returns

The timestep level (base-2 logarithm of the step size factor).

Return type

int or ndarray

dLdt()

Calculate the cooling rate ($dL/dt$) per particle.

Computes the energy loss rate by calling the cooling functions with the current density, internal energy, and Iron abundance ([Fe/H]).

Returns

Cooling rate in code units.

Return type

ndarray (float32)