API Reference#

CLI#

tracarbon.cli.add_containers_generator(location)#

Add metric generators for containers if available

Param:

country for the metric generators of containers

Returns:

the list of metric generators for containers

Parameters:

location (Country)

Return type:

List[MetricGenerator]

tracarbon.cli.get_exporter(exporter_name, metric_generators, tracarbon_builder=None)#

Get the exporter based on the name with its metrics.

Parameters:
  • exporter_name (str) – the name of the exporter

  • metric_generators (List[MetricGenerator]) – the list of the metrics generators

  • tracarbon_builder (TracarbonBuilder | None) – the configuration of Tracarbon

Returns:

the configured exporter

Return type:

Exporter

tracarbon.cli.list_exporters(displayed=True)#

List all the exporters available.

Parameters:

displayed (bool)

Return type:

List[str]

tracarbon.cli.run(exporter_name='Stdout', country_code_alpha_iso_2=None, containers=False)#

Run Tracarbon.

Parameters:
  • exporter_name (str)

  • country_code_alpha_iso_2 (str | None)

  • containers (bool)

Return type:

None

tracarbon.cli.run_metrics(exporter_name, country_code_alpha_iso_2=None, running=True, containers=False)#

Run the metrics with the selected exporter

Parameters:
  • country_code_alpha_iso_2 (str | None) – the alpha iso2 country name where it’s running

  • running (bool) – keep running the metrics

  • exporter_name (str) – the exporter name to run

  • containers (bool) – activate the containers feature

Returns:

Return type:

None

Configuration#

class tracarbon.conf.TracarbonConfiguration(metric_prefix_name='tracarbon', interval_in_seconds=60, log_level='INFO', co2signal_api_key='', co2signal_url='https://api.electricitymaps.com/v4/carbon-intensity/latest', emission_factor_type='lifecycle', env_file_path=None)#

The Configuration of Tracarbon.

Parameters:
  • metric_prefix_name (str)

  • interval_in_seconds (int)

  • log_level (str)

  • co2signal_api_key (str)

  • co2signal_url (str)

  • emission_factor_type (str)

  • env_file_path (str | None)

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

tracarbon.conf.logger_configuration(level)#

Configure the logger format.

Parameters:

level (str)

Return type:

None

Builder#

class tracarbon.builder.Tracarbon(configuration, exporter, location)#

Tracarbon instance.

Parameters:
start()#

Start Tracarbon.

Return type:

None

stop()#

Collect the final interval and stop Tracarbon.

Returns:

the total CO2 grams the host emitted since Tracarbon started

Return type:

float | None

class tracarbon.builder.TracarbonBuilder(*, exporter=None, location=None, configuration=TracarbonConfiguration(metric_prefix_name='test', log_level='INFO', interval_in_seconds=1, co2signal_api_key='', co2signal_url='https://api.electricitymaps.com/v4/carbon-intensity/latest', emission_factor_type='lifecycle'))#

Tracarbon builder for building Tracarbon.

Parameters:
build()#

Build Tracarbon with its configuration.

Return type:

Tracarbon

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

with_exporter(exporter)#

Add an exporter to the builder. :param exporter: the exporter :return:

Parameters:

exporter (Exporter)

Return type:

TracarbonBuilder

with_location(location)#

Add a location to the builder. :param location: the location :return:

Parameters:

location (Location)

Return type:

TracarbonBuilder

class tracarbon.builder.TracarbonReport(*, start_time=None, end_time=None, metric_report=<factory>)#

Tracarbon report to store running statistics.

Parameters:
  • start_time (datetime | None)

  • end_time (datetime | None)

  • metric_report (Dict[str, MetricReport])

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

property total_co2g: float | None#

Get the CO2 grams the host emitted since Tracarbon started.

Returns:

the total CO2 grams, or None if no host carbon emission was reported

Hardware#

class tracarbon.hardwares.hardware.HardwareInfo#

Hardware information.

static get_cpu_usage(interval=None)#

Get the CPU load percentage usage.

Parameters:

interval (float | None) – the minimal interval to wait between two consecutive measures

Returns:

the CPU load in %

Return type:

float

classmethod get_gpu_power_usage()#

Get the GPU power usage in watts.

Returns:

the gpu power usage in W

Return type:

float

static get_memory_total()#

Get the total physical memory available.

Returns:

the total physical memory available

Return type:

float

static get_memory_usage()#

Get the local memory usage.

Returns:

the memory used in percentage

Return type:

float

static get_number_of_cores(logical=True)#

Get the number of CPU’s cores.

Param:

logical: core as logical included

Returns:

the number of CPU’s cores

Parameters:

logical (bool)

Return type:

int

static get_platform()#

Get the platform name.

Returns:

the name of the platform

Return type:

str

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.containers.Container(*, name, cpu_usage, memory_usage)#

Container of Kubernetes.

Parameters:
  • name (str)

  • cpu_usage (float)

  • memory_usage (float)

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.containers.Kubernetes(*, namespaces=None, api, node_name=None, group='metrics.k8s.io', version='v1beta1')#

Kubernetes client.

Parameters:
  • namespaces (List[str] | None)

  • api (CustomObjectsApi)

  • node_name (str | None)

  • group (str)

  • version (str)

get_pods_usage(namespace=None)#

Get Pods with usage.

Param:

namespaces: list of namespaces for getting the pods.

Returns:

an iterator of the pods

Parameters:

namespace (str | None)

Return type:

Iterator[Pod]

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

refresh_namespaces()#

Refresh the names of the namespaces.

Return type:

None

class tracarbon.hardwares.containers.Pod(*, name, namespace, containers)#

Pod for Kubernetes.

