uclchem.model ============= .. py:module:: uclchem.model .. autoapi-nested-parse:: UCLCHEM Model Module. Core module for running gas-grain chemical models under different physical conditions. This module provides both object-oriented and functional interfaces for running UCLCHEM chemical models. The object-oriented API (model classes) is recommended for most use cases as it provides better state management and built-in analysis tools. **Model Classes (Object-Oriented API - Recommended):** - :class:`Cloud` - Static or freefall collapsing cloud - :class:`Collapse` - Collapsing cloud with various prescriptions (BE, filament, ambipolar) - :class:`PrestellarCore` - Prestellar core with heating and chemistry - :class:`CShock` - C-type shock model - :class:`JShock` - J-type shock model - :class:`Postprocess` - Custom physics from user-provided arrays - :class:`SequentialRunner` - Chain multiple physical stages - :class:`GridRunner` - Run parameter grids in parallel **Legacy Functions (Functional API):** Available in :mod:`uclchem.functional` for backward compatibility. Returns arrays/DataFrames instead of model objects. **Quick Example:** >>> import uclchem >>> >>> # Create a collapsing cloud model >>> cloud = uclchem.model.Cloud( ... param_dict={ ... "initialDens": 1e2, ... "initialTemp": 10.0, ... "finalTime": 1e6, ... "freefall": True ... } ... ) >>> >>> # Check for errors and plot >>> cloud.check_error() Model ran successfully >>> cloud.create_abundance_plot(["CO", "$CO"]) #doctest: +SKIP **Model Workflow:** 1. **Initialize**: Create model object with parameters 2. **Run**: Model runs automatically on initialization (or use `read_file` to load) 3. **Analyze**: Access results via attributes (`.final_abundances`, `.chemistry_dataframe`) 4. **Plot**: Use built-in plotting methods (`.create_abundance_plot()`) 5. **Chain**: Use as input to next stage (`.previous_model` parameter) **Common Parameters:** All models accept these key parameters in `param_dict`: - ``initialDens`` (float): Initial density [cm⁻³] - ``initialTemp`` (float): Initial temperature [K] - ``finalTime`` (float): Simulation end time [years] - ``freefall`` (bool): Enable freefall collapse (Cloud only) - ``outputFile`` (str): Output file path (optional with OO API) See the user guide for complete parameter list. **Species Naming:** - Gas phase: ``CO``, ``H2O``, ``CH3OH`` - Ice surface: ``$CO``, ``$H2O``, ``$CH3OH`` - Ice bulk: ``@CO``, ``@H2O``, ``@CH3OH`` **See Also:** - :mod:`uclchem.analysis` - Analyze model outputs and reaction pathways - :mod:`uclchem.advanced` - Advanced controls for heating and network state **Note on Thread Safety:** Model objects are **not thread-safe** when using advanced features that modify Fortran module state. Use multiprocessing (not threading) for parallel runs. Module Contents --------------- Classes ~~~~~~~ .. autoapisummary:: uclchem.model.AbstractModel uclchem.model.CShock uclchem.model.Cloud uclchem.model.Collapse uclchem.model.GridRunner uclchem.model.JShock uclchem.model.Model uclchem.model.NoDaemonPool uclchem.model.Postprocess uclchem.model.PrestellarCore uclchem.model.ReactionNamesStore uclchem.model.SequentialRunner uclchem.model.SpeciesNameStore Functions ~~~~~~~~~ .. autoapisummary:: uclchem.model.get_number_of_grid_workers uclchem.model.load_model uclchem.model.reaction_line_formatter uclchem.model.register_model Attributes ~~~~~~~~~~ .. autoapisummary:: uclchem.model.NoGridParameters uclchem.model.PHYSICAL_PARAMETERS_HEADER_FORMAT uclchem.model.PHYSICAL_PARAMETERS_VALUE_FORMAT uclchem.model.REGISTRY uclchem.model.SPECNAME_HEADER_FORMAT uclchem.model.SPECNAME_VALUE_FORMAT uclchem.model.get_reaction_names uclchem.model.get_species_names .. py:class:: AbstractModel(param_dict: dict | None = None, starting_chemistry: numpy.ndarray | None = None, previous_model: AbstractModel | None = None, timepoints: int = TIMEPOINTS, debug: bool = False, read_file: str | None = None, run_type: Literal['managed', 'external'] = 'managed', on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] = 'warning', on_error: Literal['raise', 'warn', 'ignore'] = 'raise') Bases: :py:obj:`abc.ABC` Base model class used for inheritance only. The AbstractModel class serves as an abstract class from which other model classes can be built. It is not intended to be used as a standalone class for running UCLCHEM. :param param_dict: Dictionary containing the parameters to use for the UCLCHEM model. Uses UCLCHEM default values if not provided. :type param_dict: dict | None :param starting_chemistry: Array containing the starting abundances to use for the UCLCHEM model. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: Model object, a class that inherited from AbstractModel, to use for the starting abundances of the new UCLCHEM model that will be run. Defaults to None. :type previous_model: AbstractModel | None :param timepoints: Integer value of how many timesteps should be calculated before aborting the UCLCHEM model. Defaults to `uclchem.constants.TIMEPOINTS`. :type timepoints: int :param debug: Flag if extra debug information should be printed to the terminal. Defaults to False. #TODO Add debug features :type debug: bool :param read_file: Path to the file to be read. Reading a file to a model object, prevents it from being run. Defaults to None. :type read_file: str | None :param run_type: Run type. "external" means that the model is not run directly after instantiation, but can instead be run as `model.run()`. :type run_type: Literal["managed", "external"] .. py:method:: check_conservation(element_list: list[str] | None = None, percent: bool = True) -> None Check conservation of the chemical abundances. :param element_list: List of elements to check conservation for. (Default value = None) :type element_list: list[str] | None :param percent: Flag on if percentage values should be used. Defaults to True. :type percent: bool .. py:method:: check_error(only_error: bool = False, raise_on_error: bool = True) -> None Check the model error status and raise RuntimeError on failure. :param only_error: If True, only act when there was an error (skip success message). Defaults to False. :type only_error: bool :param raise_on_error: If True (default), raises RuntimeError on failure. If False, prints. :type raise_on_error: bool .. py:method:: create_abundance_plot(species: list[str], figsize: tuple[int, int] = (16, 9), point: int = 0, plot_file: str | pathlib.Path | None = None) -> tuple[matplotlib.pyplot.Figure, matplotlib.pyplot.Axes] `uclchem.plot.create_abundance_plot` wrapper method. :param species: List of species to plot. :type species: list[str] :param figsize: The figure size to use for matplotlib Defaults to (16, 9). :type figsize: tuple[int, int] :param point: Integer referring to which point of the UCLCHEM model to use. Defaults to 0. :type point: int :param plot_file: if not None, save to a path. Default = None. :type plot_file: str | Path | None :returns: matplotlib figure and axis objects :rtype: tuple[plt.Figure, plt.Axes] :raises ValueError: If `point` is larger than the number of points in the model run. .. py:method:: from_file(file: str, name: str = 'default', debug: bool = False) :classmethod: Load a model from a file. This is a convenience class method that wraps the module-level load_model function. :param file: Path to a file that contains previously run and stored models. :type file: str :param name: Name of the stored object. Defaults to 'default'. :type name: str :param debug: Flag if extra debug information should be printed to the terminal. Defaults to False. #TODO Add debug features :type debug: bool :returns: Model object loaded from the file. :rtype: AbstractModel .. py:method:: get_dataframes(point: int | None = None, joined: bool = True, with_rate_constants: bool = False, with_heating: bool = False, with_stats: bool = False, with_level_populations: bool = False, with_se_stats: bool = False) -> pandas.DataFrame | tuple[pandas.DataFrame, Ellipsis] Convert the model physics and chemical_abun arrays from numpy to pandas arrays. :param point: Integer referring to which point of the UCLCHEM model to return. If None, returns data for all points with a 'Point' column. Defaults to None. :type point: int | None :param joined: Flag on whether the returned pandas dataframe should be one, or if two dataframes should be returned. One physical, one chemical_abun dataframe. Defaults to True. :type joined: bool :param with_rate_constants: Flag on whether to include reaction rate constants in the dataframe, and/or as a separate dataframe depending on the value of `joined`. Defaults to False. :type with_rate_constants: bool :param with_heating: Flag on whether to include heating/cooling rates in the dataframe, and/or as a separate dataframe depending on the value of `joined`. Defaults to False. :type with_heating: bool :param with_stats: Flag on whether to include DVODE solver statistics in the dataframe, and/or as a separate dataframe depending on the value of `joined`. Defaults to False. :type with_stats: bool :param with_level_populations: Flag on whether to include coolant level populations in the output. Defaults to False. :type with_level_populations: bool :param with_se_stats: Flag on whether to include SE solver statistics in the output. Defaults to False. :type with_se_stats: bool :returns: If ``joined=True``: a single ``pd.DataFrame`` with all requested columns joined horizontally. If ``joined=False``: a tuple of ``pd.DataFrame`` objects in the order ``(physics_df, chemistry_df[, rate_constants_df] [, heating_df][, stats_df][, level_populations_df] [, se_stats_df])``, where optional frames are included only when their corresponding flag is ``True``. :rtype: pd.DataFrame | tuple[pd.DataFrame, ...] .. py:method:: get_failed_solver_attempts(point: int | None = None) -> pandas.DataFrame | None Get only the failed solver attempts (ISTATE < 0). Returns a DataFrame containing only solver attempts that failed and required retry (ISTATE = -1, -2, -4, -5, etc.). :param point: Spatial point index (for multi-point models). If None, uses point 0. Defaults to None. :type point: int | None :returns: DataFrame of failed attempts, or None if no failures or stats unavailable. :rtype: pd.DataFrame | None .. rubric:: Examples >>> import uclchem >>> param_dict = {} >>> model = uclchem.model.Cloud(param_dict) >>> failures = model.get_failed_solver_attempts() >>> if failures is not None: ... print(f"Total retries needed: {len(failures)}") ... print(failures.groupby('ISTATE').size()) ... else: ... print("No failures occurred.") ... No failures occurred. .. py:method:: get_final_abundances_of_species(species: list[str]) -> numpy.ndarray Get the final abundances of a list of species. :param species: list of species names. :type species: list[str] :returns: **abundances** -- array of final abundances of ``species``. :rtype: np.ndarray .. py:method:: get_joined_dataframes(point: int | None = None, with_rate_constants: bool = False, with_heating: bool = False, with_stats: bool = False, with_level_populations: bool = False, with_se_stats: bool = False) -> pandas.DataFrame Return all model data as a single horizontally-joined DataFrame. Convenience wrapper around :meth:`get_dataframes` with ``joined=True``. :param point: Integer referring to which point of the UCLCHEM model to return. If None, returns data for all points with a 'Point' column. Defaults to None. :type point: int | None :param with_rate_constants: Flag on whether to include reaction rate constants in the joined dataframe. Defaults to False. :type with_rate_constants: bool :param with_heating: Flag on whether to include heating/cooling rates in the joined dataframe. Defaults to False. :type with_heating: bool :param with_stats: Flag on whether to include DVODE solver statistics in the joined dataframe. Defaults to False. :type with_stats: bool :param with_level_populations: Flag on whether to include coolant level populations in the joined dataframe. Defaults to False. :type with_level_populations: bool :param with_se_stats: Flag on whether to include SE solver statistics in the joined dataframe. Defaults to False. :type with_se_stats: bool :returns: Single DataFrame with physics, abundances, and any optional columns joined horizontally. :rtype: pd.DataFrame .. py:method:: get_level_populations_dataframe(point: int = 0) -> pandas.DataFrame | None Get level populations as a DataFrame for a specific grid point. :param point: Grid point index (default 0) :type point: int :returns: DataFrame with columns for each level with meaningful coolant/level names :rtype: pd.DataFrame | None .. py:method:: get_se_stats_dataframe(point: int = 0) -> pandas.DataFrame | None Get SE solver statistics as a DataFrame for a specific grid point. :param point: Grid point index. Default = 0. :type point: int :returns: DataFrame with per-coolant SE solver statistics using actual coolant names :rtype: pd.DataFrame | None .. py:method:: get_solver_efficiency_summary(point: int | None = None) -> dict[str, int | float] | None Calculate solver efficiency metrics. :param point: Spatial point index (for multi-point models). If None, uses point 0. Defaults to None. :type point: int | None :returns: dict with keys: - total_attempts: Total DVODE calls - successful_attempts: Calls that advanced the trajectory - failed_attempts: Calls that were retried - efficiency_ratio: successful / total (1.0 = no retries) - total_cpu_time: Sum of all CPU time - wasted_cpu_time: CPU time spent on failed attempts :rtype: dict[str, int | float] | None .. py:method:: get_solver_stats_dataframe(point: int | None = None) -> pandas.DataFrame | None Get all solver statistics including failed attempts. This method returns statistics for EVERY DVODE solver call, including failed attempts that were retried. This is different from the regular stats in get_dataframes() which only shows the final successful attempt per trajectory timestep. :param point: Spatial point index (for multi-point models). If None, uses point 0. Defaults to None. :type point: int | None :returns: DataFrame with columns from DVODE_STAT_NAMES, or None if stats not available. TRAJECTORY_INDEX column links solver attempts to trajectory timesteps. Rows where TRAJECTORY_INDEX=0 are filtered out (unused preallocated space). :rtype: pd.DataFrame | None .. rubric:: Examples >>> import uclchem >>> param_dict = {} >>> model = uclchem.model.Cloud(param_dict) >>> solver_stats = model.get_solver_stats_dataframe() >>> # Count failed attempts >>> failures = solver_stats[solver_stats['ISTATE'] < 0] >>> print(f"Failed attempts: {len(failures)}") # doctest: +ELLIPSIS Failed attempts: ... .. py:method:: has_attr(key: str) -> bool Check if the object has an attribute stored in ``self._meta`` or ``self._data``. :param key: name of attribute :type key: str :returns: whether the object has the attribute. :rtype: bool .. py:method:: legacy_read_output_file(read_file: str | pathlib.Path, rate_constants_load_file: str | pathlib.Path | None = None) -> None Perform classic output file reading. This reader constructs the internal :class:`xarray.Dataset` directly from the parsed header and data in the legacy ``.dat`` output format. The classic files place a `point` column between the physics and chemistry columns; we therefore use the location of `point` in the header to split the columns reliably and avoid using global constants as authoritative metadata. :param read_file: path to file :type read_file: str | Path :param rate_constants_load_file: Not used (Default value = None) :type rate_constants_load_file: str | Path | None :raises ValueError: If there is any incompatibility error. .. py:method:: legacy_read_starting_chemistry() -> None Read the starting chemistry from ``self.abundLoadFile`` in ``_param_dict``. :raises ValueError: If ``self.abundLoadFile`` is ``None``. .. py:method:: legacy_write_columnfile(column_file: str | pathlib.Path, species: list[str]) -> None Write a classic ``columnFile`` file, similar to full output but with a subset of species. Since ``out_species`` was removed from the object-oriented API, it has to be passed here. :param column_file: path to write to :type column_file: str | Path :param species: List of species names to write :type species: list[str] .. py:method:: legacy_write_full() -> None Perform classic output file writing to ``self.outputFile`` from ``_param_dict``. :raises ValueError: If ``self.outputFile`` is ``None``. .. py:method:: legacy_write_starting_chemistry() -> None Perform classic starting abundance file writing to the file `self.abundSaveFile`. provided in `_param_dict`. :raises ValueError: If ``self.abundSaveFile`` is ``None``. .. py:method:: load_from_dataset(model_ds: xarray.Dataset, debug: bool = False) -> AbstractModel :classmethod: Load an abstract model from an xr Dataset. :param model_ds: Dataset to load :type model_ds: xr.Dataset :param debug: Flag to set (Default value = False) :type debug: bool :returns: **obj** -- instantiated model :rtype: AbstractModel .. py:method:: on_interrupt(grid: bool = False, model_name: str | None = None) -> None Catch interruption. Save model to file. :param grid: whether the model was part of a grid (Default value = False) :type grid: bool :param model_name: the name of the model to save it under. If None, name is set to "interrupted". (Default value = None) :type model_name: str | None .. py:method:: pickle() -> AbstractModel Pickle the model. :returns: AbstractModel :rtype: AbstractModel .. py:method:: plot_species(ax: matplotlib.pyplot.Axes, species: list[str], point: int = 0, legend: bool = True, **plot_kwargs) -> matplotlib.pyplot.Axes `uclchem.plot.plot(species)` wrapper method. :param ax: An axis object to plot on :type ax: plt.Axes :param df: A dataframe created by `read_output_file` :type df: pd.DataFrame :param species: A list of species names to be plotted. If species name starts with "$" instead of "#" or "@", plots the sum of surface and bulk abundances. :type species: list[str] :param point: Grid point index. Default = 0. :type point: int :param legend: Whether to add a legend to the plot. Default = True. :type legend: bool :param \*\*plot_kwargs: Additional keyword arguments passed to ``ax.plot``. :type \*\*plot_kwargs: dict[str, Any] :returns: Modified input axis is returned :rtype: plt.Axes .. py:method:: run() -> None Run the model, resetting the Fortran arrays so they can be reused for new runs. :raises RuntimeError: If the model was read. :raises TypeError: If the success_flag returned from the model is not an integer. :raises ValueError: If the model's run_type is invalid. :raises KeyboardInterrupt: If the run is interrupted via ``SIGINT`` while in progress. .. py:method:: run_fortran() -> dict[str, int | list] :abstractmethod: .. py:method:: save_model(*, file_obj: h5py.File | None = None, file: str | None = None, name: str = 'default', overwrite: bool = False) -> None Save a model to file on disk. Multiple models can be saved into the same file. if different names are used to store them. :param file_obj: open file object (Default value = None) :type file_obj: h5py.File | None :param file: Path to a file to store models. (Default value = None) :type file: str | None :param name: Name to use for the group of the object. Defaults to 'default' :type name: str :param overwrite: Boolean on whether to overwrite pre-existing models, or error out. Defaults to False :type overwrite: bool :raises ValueError: If file_obj and file are both passed, or neither are passed. .. py:method:: un_pickle() -> AbstractModel Un-pickle the model. :returns: AbstractModel :rtype: AbstractModel .. py:method:: worker_build(init_kwargs, shm_desc) :classmethod: .. py:attribute:: abundLoadFile .. py:attribute:: abundSaveFile .. py:attribute:: full_array :type: Any :value: None .. py:attribute:: give_start_abund .. py:attribute:: model_type :value: '' .. py:attribute:: n_out :value: 0 .. py:attribute:: outputFile .. py:attribute:: run_type :value: 'managed' .. py:attribute:: separate_worker_types :value: ['managed'] .. py:attribute:: starting_chemistry_array :type: Any :value: None .. py:attribute:: success_flag :type: None | uclchem.utils.SuccessFlag :value: None .. py:attribute:: timepoints :value: 2000 .. py:attribute:: was_read .. py:class:: CShock(shock_vel: float = 10.0, timestep_factor: float = 0.01, minimum_temperature: float = 0.0, param_dict: dict | None = None, out_species: list[str] | None = None, starting_chemistry: numpy.ndarray | None = None, previous_model: AbstractModel | None = None, timepoints: int = TIMEPOINTS, debug: bool = False, read_file: str | None = None, run_type: Literal['managed', 'external'] = 'managed', on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] = 'warning', on_error: Literal['raise', 'warn', 'ignore'] = 'raise') Bases: :py:obj:`AbstractModel` C-Shock model class inheriting from AbstractModel. :param shock_vel: Velocity of the shock in km/s. Defaults to 10.0. :type shock_vel: float :param timestep_factor: Whilst the time is less than 2 times the dissipation time of shock, timestep is timestep_factor*dissipation time. Essentially controls how well resolved the shock is in your model. Defaults to 0.01. :type timestep_factor: float :param minimum_temperature: Minimum post-shock temperature. Defaults to 0.0 (no minimum). The shocked gas typically cools to `initialTemp` if this is not set. :type minimum_temperature: float :param param_dict: Dictionary containing the parameters to use for the UCLCHEM model. Uses UCLCHEM default values found in `defaultparameters.f90`. :type param_dict: dict :param starting_chemistry: Array containing the starting abundances to use for the UCLCHEM model. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: Model object, a class that inherited from AbstractModel, to use for the starting abundances of the new UCLCHEM model that will be run. Defaults to None. :type previous_model: AbstractModel | None :param timepoints: Integer value of how many timesteps should be calculated before aborting the UCLCHEM model. Defaults to `uclchem.constants.TIMEPOINTS`. :type timepoints: int :param debug: Flag if extra debug information should be printed to the terminal. Defaults to False. #TODO Add debug features :type debug: bool :param read_file: Path to the file to be read. Reading a file to a model object, prevents it from being run. Defaults to None. :type read_file: str | None Initialize the model with :meth:`AbstractModel.__init__`. Then run any additional commands needed for the model. :param shock_vel: Shock velocity in km/s. Defaults to 10.0. :type shock_vel: float :param timestep_factor: Factor controlling the size of individual timesteps relative to the shock dissipation time. Defaults to 0.01. :type timestep_factor: float :param minimum_temperature: Minimum post-shock temperature (K) allowed during cooling. Defaults to 0.0. :type minimum_temperature: float :param param_dict: Dictionary of UCLCHEM parameters. Uses defaults from ``defaultparameters.f90`` for any key not provided. Defaults to None. :type param_dict: dict | None :param out_species: Not supported on OO model classes; passing any value raises ``TypeError``. Use the functional interface to filter output species. Defaults to None. :type out_species: list[str] | None :param starting_chemistry: Array of starting abundances for each species. If None, uses network defaults. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: A completed model whose final abundances are used as the starting chemistry for this model. Defaults to None. :type previous_model: AbstractModel | None :param timepoints: Number of output timesteps to store. Defaults to TIMEPOINTS. :type timepoints: int :param debug: If True, print extra debug information. Defaults to False. :type debug: bool :param read_file: Path to a previously saved model file to load instead of running. Defaults to None. :type read_file: str | None :param run_type: How the Fortran model is executed. ``'managed'`` runs automatically on init; ``'external'`` defers running to the caller. Defaults to 'managed'. :type run_type: Literal['managed', 'external'] :param on_negative_abundances: Action when negative abundances are detected after a run. Defaults to 'warning'. :type on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] :param on_error: Action when the Fortran solver returns an error flag. Defaults to 'raise'. :type on_error: Literal['raise', 'warn', 'ignore'] :raises ValueError: If `read_file` is None, but `shock_vel` is also not set. :raises TypeError: If ``out_species`` is passed (not supported on OO model classes). .. py:method:: run_fortran() -> dict[str, int | list] Run the UCLCHEM model, first resetting the numpy arrays. Resetting uses `AbstractModel.run()`, then running the model. `check_error` and `array_clean` are automatically called after the model run. :returns: Dictionary with two keys: "success_flag" with value the success flag :rtype: dict[str, int | list] .. py:class:: Cloud(param_dict: dict | None = None, out_species: list[str] | None = None, starting_chemistry: numpy.ndarray | None = None, previous_model: AbstractModel | None = None, timepoints: int = TIMEPOINTS, debug: bool = False, read_file: str | None = None, run_type: Literal['managed', 'external'] = 'managed', on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] = 'warning', on_error: Literal['raise', 'warn', 'ignore'] = 'raise') Bases: :py:obj:`AbstractModel` Cloud model class inheriting from AbstractModel. :param param_dict: Dictionary containing the parameters to use for the UCLCHEM model. Uses UCLCHEM default values found in `defaultparameters.f90`. :type param_dict: dict :param starting_chemistry: Array containing the starting abundances to use for the UCLCHEM model. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: Model object, a class that inherited from AbstractModel, to use for the starting abundances of the new UCLCHEM model that will be run. Defaults to None. :type previous_model: AbstractModel | None :param timepoints: Integer value of how many timesteps should be calculated before aborting the UCLCHEM model. Defaults to `uclchem.constants.TIMEPOINTS`. :type timepoints: int :param debug: Flag if extra debug information should be printed to the terminal. Defaults to False. #TODO Add debug features :type debug: bool :param read_file: Path to the file to be read. Reading a file to a model object, prevents it from being run. Defaults to None. :type read_file: str | None Initialize the model with :meth:`AbstractModel.__init__`. Then run any additional commands needed for the model. :param param_dict: Dictionary of UCLCHEM parameters. Uses defaults from ``defaultparameters.f90`` for any key not provided. Defaults to None. :type param_dict: dict | None :param out_species: Not supported on OO model classes; passing any value raises ``TypeError``. Use the functional interface to filter output species. Defaults to None. :type out_species: list[str] | None :param starting_chemistry: Array of starting abundances for each species. If None, uses network defaults. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: A completed model whose final abundances are used as the starting chemistry for this model. Defaults to None. :type previous_model: AbstractModel | None :param timepoints: Number of output timesteps to store. Defaults to TIMEPOINTS. :type timepoints: int :param debug: If True, print extra debug information. Defaults to False. :type debug: bool :param read_file: Path to a previously saved model file to load instead of running. Defaults to None. :type read_file: str | None :param run_type: How the Fortran model is executed. ``'managed'`` runs automatically on init; ``'external'`` defers running to the caller. Defaults to 'managed'. :type run_type: Literal['managed', 'external'] :param on_negative_abundances: Action when negative abundances are detected after a run. Defaults to 'warning'. :type on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] :param on_error: Action when the Fortran solver returns an error flag. Defaults to 'raise'. :type on_error: Literal['raise', 'warn', 'ignore'] :raises TypeError: If ``out_species`` is passed (not supported on OO model classes). .. py:method:: run_fortran() -> dict[str, int | list] Run the UCLCHEM model, first resetting the numpy arrays. Resetting uses `AbstractModel.run()`, then running the model. `check_error` and `array_clean` are automatically called after the model run. :returns: Dictionary with two keys: "success_flag" with value the success flag :rtype: dict[str, int | list] .. py:class:: Collapse(collapse: str | int | uclchem.utils.CollapseMode = CollapseMode.BE1_1, param_dict: dict | None = None, out_species: list[str] | None = None, starting_chemistry: numpy.ndarray | None = None, previous_model: AbstractModel | None = None, timepoints: int = TIMEPOINTS, debug: bool = False, read_file: str | None = None, run_type: Literal['managed', 'external'] = 'managed', on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] = 'warning', on_error: Literal['raise', 'warn', 'ignore'] = 'raise') Bases: :py:obj:`AbstractModel` Collapse model class inheriting from AbstractModel. :param collapse: Collapse type. Options are 'BE1.1', 'BE4', 'filament', or 'ambipolar'. Defaults to 'BE1.1'. :type collapse: str | int | CollapseMode :param param_dict: Dictionary containing the parameters to use for the UCLCHEM model. Uses UCLCHEM default values found in `defaultparameters.f90`. :type param_dict: dict :param starting_chemistry: Array containing the starting abundances to use for the UCLCHEM model. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: Model object, a class that inherited from AbstractModel, to use for the starting abundances of the new UCLCHEM model that will be run. Defaults to None. :type previous_model: AbstractModel | None :param timepoints: Integer value of how many timesteps should be calculated before aborting the UCLCHEM model. Defaults to `uclchem.constants.TIMEPOINTS`. :type timepoints: int :param debug: Flag if extra debug information should be printed to the terminal. Defaults to False. #TODO Add debug features :type debug: bool :param read_file: Path to the file to be read. Reading a file to a model object, prevents it from being run. Defaults to None. :type read_file: str | None Initialize the model with :meth:`AbstractModel.__init__`. Then run any additional commands needed for the model. :param collapse: Collapse mode to use (e.g. ``CollapseMode.BE1_1``). Defaults to CollapseMode.BE1_1. :type collapse: str | int | CollapseMode :param param_dict: Dictionary of UCLCHEM parameters. Uses defaults from ``defaultparameters.f90`` for any key not provided. Defaults to None. :type param_dict: dict | None :param out_species: Not supported on OO model classes; passing any value raises ``TypeError``. Use the functional interface to filter output species. Defaults to None. :type out_species: list[str] | None :param starting_chemistry: Array of starting abundances for each species. If None, uses network defaults. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: A completed model whose final abundances are used as the starting chemistry for this model. Defaults to None. :type previous_model: AbstractModel | None :param timepoints: Number of output timesteps to store. Defaults to TIMEPOINTS. :type timepoints: int :param debug: If True, print extra debug information. Defaults to False. :type debug: bool :param read_file: Path to a previously saved model file to load instead of running. Defaults to None. :type read_file: str | None :param run_type: How the Fortran model is executed. ``'managed'`` runs automatically on init; ``'external'`` defers running to the caller. Defaults to 'managed'. :type run_type: Literal['managed', 'external'] :param on_negative_abundances: Action when negative abundances are detected after a run. Defaults to 'warning'. :type on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] :param on_error: Action when the Fortran solver returns an error flag. Defaults to 'raise'. :type on_error: Literal['raise', 'warn', 'ignore'] :raises ValueError: If ``rin`` and ``points`` were both set in the parameter dictionary. :raises ValueError: If ``parcelStoppingMode`` is set in the parameter dictionary. :raises ValueError: If ``endAtFinaldensity`` is False, but ``finalTime`` was not set. :raises ValueError: If ``endAtFinaldensity`` is False, but ``finalTime`` is less than the duration of the collapse for the collapse mode. :raises TypeError: If ``out_species`` is passed (not supported on OO model classes). .. py:method:: run_fortran() -> dict[str, int | list] Run the UCLCHEM model, first resetting the numpy arrays. Resetting uses `AbstractModel.run()`, then running the model. `check_error` and `array_clean` are automatically called after the model run. :returns: Dictionary with two keys: "success_flag" with value the success flag :rtype: dict[str, int | list] .. py:attribute:: collapse_final_time .. py:class:: GridRunner(model_type: str, full_parameters: dict | list, max_workers: int | None = None, grid_file: str = './default_grid_out.h5', model_name_prefix: str = '', overwrite_models: bool = False, delay_run: bool = False, log_dir: str | None = None, model_ids: list | None = None, create_grid: bool = True) GridRunner, like SequentialRunner is not an actual uclchem model,. instead it allows running multiple models on a grid of parameter space. :param model_type: Name of the registered model class to run (e.g. ``"Cloud"``, ``"Collapse"``). :type model_type: str :param full_parameters: The dictionary passed to GridRunner should nest into it, the param_dict argument that would be passed to any other model, with the addition of extra keys for the none param_dict variables of a model. Any variables that are turned into lists or arrays, will automatically be assumed to be used for the gridding. :type full_parameters: Dict :param max_workers: Maximum number of workers to use in parallel for the grid run. If None, use ``os.cpu_count()-1``. Default = None. :type max_workers: int | None :param grid_file: Name and path of the output file to which the models should be saved. Defaults to "./default_grid_out.h5". :type grid_file: str :param model_name_prefix: Name prefix convention to use. The fifth model in the grid would have the name "5>" assigned to it. Defaults to "", which would make the fifth model have the name "5", for example. :type model_name_prefix: str :param delay_run: Whether to immediately start the models upon initialization, or delay until the user calls `self.run()`. Defaults to False (start immediately). :type delay_run: bool :param log_dir: Where to write logs. If None, do not write logs. Default = None. :type log_dir: str | None :param model_ids: Optional subset of model indices (0-based column in flat_grids) to run. None means run all models in the grid. Default = None. :type model_ids: list | None .. py:method:: check_conservation(element_list: list[str] | None = None, percent: bool = True) -> None Check conservation of the chemical abundances. :param element_list: List of elements to check conservation for. If None, use `uclchem.constants.default_elements_to_check`. Default = None. :type element_list: list[str] | None :param percent: Flag on if percentage values should be used. Defaults to True. :type percent: bool .. py:method:: grid_iter(full_parameters: dict | list, param_keys: list, flattened_grids: numpy.ndarray, model_type: str) -> collections.abc.Iterator[dict[str, Any]] :staticmethod: Provide an iterable dictionary of parameters that can be used with the. grid-based multiprocessing worker distribution. :param full_parameters: dictionary or list (if model_type == SequentialRunner) of the full parameters that will be used for the model :type full_parameters: dict | list :param param_keys: list of parameters that are changing in this GridRunner object :type param_keys: list :param flattened_grids: list of all the values for the changing parameters for this GridRunner object :type flattened_grids: np.ndarray :param model_type: Type of model to use. 'SequentialRunner' results in alternative way of executing this phase as each SequentialRunner represents multiple models to be run in series. :type model_type: str :Yields: *dict[str, Any]* -- Next dictionary containing the parameter values for the model to run in the grid of models. Only offers one model per request. :raises TypeError: If ``model_type`` is not ``"SequentialRunner"`` and ``full_parameters`` is not a ``dict``. .. py:method:: load_chem(species: list[str]) -> None Load the chemistry. :param species: list of species to load abundances for. :type species: list[str] :raises NotImplementedError: If the model type is `SequentialRunner`. .. py:method:: load_phys() -> None Load the physics. :raises NotImplementedError: If the model type is `SequentialRunner`. .. py:method:: on_interrupt() -> None Handle a keyboard interrupt during a grid run. Override in subclasses to add cleanup. .. py:method:: run() -> None Run the grid. .. py:attribute:: chemical_abun_values :value: None .. py:attribute:: full_parameters .. py:attribute:: grid_file :value: './default_grid_out.h5' .. py:attribute:: log_dir :value: None .. py:attribute:: max_workers :value: None .. py:attribute:: model_id_dict :type: dict .. py:attribute:: model_ids .. py:attribute:: model_name_prefix :value: '' .. py:attribute:: model_type .. py:attribute:: models :type: list :value: [] .. py:attribute:: overwrite_models :value: False .. py:attribute:: parameters_to_grid :type: dict .. py:attribute:: physics_values :value: None .. py:class:: JShock(shock_vel: float = 10.0, param_dict: dict | None = None, out_species: list[str] | None = None, starting_chemistry: numpy.ndarray | None = None, previous_model: AbstractModel | None = None, timepoints: int = TIMEPOINTS, debug: bool = False, read_file: str | None = None, run_type: Literal['managed', 'external'] = 'managed', on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] = 'warning', on_error: Literal['raise', 'warn', 'ignore'] = 'raise') Bases: :py:obj:`AbstractModel` J-Shock model class inheriting from AbstractModel. :param shock_vel: Velocity of the shock. Defaults to 10.0. :type shock_vel: float :param param_dict: Dictionary containing the parameters to use for the UCLCHEM model. Uses UCLCHEM default values found in `defaultparameters.f90`. :type param_dict: dict | None :param starting_chemistry: Array containing the starting abundances to use for the UCLCHEM model. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: Model object, a class that inherited from AbstractModel, to use for the starting abundances of the new UCLCHEM model that will be run. Defaults to None. :type previous_model: AbstractModel | None :param timepoints: Integer value of how many timesteps should be calculated before aborting the UCLCHEM model. Defaults to `uclchem.constants.TIMEPOINTS`. :type timepoints: int :param debug: Flag if extra debug information should be printed to the terminal. Defaults to False. #TODO Add debug features :type debug: bool :param read_file: Path to the file to be read. Reading a file to a model object, prevents it from being run. Defaults to None. :type read_file: str | None Initialize the model with :meth:`AbstractModel.__init__`. Then run any additional commands needed for the model. :param shock_vel: Shock velocity in km/s. Defaults to 10.0. :type shock_vel: float :param param_dict: Dictionary of UCLCHEM parameters. Uses defaults from ``defaultparameters.f90`` for any key not provided. Defaults to None. :type param_dict: dict | None :param out_species: Not supported on OO model classes; passing any value raises ``TypeError``. Use the functional interface to filter output species. Defaults to None. :type out_species: list[str] | None :param starting_chemistry: Array of starting abundances for each species. If None, uses network defaults. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: A completed model whose final abundances are used as the starting chemistry for this model. Defaults to None. :type previous_model: AbstractModel | None :param timepoints: Number of output timesteps to store. Defaults to TIMEPOINTS. :type timepoints: int :param debug: If True, print extra debug information. Defaults to False. :type debug: bool :param read_file: Path to a previously saved model file to load instead of running. Defaults to None. :type read_file: str | None :param run_type: How the Fortran model is executed. ``'managed'`` runs automatically on init; ``'external'`` defers running to the caller. Defaults to 'managed'. :type run_type: Literal['managed', 'external'] :param on_negative_abundances: Action when negative abundances are detected after a run. Defaults to 'warning'. :type on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] :param on_error: Action when the Fortran solver returns an error flag. Defaults to 'raise'. :type on_error: Literal['raise', 'warn', 'ignore'] :raises ValueError: If `read_file` is None, but `shock_vel` is also not set. :raises TypeError: If ``out_species`` is passed (not supported on OO model classes). .. py:method:: run_fortran() -> dict[str, int | list] Run the UCLCHEM model, first resetting the numpy arrays. Resetting uses `AbstractModel.run()`, then running the model. `check_error` and `array_clean` are automatically called after the model run. :returns: Dictionary with two keys: "success_flag" with value the success flag :rtype: dict[str, int | list] .. py:class:: Model(param_dict: dict | None = None, out_species: list[str] | None = None, starting_chemistry: numpy.ndarray | None = None, previous_model: AbstractModel | None = None, time_array: numpy.ndarray | None = None, density_array: numpy.ndarray | None = None, gas_temperature_array: numpy.ndarray | None = None, dust_temperature_array: numpy.ndarray | None = None, zeta_array: numpy.ndarray | None = None, radfield_array: numpy.ndarray | None = None, debug: bool = False, read_file: str | None = None, run_type: Literal['managed', 'external'] = 'managed', on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] = 'warning', on_error: Literal['raise', 'warn', 'ignore'] = 'raise') Bases: :py:obj:`AbstractModel` Model, like Postprocess, represents a model class with additional controls. It inherits from AbstractModel. Model follows the same logic as Postprocess but without the coldens Arguments. It allows for additional controls of the time, density, gas temperature, radiation field, and cosmic ray ionization rate through the use of arrays. Using these arrays allows for experimental model crafting beyond the standard models in other model classes. :param param_dict: Dictionary containing the parameters to use for the UCLCHEM model. Uses UCLCHEM default values found in `defaultparameters.f90`. :type param_dict: dict :param starting_chemistry: Array containing the starting abundances to use for the UCLCHEM model. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: Model object, a class that inherited from AbstractModel, to use for the starting abundances of the new UCLCHEM model that will be run. Defaults to None. :type previous_model: AbstractModel | None :param time_array: Represents the time grid to be used for the model. This sets the target timesteps for which outputs will be stored. :type time_array: np.ndarray | None :param density_array: Represents the value of the density at different timepoints found in time_array. :type density_array: np.ndarray | None :param gas_temperature_array: Represents the value of the gas temperature at different timepoints found in time_array. :type gas_temperature_array: np.ndarray | None :param dust_temperature_array: Represents the value of the dust temperature at different timepoints found in time_array. :type dust_temperature_array: np.ndarray | None :param zeta_array: Represents the value of the cosmic ray ionization rate at different timepoints found in time_array. :type zeta_array: np.ndarray | None :param radfield_array: Represents the value of the UV radiation field at different timepoints found in time_array. :type radfield_array: np.ndarray | None :param debug: Flag if extra debug information should be printed to the terminal. Defaults to False. #TODO Add debug features :type debug: bool :param read_file: Path to the file to be read. Reading a file to a model object, prevents it from being run. Defaults to None. :type read_file: str | None Initialize the model with :meth:`AbstractModel.__init__`. Then run any additional commands needed for the model. :param param_dict: Dictionary of UCLCHEM parameters. Uses defaults from ``defaultparameters.f90`` for any key not provided. Defaults to None. :type param_dict: dict | None :param out_species: Not supported on OO model classes; passing any value raises ``TypeError``. Use the functional interface to filter output species. Defaults to None. :type out_species: list[str] | None :param starting_chemistry: Array of starting abundances for each species. If None, uses network defaults. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: A completed model whose final abundances are used as the starting chemistry for this model. Defaults to None. :type previous_model: AbstractModel | None :param time_array: Time grid (years) at which model outputs are stored. Defaults to None. :type time_array: np.ndarray | None :param density_array: Number density (cm⁻³) at each timestep. Defaults to None. :type density_array: np.ndarray | None :param gas_temperature_array: Gas temperature (K) at each timestep. Defaults to None. :type gas_temperature_array: np.ndarray | None :param dust_temperature_array: Dust temperature (K) at each timestep. Defaults to None. :type dust_temperature_array: np.ndarray | None :param zeta_array: Cosmic-ray ionization rate (s⁻¹) at each timestep. Defaults to None. :type zeta_array: np.ndarray | None :param radfield_array: UV radiation field strength (Habing units) at each timestep. Defaults to None. :type radfield_array: np.ndarray | None :param debug: If True, print extra debug information. Defaults to False. :type debug: bool :param read_file: Path to a previously saved model file to load instead of running. Defaults to None. :type read_file: str | None :param run_type: How the Fortran model is executed. ``'managed'`` runs automatically on init; ``'external'`` defers running to the caller. Defaults to 'managed'. :type run_type: Literal['managed', 'external'] :param on_negative_abundances: Action when negative abundances are detected after a run. Defaults to 'warning'. :type on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] :param on_error: Action when the Fortran solver returns an error flag. Defaults to 'raise'. :type on_error: Literal['raise', 'warn', 'ignore'] :raises ValueError: If not all arrays have the same length. :raises ValueError: If `read_file` is None, but `time_array` is not an array. :raises TypeError: If ``out_species`` is passed (not supported on OO model classes). .. py:method:: run_fortran() -> dict[str, int | list] Run the UCLCHEM model, first resetting the numpy arrays. Resetting uses `AbstractModel.run()`, then running the model. `check_error` and `array_clean` are automatically called after the model run. :returns: Dictionary with two keys: "success_flag" with value the success flag :rtype: dict[str, int | list] .. py:class:: NoDaemonPool(processes=None, initializer=None, initargs=(), maxtasksperchild=None, context=None) Bases: :py:obj:`multiprocessing.pool.Pool` Class which supports an async version of applying functions to arguments. .. py:method:: Process(ctx, *args, **kwargs) :staticmethod: .. py:class:: Postprocess(param_dict: dict | None = None, out_species: list[str] | None = None, starting_chemistry: numpy.ndarray | None = None, previous_model: AbstractModel | None = None, time_array: numpy.ndarray | None = None, density_array: numpy.ndarray | None = None, gas_temperature_array: numpy.ndarray | None = None, dust_temperature_array: numpy.ndarray | None = None, zeta_array: numpy.ndarray | None = None, radfield_array: numpy.ndarray | None = None, visual_extinction_array: numpy.ndarray | None = None, coldens_H_array: numpy.ndarray | None = None, coldens_H2_array: numpy.ndarray | None = None, coldens_CO_array: numpy.ndarray | None = None, coldens_C_array: numpy.ndarray | None = None, debug: bool = False, read_file: str | None = None, run_type: Literal['managed', 'external'] = 'managed', on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] = 'warning', on_error: Literal['raise', 'warn', 'ignore'] = 'raise') Bases: :py:obj:`AbstractModel` Model class with additional controls, inheriting from :class:`AbstractModel`. Postprocess allows for additional controls of the time, density, gas temperature, radiation field, cosmic ray ionization rate, atomic and molecular Hydrogen, CO and C column densities through the use of arrays. Using these arrays allows for experimental model crafting beyond the standard models in other model classes. :param param_dict: Dictionary containing the parameters to use for the UCLCHEM model. Uses UCLCHEM default values found in `defaultparameters.f90`. :type param_dict: dict | None :param starting_chemistry: Array containing the starting abundances to use for the UCLCHEM model. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: Model object, a class that inherited from AbstractModel, to use for the starting abundances of the new UCLCHEM model that will be run. Defaults to None. :type previous_model: AbstractModel | None :param time_array: Represents the time grid to be used for the model. This sets the target timesteps for which outputs will be stored. :type time_array: np.ndarray | None :param density_array: Represents the value of the density at different timepoints found in time_array. :type density_array: np.ndarray | None :param gas_temperature_array: Represents the value of the gas temperature at different timepoints found in time_array. :type gas_temperature_array: np.ndarray | None :param dust_temperature_array: Represents the value of the dust temperature at different timepoints found in time_array. :type dust_temperature_array: np.ndarray | None :param zeta_array: Represents the value of the cosmic ray ionization rate at different timepoints found in time_array. :type zeta_array: np.ndarray | None :param radfield_array: Represents the value of the UV radiation field at different timepoints found in time_array. :type radfield_array: np.ndarray | None :param coldens_H_array: Represents the value of the column density of H at different timepoints found in time_array. :type coldens_H_array: np.ndarray | None :param coldens_H2_array: Represents the value of the column density of H2 at different timepoints found in time_array. :type coldens_H2_array: np.ndarray | None :param coldens_CO_array: Represents the value of the column density of CO at different timepoints found in time_array. :type coldens_CO_array: np.ndarray | None :param coldens_C_array: Represents the value of the column density of C at different timepoints found in time_array. :type coldens_C_array: np.ndarray | None :param debug: Flag if extra debug information should be printed to the terminal. Defaults to False. #TODO Add debug features :type debug: bool :param read_file: Path to the file to be read. Reading a file to a model object, prevents it from being run. Defaults to None. :type read_file: str | None Initialize the model with :meth:`AbstractModel.__init__`. Then run any additional commands needed for the model. :param param_dict: Dictionary of UCLCHEM parameters. Uses defaults from ``defaultparameters.f90`` for any key not provided. Defaults to None. :type param_dict: dict | None :param out_species: Not supported on OO model classes; passing any value raises ``TypeError``. Use the functional interface to filter output species. Defaults to None. :type out_species: list[str] | None :param starting_chemistry: Array of starting abundances for each species. If None, uses network defaults. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: A completed model whose final abundances are used as the starting chemistry for this model. Defaults to None. :type previous_model: AbstractModel | None :param time_array: Time grid (years) at which model outputs are stored. Defaults to None. :type time_array: np.ndarray | None :param density_array: Number density (cm⁻³) at each timestep. Defaults to None. :type density_array: np.ndarray | None :param gas_temperature_array: Gas temperature (K) at each timestep. Defaults to None. :type gas_temperature_array: np.ndarray | None :param dust_temperature_array: Dust temperature (K) at each timestep. Defaults to None. :type dust_temperature_array: np.ndarray | None :param zeta_array: Cosmic-ray ionization rate (s⁻¹) at each timestep. Defaults to None. :type zeta_array: np.ndarray | None :param radfield_array: UV radiation field strength (Habing units) at each timestep. Defaults to None. :type radfield_array: np.ndarray | None :param visual_extinction_array: Visual extinction (mag) at each timestep. Mutually exclusive with ``coldens_H_array``. Defaults to None. :type visual_extinction_array: np.ndarray | None :param coldens_H_array: Atomic hydrogen column density (cm⁻²) at each timestep. Mutually exclusive with ``visual_extinction_array``. Defaults to None. :type coldens_H_array: np.ndarray | None :param coldens_H2_array: Molecular hydrogen column density (cm⁻²) at each timestep. Defaults to None. :type coldens_H2_array: np.ndarray | None :param coldens_CO_array: CO column density (cm⁻²) at each timestep. Defaults to None. :type coldens_CO_array: np.ndarray | None :param coldens_C_array: Atomic carbon column density (cm⁻²) at each timestep. Defaults to None. :type coldens_C_array: np.ndarray | None :param debug: If True, print extra debug information. Defaults to False. :type debug: bool :param read_file: Path to a previously saved model file to load instead of running. Defaults to None. :type read_file: str | None :param run_type: How the Fortran model is executed. ``'managed'`` runs automatically on init; ``'external'`` defers running to the caller. Defaults to 'managed'. :type run_type: Literal['managed', 'external'] :param on_negative_abundances: Action when negative abundances are detected after a run. Defaults to 'warning'. :type on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] :param on_error: Action when the Fortran solver returns an error flag. Defaults to 'raise'. :type on_error: Literal['raise', 'warn', 'ignore'] :raises ValueError: If not all arrays have the same length. :raises ValueError: If `read_file` is None, but `time_array` is not an array. :raises TypeError: If ``out_species`` is passed (not supported on OO model classes). :raises AssertionError: If both column density and visual extinction arrays are provided. .. py:method:: run_fortran() -> dict[str, int | list] Run the UCLCHEM model, first resetting the numpy arrays. Resetting uses `AbstractModel.run()`, then running the model. `check_error` and `array_clean` are automatically called after the model run. :returns: Dictionary with two keys: "success_flag" with value the success flag :rtype: dict[str, int | list] .. py:class:: PrestellarCore(temp_indx: int = 1, max_temperature: float = 300.0, param_dict: dict | None = None, out_species: list[str] | None = None, starting_chemistry: numpy.ndarray | None = None, previous_model: AbstractModel | None = None, timepoints: int = TIMEPOINTS, debug: bool = False, read_file: str | None = None, run_type: Literal['managed', 'external'] = 'managed', on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] = 'warning', on_error: Literal['raise', 'warn', 'ignore'] = 'raise') Bases: :py:obj:`AbstractModel` PrestellarCore model class inheriting from AbstractModel. This model type was previously known as hot core. :param temp_indx: Used to select the mass of the prestellar core from the following selection [1=1Msun, 2=5, 3=10, 4=15, 5=25,6=60]. Defaults to 1, which is 1 Msun :type temp_indx: int :param max_temperature: Value at which gas temperature will stop increasing. Defaults to 300.0. :type max_temperature: float :param param_dict: Dictionary containing the parameters to use for the UCLCHEM model. Uses UCLCHEM default values found in `defaultparameters.f90`. :type param_dict: dict :param starting_chemistry: Array containing the starting abundances to use for the UCLCHEM model. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: Model object, a class that inherited from AbstractModel, to use for the starting abundances of the new UCLCHEM model that will be run. Defaults to None. :type previous_model: AbstractModel | None :param timepoints: Integer value of how many timesteps should be calculated before aborting the UCLCHEM model. Defaults to `uclchem.constants.TIMEPOINTS`. :type timepoints: int :param debug: Flag if extra debug information should be printed to the terminal. Defaults to False. #TODO Add debug features :type debug: bool :param read_file: Path to the file to be read. Reading a file to a model object, prevents it from being run. Defaults to None. :type read_file: str | None Initialize the model with :meth:`AbstractModel.__init__`. Then run any additional commands needed for the model. :param temp_indx: Index of the temperature column in the physics array to use for hot-core heating. Defaults to 1. :type temp_indx: int :param max_temperature: Maximum temperature (K) the hot core reaches. Defaults to 300.0. :type max_temperature: float :param param_dict: Dictionary of UCLCHEM parameters. Uses defaults from ``defaultparameters.f90`` for any key not provided. Defaults to None. :type param_dict: dict | None :param out_species: Not supported on OO model classes; passing any value raises ``TypeError``. Use the functional interface to filter output species. Defaults to None. :type out_species: list[str] | None :param starting_chemistry: Array of starting abundances for each species. If None, uses network defaults. Defaults to None. :type starting_chemistry: np.ndarray | None :param previous_model: A completed model whose final abundances are used as the starting chemistry for this model. Defaults to None. :type previous_model: AbstractModel | None :param timepoints: Number of output timesteps to store. Defaults to TIMEPOINTS. :type timepoints: int :param debug: If True, print extra debug information. Defaults to False. :type debug: bool :param read_file: Path to a previously saved model file to load instead of running. Defaults to None. :type read_file: str | None :param run_type: How the Fortran model is executed. ``'managed'`` runs automatically on init; ``'external'`` defers running to the caller. Defaults to 'managed'. :type run_type: Literal['managed', 'external'] :param on_negative_abundances: Action when negative abundances are detected after a run. Defaults to 'warning'. :type on_negative_abundances: Literal[None, 'warning', 'error', 'raise'] :param on_error: Action when the Fortran solver returns an error flag. Defaults to 'raise'. :type on_error: Literal['raise', 'warn', 'ignore'] :raises ValueError: If `read_file` is None, but `temp_idx` or `max_temperature` is also None. :raises TypeError: If ``out_species`` is passed (not supported on OO model classes). .. py:method:: run_fortran() -> dict[str, int | list] Run the UCLCHEM model, first resetting the numpy arrays. Resetting uses `AbstractModel.run()`, then running the model. `check_error` and `array_clean` are automatically called after the model run. :returns: Dictionary with two keys: "success_flag" with value the success flag :rtype: dict[str, int | list] .. py:class:: ReactionNamesStore .. py:attribute:: reaction_names :value: None .. py:class:: SequentialRunner(sequenced_model_parameters: list, parameters_to_match: list | None = None, run_type: Literal['managed', 'external'] = 'managed', on_error: Literal['raise', 'warn', 'ignore'] = 'raise') The SequentialRunner class allows for multiple models to be run back to back. By defining a specific dictionary to hold the information of each model class to run in sequence, SewuentialModel allows for the automatic running of multiple models as well as matching some physical parameters from one model to the next. :param sequenced_model_parameters: The List of dictionaries to pass to SequentialRunner takes the format of [{"":{"param_dict":{}, }}, {":{"param_dict":{}, }}, ...}] :type sequenced_model_parameters: list[dict[str, Any]] :param parameters_to_match: The list provided to this argument decides which parameters should be matched from a previous model to the next model in the sequence. Currently, supports one or more of `["finalDens", "finalTemp"]`. :type parameters_to_match: list[str] :param run_type: Run type. Must be either "managed", or "external". :type run_type: Literal['managed', 'external'] :raises NotImplementedError: If a parameter in `parameters_to_match` is not one of `["finalDens", "finalTemp"]`. .. py:method:: check_conservation(element_list: list[str] | None = None, percent: bool = True) -> None Check conservation of the chemical abundances. :param element_list: List of elements to check conservation for. If None, use `uclchem.constants.default_elements_to_check`. Default = None. :type element_list: list[str] | None :param percent: Flag on if percentage values should be used. Defaults to True. :type percent: bool .. py:method:: pickle() -> None Pickle the models. .. py:method:: run() -> None Run the sequential model. :raises NotImplementedError: If a parameter in `parameters_to_match` is not one of `["finalDens", "finalTemp"]`. :raises RuntimeError: If ``previous_model`` is ``None`` when ``model_count > 0``. .. py:method:: save_model(*, file_obj: h5py.File | None = None, file: str | None = None, name: str = '', overwrite: bool = False) -> None Save a model to an open file object or to a file. :param file_obj: open file h5py file object. Default = None. :type file_obj: h5py.File | None :param file: file to write to. Default = None. :type file: str | None :param name: name to save model under. (Default value = '') :type name: str :param overwrite: Boolean on whether to overwrite pre-existing models, or error out. Defaults to False :type overwrite: bool :raises ValueError: If file_obj and file are both passed, or neither are passed. .. py:method:: un_pickle() -> None Un-pickle the models. .. py:attribute:: model_count :value: 0 .. py:attribute:: models :type: list :value: [] .. py:attribute:: parameters_to_match :value: None .. py:attribute:: run_type :value: 'managed' .. py:attribute:: sequenced_model_parameters .. py:attribute:: success_flag :type: bool | None :value: None .. py:class:: SpeciesNameStore .. py:attribute:: species_names :value: None .. py:function:: get_number_of_grid_workers(max_workers: int | None) -> int Determine the number of grid workers. :param max_workers: Maximum number of workers to use in parallel for the grid run. If None, use ``os.cpu_count()-1`` workers. Default = None. :type max_workers: int | None :returns: Number of CPU cores to use for grid models. :rtype: int :raises RuntimeError: If ``max_workers`` is None, but func:`os.cpu_count()` also returns None. .. py:function:: load_model(*, file_obj: h5py.File | None = None, file: str | None = None, name: str = 'default', debug: bool = False) -> AbstractModel Load a pre-existing model from a file. Bypasses `__init__`. :param file_obj: open h5py file object. (Default value = None) :type file_obj: h5py.File | None :param file: Path to a file that contains previously run and stored models. (Default value = None) :type file: str | None :param name: Name of the stored object, if none was provided `default` will have been used. Defaults to 'default' :type name: str :param debug: Flag if extra debug information should be printed to the terminal. Defaults to False. #TODO Add debug features :type debug: bool :returns: **obj** -- Loaded object that inherited from AbstractModel and has the class of to the model found in the loaded file. :rtype: AbstractModel :raises ValueError: If file_obj and file are both passed, or neither are passed. :raises Exception: If the model with name `name` is not found in the file. .. py:function:: reaction_line_formatter(line: list[str] | pandas.Series) -> str Format a list of strings as a reaction, while filtering out "NAN"s. :param line: list of species involved in the reaction :type line: list[str] | pd.Series :returns: formatted reaction for printing. :rtype: str .. rubric:: Examples >>> print(reaction_line_formatter(["#OH", "#H", "LH", "#H2O", "NAN", "NAN", "NAN"])) #OH + #H + LH -> #H2O >>> print(reaction_line_formatter(["H2", "PHOTON", "NAN", "H", "H", "NAN", "NAN"])) H2 + PHOTON -> H + H .. py:function:: register_model(cls: type[AbstractModel]) -> type[AbstractModel] Register a new model in the model registry. :param cls: class to register. :type cls: type[AbstractModel] :returns: **cls** -- class :rtype: type[AbstractModel] :raises ValueError: If a model with the same name as cls is already in the registry. .. py:data:: NoGridParameters :value: ['starting_chemistry', 'time_array', 'density_array', 'gas_temperature_array',... .. py:data:: PHYSICAL_PARAMETERS_HEADER_FORMAT :value: '%10s' .. py:data:: PHYSICAL_PARAMETERS_VALUE_FORMAT :value: '%10.3E, %10.4E, %10.2f, %10.2f, %10.4E, %10.4E, %10.4E, %10i, %10.4E, %10.4E, %10.4E' .. py:data:: REGISTRY :type: dict[str, type[AbstractModel]] .. py:data:: SPECNAME_HEADER_FORMAT :value: '%11s' .. py:data:: SPECNAME_VALUE_FORMAT :value: '%9.5E' .. py:data:: get_reaction_names .. py:data:: get_species_names