MusicBox#

An atmospheric chemistry box model. Powered by MUSICA.

This package contains modules for handling various aspects of a music box, including species, products, reactants, reactions, and more.

acom_music_box.music_box module#

class acom_music_box.music_box.MusicBox(box_model_options=None)#

Bases: object

Represents a box model with attributes such as box model options, conditions, solver, and state.

Attributes:

box_model_options (BoxModelOptions): Options for the box model simulation. solver: The solver used for the box model simulation. state: The current state of the box model simulation.

add_conditions(df: DataFrame) MusicBox#

Merge DataFrame with existing conditions.

Args:

df: DataFrame with conditions to merge. Must have ‘time.s’ column.

Returns:

self for method chaining.

property concentration_events: dict#

Returns concentration events - species concentrations set at specific times.

Concentrations are only applied at exact times specified, not interpolated. They represent “reset” points where chemistry is overridden.

Returns:

Dictionary mapping time -> {species: concentration} Example: {0.0: {“A”: 1.0, “B”: 0.5}, 300.0: {“D”: 1.0}}

property conditions: DataFrame#

Returns fully interpolated DataFrame at all simulation timesteps.

Returns:

DataFrame with interpolated conditions using step interpolation.

Raises:

ValueError: If simulation options are not set.

property conditions_raw: DataFrame#

Returns the raw (sparse) conditions DataFrame with only user-specified times. Contains ENV.*, PHOTO.*, EMIS.*, etc. but NOT concentrations.

Returns:

DataFrame with raw conditions (no interpolation).

export(path_to_json: str)#

Export the current box model state to a v1 JSON file.

The exported file is self-contained: conditions are written as inline data blocks (one per time point) so no external CSV files are needed. The file can be reloaded with loadJson() to reproduce identical results.

Args:

path_to_json: Path to write the JSON file.

Raises:

ValueError: If the mechanism has not been loaded.

get_condition_template() DataFrame#

Returns DataFrame with all possible columns from mechanism (all NaN).

Returns:

DataFrame template with time.s and all mechanism columns.

loadJson(path_to_json)#

Reads and parses a JSON file and create a solver.

Args:

path_to_json (str): The JSON path to the JSON file.

Returns:

None

Raises:

ValueError: If the JSON string cannot be parsed.

load_mechanism(mechanism, solver_type=<_SolverType.rosenbrock_standard_order: 2>)#

Creates a solver for the specified mechanism.

Args:

mechanism (Mechanism): The mechanism to be used for the solver. solver_type: The solver type to use.

property mechanism#
set_condition(time: float, *, temperature: float = None, pressure: float = None, concentrations: dict = None, rate_parameters: dict = None) MusicBox#

Set conditions at a specific time. Returns self for chaining.

Args:

time: The time point in seconds. temperature: Temperature in Kelvin (optional). pressure: Pressure in Pascals (optional). concentrations: Dictionary of species name to concentration in mol m-3. rate_parameters: Dictionary of rate parameter names to values.

Keys should be in format: PREFIX.name.unit

Returns:

self for method chaining.

Example:

box.set_condition(time=0, temperature=300, pressure=101325) box.set_condition(time=0, concentrations={“A”: 1.0, “B”: 0.0}) box.set_condition(time=3600, temperature=310)

set_conditions(df: DataFrame) MusicBox#

Replace all conditions from DataFrame. Must have ‘time.s’ column.

Args:
df: DataFrame with conditions. Must have ‘time.s’ column.

Column naming convention: - time.s: Time in seconds - ENV.temperature.K: Temperature in Kelvin - ENV.pressure.Pa: Pressure in Pascals - CONC.<species>.mol m-3: Species concentration - EMIS.<species>.mol m-3 s-1: Emission rate - PHOTO.<reaction>.s-1: Photolysis rate - LOSS.<species>.s-1: Loss rate - USER.<param>.<unit>: User-defined parameter

Returns:

self for method chaining.

Example:
df = pd.DataFrame({

“time.s”: [0, 3600], “ENV.temperature.K”: [300, 310], “CONC.A.mol m-3”: [1.0, None]

}) box.set_conditions(df)

solve() DataFrame#

Solve the box model simulation.

Returns:

pd.DataFrame: Results with columns time.s, ENV.temperature.K, ENV.pressure.Pa, ENV.air number density.mol m-3, and CONC.<species>.mol m-3 for each species.

acom_music_box.conditions module#

acom_music_box.evolving_conditions module#

acom_music_box.data_output module#

class acom_music_box.data_output.DataOutput(df, args)#

Bases: object

A class to handle data output operations for a DataFrame, including converting to CSV or NetCDF formats with appended units for columns. Designed for environmental data with specific units and formats.

This class manages file paths, unit mappings, and data output formats based on the provided arguments, ensuring valid paths and creating necessary directories.