Parameters:
  • name (str)

  • namespace (str)

  • containers (List[Container])

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.energy.EnergyUsage(*, host_energy_usage=0.0, cpu_energy_usage=None, memory_energy_usage=None, gpu_energy_usage=None, unit=EnergyUsageUnit.WATT)#

Energy report in watts.

Parameters:
  • host_energy_usage (float | None)

  • cpu_energy_usage (float | None)

  • memory_energy_usage (float | None)

  • gpu_energy_usage (float | None)

  • unit (EnergyUsageUnit)

convert_unit(unit)#

Convert the EnergyUsage values to the requested unit.

Parameters:

unit (EnergyUsageUnit) – the target energy usage unit for the conversion

Return type:

None

get_energy_usage_on_type(usage_type)#

Get the energy usage based on the type.

Param:

usage_type: the type of energy to return

Returns:

the energy of the type

Parameters:

usage_type (UsageType)

Return type:

float | None

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.energy.EnergyUsageUnit(value)#

Energy usage unit.

class tracarbon.hardwares.energy.Power#

Power utility

static co2g_from_watts_hour(watts_hour, co2g_per_kwh)#

Calculate the CO2g generated using watt-hours and the CO2g/kwh.

Returns:

the CO2g generated by the energy consumption

Parameters:
  • watts_hour (float)

  • co2g_per_kwh (float)

Return type:

float

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

static watt_hours_from_watts_over(watts, seconds)#

Get the energy a constant wattage delivers over a window.

The wattage is held flat over the window, so a shorter window smooths away less of a varying load. The caller measures the window, so a clock that can be stepped by an adjustment never reaches the energy.

Parameters:
  • watts (float) – the wattage in W

  • seconds (float) – the duration of the window

Returns:

watt-hours W/h

Return type:

float

static watts_from_microjoules(uj)#

Get watts from microjoules.

Param:

uj: energy in microjoules

Returns:

watts

Parameters:

uj (float)

Return type:

float

static watts_to_watt_hours(watts, previous_energy_measurement_time=None)#

Convert current watts to watt-hours W/h using the previous energy measurement.

The wattage is held flat over the interval, so a shorter interval smooths away less of a varying load. The first measurement has no interval behind it and returns zero: it only opens the window.

Parameters:
  • watts (float) – the wattage in W

  • previous_energy_measurement_time (datetime | None) – the previous measurement time

Returns:

watt-hours W/h

Return type:

float

class tracarbon.hardwares.energy.UsageType(value)#

Usage type.

class tracarbon.hardwares.gpu.AMDGPU#

AMD GPU information using rocm-smi or amd-smi. Supports multiple GPUs by summing power consumption across all detected GPUs.

classmethod get_gpu_power_usage()#

Get the AMD GPU power usage in watts. Supports multiple GPUs by summing power consumption.

Returns:

the total gpu power usage in W

Return type:

float

classmethod launch_shell_command()#

Launch a shell command to query AMD GPU power. Tries rocm-smi first, then falls back to amd-smi.

Returns:

result of the shell command and returncode

Return type:

Tuple[bytes, int]

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.gpu.AppleSiliconGPU#

Apple Silicon GPU information using powermetrics. Note: powermetrics may require sudo privileges for full access.

classmethod get_gpu_power_usage()#

Get the Apple Silicon GPU power usage in watts.

Returns:

the gpu power usage in W

Return type:

float

classmethod launch_shell_command()#

Launch powermetrics to query GPU power. Delegates to AppleSiliconPowerMetrics.

Returns:

result of the shell command and returncode

Return type:

Tuple[bytes, int]

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.gpu.AppleSiliconPowerMetrics#

Apple Silicon power metrics using powermetrics. Parses CPU, GPU, and ANE power from powermetrics output. Note: powermetrics requires sudo privileges.

The ANE runs on its own rail and powermetrics reports it through its own sampler, so asking for cpu_power and gpu_power alone returns no ANE line at all. Hardware old enough to have no ANE rail rejects the sampler, and the samplers are asked for again without it.

classmethod get_combined_power()#

Get the combined power (CPU + GPU + ANE) in watts. Falls back to summing individual components if Combined Power line is not found.

Returns:

combined power in watts, or None if unavailable

Return type:

float | None

classmethod get_power_breakdown()#

Get CPU, GPU, and ANE power in watts from powermetrics.

Returns:

tuple of (cpu_power, gpu_power, ane_power) in watts, None if unavailable

Return type:

Tuple[float | None, float | None, float | None]

classmethod launch_shell_command()#

Launch powermetrics to query CPU, GPU and ANE power.

Hardware with no ANE rail rejects the sampler by name. Every other failure, a missing privilege above all, fails the same way without it, so it is not worth asking twice.

Returns:

result of the shell command and returncode

Return type:

Tuple[bytes, int]

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.gpu.GPUInfo#

GPU information with auto-detection and graceful fallback. Tries all available GPU types and returns 0.0 if none found.

classmethod get_gpu_power_usage()#

Get the GPU power usage in watts. Auto-detects GPU type and falls back to 0.0 if no GPU is found.

Returns:

the gpu power usage in W, or 0.0 if no GPU detected

Return type:

float

classmethod get_gpu_power_usage_or_none()#

Get the GPU power usage in watts, or None if no GPU is available.

Returns:

the gpu power usage in W, or None if no GPU detected

Return type:

float | None

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.gpu.NvidiaGPU#

Nvidia GPU information. Supports multiple GPUs by summing power consumption across all detected GPUs.

classmethod get_gpu_power_usage()#

Get the GPU power usage in watts. Supports multiple GPUs by summing power consumption.

Returns:

