Skip to main content

A library for calculating carbon emissions and managing related data.

Project description

Carbon Emissions Library

Description:

This library provides tools for calculating and tracking carbon emissions, integrating with the Carbon Interface API for up-to-date emission factors, and utilizing AWS DynamoDB for data storage. It's designed to be used both in general Python environments and seamlessly within AWS Lambda functions.

Features

  • Carbon Emission Calculation: Calculates carbon emissions for various activity types (electricity, transportation, food) using the Carbon Interface API.
  • AWS Integration: Integrates with AWS DynamoDB for persistent data storage.
  • Data Storage: Stores carbon emission data (user ID, activity type, value, emission) in a DynamoDB table.
  • Data Validation: Ensures data integrity through validation of required fields and data types.
  • Automatic API Key Handling: Automatically retrieves the Carbon Interface API key from environment variables, especially useful in AWS Lambda.
  • Modular Design: Organized into reusable modules for calculations, data storage, and validation.
  • Environment Variable Configuration: Designed to be configured via environment variables.

Installation

If you have uploaded the library to PyPI:

pip install carbon_footprint_cal

Usage

This library uses carbon interface API to fetch the emissions factor. An API key (CARBON_INTERFACE_API_KEY)is required to fetch the emission factor which can be set as an environment variable.

Calculations

from carbon_footprint_cal.emissions.calculations import Calculations
import os

carbon_interface_api_key = os.environ.get("CARBON_INTERFACE_API_KEY")
carbon_calculator = Calculations(carbon_interface_api_key)

# Electricity Calculation
electricity_value = 100  # kWh or mwh
location = "US-CA"  # Example: "country-state"
electricity_emission = carbon_calculator.calculate_electricity_emission(electricity_value, location, unit="kwh") #unit is optional, and defaults to kwh.
print(f"Calculated electricity emission: {electricity_emission} kg CO2e")

# Flight Calculation
passengers = 2
legs = [{"departure_airport": "sfo", "destination_airport": "yyz"}, {"departure_airport": "yyz", "destination_airport": "sfo"}]
flight_emission = carbon_calculator.calculate_flight_emission(passengers, legs)
print(f"Calculated flight emission: {flight_emission} kg CO2e")

# Shipping Calculation
weight_value = 200
weight_unit = "g"
distance_value = 2000
distance_unit = "km"
transport_method = "truck"
shipping_emission = carbon_calculator.calculate_shipping_emission(weight_value, weight_unit, distance_value, distance_unit, transport_method)
print(f"Calculated shipping emission: {shipping_emission} kg CO2e")

AWS Lambda Environment:

If you configure the CARBON_INTERFACE_API_KEY environment variable in your Lambda function's settings, you can simplify the code:

from carbon_footprint_cal.emissions.calculations import Calculations

def lambda_handler(event, context):
    carbon_calculator = Calculations() #The API key is automatically retrieved.
    emission = carbon_calculator.calculate_emission("electricity", 100, location="US")
    return {
        'statusCode': 200,
        'body': f'Emission: {emission}'
    }

Data Storage

from carbon_footprint_cal.data_storage import DataStorage
import os
from decimal import Decimal

data_storage = DataStorage(table_name="TestTable") #Ensure to create the table beforehand.

user_id = "user123"
activity_type = "electricity"
input_params = {"location": "US-CA", "value": Decimal("100"), "unit": "kwh"}
carbon_kg = Decimal("50")

data_storage.store_emission_data(user_id, activity_type, input_params, carbon_kg)
user_data = data_storage.get_user_emissions(user_id)
print(user_data)

Data Validation

from carbon_footprint_cal.validation import Validation

validation = Validation()

# Example: Electricity validation
try:
    validation.validate_electricity_params("US-CA", 100, "kwh")
    print("Electricity data is valid")
except ValueError as e:
    print(f"Electricity data is invalid: {e}")

# Example: Flight validation
try:
    legs = [{"departure_airport": "sfo", "destination_airport": "yyz"}]
    validation.validate_flight_params(2, legs)
    print("Flight data is valid")
except ValueError as e:
    print(f"Flight data is invalid: {e}")

# Example: Shipping validation
try:
    validation.validate_shipping_params(200, "g", 2000, "km", "truck")
    print("Shipping data is valid")
except ValueError as e:
    print(f"Shipping data is invalid: {e}")

Data Storage

The library uses AWS DynamoDB for persistent storage.

Table Name: The DynamoDB table name is configurable via the DYNAMODB_TABLE_NAME environment variable or defaults to "CarbonFootprint". Usage: The data_storage module provides methods to store and retrieve data.

Data Validation

The library includes data validation to ensure data integrity.

Validation Rules: Checks for required fields (e.g., location, departure_airport, destination_airport, etc) and ensures that values are of the correct type (e.g., non-negative numbers). Refer https://docs.carboninterface.com/ for the rules to pass data to Carbon Interface API. Error Handling: Returns an error message if validation fails. Usage: The validation module provides a method to validate data.

Dependencies

  • requests
  • boto3
  • os
  • logging
  • requests_mock (for testing)

Environment Variables

CARBON_INTERFACE_API_KEY: Your Carbon Interface API key. DYNAMODB_TABLE_NAME: (Optional) The name of the DynamoDB table to use.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

carbon_footprint_cal-1.0.0.tar.gz (10.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

carbon_footprint_cal-1.0.0-py3-none-any.whl (9.9 kB view details)

Uploaded Python 3

File details

Details for the file carbon_footprint_cal-1.0.0.tar.gz.

File metadata

  • Download URL: carbon_footprint_cal-1.0.0.tar.gz
  • Upload date:
  • Size: 10.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.20

File hashes

Hashes for carbon_footprint_cal-1.0.0.tar.gz
Algorithm Hash digest
SHA256 7a8f69ac4e330a34b8f336ec8a398eb02a05af157f118e656dfac3e0731858d8
MD5 ae94ef3301019d818f94a05c0308f0b9
BLAKE2b-256 8695fb0be7025610720682142bb0c9f09c3b6a0715768b40592d3022e775316d

See more details on using hashes here.

File details

Details for the file carbon_footprint_cal-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for carbon_footprint_cal-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 17a621f1f323e2533384854b79f3a9ccef746676767990d33e780881f8778762
MD5 6b6ad748e5ef17da62b203e0c80aefab
BLAKE2b-256 2ab19c99b3992d3cb7ac095266f9a6eac96612e8ffa9616cbdc3b8092a22982b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page