uclchem.utils#

Helper functions and utilities for UCLCHEM operations.

This module provides utility functions for: - Error handling and reporting - Physics calculations (shock dissipation times) - Parameter validation - File path management

Key Functions:

Example Usage:
>>> import uclchem
>>>
>>> model = uclchem.model.Cloud({})
>>> success_flag = model.success_flag
>>>
>>> # Check error from model run
>>> success_flag.check_error()
Model ran successfully
>>>
>>> # Only print if an error occurred
>>> success_flag.check_error(only_error=True)
>>> # Calculate shock timescale
>>> t_diss = uclchem.utils.cshock_dissipation_time(
...     shock_vel=50.0,  # km/s
...     initial_dens=1e4,  # cm^-3
... )
>>> print(f"Dissipation time: {t_diss:.1e} years")
Dissipation time: ... years

Error Codes:

UCLCHEM model functions return SuccessFlag instances:

  • -1: Parameter read failed (misspelled parameter)

  • -2: Physics initialization failed (invalid parameters)

  • -3: Chemistry initialization failed

  • -4: Integrator error (DVODE failed)

and more…

Use SuccessFlag.check_error() to get human-readable error messages.

See Also:

Module Contents#

Classes#

CollapseMode

Collapse mode.

SuccessFlag

SuccessFlag indicates whether the model failed or ran successfully,.

TempMode

Interpolation scheme for get_protostellar_Teff().

Functions#

collapse_radial_velocity(→ pandas.Series)

Return the radial velocity (cm/s) for a parcel of a Collapse model.

configure_logging(→ None)

Configure the uclchem logger.

cshock_dissipation_time(→ float)

Calculate the dissipation time of a C-type shock.

find_number_of_consecutive_digits(→ int)

Determine the number of consecutive digits in a string, starting.

get_collapse_mode(→ CollapseMode)

Get the CollapseMode instance.

get_dtype(→ type | numpy.dtype)

Convert a dtype shorthand string or numpy dtype to a numpy dtype.

get_protostellar_Teff(→ float)

Return the effective temperature [K] for a protostellar object.

get_protostellar_model_index(→ int)

Obtain the right model index for protostellar core models in 1D mode based on the.

get_reaction_table(→ pandas.DataFrame)

Load the reaction table from the UCLCHEM network into a pandas dataframe.

get_species(→ list[str])

Load the list of species present in the UCLCHEM network.

get_species_table(→ pandas.DataFrame)

Load the list of species in the UCLCHEM network into a pandas dataframe.

Attributes#

L_SUN

MISSING_VALUE_FLOAT

Float to indicate a missing value

MISSING_VALUE_INTEGER

Integer to indicate a missing value

NO_REACTANT_OR_PRODUCT

Integer to indicate that there is no reactant or product.

UCLCHEM_ROOT_DIR

UCLCHEM root directory

class uclchem.utils.CollapseMode[source]#

Bases: enum.IntEnum

Collapse mode.

Initialize self. See help(type(self)) for accurate signature.

AMBIPOLAR = 4[source]#
BE1_1 = 1[source]#
BE4 = 2[source]#
FILAMENT = 3[source]#
class uclchem.utils.SuccessFlag[source]#

Bases: enum.IntEnum

SuccessFlag indicates whether the model failed or ran successfully,.

and if it failed how.

Initialize self. See help(type(self)) for accurate signature.

check_error(only_error: bool = False, raise_on_error: bool = True) str | None[source]#

Convert the UCLCHEM integer result flag to a message explaining what went wrong.

Parameters:
  • only_error (bool) – If True, skip printing if the model ran successfully, and only error out if it did not. Default = False.

  • raise_on_error (bool) – If True, raises RuntimeError if the self is not SuccessFlag.SUCCESS. If False, returns the message string. Default = True.

Returns:

Error message, or None if the model ran successfully.

Return type:

str | None

Raises:

RuntimeError – If raise_on_error is True.