the total gpu power usage in W

Return type:

float

classmethod launch_shell_command()#

Launch a shell command to query GPU power.

Returns:

result of the shell command and returncode

Return type:

Tuple[bytes, int]

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.ioreport.IOReportEnergy#

Report average Apple Silicon power between consecutive IOReport samples.

async get_energy_report()#

Return watts per component, including ANE energy in the host total.

Return type:

EnergyUsage

class tracarbon.hardwares.rapl.RAPL(*, path='/sys/class/powercap/intel-rapl', rapl_separator=':', rapl_results=<factory>, file_list=<factory>, max_power_watts=<factory>)#

RAPL to read energy consumption with Intel hardware

Parameters:
  • path (str)

  • rapl_separator (str)

  • rapl_results (Dict[str, RAPLResult])

  • file_list (List[str])

  • max_power_watts (Dict[str, float])

async get_energy_report()#

Get the energy report based on RAPL.

Returns:

the energy usage report of the RAPL measurements

Return type:

EnergyUsage

get_rapl_files_list()#

Get the list of files containing RAPL energy measurements. Raise error if it’s the hardware is not compatible with RAPL.

Returns:

the list of files path containing RAPL energy measurements.

Return type:

None

async get_rapl_power_usage()#

Read the RAPL energy measurements files on paths provided.

If energy_uj is greater than max_energy_range_uj, the value is set to 0. In this case, max_energy_range_uj contanst must be returned.

Returns:

a list of the RAPL results.

Return type:

List[RAPLResult]

is_rapl_compatible()#

Check if the path of the hardware for reading RAPL energy measurements exists. :return: if the RAPL files path exists

Return type:

bool

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.rapl.RAPLResult(*, name, energy_uj, max_energy_uj, timestamp, monotonic_time=None)#

RAPL result after reading the RAPL registry.

Parameters:
  • name (str)

  • energy_uj (float)

  • max_energy_uj (float)

  • timestamp (datetime)

  • monotonic_time (float | None)

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.amd_rapl.AMDRAPL(*, hwmon_base_path='/sys/class/hwmon', amd_energy_path=None, rapl_results=<factory>, energy_files=<factory>)#

AMD RAPL to read energy consumption via HWMON interface.

The amd_energy driver exposes energy counters at: /sys/class/hwmon/hwmon*/energy*_input (in microjoules) /sys/class/hwmon/hwmon*/energy*_label (domain label)

Labels follow the pattern: - Esocket0, Esocket1, … : Package/socket level energy - Ecore0, Ecore1, … : Per-core energy

Parameters:
  • hwmon_base_path (str)

  • amd_energy_path (str | None)

  • rapl_results (Dict[str, AMDRAPLResult])

  • energy_files (List[str])

async get_amd_rapl_power_usage()#

Read the AMD RAPL energy measurements from HWMON files.

Returns:

List of AMD RAPL results

Return type:

List[AMDRAPLResult]

get_energy_files_list()#

Get the list of energy files from the AMD HWMON interface.

Raises:

ValueError – If AMD energy interface is not available

Return type:

None

async get_energy_report()#

Get the energy report based on AMD RAPL HWMON readings.

AMD RAPL domains: - Esocket*: Package-level power (similar to Intel’s package domain) - Ecore*: Per-core power

Note: AMD RAPL does not expose separate RAM domain via HWMON. For RAM measurements, the package domain includes integrated memory controller.

Returns:

EnergyUsage report from AMD RAPL measurements

Return type:

EnergyUsage

async is_amd_rapl_compatible()#

Check if AMD RAPL energy measurement is available via HWMON.

Returns:

True if AMD energy HWMON interface is available

Return type:

bool

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.amd_rapl.AMDRAPLResult(*, name, label, energy_uj, timestamp)#

AMD RAPL result after reading the HWMON energy files.

Parameters:
  • name (str)

  • label (str)

  • energy_uj (float)

  • timestamp (datetime)

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.sensors.AMDRAPL(*, hwmon_base_path='/sys/class/hwmon', amd_energy_path=None, rapl_results=<factory>, energy_files=<factory>)#

AMD RAPL to read energy consumption via HWMON interface.

The amd_energy driver exposes energy counters at: /sys/class/hwmon/hwmon*/energy*_input (in microjoules) /sys/class/hwmon/hwmon*/energy*_label (domain label)

Labels follow the pattern: - Esocket0, Esocket1, … : Package/socket level energy - Ecore0, Ecore1, … : Per-core energy

Parameters:
  • hwmon_base_path (str)

  • amd_energy_path (str | None)

  • rapl_results (Dict[str, AMDRAPLResult])

  • energy_files (List[str])

async get_amd_rapl_power_usage()#

Read the AMD RAPL energy measurements from HWMON files.

Returns:

List of AMD RAPL results

Return type:

List[AMDRAPLResult]

get_energy_files_list()#

Get the list of energy files from the AMD HWMON interface.

Raises:

ValueError – If AMD energy interface is not available

Return type:

None

async get_energy_report()#

Get the energy report based on AMD RAPL HWMON readings.

AMD RAPL domains: - Esocket*: Package-level power (similar to Intel’s package domain) - Ecore*: Per-core power

Note: AMD RAPL does not expose separate RAM domain via HWMON. For RAM measurements, the package domain includes integrated memory controller.

Returns:

EnergyUsage report from AMD RAPL measurements

Return type:

EnergyUsage

async is_amd_rapl_compatible()#

Check if AMD RAPL energy measurement is available via HWMON.

Returns:

True if AMD energy HWMON interface is available

Return type:

