Skip to content
ReEmission 1.0.0 documentation
⌘ K
ReEmission 1.0.0 documentation

Contents:

  • About the Library
  • Theoretical Background
  • Configuration
  • Installation
    • Installing RE-Emission
    • About Docker
    • Building the ReEmission Docker Image
    • Using the ReEmission Docker Image
  • Usage
  • Running the ReEmission Docker Container
  • Tutorials
  • Demo
  • JSON file format description
  • Configuration
  • Reporting Calculation Outputs
  • Visualisation
  • Integration with GeoCARET
  • Python API reference
    • Model (Main)
    • Input Model
    • Reservoir Model
    • Catchment Model
    • Post-impoundment catchment
    • Emissions
    • Emission Profile Calculator
    • MonthlyTemperature
    • Biogenic Factors
    • Presenter
    • Utility functions
    • Auxiliary functions
    • Constants
    • Mixins
    • Document \(\LaTeX\) Compiler
    • Custom Exceptions
    • App Logger
    • External Data Downloader
    • Global variables
    • Main
    • SALib Integration
    • Postprocessing
  • License
ReEmission 1.0.0 documentation
/
1. Define inputs for the step-by-step emissions calculations

a0f281e37fec4b8aa9e3599059edbb9b

Modification of configuration options via custom configuration files and on-the-fly

This notebook demonstrates how to:

  1. Read a custom configuration file from a user’s file-system to update model parameters

  2. Update selected config variables after loading the configuration file

  3. Run step-by-step manual calculations with different model parameterizations

  4. Run calculations for batches of reservoirs with custom configurations

< Saving Results To LaTeX | Contents | Parametric Uncertainty >

Open in Colab

[8]:
from dataclasses import dataclass
from os.path import exists
import pathlib
import gdown
from typing import List, Dict, Tuple, Any, NamedTuple
from rich import print as rprint
try:
    import reemission
except ImportError:
    print("Unable to import reemission. Please ensure it is installed.")
    %pip install git+https://github.com/tomjanus/reemission.git --quiet

DEV_MODE = False

if  DEV_MODE:
    import importlib
    importlib.reload(reemission)

# Import from the temperature module
from reemission.temperature import MonthlyTemperature
# Import from the emissions module
from reemission.emissions import CarbonDioxideEmission, MethaneEmission
# Import from the constants module
from reemission.constants import Climate, SoilType, Biome, TreatmentFactor, LanduseIntensity
# Import from the catchment module
from reemission.catchment import Catchment
# Import from the reservoir module
from reemission.reservoir import Reservoir
# Import from the biogenic module
from reemission.biogenic import BiogenicFactors
# Import function for resetting configuration to default settings
from reemission.config_registration import reset_all as reset_all_configs
from reemission.registry import config
# Import from the model module
from reemission.model import EmissionModel
# Import from the input module
from reemission.input import Inputs

# Helper class to encapsulate inputs for running emissions calculation with different input values
@dataclass
class ReemissionInputs:
    mt: MonthlyTemperature
    coordinates: List[float]
    catchment_inputs: Dict[str, Any]
    reservoir_inputs: Dict[str, Any]
    year_profile: Tuple[int | float, ...]

# Helper class to encapsulate the results of emissions calculations
class EmissionResults(NamedTuple):
    net_co2: float
    net_ch4: float
    net_total: float

    def __str__(self):
        return (
            f"Net areal CO2 emissions: {self.net_co2:.2f} g CO2e m-2 yr-1\n"
            f"Net areal CH4 emissions: {self.net_ch4:.2f} g CO2e m-2 yr-1\n"
            f"Net areal total emissions: {self.net_total:.2f} g CO2e m-2 yr-1"
        )

    __repr__ = __str__

1. Define inputs for the step-by-step emissions calculations

see 01-Step-By-Step-Manual-Calculations.ipynb for more details