CHEM_INIT_ERROR[source]#
CONSERVATION_ERROR[source]#
COOLANT_CONFIG_ERROR[source]#
COOLANT_DATA_ERROR[source]#
COOLANT_FILE_ERROR[source]#
COOLANT_FREQ_TOL_ERROR[source]#
COOLANT_POP_TOL_ERROR[source]#
COOLANT_SOLVER_ERROR[source]#
INT_TOO_MANY_FAILS_ERROR[source]#
INT_UNRECOVERABLE_ERROR[source]#
NEGATIVE_ABUNDANCE_ERROR[source]#
NOT_ENOUGH_TIMEPOINTS_ERROR[source]#
PARAMETER_READ_ERROR[source]#
PHYSICS_INIT_ERROR[source]#
PHYSICS_UPDATE_ERROR[source]#
SOLVER_STATS_OVERFLOW_ERROR[source]#
SUCCESS = (0, 'Model ran successfully')[source]#
ZERO_INNER_RADIUS_ERROR[source]#
class uclchem.utils.TempMode(*args, **kwds)[source]#

Bases: enum.Enum

Interpolation scheme for get_protostellar_Teff().

BINS = 'bins'[source]#
SMOOTH = 'smooth'[source]#
SMOOTH_CUSTOM = 'smooth_custom'[source]#
SMOOTH_HIGH = 'smooth_high'[source]#
SMOOTH_LOW = 'smooth_low'[source]#
uclchem.utils.collapse_radial_velocity(model: uclchem.model.Collapse, point: int = 0) pandas.Series[source]#

Return the radial velocity (cm/s) for a parcel of a Collapse model.

For filament (mode 3) and ambipolar (mode 4) collapse modes, uses the analytical radial-velocity fit functions from Priestley et al. (2018).

For BE1.1 and BE4 modes (1 & 2), the radius is tracked via mass-conservation integration in Fortran, not a velocity fit. The radial velocity is therefore a finite-difference approximation of parcel_radius — it is NOT the relationship used to generate the model and should be treated as an estimate only.

Parameters:
  • model (Collapse) – A successfully run Collapse instance.

  • point (int) – Parcel index (0-based). Defaults to 0.

Returns:

Radial velocity in cm s⁻¹, indexed by time in years. Negative values indicate infall.

Return type:

pd.Series

Raises:
  • TypeError – If model is not a Collapse model instance.

  • TypeError – If model.collapse is not an instance of class:CollapseMode.

uclchem.utils.configure_logging(level: str = 'WARNING', stream: None | str | Any = None) None[source]#

Configure the uclchem logger.

Parameters:
  • level (str) – Logging level name (e.g. "DEBUG", "WARNING"). Default "WARNING".

  • stream (None | str | Any) – Where to send log output. None suppresses all output (no handlers, propagation disabled). A string is treated as a file path and a FileHandler is added. Any other value (e.g. sys.stdout) is wrapped in a StreamHandler. Defaults to None.

uclchem.utils.cshock_dissipation_time(shock_vel: float, initial_dens: float) float[source]#

Calculate the dissipation time of a C-type shock.

Use to obtain a useful timescale for your C-shock model runs. Velocity of ions and neutrals equalizes at dissipation time and full cooling takes a few dissipation times.

Parameters:
  • shock_vel (float) – Velocity of the shock in km/s

  • initial_dens (float) – Preshock density of the gas in cm$^{-3}$

Returns:

The dissipation time of the shock in years

Return type:

float

uclchem.utils.find_number_of_consecutive_digits(string: str, start: int) int[source]#

Determine the number of consecutive digits in a string, starting.

from some index start.

Parameters:
  • string (str) – the string

  • start (int) – the starting index

Returns:

num_digits – the number of consecutive digits in the string starting from “start”.

Return type:

int

Examples

>>> find_number_of_consecutive_digits("Hello123", 0)
0
>>> find_number_of_consecutive_digits("Hello123", 5)
3
>>> find_number_of_consecutive_digits("Hello123", 6)
2
>>> find_number_of_consecutive_digits("He1llo23", 2)
1
uclchem.utils.get_collapse_mode(mode: str | int | CollapseMode) CollapseMode[source]#

Get the CollapseMode instance.

Integers are converted to the CollapseMode, CollapseMode instances are returned unchanged, and strings are converted according to the names of the different modes.

Parameters:

mode (str | int | CollapseMode) – Collapse mode.

Returns:

collapse mode Enum

Return type:

CollapseMode

Raises:
  • TypeError – If mode is not a string, integer or CollapseMode.

  • ValueError – If mode is a string, but not one of ["BE1.1", "BE4", "filament", "ambipolar"] (case insensitive).