bool

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.sensors.AWSEC2EnergyConsumption(instance_type, *, init=False, cpu_idle, cpu_at_10, cpu_at_50, cpu_at_100, memory_idle, memory_at_10, memory_at_50, memory_at_100, has_gpu, delta_full_machine)#

The AWS EC2 Energy Consumption.

Parameters:
  • instance_type (str)

  • init (bool)

  • cpu_idle (float)

  • cpu_at_10 (float)

  • cpu_at_50 (float)

  • cpu_at_100 (float)

  • memory_idle (float)

  • memory_at_10 (float)

  • memory_at_50 (float)

  • memory_at_100 (float)

  • has_gpu (bool)

  • delta_full_machine (float)

async get_energy_usage()#

Run the sensor and generate energy usage.

Returns:

the generated energy usage.

Return type:

EnergyUsage

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.sensors.AppleSiliconPowerMetrics#

Apple Silicon power metrics using powermetrics. Parses CPU, GPU, and ANE power from powermetrics output. Note: powermetrics requires sudo privileges.

The ANE runs on its own rail and powermetrics reports it through its own sampler, so asking for cpu_power and gpu_power alone returns no ANE line at all. Hardware old enough to have no ANE rail rejects the sampler, and the samplers are asked for again without it.

classmethod get_combined_power()#

Get the combined power (CPU + GPU + ANE) in watts. Falls back to summing individual components if Combined Power line is not found.

Returns:

combined power in watts, or None if unavailable

Return type:

float | None

classmethod get_power_breakdown()#

Get CPU, GPU, and ANE power in watts from powermetrics.

Returns:

tuple of (cpu_power, gpu_power, ane_power) in watts, None if unavailable

Return type:

Tuple[float | None, float | None, float | None]

classmethod launch_shell_command()#

Launch powermetrics to query CPU, GPU and ANE power.

Hardware with no ANE rail rejects the sampler by name. Every other failure, a missing privilege above all, fails the same way without it, so it is not worth asking twice.

Returns:

result of the shell command and returncode

Return type:

Tuple[bytes, int]

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.sensors.AzureEnergyConsumption(instance_type, *, init=False, min_watts, max_watts, vcpus, memory_gb)#

The Azure VM Energy Consumption.

Parameters:
  • instance_type (str)

  • init (bool)

  • min_watts (float)

  • max_watts (float)

  • vcpus (float)

  • memory_gb (float)

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.sensors.CloudEnergyConsumption(instance_type, *, init=False, min_watts, max_watts, vcpus, memory_gb)#

Base class for cloud provider energy consumption. Uses linear interpolation between min and max watts based on CPU usage.

Parameters:
  • instance_type (str)

  • init (bool)

  • min_watts (float)

  • max_watts (float)

  • vcpus (float)

  • memory_gb (float)

async get_energy_usage()#

Run the sensor and generate energy usage using linear interpolation.

Returns:

the generated energy usage.

Return type:

EnergyUsage

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.sensors.EnergyConsumption(*, init=False)#

A sensor to calculate the energy consumption.

Parameters:

init (bool)

static from_platform(platform='Linux')#

Get the energy consumption from the local platform or cloud provider.

Returns:

the Energy Consumption

Parameters:

platform (str)

Return type:

EnergyConsumption

abstract async get_energy_usage()#

Run the sensor and generate energy usage.

Returns:

the generated energy usage.

Return type:

EnergyUsage

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.sensors.EnergyUsage(*, host_energy_usage=0.0, cpu_energy_usage=None, memory_energy_usage=None, gpu_energy_usage=None, unit=EnergyUsageUnit.WATT)#

Energy report in watts.

Parameters:
  • host_energy_usage (float | None)

  • cpu_energy_usage (float | None)

  • memory_energy_usage (float | None)

  • gpu_energy_usage (float | None)

  • unit (EnergyUsageUnit)

convert_unit(unit)#

Convert the EnergyUsage values to the requested unit.

Parameters:

unit (EnergyUsageUnit) – the target energy usage unit for the conversion

Return type:

None

get_energy_usage_on_type(usage_type)#

Get the energy usage based on the type.

Param:

usage_type: the type of energy to return

Returns:

the energy of the type

Parameters:

usage_type (UsageType)

Return type:

float | None

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.sensors.GCPEnergyConsumption(instance_type, *, init=False, min_watts, max_watts, vcpus, memory_gb)#

The GCP Compute Engine Energy Consumption.

Parameters:
  • instance_type (str)

  • init (bool)

  • min_watts (float)

  • max_watts (float)

  • vcpus (float)

  • memory_gb (float)

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.sensors.GPUInfo#

GPU information with auto-detection and graceful fallback. Tries all available GPU types and returns 0.0 if none found.

classmethod get_gpu_power_usage()#

Get the GPU power usage in watts. Auto-detects GPU type and falls back to 0.0 if no GPU is found.

Returns:

the gpu power usage in W, or 0.0 if no GPU detected

Return type:

float

classmethod get_gpu_power_usage_or_none()#

Get the GPU power usage in watts, or None if no GPU is available.

Returns:

the gpu power usage in W, or None if no GPU detected

Return type:

float | None

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.sensors.HardwareInfo#

Hardware information.

static get_cpu_usage(interval=None)#

Get the CPU load percentage usage.

Parameters:

interval (float | None) – the minimal interval to wait between two consecutive measures

Returns:

the CPU load in %

Return type:

float

classmethod get_gpu_power_usage()#

Get the GPU power usage in watts.

Returns:

the gpu power usage in W

Return type:

float

static get_memory_total()#

Get the total physical memory available.

Returns:

the total physical memory available

Return type:

float

static get_memory_usage()#

Get the local memory usage.

Returns:

the memory used in percentage

Return type:

