dynamic-characterization 1.3.1__tar.gz → 1.4.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. {dynamic_characterization-1.3.1/dynamic_characterization.egg-info → dynamic_characterization-1.4.1}/PKG-INFO +4 -4
  2. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/README.md +3 -3
  3. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/__init__.py +2 -2
  4. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/dynamic_characterization.py +188 -20
  5. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/ipcc_ar6/radiative_forcing.py +86 -95
  6. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/__init__.py +1 -1
  7. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/agtp.py +1 -1
  8. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/agwp.py +1 -1
  9. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/config.py +1 -1
  10. dynamic_characterization-1.4.1/dynamic_characterization/prospective/data/es5c12391_si_001.xlsx +0 -0
  11. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/radiative_forcing.py +4 -4
  12. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1/dynamic_characterization.egg-info}/PKG-INFO +4 -4
  13. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization.egg-info/SOURCES.txt +1 -0
  14. dynamic_characterization-1.4.1/tests/test_default_characterization_functions.py +210 -0
  15. dynamic_characterization-1.3.1/dynamic_characterization/prospective/data/es5c12391_si_001.xlsx +0 -0
  16. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/LICENSE +0 -0
  17. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/MANIFEST.in +0 -0
  18. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/classes.py +0 -0
  19. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/ipcc_ar6/__init__.py +0 -0
  20. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/ipcc_ar6/data/decay_multipliers.json +0 -0
  21. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/ipcc_ar6/data/hodnebrog20.csv +0 -0
  22. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/original_temporalis_functions/__init__.py +0 -0
  23. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/original_temporalis_functions/radiative_forcing.py +0 -0
  24. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_002.xlsx +0 -0
  25. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_003.xlsx +0 -0
  26. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_004.xlsx +0 -0
  27. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_009.xlsx +0 -0
  28. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_010.xlsx +0 -0
  29. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_011.xlsx +0 -0
  30. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_012.xlsx +0 -0
  31. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_013.xlsx +0 -0
  32. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_014.xlsx +0 -0
  33. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_015.xlsx +0 -0
  34. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_016.xlsx +0 -0
  35. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_017.xlsx +0 -0
  36. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_018.xlsx +0 -0
  37. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_019.xlsx +0 -0
  38. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_020.xlsx +0 -0
  39. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_021.xlsx +0 -0
  40. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_022.xlsx +0 -0
  41. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_023.xlsx +0 -0
  42. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_024.xlsx +0 -0
  43. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_025.xlsx +0 -0
  44. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data/es5c12391_si_026.xlsx +0 -0
  45. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization/prospective/data_loader.py +0 -0
  46. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization.egg-info/dependency_links.txt +0 -0
  47. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization.egg-info/requires.txt +0 -0
  48. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/dynamic_characterization.egg-info/top_level.txt +0 -0
  49. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/pyproject.toml +0 -0
  50. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/setup.cfg +0 -0
  51. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/tests/test_characterize_dynamic_inventory.py +0 -0
  52. {dynamic_characterization-1.3.1 → dynamic_characterization-1.4.1}/tests/test_prospective.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dynamic_characterization
3
- Version: 1.3.1
3
+ Version: 1.4.1
4
4
  Summary: Collection of functions for characterizing life cycle inventories with temporal information
5
5
  Author-email: Timo Diepers <timo.diepers@ltt.rwth-aachen.de>
6
6
  Maintainer-email: Timo Diepers <timo.diepers@ltt.rwth-aachen.de>
@@ -54,7 +54,7 @@ The following dynamic characterization functions are currently included:
54
54
  | module |impact category | metric | covered emissions | source
55
55
  |--------|-------|----------|----------|--|
