A Python library for interacting with openLCA desktop application through the IPC protocol for life cycle assessment (LCA) workflows.
Project description
openLCA IPC Python Library
A comprehensive Python library for interacting with openLCA desktop application through the IPC (Inter-Process Communication) protocol. Built for life cycle assessment (LCA) workflows based on ISO-14040/14044 standards.
Features
- Simple, Pythonic API - High-level utilities that abstract complex IPC operations
- Comprehensive LCA Workflow - Search, create, calculate, and analyze in one package
- Contribution Analysis - Identify key contributors to environmental impacts
- Uncertainty Analysis - Monte Carlo simulations with statistical summaries
- Scenario Analysis - Parameter sensitivity and scenario comparison
- Export Utilities - CSV and Excel export for results
- AI Agent Friendly - Clear documentation and structured outputs for automation
- ISO Compliant - Follows ISO-14040/14044 LCA standards
Installation
Prerequisites
- Python 3.10 or higher
- openLCA desktop application (version 2.x)
- openLCA IPC server running (Tools → Developer Tools → IPC Server)
Install from PyPI (Coming Soon)
pip install openlca-ipc
Install from Source
# Clone the repository
git clone https://github.com/dernestbank/openlca-ipc.git
cd openlca-ipc
# Install in editable mode
pip install -e .
# Or install with optional dependencies
pip install -e ".[full]"
Install Dependencies
# Core dependencies only
pip install -r requirements.txt
# Development dependencies
pip install -r requirements-dev.txt
Quick Start
1. Start openLCA IPC Server
Before using the library, start the IPC server in openLCA:
- Open openLCA desktop application
- Go to Tools → Developer Tools → IPC Server
- Click Start (default port: 8080)
2. Basic Usage
from openlca_ipc import OLCAClient
# Connect to openLCA
with OLCAClient(port=8080) as client:
# Test connection
if client.test_connection():
print("Connected to openLCA!")
# Search for a material
steel_flow = client.search.find_flow(['steel', 'production'])
print(f"Found: {steel_flow.name}")
# Find provider process
provider = client.search.find_best_provider(steel_flow)
print(f"Provider: {provider.name if provider else 'None'}")
Usage Examples
Example 1: Complete LCA Workflow
from openlca_ipc import OLCAClient
with OLCAClient(port=8080) as client:
# 1. Search for materials
steel = client.search.find_flow(['steel'])
steel_provider = client.search.find_best_provider(steel)
# 2. Create a new process
product = client.data.create_product_flow("Steel plate")
exchanges = [
client.data.create_exchange(product, 1.0, is_input=False, is_quantitative_reference=True),
client.data.create_exchange(steel, 1.0, is_input=True, provider=steel_provider)
]
process = client.data.create_process("Plate production", exchanges=exchanges)
# 3. Create product system
system = client.systems.create_product_system(process)
# 4. Select impact method
method = client.search.find_impact_method(['TRACI'])
# 5. Calculate impacts
result = client.calculate.simple_calculation(system, method)
# 6. Get results
impacts = client.results.get_total_impacts(result)
for impact in impacts:
print(f"{impact['name']}: {impact['amount']:.4e} {impact['unit']}")
# 7. Clean up
result.dispose()
Example 2: Contribution Analysis
from openlca_ipc import OLCAClient
client = OLCAClient(port=8080)
# Run calculation with contribution analysis
result = client.calculate.contribution_analysis(system, method)
# Get all impacts
impacts = client.results.get_total_impacts(result)
# Analyze top contributors for each impact
for impact in impacts:
print(f"\n{impact['name']}:")
# Get top 5 contributors
contributors = client.contributions.get_top_contributors(
result,
impact['category'],
n=5,
min_share=0.01 # Minimum 1% contribution
)
for i, contrib in enumerate(contributors, 1):
print(f" {i}. {contrib.name}: {contrib.share*100:.1f}% ({contrib.amount:.4e})")
result.dispose()
Example 3: Monte Carlo Uncertainty Analysis
from openlca_ipc import OLCAClient
import matplotlib.pyplot as plt
client = OLCAClient(port=8080)
# Run Monte Carlo simulation
results = client.uncertainty.run_monte_carlo(
system=my_system,
impact_method=traci_method,
iterations=1000,
progress_callback=lambda i, total: print(f"Progress: {i}/{total}")
)
# Analyze global warming potential
gwp_key = next(k for k in results.keys() if 'warming' in k.lower())
gwp_result = results[gwp_key]
print(f"Mean: {gwp_result.mean:.4e}")
print(f"Std Dev: {gwp_result.std:.4e}")
print(f"CV: {gwp_result.cv:.2%}")
print(f"95% CI: [{gwp_result.percentile_5:.4e}, {gwp_result.percentile_95:.4e}]")
# Plot distribution
plt.figure(figsize=(10, 6))
plt.hist(gwp_result.values, bins=50, edgecolor='black', alpha=0.7)
plt.axvline(gwp_result.mean, color='red', linestyle='--', label='Mean')
plt.xlabel('Global Warming Potential')
plt.ylabel('Frequency')
plt.title('Monte Carlo Simulation Results')
plt.legend()
plt.savefig('gwp_distribution.png')
Example 4: Scenario Analysis
from openlca_ipc import OLCAClient
import pandas as pd
client = OLCAClient(port=8080)
# Analyze how transport distance affects impacts
scenarios = client.parameters.run_scenario_analysis(
system=transport_system,
impact_method=traci_method,
parameter_name='transport_distance',
values=[100, 200, 500, 1000, 2000, 5000]
)
# Create comparison DataFrame
data = []
for distance, impacts in scenarios.items():
row = {'Distance (km)': distance}
for impact in impacts:
row[impact['name']] = impact['amount']
data.append(row)
df = pd.DataFrame(data)
print(df)
# Export to CSV
client.export.export_comparison_to_csv(scenarios, 'scenario_results.csv')
Module Overview
The library is organized into specialized modules:
OLCAClient- Main client for connecting to openLCA IPC serversearch- Search and discovery utilities for flows, processes, and impact methodsdata- Create and modify flows, exchanges, and processessystems- Build and configure product systemscalculate- Run LCA calculations with various configurationsresults- Extract and format calculation resultscontributions- Analyze contributions by process or flowuncertainty- Monte Carlo simulations and statistical analysisparameters- Parameter scenarios and sensitivity analysisexport- Export results to CSV, Excel, and other formats
Best Practices
1. Always Dispose Results
# Good - automatic cleanup with context manager
with OLCAClient(port=8080) as client:
result = client.calculate.simple_calculation(system, method)
impacts = client.results.get_total_impacts(result)
result.dispose() # Always dispose!
# Also good - explicit cleanup
client = OLCAClient(port=8080)
try:
result = client.calculate.simple_calculation(system, method)
# Process results
finally:
result.dispose()
2. Handle Missing Data
# Always check search results
pet_flow = client.search.find_flow(['polyethylene', 'terephthalate'])
if not pet_flow:
# Try alternative keywords
pet_flow = client.search.find_flow(['PET'])
if not pet_flow:
print("Material not found in database")
return
# Proceed safely
provider = client.search.find_best_provider(pet_flow)
3. Use Logging
import logging
# Enable logging to see what's happening
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Library modules will log automatically
client = OLCAClient(port=8080)
# Output: "INFO - Connected to openLCA IPC server on port 8080"
Documentation
- Setup Guide - Detailed installation and configuration
- Examples - Working example scripts and Jupyter notebooks
- API Reference - Module structure and API details
Requirements
Core Dependencies
olca-ipc>=2.4.0- openLCA IPC protocol implementationolca-schema>=2.4.0- openLCA data schemanumpy>=1.24.0- Numerical operations
Optional Dependencies
Install with pip install openlca-ipc[full]:
scipy>=1.10.0- Statistical analysis for uncertaintymatplotlib>=3.7.0- Visualizationpandas>=2.0.0- Data export and analysis
Development
Setting Up Development Environment
# Clone repository
git clone https://github.com/dernestbank/openlca-ipc.git
cd openlca-ipc
# Create conda environment (if using conda)
conda create -n openlca_dev python=3.11
conda activate openlca_dev
# Install in editable mode with dev dependencies
pip install -e ".[full]"
pip install -r requirements-dev.txt
Running Tests
# Install test dependencies
pip install pytest pytest-cov
# Run tests
pytest tests/
# Run with coverage
pytest --cov=openlca_ipc tests/
Code Quality
# Format code
black openlca_ipc/
# Lint code
flake8 openlca_ipc/
# Type checking
mypy openlca_ipc/
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Troubleshooting
Connection Refused Error
Problem: Cannot connect to openLCA IPC server
Solution:
- Ensure openLCA desktop application is running
- Start IPC server: Tools → Developer Tools → IPC Server
- Check port number (default: 8080)
- Verify firewall settings
Material Not Found
Problem: Search returns None for materials
Solution:
- Check if the material exists in your openLCA database
- Try different search keywords
- Use partial matching:
client.search.find_flows(['steel'])instead of exact names
Zero Impact Values
Problem: All impact values are zero or very small
Solution:
- Verify that input exchanges have providers linked
- Check that the product system was created correctly
- Ensure the impact method is appropriate for your flows
- Verify that your database has characterization factors
License
This project is licensed under the MIT License - see the LICENSE file for details.
Citation
If you use this library in your research, please cite:
@software{openlca_ipc,
author = {Danquah, Ernest Boakye},
title = {openLCA IPC Python Library},
year = {2025},
url = {https://github.com/dernestbank/openlca-ipc}
}
Acknowledgments
- Built on top of olca-ipc and olca-schema
- Follows ISO 14040 and ISO 14044 standards
- Inspired by the openLCA community and LCA practitioners worldwide
Support
- Issues: GitHub Issues
- Documentation: Read the Docs
- Email: dernestbanksch@gmail.com
Made with ❤️ for the LCA Community
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file openlca_ipc-0.1.0.tar.gz.
File metadata
- Download URL: openlca_ipc-0.1.0.tar.gz
- Upload date:
- Size: 25.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
78eb2194bf2f8ea0c0b08b6a984907cb75aab6aa5ffeef5de0a164bd3bf85849
|
|
| MD5 |
2db4662cca58055d816357f25f5ce976
|
|
| BLAKE2b-256 |
76bf5218bb4cd05e3d0ce80b7745b81d985a8a1b778012e5bd2e0f6291671047
|
File details
Details for the file openlca_ipc-0.1.0-py3-none-any.whl.
File metadata
- Download URL: openlca_ipc-0.1.0-py3-none-any.whl
- Upload date:
- Size: 27.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cdc446209074a47871ca1801579df3262eacd261977cd1bb643c746f96e3aa91
|
|
| MD5 |
7238f88b9b1959ed2ebda81ee7185f12
|
|
| BLAKE2b-256 |
b70f2a11e7844054b977f85f9f65240437e304ef6b27c715abed6fb5cee41c4b
|