float

static get_number_of_cores(logical=True)#

Get the number of CPU’s cores.

Param:

logical: core as logical included

Returns:

the number of CPU’s cores

Parameters:

logical (bool)

Return type:

int

static get_platform()#

Get the platform name.

Returns:

the name of the platform

Return type:

str

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.sensors.LinuxEnergyConsumption(*, init=False, rapl=RAPL(path='/sys/class/powercap/intel-rapl', rapl_separator=':', rapl_results={}, file_list=[], max_power_watts={}), amd_rapl=AMDRAPL(hwmon_base_path='/sys/class/hwmon', amd_energy_path=None, rapl_results={}, energy_files=[]))#

Energy Consumption of a Linux device.

Supports both Intel and AMD processors via RAPL: - Intel: Uses powercap interface at /sys/class/powercap/intel-rapl - AMD (kernel 5.8+): Also uses powercap interface (same path as Intel) - AMD (older/alternative): Uses HWMON interface via amd_energy driver

Parameters:
async get_energy_usage()#

Run the sensor and generate energy usage.

Tries sensors in order of preference: 1. Intel RAPL (powercap) - works for Intel and AMD on kernel 5.8+ 2. AMD RAPL (HWMON) - fallback for AMD with amd_energy driver

NVIDIA power is added to the RAPL host and GPU readings. AMD power remains a component fallback because its CLI aggregate can include an APU’s CPU.

Returns:

the generated energy usage.

Return type:

EnergyUsage

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

class tracarbon.hardwares.sensors.MacEnergyConsumption(*, init=False, shell_command="ioreg -rw0 -a -c AppleSmartBattery | plutil -extract '0.BatteryData.SystemPower' raw -", adapter_shell_command="ioreg -rw0 -a -c AppleSmartBattery | plutil -extract '0.BatteryData.AdapterPower' raw -")#

Energy Consumption of a Mac in watts.

Reads the IOReport energy counters on Apple Silicon, which give the energy of an interval rather than a power reading held over it, need no elevated privileges and cover CPU, GPU, memory and ANE.

Falls back to powermetrics, which measures the same components but has to be run as root, and then to the system power ioreg reports. That last one is the power of the whole machine rather than of the chip, and the battery only refreshes it every few tens of seconds, so it does not follow what the machine computes and is a last resort.

Parameters:
  • init (bool)

  • shell_command (str)

  • adapter_shell_command (str)

async get_energy_usage()#

Run the sensor and generate energy usage.

Tries the IOReport energy counters first, then powermetrics for the same components, then the system power ioreg reports for the whole machine.

Returns:

the generated energy usage.

Return type:

EnergyUsage

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

class tracarbon.hardwares.sensors.RAPL(*, path='/sys/class/powercap/intel-rapl', rapl_separator=':', rapl_results=<factory>, file_list=<factory>, max_power_watts=<factory>)#

RAPL to read energy consumption with Intel hardware

Parameters:
  • path (str)

  • rapl_separator (str)

  • rapl_results (Dict[str, RAPLResult])

  • file_list (List[str])

  • max_power_watts (Dict[str, float])

async get_energy_report()#

Get the energy report based on RAPL.

Returns:

the energy usage report of the RAPL measurements

Return type:

EnergyUsage

get_rapl_files_list()#

Get the list of files containing RAPL energy measurements. Raise error if it’s the hardware is not compatible with RAPL.

Returns:

the list of files path containing RAPL energy measurements.

Return type:

None

async get_rapl_power_usage()#

Read the RAPL energy measurements files on paths provided.

If energy_uj is greater than max_energy_range_uj, the value is set to 0. In this case, max_energy_range_uj contanst must be returned.

Returns:

a list of the RAPL results.

Return type:

List[RAPLResult]

is_rapl_compatible()#

Check if the path of the hardware for reading RAPL energy measurements exists. :return: if the RAPL files path exists

Return type:

bool

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.sensors.Sensor#

The Sensor contract.

abstract async get_energy_usage()#

Run the sensor and generate energy usage in watt.

Returns:

the generated energy usage.

Return type:

EnergyUsage

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.hardwares.sensors.WindowsEnergyConsumption(*, init=False)#

NVIDIA GPU power on Windows. CPU, memory and host power are unavailable.

Parameters:

init (bool)

async get_energy_usage()#

Run the sensor and generate energy usage.

Returns:

the generated energy usage.

Return type:

EnergyUsage

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Exporters#

class tracarbon.exporters.exporter.Exporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report=<factory>)#

The Exporter interface.

Parameters:
  • metric_generators (List[MetricGenerator])

  • event (Event | None)

  • stopped (bool)

  • metric_prefix_name (str | None)

  • metric_report (Dict[str, MetricReport])

async add_metric_to_report(metric, value)#

Add the generated metric to the report asynchronously.

Parameters:
  • metric (Metric) – the metric to add

  • value (float) – the metric value to add

Returns:

Return type:

MetricReport

finish()#

Stop periodic collection and collect the last interval once.

Return type:

None

abstract classmethod get_name()#

Get the name of the exporter.

Returns:

the Exporter’s name

Return type:

str

abstract async launch(metric_generator)#

Launch the exporter. Add the metric generator to the metric reporter.

Parameters:

metric_generator (MetricGenerator) – the metric generator

Return type:

None

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

start(interval_in_seconds)#

Start the exporter and a dedicated timer configured with the configured timeout.

Param:

interval_in_seconds: the interval for the timer

Parameters:

interval_in_seconds (int)

Return type:

None

stop()#

Stop scheduling and wait for collection, except when called by that collection.

Returns:

Return type:

None