56
56
  | ipcc_ar6 | climate change | radiative forcing, GWP | 247 GHGs | radiative efficiencies & lifetimes from [IPCC AR6 Ch.7](https://www.ipcc.ch/report/ar6/wg1/chapter/chapter-7/) |
57
- | prospective | climate change | prospective_radiative_forcing, pGWP, pGTP | CO2, CH4, N2O | prospective characterization factors from [Barbosa Watanabe et al. (2026)](https://pubs.acs.org/doi/10.1021/acs.est.5c12391) |
57
+ | prospective | climate change | prospective radiative forcing, pGWP, pGTP | CO2, CH4, N2O | [Watanabe et al. (2026)](https://pubs.acs.org/doi/10.1021/acs.est.5c12391) |
58
58
  | original_temporalis_functions| climate change | radiative forcing | CO2, CH4 |[bw_temporalis](https://github.com/brightway-lca/bw_temporalis/tree/main)|
59
59
 
60
60
  ## What do dynamic characterization functions do?
@@ -130,11 +130,11 @@ df_characterized = characterize(
130
130
 
131
131
  ## Prospective Characterization
132
132
 
133
- The `prospective` module provides **prospective characterization factors** based on [Barbosa Watanabe et al. (2026)](https://pubs.acs.org/doi/10.1021/acs.est.5c12391). These factors account for how radiative efficiencies change over time under different climate scenarios, making them more appropriate for future-oriented LCA studies.
133
+ The `prospective` module provides **prospective characterization factors** based on [Watanabe et al. (2026)](https://pubs.acs.org/doi/10.1021/acs.est.5c12391). These factors account for how radiative efficiencies change over time under different climate scenarios, making them more appropriate for future-oriented LCA studies. This particularly enables more temporally consistent results when used alongside IAM-based prospective LCI adaptations, e.g., in [time-explicit LCA](https://link.springer.com/article/10.1007/s11367-025-02539-3).
134
134
 
135
135
  > For an interactive demo of pLCIA, [open the example notebook on Binder](https://mybinder.org/v2/gh/brightway-lca/dynamic_characterization/main?labpath=notebooks%2Fprospective_dynamic_lcia_demo.ipynb)
136
136
 
137
- > NOTE: Currently, only the IAM scenarios and pathways from Barbosa Watanabe et al. (2026) are supported. This will change soon.
137
+ > NOTE: Currently, only the IAM scenarios and pathways from Watanabe et al. (2026) are supported. This will change soon.
138
138
 
139
139
  ### Setting up a scenario
140
140
 
@@ -13,7 +13,7 @@ The following dynamic characterization functions are currently included:
13
13
  | module |impact category | metric | covered emissions | source
14
14
  |--------|-------|----------|----------|--|
15
15
  | ipcc_ar6 | climate change | radiative forcing, GWP | 247 GHGs | radiative efficiencies & lifetimes from [IPCC AR6 Ch.7](https://www.ipcc.ch/report/ar6/wg1/chapter/chapter-7/) |
16
- | prospective | climate change | prospective_radiative_forcing, pGWP, pGTP | CO2, CH4, N2O | prospective characterization factors from [Barbosa Watanabe et al. (2026)](https://pubs.acs.org/doi/10.1021/acs.est.5c12391) |
16
+ | prospective | climate change | prospective radiative forcing, pGWP, pGTP | CO2, CH4, N2O | [Watanabe et al. (2026)](https://pubs.acs.org/doi/10.1021/acs.est.5c12391) |
17
17
  | original_temporalis_functions| climate change | radiative forcing | CO2, CH4 |[bw_temporalis](https://github.com/brightway-lca/bw_temporalis/tree/main)|
18
18
 
19
19
  ## What do dynamic characterization functions do?
@@ -89,11 +89,11 @@ df_characterized = characterize(
89
89
 
90
90
  ## Prospective Characterization
91
91
 
92
- The `prospective` module provides **prospective characterization factors** based on [Barbosa Watanabe et al. (2026)](https://pubs.acs.org/doi/10.1021/acs.est.5c12391). These factors account for how radiative efficiencies change over time under different climate scenarios, making them more appropriate for future-oriented LCA studies.
92
+ The `prospective` module provides **prospective characterization factors** based on [Watanabe et al. (2026)](https://pubs.acs.org/doi/10.1021/acs.est.5c12391). These factors account for how radiative efficiencies change over time under different climate scenarios, making them more appropriate for future-oriented LCA studies. This particularly enables more temporally consistent results when used alongside IAM-based prospective LCI adaptations, e.g., in [time-explicit LCA](https://link.springer.com/article/10.1007/s11367-025-02539-3).
93
93
 
94
94
  > For an interactive demo of pLCIA, [open the example notebook on Binder](https://mybinder.org/v2/gh/brightway-lca/dynamic_characterization/main?labpath=notebooks%2Fprospective_dynamic_lcia_demo.ipynb)
95
95
 
96
- > NOTE: Currently, only the IAM scenarios and pathways from Barbosa Watanabe et al. (2026) are supported. This will change soon.
96
+ > NOTE: Currently, only the IAM scenarios and pathways from Watanabe et al. (2026) are supported. This will change soon.
97
97
 
98
98
  ### Setting up a scenario
99
99
 
@@ -3,7 +3,7 @@ Collection of dynamic characterization functions for life cycle inventories with
3
3
 
4
4
  Provides:
5
5
  - ipcc_ar6: IPCC AR6-based characterization functions for CO2, CH4, N2O, etc.
6
- - prospective: Prospective characterization factors from Barbosa Watanabe et al. (2026)
6
+ - prospective: Prospective characterization factors from Watanabe et al. (2026)
7
7
  - original_temporalis_functions: Legacy functions from bw_temporalis
8
8
 
9
9
  For prospective metrics (pGWP, pGTP), set the scenario first:
@@ -20,7 +20,7 @@ __all__ = (
20
20
  "prospective",
21
21
  )
22
22
 
23
- __version__ = "1.3.1"
23
+ __version__ = "1.4.1"
24
24
 
25
25
  from . import ipcc_ar6, original_temporalis_functions, prospective
26
26
  from .dynamic_characterization import (
@@ -1,6 +1,8 @@
1
+ import inspect
1
2
  import json
2
3
  import os
3
4
  import warnings
5
+ from collections import namedtuple
4
6
  from collections.abc import Collection
5
7
  from datetime import datetime
6
8
  from typing import Callable, Dict, Tuple
@@ -29,6 +31,17 @@ from dynamic_characterization.prospective.radiative_forcing import (
29
31
  )
30
32
 
31
33
 
34
+ # Building the default characterization functions reloads decay_multipliers.json and
35
+ # issues one biosphere DB query per method flow. The result only depends on the BW
36
+ # project, the method, and the boolean flags, so it is memoized across calls.
37
+ _CHARACTERIZATION_FUNCTION_CACHE = {}
38
+
39
+
40
+ def clear_characterization_function_cache() -> None:
41
+ """Clear the memoized default characterization functions (e.g. after editing a method)."""
42
+ _CHARACTERIZATION_FUNCTION_CACHE.clear()
43
+
44
+
32
45
  def characterize(
33
46
  dynamic_inventory_df: pd.DataFrame,
34
47
  metric: str = "radiative_forcing",
@@ -40,12 +53,13 @@ def characterize(
40
53
  characterization_function_co2: Callable = None,
41
54
  time_varying_re: bool = False,
42
55
  fallback_to_ipcc: bool = True,
56
+ characterize_biogenic_uptake: bool = True,
43
57
  ) -> pd.DataFrame:
44
58
  """
45
59
  Characterizes the dynamic inventory, formatted as a Dataframe, by evaluating each emission (row in DataFrame) using given dynamic characterization functions.
46
60
 
47
61
  Available metrics are radiative forcing [W/m2] and GWP [kg CO2eq], defaulting to `radiative_forcing`.
48
- Additional prospective metrics pGWP, pGTP, and prospective_radiative_forcing use Barbosa Watanabe et al. (2026)
62
+ Additional prospective metrics pGWP, pGTP, and prospective_radiative_forcing use Watanabe et al. (2026)
49
63
  scenario-based characterization factors. For these, set the scenario first via prospective.set_scenario().
50
64
 
51
65
  In case users don't provide own dynamic characterization functions, it adds dynamic characterization functions from the timex submodule
@@ -65,9 +79,9 @@ def characterize(
65
79
  The metric for which the dynamic LCIA should be calculated. Available: "radiative_forcing", "GWP", "pGWP", "pGTP", "prospective_radiative_forcing". Default is "radiative_forcing".
66
80
  - "radiative_forcing": Returns W/m2 time series using IPCC AR6 functions
67
81
  - "GWP": Returns kg CO2eq using IPCC AR6 functions
68
- - "pGWP": Returns kg CO2eq using Barbosa Watanabe et al. (2026) prospective GWP (requires scenario)
69
- - "pGTP": Returns kg CO2eq using Barbosa Watanabe et al. (2026) prospective GTP (requires scenario)
70
- - "prospective_radiative_forcing": Returns W/m2 time series using Barbosa Watanabe et al. (2026) functions (requires scenario)
82
+ - "pGWP": Returns kg CO2eq using Watanabe et al. (2026) prospective GWP (requires scenario)
83
+ - "pGTP": Returns kg CO2eq using Watanabe et al. (2026) prospective GTP (requires scenario)
84
+ - "prospective_radiative_forcing": Returns W/m2 time series using Watanabe et al. (2026) functions (requires scenario)
71
85
  characterization_functions : dict, optional
72
86
  A dictionary of the form {biosphere_flow_id: dynamic_characterization_function} allowing users to specify their own functions and what flows to apply them to.
73
87
  Default is none, in which case a set of default functions are added based on the base_lcia_method.
@@ -88,7 +102,11 @@ def characterize(
88
102
  fallback_to_ipcc: bool, optional
89
103
  Only for prospective metrics. If True (default), use IPCC AR6 characterization functions for GHGs not available
90
104
  in the Watanabe module (e.g., CO and other GHGs). If False, only GHGs available in Watanabe (CO2, CH4, N2O) are characterized.
91
-
105
+ characterize_biogenic_uptake: bool, optional
106
+ Whether to characterize biogenic uptake flows (e.g. CO2 uptake by soil or biomass, or CDR processes).
107
+ If True, the default characterization functions include uptake flows and these are characterized with a negative emission profile. Default is True.
108
+ Set to False if you want to explicitly model uptake outside of the dynamic characterization (e.g. from a forest model)
109
+
92
110
  Returns
93
111
  -------
94
112
  pd.DataFrame
@@ -116,12 +134,25 @@ def characterize(
116
134
  functions on."
117
135
  )
118
136
  characterization_functions = create_characterization_functions_from_method(
119
- base_lcia_method, use_prospective=use_prospective, fallback_to_ipcc=fallback_to_ipcc
137
+ base_lcia_method, use_prospective=use_prospective, fallback_to_ipcc=fallback_to_ipcc, characterize_uptake=characterize_biogenic_uptake
120
138
  )
121
139
 
122
140
  if metric == "GWP" and not characterization_function_co2:
123
141
  characterization_function_co2 = characterize_co2
124
142
 
143
+ # Fast path: for the (default) radiative_forcing metric without a fixed time
144
+ # horizon, every row of a given flow uses the same characterization function
145
+ # with the same period. The per-emission response is linear in the emission
146
+ # amount and its shape is independent of the emission date, so we can evaluate
147
+ # each characterization function once per flow and broadcast over all its rows
148
+ # instead of iterating the inventory row by row.
149
+ if metric == "radiative_forcing" and not fixed_time_horizon:
150
+ vectorized = _vectorized_radiative_forcing(
151
+ dynamic_inventory_df, characterization_functions, time_horizon
152
+ )
153
+ if vectorized is not None:
154
+ return vectorized
155
+
125
156
  characterized_inventory_data = []
126
157
 
127
158
  for row in dynamic_inventory_df.itertuples(index=False):
@@ -207,14 +238,125 @@ def characterize(
207
238
  return characterized_inventory
208
239
 
209
240
 
241
+ _VectorizationRow = namedtuple(
242
+ "_VectorizationRow", ["date", "amount", "flow", "activity"]
243
+ )
244
+
245
+
246
+ def _vectorized_radiative_forcing(
247
+ dynamic_inventory_df: pd.DataFrame,
248
+ characterization_functions: Dict[int, Callable],
249
+ period: int,
250
+ ):
251
+ """
252
+ Vectorized evaluation of the ``radiative_forcing`` metric without a fixed
253
+ time horizon.
254
+
255
+ Each characterization function is evaluated once per flow (in cumulative
256
+ mode, giving the signed per-unit decay array) and then broadcast over all
257
+ inventory rows of that flow. ``np.diff`` is applied to ``amount * decay``
258
+ exactly as in the per-row implementation, so the result is bit-for-bit
259
+ identical to the row-by-row loop.
260
+
261
+ Returns the characterized inventory DataFrame, or ``None`` to signal that
262
+ the caller should fall back to the generic row-by-row loop (nothing to
263
+ characterize, a function without a ``cumulative`` keyword, or an unexpected
264
+ response length).
265
+ """
266
+ flow_values = dynamic_inventory_df["flow"].to_numpy()
267
+ known = np.fromiter(
268
+ (f in characterization_functions for f in flow_values),
269
+ dtype=bool,
270
+ count=len(flow_values),
271
+ )
272
+ if not known.any():
273
+ return None # let the row loop emit the "nothing to characterize" warning
274
+
275
+ df = dynamic_inventory_df.loc[known]
276
+ dates_all = df["date"].to_numpy()
277
+ amounts_all = df["amount"].to_numpy().astype("float64")
278
+ flows_all = df["flow"].to_numpy()
279
+ activities_all = df["activity"].to_numpy()
280
+
281
+ # timedelta offsets identical to those built inside every IPCC AR6 / generic
282
+ # characterization function
283
+ offsets = np.arange(start=0, stop=period, dtype="timedelta64[Y]").astype(
284
+ "timedelta64[s]"
285
+ )
286
+
287
+ date_blocks = []
288
+ amount_blocks = []
289
+ flow_blocks = []
290
+ activity_blocks = []
291
+
292
+ for flow_id in pd.unique(flows_all):
293
+ func = characterization_functions[flow_id]
294
+
295
+ # The fast path calls the function in cumulative mode to obtain the
296
+ # signed per-unit decay array. If it does not accept `cumulative`, or
297
+ # returns an unexpected length, fall back to the safe row loop.
298
+ try:
299
+ params = inspect.signature(func).parameters
300
+ except (TypeError, ValueError):
301
+ return None
302
+ if "cumulative" not in params:
303
+ return None
304
+
305
+ mask = flows_all == flow_id
306
+ sub_dates = dates_all[mask]
307
+ sub_amounts = amounts_all[mask]
308
+ sub_activities = activities_all[mask]
309
+
310
+ sample = _VectorizationRow(
311
+ date=pd.Timestamp(sub_dates[0]),
312
+ amount=1.0,
313
+ flow=flow_id,
314
+ activity=sub_activities[0],
315
+ )
316
+ unit_cumulative = np.asarray(
317
+ func(sample, period, cumulative=True).amount, dtype="float64"
318
+ )
319
+ if unit_cumulative.shape != (period,):
320
+ return None
321
+
322
+ # forcing[i, k] = amount_i * decay_k, then marginalized with np.diff,
323
+ # exactly reproducing the per-row `np.diff(amount * decay, prepend=0)`
324
+ forcing = sub_amounts[:, None] * unit_cumulative[None, :]
325
+ forcing = np.diff(forcing, prepend=0, axis=1)
326
+
327
+ n = sub_amounts.shape[0]
328
+ date_blocks.append((sub_dates[:, None] + offsets[None, :]).reshape(-1))
329
+ amount_blocks.append(forcing.reshape(-1))
330
+ flow_blocks.append(np.full(n * period, flow_id))
331
+ activity_blocks.append(np.repeat(sub_activities, period))
332
+
333
+ characterized_inventory = (
334
+ pd.DataFrame(
335
+ {
336
+ "date": np.concatenate(date_blocks),
337
+ "amount": np.concatenate(amount_blocks),
338
+ "flow": np.concatenate(flow_blocks),
339
+ "activity": np.concatenate(activity_blocks),
340
+ }
341
+ )
342
+ .astype({"date": "datetime64[s]", "amount": "float64"})
343
+ .query("amount != 0")[["date", "amount", "flow", "activity"]]
344
+ .sort_values(by=["date", "amount"])
345
+ .reset_index(drop=True)
346
+ )
347
+
348
+ return characterized_inventory
349
+
350
+
210
351
  def create_characterization_functions_from_method(
211
352
  base_lcia_method: Tuple[str, ...],
212
353
  use_prospective: bool = False,
213
354
  fallback_to_ipcc: bool = True,
355
+ characterize_uptake: bool = True,
214
356
  ) -> dict:
215
357
  """
216
358
  Add default dynamic characterization functions for CO2, CH4, N2O and other GHGs, based on IPCC
217
- AR6 Chapter 7 decay curves. If use_prospective=True, uses Barbosa Watanabe et al. (2026) functions
359
+ AR6 Chapter 7 decay curves. If use_prospective=True, uses Watanabe et al. (2026) functions
218
360
  for CO2, CH4, and N2O (requires scenario to be set first).
219
361
 
220
362
  Please note: Currently, only CO2, CH4 and N2O include climate-carbon feedbacks.
@@ -228,12 +370,16 @@ def create_characterization_functions_from_method(
228
370
  base_lcia_method : tuple
229
371
  Tuple of the selected the LCIA method, e.g. `("EF v3.1", "climate change", "global warming potential (GWP100)")`.
230
372
  use_prospective : bool, optional
231
- If True, use Barbosa Watanabe et al. (2026) prospective characterization functions for CO2, CH4, N2O.
373
+ If True, use Watanabe et al. (2026) prospective characterization functions for CO2, CH4, N2O.
232
374
  Default is False.
233
375
  fallback_to_ipcc : bool, optional
234
376
  Only relevant when use_prospective=True. If True (default), use IPCC AR6 characterization functions
235
377
  for GHGs not available in the Watanabe module (e.g., CO and other GHGs). If False, only GHGs
236
378
  available in Watanabe (CO2, CH4, N2O) are characterized.
379
+ characterize_uptake: bool, optional
380
+ Whether to include characterization functions for biogenic uptake flows (e.g. CO2 uptake by soil or biomass, or CDR processes).
381
+ If True (default), the default characterization functions include uptake. Set to False
382
+ if you want to explicitly model uptake outside of the dynamic characterization (e.g. from a forest model)
237
383
 
238
384
  Returns
239
385
  -------
@@ -242,6 +388,17 @@ def create_characterization_functions_from_method(
242
388
 
243
389
  """
244
390
 
391
+ cache_key = (
392
+ bd.projects.current,
393
+ tuple(base_lcia_method),
394
+ use_prospective,
395
+ fallback_to_ipcc,
396
+ characterize_uptake,
397
+ )
398
+ cached = _CHARACTERIZATION_FUNCTION_CACHE.get(cache_key)
399
+ if cached is not None:
400
+ return cached
401
+
245
402
  characterization_functions = dict()
246
403
 
247
404
  filepath = os.path.join(
@@ -300,16 +457,26 @@ def create_characterization_functions_from_method(
300
457
 
301
458
  for node in bioflow_nodes:
302
459
  if "carbon dioxide" in node["name"].lower():
303
- if "soil" in node.get("categories", []):
304
- characterization_functions[node.id] = (
305
- co2_uptake_func # negative emission because uptake by soil
306
- )
307
- elif "in air" in node.get("categories", []) and node.get("type", []) == 'natural resource':
308
- # CO2 as a natural resource in air is assumed to be used for uptake in CDR processes
309
- characterization_functions[node.id] = (
310
- co2_uptake_func # negative emission because uptake by CDR processes
311
- )
460
+ categories = node.get("categories") or ()
461
+ # uptake by soil, i.e. CO2 leaving the technosphere towards the soil compartment.
462
+ # Only the categories are checked, so that emissions to air from flows like
463
+ # "Carbon dioxide, from soil or biomass stock" are not misread as uptake.
464
+ is_soil_uptake = "soil" in categories
465
+ # CO2 as a natural resource in air is assumed to be used for uptake in biomass
466
+ # or CDR processes
467
+ is_uptake_resource = (
468
+ "in air" in categories and node.get("type") == "natural resource"
469
+ )
470
+
471
+ if is_soil_uptake or is_uptake_resource:
472
+ if characterize_uptake:
473
+ characterization_functions[node.id] = (
474
+ co2_uptake_func # negative emission because of uptake
475
+ )
476
+ # else: uptake is modelled outside of the dynamic characterization,
477
+ # so these flows are intentionally left uncharacterized
312
478
  else:
479
+ # all remaining CO2 flows are emissions, regardless of the air subcategory
313
480
  characterization_functions[node.id] = co2_func
314
481
 
315
482
  elif (
@@ -337,6 +504,7 @@ def create_characterization_functions_from_method(
337
504
  characterization_functions[node.id] = (
338
505
  create_generic_characterization_function(np.array(decay_series))
339
506
  )
507
+ _CHARACTERIZATION_FUNCTION_CACHE[cache_key] = characterization_functions
340
508
  return characterization_functions
341
509
 
342
510
 
@@ -423,7 +591,7 @@ def _characterize_pgwp(
423
591
  time_varying_re: bool = False,
424
592
  ) -> CharacterizedRow:
425
593
  """
426
- Calculate prospective GWP using Barbosa Watanabe et al. (2026) characterization.
594
+ Calculate prospective GWP using Watanabe et al. (2026) characterization.
427
595
 
428
596
  Uses AGWP_gas / AGWP_CO2 to calculate kg CO2 equivalent.
429
597
  Emission year is extracted from the row's date.
@@ -466,7 +634,7 @@ def _characterize_pgtp(
466
634
  time_varying_re: bool = False,
467
635
  ) -> CharacterizedRow:
468
636
  """
469
- Calculate prospective GTP using Barbosa Watanabe et al. (2026) characterization.
637
+ Calculate prospective GTP using Watanabe et al. (2026) characterization.
470
638
 
471
639
  Uses AGTP_gas / AGTP_CO2 to calculate kg CO2 equivalent.
472
640
  Emission year is extracted from the row's date.
@@ -535,7 +703,7 @@ def _characterize_prospective_radiative_forcing(
535
703
  time_varying_re: bool = False,
536
704
  ) -> CharacterizedRow:
537
705
  """
538
- Calculate prospective radiative forcing using Barbosa Watanabe et al. (2026) characterization.
706
+ Calculate prospective radiative forcing using Watanabe et al. (2026) characterization.
539
707
 
540
708
  For GHGs available in Watanabe (CO2, CH4, N2O), uses scenario-based radiative efficiencies.
541
709
  For other GHGs (when fallback_to_ipcc=True), uses standard IPCC AR6 functions.
@@ -1,3 +1,5 @@
1
+ from functools import lru_cache
2
+
1
3
  import numpy as np
2
4
  import pandas as pd
3
5
 
@@ -30,6 +32,85 @@ def IRF_co2(year) -> callable:
30
32
  )
31
33
 
32
34
 
35
+ # The decay-multiplier arrays below depend only on `period`, not on the emission
36
+ # row, so they were previously recomputed for every row of the inventory. They are
37
+ # memoized here and returned read-only; callers only ever multiply by them.
38
+ @lru_cache(maxsize=None)
39
+ def _co2_decay_multipliers(period: int) -> np.ndarray:
40
+ radiative_efficiency_ppb = 1.33e-5
41
+ M_co2 = 44.01
42
+ M_air = 28.97
43
+ m_atmosphere = 5.135e18
44
+ radiative_efficiency_kg = (
45
+ radiative_efficiency_ppb * M_air / M_co2 * 1e9 / m_atmosphere
46
+ )
47
+ arr = np.array(
48
+ [radiative_efficiency_kg * IRF_co2(year) for year in range(period)]
49
+ )
50
+ arr.setflags(write=False)
51
+ return arr
52
+
53
+
54
+ @lru_cache(maxsize=None)
55
+ def _co_decay_multipliers(period: int) -> np.ndarray:
56
+ radiative_efficiency_ppb = 1.33e-5
57
+ M_co2 = 44.01
58
+ M_co = 28.01
59
+ M_air = 28.97
60
+ m_atmosphere = 5.135e18
61
+ radiative_efficiency_kg = (
62
+ radiative_efficiency_ppb * M_air / M_co2 * 1e9 / m_atmosphere
63
+ )
64
+ arr = np.array(
65
+ [
66
+ M_co2 / M_co * radiative_efficiency_kg * IRF_co2(year)
67
+ for year in range(period)
68
+ ]
69
+ )
70
+ arr.setflags(write=False)
71
+ return arr
72
+
73
+
74
+ @lru_cache(maxsize=None)
75
+ def _ch4_decay_multipliers(period: int) -> np.ndarray:
76
+ radiative_efficiency_ppb = 5.7e-4
77
+ M_ch4 = 16.04
78
+ M_air = 28.97
79
+ m_atmosphere = 5.135e18
80
+ radiative_efficiency_kg = (
81
+ radiative_efficiency_ppb * M_air / M_ch4 * 1e9 / m_atmosphere
82
+ )
83
+ tau = 11.8
84
+ arr = np.array(
85
+ [
86
+ radiative_efficiency_kg * tau * (1 - np.exp(-year / tau))
87
+ for year in range(period)
88
+ ]
89
+ )
90
+ arr.setflags(write=False)
91
+ return arr
92
+
93
+
94
+ @lru_cache(maxsize=None)
95
+ def _n2o_decay_multipliers(period: int) -> np.ndarray:
96
+ radiative_efficiency_ppb = 2.8e-3
97
+ M_n2o = 44.01
98
+ M_air = 28.97
99
+ m_atmosphere = 5.135e18
100
+ radiative_efficiency_kg = (
101
+ radiative_efficiency_ppb * M_air / M_n2o * 1e9 / m_atmosphere
102
+ )
103
+ tau = 109
104
+ arr = np.array(
105
+ [
106
+ radiative_efficiency_kg * tau * (1 - np.exp(-year / tau))
107
+ for year in range(period)
108
+ ]
109
+ )
110
+ arr.setflags(write=False)
111
+ return arr
112
+
113
+
33
114
  def characterize_co2(
34
115
  series,
35
116
  period: int | None = 100,
@@ -60,28 +141,12 @@ def characterize_co2(
60
141
  Forster2023: Updated numerical values from IPCC AR6 Chapter 7 (Table 7.15): https://doi.org/10.1017/9781009157896.009
61
142
  """
62
143
 
63
- # functional variables and units (from publications listed in docstring)
64
- radiative_efficiency_ppb = (
65
- 1.33e-5 # W/m2/ppb; 2019 background co2 concentration; IPCC AR6 Table 7.15
66
- )
67
-
68
- # for conversion from ppb to kg-CO2
69
- M_co2 = 44.01 # g/mol
70
- M_air = 28.97 # g/mol, dry air
71
- m_atmosphere = 5.135e18 # kg [Trenberth and Smith, 2005]
72
-
73
- radiative_efficiency_kg = (
74
- radiative_efficiency_ppb * M_air / M_co2 * 1e9 / m_atmosphere
75
- ) # W/m2/kg-CO2
76
-
77
144
  date_beginning: np.datetime64 = series.date.to_numpy()
78
145
  dates_characterized: np.ndarray = date_beginning + np.arange(
79
146
  start=0, stop=period, dtype="timedelta64[Y]"
80
147
  ).astype("timedelta64[s]")
81
148
 
82
- decay_multipliers: np.ndarray = np.array(
83
- [radiative_efficiency_kg * IRF_co2(year) for year in range(period)]
84
- )
149
+ decay_multipliers = _co2_decay_multipliers(period)
85
150
 
86
151
  forcing = np.array(series.amount * decay_multipliers, dtype="float64")
87
152
 
@@ -128,28 +193,12 @@ def characterize_co2_uptake(
128
193
  Forster2023: Updated numerical values from IPCC AR6 Chapter 7 (Table 7.15): https://doi.org/10.1017/9781009157896.009
129
194
  """
130
195
 
131
- # functional variables and units (from publications listed in docstring)
132
- radiative_efficiency_ppb = (
133
- 1.33e-5 # W/m2/ppb; 2019 background co2 concentration; IPCC AR6 Table 7.15
134
- )
135
-
136
- # for conversion from ppb to kg-CO2
137
- M_co2 = 44.01 # g/mol
138
- M_air = 28.97 # g/mol, dry air
139
- m_atmosphere = 5.135e18 # kg [Trenberth and Smith, 2005]
140
-
141
- radiative_efficiency_kg = (
142
- radiative_efficiency_ppb * M_air / M_co2 * 1e9 / m_atmosphere
143
- ) # W/m2/kg-CO2
144
-
145
196
  date_beginning: np.datetime64 = series.date.to_numpy()
146
197
  dates_characterized: np.ndarray = date_beginning + np.arange(
147
198
  start=0, stop=period, dtype="timedelta64[Y]"
148
199
  ).astype("timedelta64[s]")
149
200
 
150
- decay_multipliers: np.ndarray = np.array(
151
- [radiative_efficiency_kg * IRF_co2(year) for year in range(period)]
152
- )
201
+ decay_multipliers = _co2_decay_multipliers(period)
153
202
 
154
203
  forcing = np.array(series.amount * decay_multipliers, dtype="float64")
155
204
 
@@ -201,32 +250,12 @@ def characterize_co(
201
250
  Forster2023: Updated numerical values from IPCC AR6 Chapter 7 (Table 7.15): https://doi.org/10.1017/9781009157896.009
202
251
  """
203
252
 
204
- # functional variables and units (from publications listed in docstring)
205
- radiative_efficiency_ppb = (
206
- 1.33e-5 # W/m2/ppb; 2019 background co2 concentration; IPCC AR6 Table 7.15
207
- )
208
-
209
- # for conversion from ppb to kg-CO2
210
- M_co2 = 44.01 # g/mol
211
- M_co = 28.01 # g/mol
212
- M_air = 28.97 # g/mol, dry air
213
- m_atmosphere = 5.135e18 # kg [Trenberth and Smith, 2005]
214
-
215
- radiative_efficiency_kg = (
216
- radiative_efficiency_ppb * M_air / M_co2 * 1e9 / m_atmosphere
217
- ) # W/m2/kg-CO2
218
-
219
253
  date_beginning: np.datetime64 = series.date.to_numpy()
220
254
  dates_characterized: np.ndarray = date_beginning + np.arange(
221
255
  start=0, stop=period, dtype="timedelta64[Y]"
222
256
  ).astype("timedelta64[s]")
223
257
 
224
- decay_multipliers: np.ndarray = np.array(
225
- [
226
- M_co2 / M_co * radiative_efficiency_kg * IRF_co2(year)
227
- for year in range(period)
228
- ] # <-- Scaling from co2 to co is done here
229
- )
258
+ decay_multipliers = _co_decay_multipliers(period)
230
259
 
231
260
  forcing = np.array(series.amount * decay_multipliers, dtype="float64")
232
261
 
@@ -287,31 +316,12 @@ def characterize_ch4(
287
316
  Forster2023: Updated numerical values from IPCC AR6 Chapter 7 (Table 7.15): https://doi.org/10.1017/9781009157896.009
288
317
  """
289
318
 
290
- # functional variables and units (from publications listed in docstring)
291
- radiative_efficiency_ppb = 5.7e-4 # # W/m2/ppb; 2019 background cch4 concentration; IPCC AR6 Table 7.15. This number includes indirect effects.
292
-
293
- # for conversion from ppb to kg-CH4
294
- M_ch4 = 16.04 # g/mol
295
- M_air = 28.97 # g/mol, dry air
296
- m_atmosphere = 5.135e18 # kg [Trenberth and Smith, 2005]
297
-
298
- radiative_efficiency_kg = (
299
- radiative_efficiency_ppb * M_air / M_ch4 * 1e9 / m_atmosphere
300
- ) # W/m2/kg-CH4
301
-
302
- tau = 11.8 # Lifetime (years)
303
-
304
319
  date_beginning: np.datetime64 = series.date.to_numpy()
305
320
  dates_characterized: np.ndarray = date_beginning + np.arange(
306
321
  start=0, stop=period, dtype="timedelta64[Y]"
307
322
  ).astype("timedelta64[s]")
308
323
 
309
- decay_multipliers: list = np.array(
310
- [
311
- radiative_efficiency_kg * tau * (1 - np.exp(-year / tau))
312
- for year in range(period)
313
- ]
314
- )
324
+ decay_multipliers = _ch4_decay_multipliers(period)
315
325
 
316
326
  forcing = np.array(series.amount * decay_multipliers, dtype="float64")
317
327
 
@@ -365,31 +375,12 @@ def characterize_n2o(
365
375
  Forster2023: Updated numerical values from IPCC AR6 Chapter 7 (Table 7.15): https://doi.org/10.1017/9781009157896.009
366
376
  """
367
377
 
368
- # functional variables and units (from publications listed in docstring)
369
- radiative_efficiency_ppb = 2.8e-3 # # W/m2/ppb; 2019 background cch4 concentration; IPCC AR6 Table 7.15. This number includes indirect effects.
370
-
371
- # for conversion from ppb to kg-CH4
372
- M_n2o = 44.01 # g/mol
373
- M_air = 28.97 # g/mol, dry air
374
- m_atmosphere = 5.135e18 # kg [Trenberth and Smith, 2005]
375
-
376
- radiative_efficiency_kg = (
377
- radiative_efficiency_ppb * M_air / M_n2o * 1e9 / m_atmosphere
378
- ) # W/m2/kg-N2O
379
-
380
- tau = 109 # Lifetime (years)
381
-
382
378
  date_beginning: np.datetime64 = series.date.to_numpy()
383
379
  dates_characterized: np.ndarray = date_beginning + np.arange(
384
380
  start=0, stop=period, dtype="timedelta64[Y]"
385
381
  ).astype("timedelta64[s]")
386
382
 
387
- decay_multipliers: list = np.array(
388
- [
389
- radiative_efficiency_kg * tau * (1 - np.exp(-year / tau))
390
- for year in range(period)
391
- ]
392
- )
383
+ decay_multipliers = _n2o_decay_multipliers(period)
393
384
 
394
385
  forcing = np.array(series.amount * decay_multipliers, dtype="float64")
395
386
  if not cumulative:
@@ -1,5 +1,5 @@
1
1
  """
2
- Prospective characterization factors based on Barbosa Watanabe et al. (2026).
2
+ Prospective characterization factors based on Watanabe et al. (2026).
3
3
 
4
4
  Implements scenario-based characterization using time-varying radiative
5
5
  efficiencies from IAM-SSP-RCP scenarios.
@@ -1,7 +1,7 @@
1
1
  """
2
2
  Absolute Global Temperature Potential (AGTP) calculations.
3
3
 
4
- Based on Barbosa Watanabe et al. (2026) using two-layer energy balance model.
4
+ Based on Watanabe et al. (2026) using two-layer energy balance model.
5
5
 
6
6
  AGTP = integral_0^t RF(t') * R(t-t') dt'
7
7
 
@@ -1,7 +1,7 @@
1
1
  """
2
2
  Absolute Global Warming Potential (AGWP) calculations.
3
3
 
4
- Based on Barbosa Watanabe et al. (2026) equations using prospective RE and IRF.
4
+ Based on Watanabe et al. (2026) equations using prospective RE and IRF.
5
5
 
6
6
  AGWP = integral_0^t RE(t') * IRF(t') dt'
7
7
 
@@ -50,7 +50,7 @@ def set_scenario(iam: str, ssp: str, rcp: str) -> None:
50
50
  Raises
51
51
  ------
52
52
  ValueError
53
- If the combination is not valid per Barbosa Watanabe et al. (2026).
53
+ If the combination is not valid per Watanabe et al. (2026).
54
54
  """
55
55
  global _current_scenario
56
56
 
@@ -2,7 +2,7 @@
2
2
  Watanabe prospective characterization functions.
3
3
 
4
4
  Returns radiative forcing time series matching the existing ipcc_ar6 API,
5
- but using scenario-based radiative efficiencies from Barbosa Watanabe et al. (2026).
5
+ but using scenario-based radiative efficiencies from Watanabe et al. (2026).
6
6
 
7
7
  Reference: https://doi.org/10.1021/acs.est.5b01118
8
8
  """
@@ -81,7 +81,7 @@ def characterize_co2(
81
81
  """
82
82
  Calculate radiative forcing time series for 1 kg CO2 emission.
83
83
 
84
- Uses scenario-based radiative efficiencies from Barbosa Watanabe et al. (2026).
84
+ Uses scenario-based radiative efficiencies from Watanabe et al. (2026).
85
85
  Scenario must be set via prospective.set_scenario() before calling.
86
86
 
87
87
  Parameters
@@ -193,7 +193,7 @@ def characterize_ch4(
193
193
  """
194
194
  Calculate radiative forcing time series for 1 kg CH4 emission.
195
195
 
196
- Uses scenario-based radiative efficiencies from Barbosa Watanabe et al. (2026).
196
+ Uses scenario-based radiative efficiencies from Watanabe et al. (2026).
197
197
  Scenario must be set via prospective.set_scenario() before calling.
198
198
 
199
199
  This includes only direct effects. For indirect effects (ozone, water vapor),
@@ -282,7 +282,7 @@ def characterize_n2o(
282
282
  """
283
283
  Calculate radiative forcing time series for 1 kg N2O emission.
284
284
 
285
- Uses scenario-based radiative efficiencies from Barbosa Watanabe et al. (2026).
285
+ Uses scenario-based radiative efficiencies from Watanabe et al. (2026).
286
286
  Scenario must be set via prospective.set_scenario() before calling.
287
287
 
288
288
  Parameters
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dynamic_characterization
3
- Version: 1.3.1
3
+ Version: 1.4.1
4
4
  Summary: Collection of functions for characterizing life cycle inventories with temporal information
5
5
  Author-email: Timo Diepers <timo.diepers@ltt.rwth-aachen.de>
6
6
  Maintainer-email: Timo Diepers <timo.diepers@ltt.rwth-aachen.de>
@@ -54,7 +54,7 @@ The following dynamic characterization functions are currently included:
54
54
  | module |impact category | metric | covered emissions | source
55
55
  |--------|-------|----------|----------|--|
56
56
  | ipcc_ar6 | climate change | radiative forcing, GWP | 247 GHGs | radiative efficiencies & lifetimes from [IPCC AR6 Ch.7](https://www.ipcc.ch/report/ar6/wg1/chapter/chapter-7/) |
57
- | prospective | climate change | prospective_radiative_forcing, pGWP, pGTP | CO2, CH4, N2O | prospective characterization factors from [Barbosa Watanabe et al. (2026)](https://pubs.acs.org/doi/10.1021/acs.est.5c12391) |
57
+ | prospective | climate change | prospective radiative forcing, pGWP, pGTP | CO2, CH4, N2O | [Watanabe et al. (2026)](https://pubs.acs.org/doi/10.1021/acs.est.5c12391) |
58
58
  | original_temporalis_functions| climate change | radiative forcing | CO2, CH4 |[bw_temporalis](https://github.com/brightway-lca/bw_temporalis/tree/main)|
59
59
 
60
60
  ## What do dynamic characterization functions do?
@@ -130,11 +130,11 @@ df_characterized = characterize(
130
130
 
131
131
  ## Prospective Characterization
132
132
 
133
- The `prospective` module provides **prospective characterization factors** based on [Barbosa Watanabe et al. (2026)](https://pubs.acs.org/doi/10.1021/acs.est.5c12391). These factors account for how radiative efficiencies change over time under different climate scenarios, making them more appropriate for future-oriented LCA studies.
133
+ The `prospective` module provides **prospective characterization factors** based on [Watanabe et al. (2026)](https://pubs.acs.org/doi/10.1021/acs.est.5c12391). These factors account for how radiative efficiencies change over time under different climate scenarios, making them more appropriate for future-oriented LCA studies. This particularly enables more temporally consistent results when used alongside IAM-based prospective LCI adaptations, e.g., in [time-explicit LCA](https://link.springer.com/article/10.1007/s11367-025-02539-3).
134
134
 
135
135
  > For an interactive demo of pLCIA, [open the example notebook on Binder](https://mybinder.org/v2/gh/brightway-lca/dynamic_characterization/main?labpath=notebooks%2Fprospective_dynamic_lcia_demo.ipynb)
136
136
 
137
- > NOTE: Currently, only the IAM scenarios and pathways from Barbosa Watanabe et al. (2026) are supported. This will change soon.
137
+ > NOTE: Currently, only the IAM scenarios and pathways from Watanabe et al. (2026) are supported. This will change soon.
138
138
 
139
139
  ### Setting up a scenario
140
140
 
@@ -82,4 +82,5 @@ dynamic_characterization/prospective/data/es5c12391_si_024.xlsx
82
82
  dynamic_characterization/prospective/data/es5c12391_si_025.xlsx
83
83
  dynamic_characterization/prospective/data/es5c12391_si_026.xlsx
84
84
  tests/test_characterize_dynamic_inventory.py
85
+ tests/test_default_characterization_functions.py
85
86
  tests/test_prospective.py
@@ -0,0 +1,210 @@
1
+ """Tests for the default characterization functions built from a static LCIA method."""
2
+
3
+ import bw2data as bd
4
+ import numpy as np
5
+ import pandas as pd
6
+ import pytest
7
+ from bw2data.tests import bw2test
8
+
9
+ from dynamic_characterization import characterize
10
+ from dynamic_characterization.dynamic_characterization import (
11
+ clear_characterization_function_cache,
12
+ create_characterization_functions_from_method,
13
+ )
14
+ from dynamic_characterization.ipcc_ar6.radiative_forcing import (
15
+ characterize_ch4,
16
+ characterize_co2,
17
+ characterize_co2_uptake,
18
+ )
19
+
20
+ METHOD = ("test", "climate change", "GWP100")
21
+
22
+ BIOFLOWS = {
23
+ "co2_fossil_high_stacks": {
24
+ "name": "Carbon dioxide, fossil",
25
+ "categories": ("air", "non-urban air or from high stacks"),
26
+ "type": "emission",
27
+ "CAS number": "000124-38-9",
28
+ },
29
+ "co2_fossil_unspecified": {
30
+ "name": "Carbon dioxide, fossil",
31
+ "categories": ("air",),
32
+ "type": "emission",
33
+ "CAS number": "000124-38-9",
34
+ },
35
+ "co2_fossil_urban": {
36
+ "name": "Carbon dioxide, fossil",
37
+ "categories": ("air", "urban air close to ground"),
38
+ "type": "emission",
39
+ "CAS number": "000124-38-9",
40
+ },
41
+ "co2_fossil_stratosphere": {
42
+ "name": "Carbon dioxide, fossil",
43
+ "categories": ("air", "lower stratosphere + upper troposphere"),
44
+ "type": "emission",
45
+ "CAS number": "000124-38-9",
46
+ },
47
+ "co2_non_fossil": {
48
+ "name": "Carbon dioxide, non-fossil",
49
+ "categories": ("air", "non-urban air or from high stacks"),
50
+ "type": "emission",
51
+ "CAS number": "000124-38-9",
52
+ },
53
+ "co2_from_soil_or_biomass_stock": {
54
+ "name": "Carbon dioxide, from soil or biomass stock",
55
+ "categories": ("air",),
56
+ "type": "emission",
57
+ "CAS number": "000124-38-9",
58
+ },
59
+ "co2_to_soil": {
60
+ "name": "Carbon dioxide, to soil or biomass stock",
61
+ "categories": ("soil",),
62
+ "type": "emission",
63
+ "CAS number": "000124-38-9",
64
+ },
65
+ "co2_in_air": {
66
+ "name": "Carbon dioxide, in air",
67
+ "categories": ("natural resource", "in air"),
68
+ "type": "natural resource",
69
+ "CAS number": "000124-38-9",
70
+ },
71
+ "ch4_fossil": {
72
+ "name": "Methane, fossil",
73
+ "categories": ("air", "non-urban air or from high stacks"),
74
+ "type": "emission",
75
+ "CAS number": "000074-82-8",
76
+ },
77
+ }
78
+
79
+ # static CFs, roughly EF v3.1 GWP100; uptake flows are negative
80
+ CHARACTERIZATION_FACTORS = {
81
+ "co2_fossil_high_stacks": 1.0,
82
+ "co2_fossil_unspecified": 1.0,
83
+ "co2_fossil_urban": 1.0,
84
+ "co2_fossil_stratosphere": 1.0,
85
+ "co2_non_fossil": 1.0,
86
+ "co2_from_soil_or_biomass_stock": 1.0,
87
+ "co2_to_soil": -1.0,
88
+ "co2_in_air": -1.0,
89
+ "ch4_fossil": 29.8,
90
+ }
91
+
92
+
93
+ def setup_project():
94
+ """Write a minimal biosphere database and static method into the current project."""
95
+ clear_characterization_function_cache()
96
+ biosphere = bd.Database(bd.config.biosphere)
97
+ biosphere.write(
98
+ {
99
+ (bd.config.biosphere, code): data | {"code": code}
100
+ for code, data in BIOFLOWS.items()
101
+ }
102
+ )
103
+ bd.Method(METHOD).write(
104
+ [
105
+ ((bd.config.biosphere, code), factor)
106
+ for code, factor in CHARACTERIZATION_FACTORS.items()
107
+ ]
108
+ )
109
+ return {code: biosphere.get(code).id for code in BIOFLOWS}
110
+
111
+
112
+ @pytest.mark.parametrize(
113
+ "code",
114
+ [
115
+ "co2_fossil_high_stacks",
116
+ "co2_fossil_unspecified",
117
+ "co2_fossil_urban",
118
+ "co2_fossil_stratosphere",
119
+ "co2_non_fossil",
120
+ "co2_from_soil_or_biomass_stock",
121
+ ],
122
+ )
123
+ @bw2test
124
+ def test_co2_emission_flows_get_co2_function(code):
125
+ ids = setup_project()
126
+ functions = create_characterization_functions_from_method(METHOD)
127
+ assert functions[ids[code]] is characterize_co2
128
+
129
+
130
+ @bw2test
131
+ def test_co2_emission_flows_characterized_without_uptake():
132
+ """Disabling uptake must not drop the ordinary CO2 emission flows."""
133
+ ids = setup_project()
134
+ functions = create_characterization_functions_from_method(
135
+ METHOD, characterize_uptake=False
136
+ )
137
+ assert functions[ids["co2_fossil_high_stacks"]] is characterize_co2
138
+ assert functions[ids["co2_from_soil_or_biomass_stock"]] is characterize_co2
139
+
140
+
141
+ @bw2test
142
+ def test_uptake_flows_use_uptake_function():
143
+ ids = setup_project()
144
+ functions = create_characterization_functions_from_method(METHOD)
145
+ assert functions[ids["co2_in_air"]] is characterize_co2_uptake
146
+ assert functions[ids["co2_to_soil"]] is characterize_co2_uptake
147
+
148
+
149
+ @bw2test
150
+ def test_uptake_flows_absent_when_uptake_disabled():
151
+ ids = setup_project()
152
+ functions = create_characterization_functions_from_method(
153
+ METHOD, characterize_uptake=False
154
+ )
155
+ assert ids["co2_in_air"] not in functions
156
+ assert ids["co2_to_soil"] not in functions
157
+
158
+
159
+ @bw2test
160
+ def test_all_method_flows_are_characterized():
161
+ ids = setup_project()
162
+ functions = create_characterization_functions_from_method(METHOD)
163
+ assert set(functions) == set(ids.values())
164
+ assert functions[ids["ch4_fossil"]] is characterize_ch4
165
+
166
+
167
+ @bw2test
168
+ def test_dynamic_gwp100_matches_static_score():
169
+ """
170
+ End-to-end: with fixed_time_horizon=False, dynamic GWP100 of an inventory
171
+ must match the static GWP100 score of the same inventory within a few percent.
172
+ """
173
+ ids = setup_project()
174
+
175
+ amounts = {
176
+ "co2_fossil_high_stacks": 17864.7,
177
+ "co2_fossil_unspecified": 2322.3,
178
+ "co2_fossil_urban": 1287.9,
179
+ "co2_fossil_stratosphere": 1.9,
180
+ "co2_from_soil_or_biomass_stock": 24.7,
181
+ "co2_non_fossil": 100.0,
182
+ "co2_to_soil": 50.0,
183
+ "co2_in_air": 200.0,
184
+ "ch4_fossil": 30.0,
185
+ }
186
+
187
+ dynamic_inventory_df = pd.DataFrame(
188
+ {
189
+ "date": pd.Series(
190
+ ["2024-01-01"] * len(amounts), dtype="datetime64[s]"
191
+ ),
192
+ "amount": pd.Series(list(amounts.values()), dtype="float64"),
193
+ "flow": pd.Series([ids[code] for code in amounts], dtype="int"),
194
+ "activity": pd.Series([1] * len(amounts), dtype="int"),
195
+ }
196
+ )
197
+
198
+ static_score = sum(
199
+ amount * CHARACTERIZATION_FACTORS[code] for code, amount in amounts.items()
200
+ )
201
+
202
+ characterized = characterize(
203
+ dynamic_inventory_df,
204
+ metric="GWP",
205
+ base_lcia_method=METHOD,
206
+ time_horizon=100,
207
+ fixed_time_horizon=False,
208
+ )
209
+
210
+ assert np.isclose(characterized.amount.sum(), static_score, rtol=0.05)