[ ]:
# Define inputs (see 01-Step-By-Step-Manual-Calculations.ipynb for more details)
mt = MonthlyTemperature([10.56,11.99,15.46,18.29,20.79,22.09,22.46,22.66,21.93,19.33,15.03,11.66])
coordinates = [22.6, 94.7]
biogenic_factors = BiogenicFactors(
    biome = Biome.TROPICALMOISTBROADLEAF,
    climate = Climate.TROPICAL,
    soil_type=SoilType.MINERAL,
    treatment_factor = TreatmentFactor.NONE,
    landuse_intensity = LanduseIntensity.LOW)
catchment_area_fractions = [
    0.0, 0.0, 0.0, 0.0, 0.0, 0.01092, 0.11996, 0.867257, 0.0]
reservoir_area_fractions = [
    0.0, 0.0, 0.0, 0.0, 0.0, 0.45, 0.15, 0.4, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0,  0.0,  0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0,  0.0,  0.0, 0.0]
catchment_inputs = {
    'runoff': 1685.5619, 'area': 78203.0, 'population': 8463, 'riv_length': 9.2,
    'area_fractions': catchment_area_fractions, 'slope': 8.0, 'precip': 2000.0,
    'etransp': 400.0, 'soil_wetness': 140.0, 'mean_olsen': 5.85,
    'biogenic_factors': biogenic_factors}
reservoir_inputs = {
    'volume': 7663812, 'area': 100.56470, 'max_depth': 32.0, 'mean_depth': 13.6,
    'area_fractions': reservoir_area_fractions, 'soil_carbon': 10.228,
    'mean_radiance': 4.5, 'mean_radiance_may_sept': 4.5, 'mean_radiance_nov_mar': 3.2,
    'mean_monthly_windspeed': 3.8, 'water_intake_depth': 20.0}
year_profile = (1, 5, 10, 20, 30, 40, 50, 65, 80, 100)

inputs = ReemissionInputs(
    mt=mt,
    coordinates=coordinates,
    catchment_inputs=catchment_inputs,
    reservoir_inputs=reservoir_inputs,
    year_profile=year_profile
)

2. Define a function that goes through all steps of emission calculations and returns net areal CO2, CH4 emissions and total net aerial emissions

[ ]:

def calculate_emissions_step_by_step( inputs: ReemissionInputs, p_calc_method: str = 'g-res') -> EmissionResults: """ """ # Initialize the catchment and reservoir objects with input data catchment_1 = Catchment(**inputs.catchment_inputs) rprint(catchment_1.biogenic_factors) reservoir_1 = Reservoir( **inputs.reservoir_inputs, temperature = inputs.mt, coordinates=inputs.coordinates, inflow_rate=catchment_1.discharge) # Calculate net areal CO2 an CH4 emissions em_co2 = CarbonDioxideEmission( catchment=catchment_1, reservoir=reservoir_1, eff_temp=inputs.mt.eff_temp(gas='co2'), p_calc_method=p_calc_method) em_ch4 = MethaneEmission( catchment=catchment_1, reservoir=reservoir_1, monthly_temp=inputs.mt) net_areal_co2 = em_co2.factor( number_of_years = inputs.year_profile[-1]) net_areal_ch4 = em_ch4.factor() net_areal_total = net_areal_co2 + net_areal_ch4 return EmissionResults( net_co2=net_areal_co2, net_ch4=net_areal_ch4, net_total=net_areal_total )

3. Source inputs and instantiate the EmissionModel object for batch emission calculations

[ ]:
if not exists(pathlib.Path('./inputs.json')):
    # Download the required input file from an external link
    !gdown 1T9Pal8h9Ce6phw1qdPM5AkuZM_hnvBGT
input_data = Inputs.fromfile('inputs.json')
model_batch = EmissionModel(inputs=input_data, p_model='g-res')

4. Modify individual configuration parameters in global config on-the-fly using config.update