class tracarbon.exporters.exporter.Metric(*, name, value, tags=<factory>)#

Global metric to use for the exporters.

Parameters:
  • name (str)

  • value (Callable[[], Awaitable[float | None]])

  • tags (List[Tag])

format_name(metric_prefix_name=None, separator='.')#

Format the name of the metric with a prefix and separator.

Parameters:
  • metric_prefix_name (str | None) – the prefix to insert before the separator and the name.

  • separator (str) – the separator to use between the prefix and the name.

Return type:

str

format_tags(separator=':')#

Format tags with a separator.

Parameters:

separator (str) – the separator to insert between the key and value.

Return type:

List[str]

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

unit()#

Get the unit the values of this metric are reported in.

Returns:

the unit, or None if the metric declares none

Return type:

str | None

class tracarbon.exporters.exporter.MetricGenerator(*, metrics, platform='Linux', location=None)#

MetricGenerator generates metrics for the Exporter.

Parameters:
async generate()#

Generate a metric.

Return type:

AsyncGenerator[Metric, None]

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

reset()#

Reset measurement state before a new exporter run.

Return type:

None

class tracarbon.exporters.exporter.MetricReport(*, exporter_name, metric, average_interval_in_seconds=None, last_report_time=None, total=0.0, total_unit=None, average=0.0, minimum=1.7976931348623157e+308, maximum=0.0, call_count=0)#

MetricReport is a report of the generated metrics.

A metric reported in watts is power, so it is integrated over the interval it was measured on and totalled as the watt-hours total_unit carries. Every series sharing a metric name is integrated on its own interval.

Parameters:
  • exporter_name (str)

  • metric (Metric)

  • average_interval_in_seconds (float | None)

  • last_report_time (datetime | None)

  • total (float)

  • total_unit (str | None)

  • average (float)

  • minimum (float)

  • maximum (float)

  • call_count (int)

accumulate(metric, value, measured_at)#

Add one reported value to the running total, the average and the bounds.

Parameters:
  • metric (Metric) – the metric the value was reported for

  • value (float) – the reported value

  • measured_at (float) – when it was reported, on a clock that only moves forward

Return type:

None

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

class tracarbon.exporters.exporter.Tag(*, key, value)#

Tag for a metric.

Parameters:
  • key (str)

  • value (str)

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.exporters.stdout.StdoutExporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report=<factory>)#

Print the metrics to Stdout.

Parameters:
  • metric_generators (List[MetricGenerator])

  • event (Event | None)

  • stopped (bool)

  • metric_prefix_name (str | None)

  • metric_report (Dict[str, MetricReport])

classmethod get_name()#

Get the name of the exporter.

Returns:

the Exporter’s name

Return type:

str

async launch(metric_generator)#

Launch the Stdout exporter with the metrics.

Parameters:

metric_generator (MetricGenerator) – the metric generator

Return type:

None

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

class tracarbon.exporters.datadog_exporter.DatadogExporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report=<factory>, api_key=None, app_key=None, stats=None, disable_buffering=False, datadog_flush_interval=10)#

Datadog exporter for the metrics.

Parameters:
  • metric_generators (List[MetricGenerator])

  • event (Event | None)

  • stopped (bool)

  • metric_prefix_name (str | None)

  • metric_report (Dict[str, MetricReport])

  • api_key (str | None)

  • app_key (str | None)

  • stats (ThreadStats | None)

  • disable_buffering (bool)

  • datadog_flush_interval (int)

classmethod get_name()#

Get the name of the exporter.

Returns:

the Exporter’s name

Return type:

str

async launch(metric_generator)#

Launch the Datadog exporter with the metrics.

Parameters:

metric_generator (MetricGenerator) – the metric generators

Returns:

Return type:

None

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

class tracarbon.exporters.json_exporter.JSONExporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report=<factory>, path='', indent=4)#

Write the metrics to a local JSON file.

Parameters:
  • metric_generators (List[MetricGenerator])

  • event (Event | None)

  • stopped (bool)

  • metric_prefix_name (str | None)

  • metric_report (Dict[str, MetricReport])

  • path (str)

  • indent (int)

flush()#

Close the JSON array if needed by appending a closing bracket.

Return type:

None

classmethod get_name()#

Get the name of the exporter.

Returns:

the Exporter’s name

Return type:

str

async launch(metric_generator)#

Append each metric value as a JSON object inside a growing JSON array file.

Parameters:

metric_generator (MetricGenerator) – produces metrics to serialize

Return type:

None

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

class tracarbon.exporters.prometheus_exporter.PrometheusExporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report=<factory>, prometheus_metrics=<factory>, address=None, port=None)#

Send the metrics to Prometheus by running an HTTP server for the metrics exposure.

Parameters:
  • metric_generators (List[MetricGenerator])

  • event (Event | None)

  • stopped (bool)

  • metric_prefix_name (str | None)

  • metric_report (Dict[str, MetricReport])

  • prometheus_metrics (Dict[str, Gauge])

  • address (str | None)

  • port (int | None)

classmethod get_name()#

Get the name of the exporter.

Returns:

the Exporter’s name

Return type:

str

async launch(metric_generator)#

Launch the Prometheus exporter with the metrics.

Parameters:

metric_generator (MetricGenerator) – the metric generator

Return type:

None

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

Emissions#

class tracarbon.emissions.carbon_emissions.CarbonEmission(*, location, energy_consumption, previous_energy_consumption_time=None)#

Carbon Metric sensor in watts per second to calculate the CO2g/kwh emitted.

Parameters:
async get_co2_usage()#

Run the Carbon Emission sensor and get the carbon emission generated.

Returns:

the carbon usage.

Return type:

CarbonUsage