Attributes#

dfpandas.DataFrame

The DataFrame to be output.

argsargparse.Namespace

Command-line arguments or configurations specifying output options.

unit_mappingdict

A dictionary mapping specific columns to their respective units.

Examples#

>>> import pandas as pd
>>> from argparse import Namespace
>>> df = pd.DataFrame({
...     'ENV.temperature': [290, 295, 300],
...     'ENV.pressure': [101325, 100000, 98500],
...     'ENV.number_density_air': [102, 5096, 850960],
...     'time': [0, 1, 2]
... })
>>> args = Namespace(output='output.nc')
>>> data_output = DataOutput(df, args)
>>> data_output.output()
output()#

Main method to handle output based on the provided arguments.

acom_music_box.plot_output module#

class acom_music_box.plot_output.PlotOutput(df, args)#

Bases: object

A class to handle plotting operations for a DataFrame, including plotting species concentrations over time using matplotlib.

This class manages the plotting tool, species list, and data output formats based on the provided arguments, ensuring valid paths and creating necessary directories.

Attributes#

dfpandas.DataFrame

The DataFrame to be plotted.

argsargparse.Namespace

Command-line arguments or configurations specifying plot options.

species_listlist of lists

A list of lists, where each sublist contains species to be plotted in a separate window.

Examples#

>>> import pandas as pd
>>> from argparse import Namespace
>>> df = pd.DataFrame({
...     'time': [0, 1, 2],
...     'CONC.A.mol m-3': [1, 2, 3],
...     'CONC.B.mol m-3': [4, 5, 6],
...     'CONC.C.mol m-3': [7, 8, 9]
... })
>>> args = Namespace(plot=['CONC.A,CONC.B'], plot_tool='matplotlib')
>>> plot_output = PlotOutput(df, args)
>>> plot_output.plot()
plot()#

Plot the specified species using matplotlib.

acom_music_box.model_options module#

class acom_music_box.model_options.BoxModelOptions(chem_step_time=None, output_step_time=None, simulation_length=None, grid='box', max_iterations=1000)#

Bases: object

Represents options for a box model simulation.

Attributes:

grid (str): The type of grid. Default is “box”. chemStepTime (float): Time step for chemical reactions in the simulation in seconds. outputStepTime (float): Time step for output data in the simulation in hours. simulationLength (float): Length of the simulation in hours.

classmethod from_config(config_JSON)#

Create a new instance of the BoxModelOptions class from a JSON object from a configuration JSON.

Args:

UI_JSON (dict): A JSON object representing box model options.

Returns:

BoxModelOptions: A new instance of the BoxModelOptions class.

acom_music_box.utils module#

acom_music_box.utils.calculate_air_density(temperature, pressure)#

Calculate the air density in moles m-3

Args:

temperature (float): The temperature in Kelvin. pressure (float): The pressure in Pascals.

Returns:

float: The air density in moles m-3

acom_music_box.utils.convert_concentration(data, key, temperature, pressure)#

Convert the concentration from the input data to moles per cubic meter. This function assumes you are passing data from a music box configuration.

Args:

data (dict): The input data. key (str): The key for the concentration in the input data. temperature (float): The temperature in Kelvin. pressure (float): The pressure in Pascals.

Returns:

float: The concentration in moles per cubic meter.

acom_music_box.utils.convert_from_number_density(data, output_unit, temperature, pressure)#

Convert from mol m-3 to some other units

Args:

data (float): The data to convert in mol m-3. output_unit (str): The output units temperature (float): The temperature in Kelvin. pressure (float): The pressure in Pascals.

Returns:

float: The data in the output unit.

acom_music_box.utils.convert_pressure(data, key)#

Convert the pressure from the input data to Pascals.

Args:

data (dict): The input data. key (str): The key for the pressure in the input data.

Returns:

float: The pressure in Pascals.

acom_music_box.utils.convert_temperature(data, key)#

Convert the temperature from the input data to Kelvin.

Args:

data (dict): The input data. key (str): The key for the temperature in the input data.

Returns:

float: The temperature in Kelvin.

acom_music_box.utils.convert_time(data, key)#

Convert the time from the input data to seconds.

Args:

data (dict): The input data. key (str): The key for the time in the input data.

Returns:

float: The time in seconds.

acom_music_box.utils.convert_to_number_density(data, input_unit, temperature, pressure)#

Convert from some other units to mol m-3

Args:

data (float): The data to convert in the input unit. input_unit (str): The input units temperature (float): The temperature in Kelvin. pressure (float): The pressure in Pascals.

Returns:

float: The data in the output unit.

acom_music_box.utils.extract_unit(data, key)#

Extract the value and unit from the key in data.

acom_music_box.utils.get_available_units()#

Get the list of available units for conversion.

Returns:

list: The list of available units.