[ ]:
# Calculate emissions with manually defined inputs and inputs sourced from inputs .json file
rprint("Calculating emissions with the default `k1_diff` value")
reset_all_configs() # Resets config to defaults
model_outputs_step_by_step = calculate_emissions_step_by_step(inputs, p_calc_method='g-res')
rprint(model_outputs_step_by_step)
model_batch.calculate()
outputs_batch = model_batch.outputs
rprint("")
rprint("Reservoir 1 CO2 net emissions: ", outputs_batch['Reservoir 1']['co2_net'])
rprint("Reservoir 1 CH4 net emissions: ", outputs_batch['Reservoir 1']['ch4_net'])
rprint("Reservoir 1 total net emissions: ", outputs_batch['Reservoir 1']['co2_net'] + outputs_batch['Reservoir 1']['ch4_net'])
# Recalculate emissions after modifying the value of k1_diff parameter for CO2 emission calculations
rprint("\nCalculating emissions with the modified `k1_diff` value")
config.update("model_config", {("CARBON_DIOXIDE",): {"k1_diff": 0.5}})
model_outputs_step_by_step = calculate_emissions_step_by_step(inputs, p_calc_method='g-res')
rprint(model_outputs_step_by_step)
model_batch.calculate()
outputs_batch = model_batch.outputs
rprint("")
rprint("Reservoir 1 CO2 net emissions: ", outputs_batch['Reservoir 1']['co2_net'])
rprint("Reservoir 1 CH4 net emissions: ", outputs_batch['Reservoir 1']['ch4_net'])
rprint("Reservoir 1 total net emissions: ", outputs_batch['Reservoir 1']['co2_net'] + outputs_batch['Reservoir 1']['ch4_net'])

5. Run the model with the updated k1_diff value by overriding config with custom_config.ini and config.override method

[ ]:
# Calculate emissions with manually defined inputs and inputs sourced from inputs .json file
rprint("Calculating emissions with the default 'model_config'")
reset_all_configs() # Resets config to defaults
model_outputs_step_by_step = calculate_emissions_step_by_step(inputs, p_calc_method='g-res')
rprint(model_outputs_step_by_step)
model_batch.calculate()
outputs_batch = model_batch.outputs
rprint("")
rprint("Reservoir 1 CO2 net emissions: ", outputs_batch['Reservoir 1']['co2_net'])
rprint("Reservoir 1 CH4 net emissions: ", outputs_batch['Reservoir 1']['ch4_net'])
rprint("Reservoir 1 total net emissions: ",
      outputs_batch['Reservoir 1']['co2_net'] + outputs_batch['Reservoir 1']['ch4_net'])
# Recalculate emissions after modifying the value of k1_diff parameter for CO2 emission calculations
rprint("\nCalculating emissions with custom 'model_config' containing modified `k1_diff` value")
config.override("model_config", 'custom_config.ini')

model_outputs_step_by_step = calculate_emissions_step_by_step(inputs, p_calc_method='g-res')
rprint(model_outputs_step_by_step)
model_batch.calculate()
outputs_batch = model_batch.outputs
rprint("")
rprint("Reservoir 1 CO2 net emissions: ", outputs_batch['Reservoir 1']['co2_net'])
rprint("Reservoir 1 CH4 net emissions: ", outputs_batch['Reservoir 1']['ch4_net'])
rprint("Reservoir 1 total net emissions: ",
      outputs_batch['Reservoir 1']['co2_net'] + outputs_batch['Reservoir 1']['ch4_net'])

Open in Colab

On this page

  • 2. Define a function that goes through all steps of emission calculations and returns net areal CO2, CH4 emissions and total net aerial emissions
  • 3. Source inputs and instantiate the EmissionModel object for batch emission calculations
  • 4. Modify individual configuration parameters in global config on-the-fly using config.update
  • 5. Run the model with the updated k1_diff value by overriding config with custom_config.ini and config.override method

© 2024, Tomasz Janus, University of Manchester, United Kingdom Built with Sphinx 8.1.3