A Python library for handling units, conversions, and calculations in energy system modeling. Designed for techno-economic analysis, energy planning, and quantitative energy research.
Status: Under active development. API may change between versions.
- Universal Conversions: Energy, power, mass, volume, time, and cost units with intelligent dimensional analysis
- Substance-Aware: Built-in fuel properties database (IPCC-verified) with heating values, densities, and emission factors
- Economic Modeling: Inflation adjustment (USD/EUR, 2010-2030) and year-dependent currency exchange rates (GBP, JPY, CNY)
- Smart Arithmetic: Natural mathematical operations with automatic unit handling and compound unit cancellation
- Discovery API: Explore available units, substances, and currencies programmatically
- Data-Driven Architecture: All configuration in JSON - extend with custom units, fuels, and dimensional rules
- Pandas Ready: Optional DataFrame integration for bulk operations
- Jupyter Ready: Rich HTML display in notebooks with color-coded badges
# Clone the repository
git clone https://github.com/0-k/energyunits.git
cd energyunits
# Install in development mode
pip install -e .
# Or install with development dependencies
pip install -e .[dev]from energyunits import Quantity
# Simple unit conversions
energy = Quantity(100, "MWh")
print(energy.to("GJ")) # -> 360.0 GJ
# Substance-based calculations
coal = Quantity(1000, "t", substance="coal")
energy_content = coal.to("MWh") # Uses heating value
co2_emissions = coal.to("t", substance="CO2") # Combustion emissions
# Economic calculations with inflation
capex_2020 = Quantity(1000, "USD/kW", reference_year=2020)
capex_2025 = capex_2020.to(reference_year=2025) # Auto-adjusts for inflation
# Currency conversion with year-dependent exchange rates
cost_eur = Quantity(50, "EUR/MWh", reference_year=2015)
cost_usd = cost_eur.to("USD/MWh", reference_year=2024) # Inflates, then converts
# Natural arithmetic operations
power = Quantity(100, "MW")
time = Quantity(24, "h")
energy = power * time # -> 2400 MWh (POWER x TIME -> ENERGY via data-driven rules)
# Smart compound unit cancellation
capex = Quantity(1500, "USD/kW")
capacity = Quantity(500, "MW")
payment = capex * capacity # -> 750,000,000 USD (auto-converts MW->kW, then cancels)from energyunits import Quantity
from energyunits.units import MWh, GJ, MW, USD, EUR, t, h
energy = Quantity(100, MWh)
result = energy.to(GJ) # Autocompletion, no typosfrom energyunits import Quantity
Quantity.list_units("ENERGY") # ['EJ', 'GJ', 'GWh', 'J', 'MJ', 'MMBTU', 'MWh', ...]
Quantity.list_dimensions() # ['CURRENCY', 'ENERGY', 'MASS', 'POWER', 'TIME', 'VOLUME']
Quantity.list_substances("hhv") # Fuels with heating values
Quantity.list_currencies() # ['CNY', 'EUR', 'GBP', 'JPY', 'USD']# Power plant performance analysis
fuel_input = Quantity(1000, "t", "coal")
electricity_output = Quantity(400, "MWh")
# Calculate efficiency
efficiency = electricity_output / fuel_input.to("MWh")
print(f"Plant efficiency: {efficiency.value:.1%}")
# Emission intensity
co2_rate = fuel_input.to("t", substance="CO2") / electricity_output
print(f"CO2 intensity: {co2_rate.value:.2f} t CO2/MWh")# LCOE calculation with inflation adjustment
capex_2015 = Quantity(1200, "USD/kW", reference_year=2015)
capex_today = capex_2015.to(reference_year=2024)
capacity_factor = 0.45
annual_generation = Quantity(8760 * capacity_factor, "h") * Quantity(1, "MW")
# Calculate levelized cost component
lcoe_capex = capex_today / (annual_generation * 20) # 20-year lifetime
print(f"CAPEX component: {lcoe_capex.value:.2f} USD/MWh")# Compare fuel heating values
coal_hhv = Quantity(1, "t", "coal").to("MWh", basis="HHV")
coal_lhv = Quantity(1, "t", "coal").to("MWh", basis="LHV")
wood_lhv = Quantity(1, "t", "wood_pellets").to("MWh", basis="LHV")
print(f"Coal HHV: {coal_hhv.value:.1f}")
print(f"Coal LHV: {coal_lhv.value:.1f}")
print(f"Wood LHV: {wood_lhv.value:.1f}")# Energy intensity analysis
steel_production = Quantity(1000, "t")
energy_use = Quantity(20, "GWh")
intensity = energy_use / steel_production # -> 20 GWh/kt
# Cost analysis
fuel_cost = Quantity(50, "USD/t", "coal")
fuel_mass = Quantity(100, "t", "coal")
total_cost = fuel_cost * fuel_mass # -> 5000 USD# Complex conversion chains
coal_mass = Quantity(1000, "kg", "coal")
# Convert mass -> energy -> emissions in one call
result = coal_mass.to("t", basis="LHV", substance="CO2")
print(f"Coal: {coal_mass} -> CO2: {result}")
# Equivalent step-by-step
energy = coal_mass.to("MWh", basis="LHV")
co2 = energy.to("t", substance="CO2")# Historical cost analysis
costs_2010 = Quantity([800, 900, 1000], "USD/kW", reference_year=2010)
costs_2024 = costs_2010.to(reference_year=2024)
print(f"2010 costs: {costs_2010.value}")
print(f"2024 costs: {costs_2024.value}") # Inflation-adjustedbudget = Quantity(500, "MWh")
consumed = Quantity(120000, "kWh") # Different unit, auto-converted
remaining = budget - consumed # -> 380 MWhWh,kWh,MWh,GWh,TWh,PWhJ,kJ,MJ,GJ,TJ,PJ,EJMMBTU(Million British Thermal Units)
W,kW,MW,GW,TW
g,kg,t(metric tons),Mt,Gt
L,m3,barrel
s,min,h,a(years)
USD,EUR,GBP,JPY,CNYwith inflation adjustment and year-dependent exchange rates- Compound units:
USD/kW,EUR/MWh, etc.
The library includes a database of fuel and material properties, verified against IPCC 2006 Guidelines and IEA data (see DATA_SOURCES.md):
- Coal types:
coal(generic),anthracite,bituminous,lignite - Gas:
natural_gas,methane,lng - Petroleum:
crude_oil,oil,diesel,gasoline,fuel_oil - Biomass:
wood_pellets,wood_chips - Other fuels:
hydrogen,methanol - Zero-carbon:
wind,solar,hydro,nuclear - Combustion products:
CO2,H2O,ash
Each substance includes:
- Higher/Lower Heating Values (HHV/LHV) in MJ/kg
- Density (kg/m3) for volume conversions
- Carbon, hydrogen, and ash content for emission calculations
The library uses a data-driven architecture. All unit definitions, substance properties, and dimensional operation rules are stored in JSON configuration files under energyunits/data/.
from energyunits.registry import registry
# Load custom unit definitions, conversion factors, and dimensional rules
registry.load_units("custom_units.json")
# Example custom_units.json structure:
{
"dimensions": {"BTU": "ENERGY"},
"conversion_factors": {"BTU": 0.000293071},
"dimensional_multiplication_rules": [
{
"dimensions": ["FORCE", "LENGTH"],
"result_dimension": "ENERGY",
"source_dimension": "FORCE"
}
]
}from energyunits.substance import substance_registry
# Load custom fuel properties
substance_registry.load_substances("custom_fuels.json")
# Example custom_fuels.json structure:
{
"custom_coal": {
"name": "Regional Coal Blend",
"hhv": 28.5,
"lhv": 27.2,
"density": 850,
"carbon_content": 0.72,
"hydrogen_content": 0.05,
"ash_content": 0.12
}
}import pandas as pd
from energyunits.pandas_tools import add_units, convert_units
# Add unit metadata to a DataFrame column
df = pd.DataFrame({'generation': [100, 200, 300]})
df = add_units(df, 'generation', 'MWh')
# Bulk-convert entire columns
df_gj = convert_units(df, 'generation', 'GJ')git clone https://github.com/0-k/energyunits.git
cd energyunits
pip install -e .[dev]pytest # Run all tests
pytest --cov=energyunits # With coverage
pytest -v # Verbose outputblack energyunits/ # Format code
flake8 energyunits/ # Lint
isort energyunits/ # Sort imports- ARCHITECTURE.md: Complete architecture documentation, design decisions, and extensibility guide
- DATA_SOURCES.md: Citations and references for all energy conversion values and emission factors
- CHANGELOG.md: Version history and release notes
- RELEASE.md: Release process and PyPI publishing guide
- Examples: See
examples/directory for usage demonstrations
Contributions are welcome! Please see our contributing guidelines and submit pull requests for any improvements.
This project is licensed under the MIT License - see the LICENSE file for details.
Martin Klein, 2024-2026