uclchem.utils.get_dtype(dtype: str | type | numpy.dtype) type | numpy.dtype[source]#

Convert a dtype shorthand string or numpy dtype to a numpy dtype.

Parameters:

dtype (str | type | np.dtype) – Either a shorthand string (“fp64”, “fp32”, “fp16”) or a numpy dtype/type.

Returns:

The corresponding numpy dtype or type.

Return type:

type | np.dtype

Raises:

ValueError – If dtype is a string not in {"fp64", "fp32", "fp16"}.

uclchem.utils.get_protostellar_Teff(L_star: float, *, mode: TempMode = TempMode.BINS, custom_T0: float | None = None, custom_alpha: float | None = None, L_star_unit: str = 'L_sun') float[source]#

Return the effective temperature [K] for a protostellar object.

Parameters:
  • L_star (float) – Stellar luminosity. Valid range depends on mode; see _RANGES.

  • mode (TempMode) –

    Interpolation scheme:

    Defaults to TempMode.BINS.

  • custom_T0 (float | None) – Temperature constant T0 in the power-law fit T = T0 * L^alpha, used only when mode is TempMode.SMOOTH_CUSTOM. Defaults to None.

  • custom_alpha (float | None) – Power-law exponent alpha in T = T0 * L^alpha, used only when mode is TempMode.SMOOTH_CUSTOM. Defaults to None.

  • L_star_unit (str) – Unit of L_star. Either 'L_sun' or 'W'. Defaults to 'L_sun'.

Returns:

Effective temperature in Kelvin.

Return type:

float

Raises:
  • TypeError – If L_star is not a real number.

  • ValueError – If L_star is outside the valid range for the chosen mode, or if custom fit parameters are provided but mode is not TempMode.SMOOTH_CUSTOM.

  • RuntimeError – If no bin matches L_star in TempMode.BINS mode (indicates a bug).

Examples

>>> get_protostellar_Teff(1.0, mode=TempMode.SMOOTH)    # 1 L_sun, smooth
4788.72
>>> get_protostellar_Teff(1000.0, mode=TempMode.BINS)   # 1000 L_sun, bins
20000.0
uclchem.utils.get_protostellar_model_index(L_star: float) int[source]#

Obtain the right model index for protostellar core models in 1D mode based on the.

stellar luminosity

Parameters:

L_star (float) – Stellar luminosity in units of solar luminosity (L_sun)

Returns:

The model index for the protostellar core model.

Return type:

int

Raises:

ValueError – If the stellar luminosity is below the minimum valid value.

uclchem.utils.get_reaction_table(file: str | pathlib.Path | None = None) pandas.DataFrame[source]#

Load the reaction table from the UCLCHEM network into a pandas dataframe.

Parameters:

file (str | Path | None) – Path to the reactions CSV file. If None, uses UCLCHEM_ROOT_DIR / "reactions.csv". Default = None.

Returns:

reactions – A dataframe containing the reactions and their rates

Return type:

pd.DataFrame

uclchem.utils.get_species(file: str | pathlib.Path | None = None) list[str][source]#

Load the list of species present in the UCLCHEM network.

Parameters:

file (str | Path | None) – Path to the species CSV file. If None, uses UCLCHEM_ROOT_DIR / "species.csv". Default = None.

Returns:

species_list – A list of species names

Return type:

list[str]

uclchem.utils.get_species_table(file: str | pathlib.Path | None = None) pandas.DataFrame[source]#

Load the list of species in the UCLCHEM network into a pandas dataframe.

Parameters:

file (str | Path | None) – Path to the species CSV file. If None, uses UCLCHEM_ROOT_DIR / "species.csv". Default = None.

Returns:

species – A dataframe containing the species names and their details

Return type:

pd.DataFrame

uclchem.utils.L_SUN: float = 3.828e+26[source]#
uclchem.utils.MISSING_VALUE_FLOAT: float = -1.0[source]#

Float to indicate a missing value

uclchem.utils.MISSING_VALUE_INTEGER: int = -1[source]#

Integer to indicate a missing value

uclchem.utils.NO_REACTANT_OR_PRODUCT: int = 9999[source]#

Integer to indicate that there is no reactant or product.

uclchem.utils.UCLCHEM_ROOT_DIR: pathlib.Path[source]#

UCLCHEM root directory