async get_energy_usage()#

Generate energy usage.

Returns:

the generated energy usage.

Return type:

EnergyUsage

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

reset()#

Open a new measurement window without including time from an earlier run.

Return type:

None

class tracarbon.emissions.carbon_emissions.CarbonUsage(*, host_carbon_usage=0.0, cpu_carbon_usage=None, memory_carbon_usage=None, gpu_carbon_usage=None, unit=CarbonUsageUnit.CO2_G, carbon_intensity_metadata=<factory>)#

Carbon Usage of the different types.

Parameters:
  • host_carbon_usage (float | None)

  • cpu_carbon_usage (float | None)

  • memory_carbon_usage (float | None)

  • gpu_carbon_usage (float | None)

  • unit (CarbonUsageUnit)

  • carbon_intensity_metadata (CarbonIntensityMetadata)

convert_unit(unit)#

Convert the carbon usage with the right carbon usage type.

Param:

unit: the carbon usage unit for the conversion

Parameters:

unit (CarbonUsageUnit)

Return type:

None

get_carbon_usage_on_type(usage_type)#

Get the carbon usage based on the type.

Param:

usage_type: the type of energy to return

Returns:

the carbon of the type

Parameters:

usage_type (UsageType)

Return type:

float | None

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.emissions.carbon_emissions.CarbonUsageUnit(value)#

Carbon usage unit.

Locations#

class tracarbon.locations.location.CarbonIntensityMetadata(*, source=CarbonIntensitySource.FILE, co2g_kwh=None, zone=None, datetime=None, updated_at=None, emission_factor_type=None, is_estimated=None, estimation_method=None, fallback_used=False)#

Metadata about the carbon intensity value used for emission calculations.

Parameters:
  • source (CarbonIntensitySource)

  • co2g_kwh (float | None)

  • zone (str | None)

  • datetime (str | None)

  • updated_at (str | None)

  • emission_factor_type (EmissionFactorType | None)

  • is_estimated (bool | None)

  • estimation_method (str | None)

  • fallback_used (bool)

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.locations.location.CarbonIntensitySource(value)#

An enumeration.

class tracarbon.locations.location.EmissionFactorType(value)#

An enumeration.

class tracarbon.locations.location.Location(*, name, co2g_kwh_source=CarbonIntensitySource.FILE, co2signal_api_key=None, co2signal_url=None, co2g_kwh=None, emission_factor_type=EmissionFactorType.LIFECYCLE, carbon_intensity_metadata=<factory>)#

Generic Location.

Parameters:
abstract async get_latest_co2g_kwh()#

Get the latest co2g_kwh for France.

Returns:

the latest co2g_kwh

Return type:

float

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

async classmethod request(url, headers=None)#

Launch an async request.

Parameters:
  • url (str) – url to request

  • headers (Dict[str, str] | None) – headers to add to the request

Returns:

the response

Return type:

Dict[str, Any]

class tracarbon.locations.country.AWSLocation(region_name, *, name, co2g_kwh_source=CarbonIntensitySource.FILE, co2signal_api_key=None, co2signal_url=None, co2g_kwh=None, emission_factor_type=EmissionFactorType.LIFECYCLE, carbon_intensity_metadata=<factory>, data_center_provider=None, data_center_region=None)#

AWS Location.

Parameters:
  • region_name (str)

  • name (str)

  • co2g_kwh_source (CarbonIntensitySource)

  • co2signal_api_key (str | None)

  • co2signal_url (str | None)

  • co2g_kwh (float | None)

  • emission_factor_type (EmissionFactorType)

  • carbon_intensity_metadata (CarbonIntensityMetadata)

  • data_center_provider (str | None)

  • data_center_region (str | None)

async get_co2g_kwh()#

Get the Co2g per kwh.

Returns:

the co2g/kwh value

Return type:

float

async get_latest_co2g_kwh()#

Get the latest co2g_kwh for AWS.

Returns:

the latest co2g_kwh

Return type:

float

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

class tracarbon.locations.country.AzureLocation(region_name, *, name, co2g_kwh_source=CarbonIntensitySource.FILE, co2signal_api_key=None, co2signal_url=None, co2g_kwh=None, emission_factor_type=EmissionFactorType.LIFECYCLE, carbon_intensity_metadata=<factory>, data_center_provider=None, data_center_region=None)#

Azure Location.

Parameters:
  • region_name (str)

  • name (str)

  • co2g_kwh_source (CarbonIntensitySource)

  • co2signal_api_key (str | None)

  • co2signal_url (str | None)

  • co2g_kwh (float | None)

  • emission_factor_type (EmissionFactorType)

  • carbon_intensity_metadata (CarbonIntensityMetadata)

  • data_center_provider (str | None)

  • data_center_region (str | None)

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

class tracarbon.locations.country.CloudLocation(region_name, *, name, co2g_kwh_source=CarbonIntensitySource.FILE, co2signal_api_key=None, co2signal_url=None, co2g_kwh=None, emission_factor_type=EmissionFactorType.LIFECYCLE, carbon_intensity_metadata=<factory>, data_center_provider=None, data_center_region=None)#

Base class for cloud provider locations.

Parameters:
  • region_name (str)

  • name (str)

  • co2g_kwh_source (CarbonIntensitySource)

  • co2signal_api_key (str | None)

  • co2signal_url (str | None)

  • co2g_kwh (float | None)

  • emission_factor_type (EmissionFactorType)

  • carbon_intensity_metadata (CarbonIntensityMetadata)

  • data_center_provider (str | None)

  • data_center_region (str | None)

async get_co2g_kwh()#

Get the Co2g per kwh.

Returns:

