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:
SuccessFlag.check_error()- Convert UCLCHEM error codes to messagescshock_dissipation_time()- Calculate C-shock dissipation timescale
- 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:
uclchem.model- Model classes that use these utilities
Module Contents#
Classes#
Collapse mode. |
|
SuccessFlag indicates whether the model failed or ran successfully,. |
|
Interpolation scheme for |
Functions#
|
Return the radial velocity (cm/s) for a parcel of a Collapse model. |
|
Configure the |
|
Calculate the dissipation time of a C-type shock. |
Determine the number of consecutive digits in a string, starting. |
|
|
Get the CollapseMode instance. |
|
Convert a dtype shorthand string or numpy dtype to a numpy dtype. |
|
Return the effective temperature [K] for a protostellar object. |
|
Obtain the right model index for protostellar core models in 1D mode based on the. |
|
Load the reaction table from the UCLCHEM network into a pandas dataframe. |
|
Load the list of species present in the UCLCHEM network. |
|
Load the list of species in the UCLCHEM network into a pandas dataframe. |
Attributes#
Float to indicate a missing value |
|
Integer to indicate a missing value |
|
Integer to indicate that there is no reactant or product. |
|
UCLCHEM root directory |
- class uclchem.utils.CollapseMode[source]#
Bases:
enum.IntEnumCollapse mode.
Initialize self. See help(type(self)) for accurate signature.
- class uclchem.utils.SuccessFlag[source]#
Bases:
enum.IntEnumSuccessFlag 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:
- Returns:
Error message, or
Noneif the model ran successfully.- Return type:
str | None
- Raises:
RuntimeError – If raise_on_error is True.
- class uclchem.utils.TempMode(*args, **kwds)[source]#
Bases:
enum.EnumInterpolation scheme for
get_protostellar_Teff().
- 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:
- Returns:
Radial velocity in cm s⁻¹, indexed by time in years. Negative values indicate infall.
- Return type:
pd.Series
- Raises:
- uclchem.utils.configure_logging(level: str = 'WARNING', stream: None | str | Any = None) None[source]#
Configure the
uclchemlogger.- Parameters:
level (str) – Logging level name (e.g.
"DEBUG","WARNING"). Default"WARNING".stream (None | str | Any) – Where to send log output.
Nonesuppresses all output (no handlers, propagation disabled). A string is treated as a file path and aFileHandleris added. Any other value (e.g.sys.stdout) is wrapped in aStreamHandler. Defaults toNone.
- 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.
- 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:
- Returns:
num_digits – the number of consecutive digits in the string starting from “start”.
- Return type:
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:
- Raises:
TypeError – If
modeis not a string, integer orCollapseMode.ValueError – If
modeis 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
dtypeis 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:
TempMode.SMOOTH(default) — global power-law fit to all seven bins, valid 1 – 1e6 L_sun.TempMode.BINS— discrete stepwise lookup, valid 1 – 1e6 L_sun.TempMode.SMOOTH_LOW— power-law fit to bins 1–3, valid 1 – 1e4 L_sun.TempMode.SMOOTH_HIGH— power-law fit to bins 4–7, valid 1e3 – 1e6 L_sun.
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 toNone.custom_alpha (float | None) – Power-law exponent alpha in T = T0 * L^alpha, used only when mode is
TempMode.SMOOTH_CUSTOM. Defaults toNone.L_star_unit (str) – Unit of
L_star. Either'L_sun'or'W'. Defaults to'L_sun'.
- Returns:
Effective temperature in Kelvin.
- Return type:
- Raises:
TypeError – If
L_staris not a real number.ValueError – If
L_staris outside the valid range for the chosen mode, or if custom fit parameters are provided but mode is notTempMode.SMOOTH_CUSTOM.RuntimeError – If no bin matches
L_starinTempMode.BINSmode (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:
- 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.
- 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.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