Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions codecarbon/core/emissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ def _global_energy_mix_to_emissions_rate(energy_mix: Dict) -> EmissionsPerKWh:
in Kgs.CO2 / kWh
"""
# If we have the chance to have the carbon intensity for this country
if energy_mix.get("carbon_intensity"):
if energy_mix.get("carbon_intensity") is not None:
return EmissionsPerKWh.from_g_per_kWh(energy_mix.get("carbon_intensity"))

# Else we compute it from the energy mix.
Expand All @@ -353,7 +353,7 @@ def _global_energy_mix_to_emissions_rate(energy_mix: Dict) -> EmissionsPerKWh:
carbon_intensity_for_type = carbon_intensity_per_source.get(
energy_type[: -len("_TWh")]
)
if carbon_intensity_for_type: # to ignore "total_TWh"
if carbon_intensity_for_type is not None: # to ignore "total_TWh"
carbon_intensity += (
energy_per_year / energy_sum
) * carbon_intensity_for_type
Expand Down
34 changes: 34 additions & 0 deletions tests/test_zero_carbon_intensity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from unittest.mock import patch

import pytest

from codecarbon.core.emissions import Emissions


@pytest.mark.parametrize("intensity", [0, 0.0, 42.0])
def test_explicit_carbon_intensity_is_used(intensity):
with patch(
"codecarbon.input.DataSource.get_carbon_intensity_per_source_data",
side_effect=AssertionError("Source factors should not be needed"),
):
rate = Emissions._global_energy_mix_to_emissions_rate(
{"carbon_intensity": intensity}
)
assert rate.kgs_per_kWh == intensity / 1000


@pytest.mark.parametrize(
"mix,expected",
[
({"total_TWh": 1, "wind_TWh": 1}, 0.0),
({"total_TWh": 2, "wind_TWh": 1, "coal_TWh": 1}, 0.4),
({"total_TWh": 1, "coal_TWh": 1}, 0.8),
],
)
def test_zero_source_factor_counts_toward_energy_coverage(mix, expected):
with patch(
"codecarbon.input.DataSource.get_carbon_intensity_per_source_data",
return_value={"wind": 0, "coal": 800, "world_average": 475},
):
rate = Emissions._global_energy_mix_to_emissions_rate(mix)
assert rate.kgs_per_kWh == expected
Loading