the co2g/kwh value

Return type:

float

async get_latest_co2g_kwh()#

Get the latest co2g_kwh for this cloud provider.

Returns:

the latest co2g_kwh

Return type:

float

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

class tracarbon.locations.country.Country(*, name, co2g_kwh_source=CarbonIntensitySource.FILE, co2signal_api_key=None, co2signal_url=None, co2g_kwh=None, emission_factor_type=EmissionFactorType.LIFECYCLE, carbon_intensity_metadata=<factory>, data_center_provider=None, data_center_region=None)#

Country definition.

Parameters:
classmethod from_eu_file(country_code_alpha_iso_2)#

Get the country from the file.

Parameters:

country_code_alpha_iso_2 (str) – the alpha_iso_2 name of the country

Returns:

Return type:

Country

classmethod get_current_country(url='https://ipinfo.io/json', timeout=10, token=None)#

Get the client’s country using an internet access.

Parameters:
  • url (str) – the url to fetch the country from IP

  • timeout (int) – the timeout in seconds for the request

  • token (str | None) – an ipinfo.io API token to lift the anonymous rate limit, falling back to the TRACARBON_IPINFO_TOKEN environment variable

Returns:

the client’s country alpha_iso_2 name.

Return type:

str

async get_latest_co2g_kwh()#

Get the latest CO2g_kwh for the Location from Electricity Maps API or CO2 Signal API.

Returns:

the latest CO2g_kwh

Return type:

float

classmethod get_location(co2signal_api_key=None, co2signal_url=None, country_code_alpha_iso_2=None, emission_factor_type=None)#

Get the current location automatically: on cloud provider or a country.

Parameters:
  • country_code_alpha_iso_2 (str | None) – the alpha iso 2 country name.

  • co2signal_api_key (str | None) – api key for fetching CO2 Signal API or Electricity Maps API.

  • co2signal_url (str | None) – api url for fetching the carbon intensity API endpoint.

  • emission_factor_type (str | None) – the emission factor type (lifecycle or direct) for Electricity Maps API.

Returns:

the country

Return type:

Country

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

class tracarbon.locations.country.GCPLocation(region_name, *, name, co2g_kwh_source=CarbonIntensitySource.FILE, co2signal_api_key=None, co2signal_url=None, co2g_kwh=None, emission_factor_type=EmissionFactorType.LIFECYCLE, carbon_intensity_metadata=<factory>, data_center_provider=None, data_center_region=None)#

GCP Location.

Parameters:
  • region_name (str)

  • name (str)

  • co2g_kwh_source (CarbonIntensitySource)

  • co2signal_api_key (str | None)

  • co2signal_url (str | None)

  • co2g_kwh (float | None)

  • emission_factor_type (EmissionFactorType)

  • carbon_intensity_metadata (CarbonIntensityMetadata)

  • data_center_provider (str | None)

  • data_center_region (str | None)

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context, /)#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

Parameters:
  • self (BaseModel)

  • context (Any)

Return type:

None

Exceptions#

exception tracarbon.exceptions.AWSSensorException#

Error in the AWS Sensor Error.

exception tracarbon.exceptions.AzureSensorException#

Error in the Azure Sensor.

exception tracarbon.exceptions.CO2SignalAPIKeyIsMissing#

The C02 Signal API key is missing.

exception tracarbon.exceptions.CloudProviderRegionIsMissing#

The region of the cloud provider is missing.

exception tracarbon.exceptions.CountryIsMissing#

The country is missing.

exception tracarbon.exceptions.GCPSensorException#

Error in the GCP Sensor.

exception tracarbon.exceptions.HardwareIOReportException#

Exception raised when the IOReport energy counters cannot be read.

exception tracarbon.exceptions.HardwareNoGPUDetectedException#

The hardware does not have a GPU.

exception tracarbon.exceptions.HardwareRAPLException#

The hardware is not compatible with RAPL.

exception tracarbon.exceptions.TracarbonException#

General Tracarbon Exception.

General Metrics#

class tracarbon.general_metrics.CarbonEmissionGenerator(location=None, *, metrics, platform='Linux', carbon_emission, co2signal_api_key=None)#

Carbon emission generator to generate carbon emissions.

Parameters:
async generate()#

Generate metrics for the carbon emission.

Returns:

an async generator of the metrics

Return type:

AsyncGenerator[Metric, None]

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

reset()#

Reset measurement state before a new exporter run.

Return type:

None

class tracarbon.general_metrics.CarbonEmissionKubernetesGenerator(location, *, metrics, platform='Linux', carbon_emission, kubernetes, co2signal_api_key=None)#

Carbon emission generator to generate carbon emissions of the containers.

Parameters:
async generate()#

Generate metrics for the carbon emission with Kubernetes.

Returns:

an async generator of the metrics

Return type:

AsyncGenerator[Metric, None]

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

reset()#

Reset measurement state before a new exporter run.

Return type:

None

class tracarbon.general_metrics.EnergyConsumptionGenerator(location=None, *, metrics, platform='Linux', energy_consumption)#

Energy consumption generator for energy consumption.

Parameters:
async generate()#

Generate a metric for energy consumption.

Returns:

an async generator of the metrics

Return type:

AsyncGenerator[Metric, None]

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class tracarbon.general_metrics.EnergyConsumptionKubernetesGenerator(*, metrics, platform='Linux', location=None, energy_consumption, kubernetes)#

Energy consumption generator for energy consumption of the containers.

Parameters:
async generate()#

Generate metrics for the energy consumption with Kubernetes.

Returns:

an async generator of the metrics

Return type:

AsyncGenerator[Metric, None]

model_config: ClassVar[ConfigDict] = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].