Skip to content

Commit eb14ec3

Browse files
committed
Initial emissions calculator MVP
0 parents  commit eb14ec3

22 files changed

Lines changed: 2295 additions & 0 deletions

.gitattributes

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
* text=auto
2+
3+
*.py text eol=lf
4+
*.md text eol=lf
5+
*.yml text eol=lf
6+
*.yaml text eol=lf
7+
*.json text eol=lf
8+
*.csv text eol=lf
9+
*.txt text eol=lf

.github/workflows/tests.yml

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
name: tests
2+
3+
on:
4+
push:
5+
branches:
6+
- main
7+
pull_request:
8+
9+
jobs:
10+
pytest:
11+
runs-on: ubuntu-latest
12+
13+
steps:
14+
- name: Check out repository
15+
uses: actions/checkout@v4
16+
17+
- name: Set up Python
18+
uses: actions/setup-python@v5
19+
with:
20+
python-version: "3.11"
21+
22+
- name: Install dependencies
23+
run: |
24+
python -m pip install --upgrade pip
25+
python -m pip install -r requirements.txt
26+
27+
- name: Run tests
28+
run: python -m pytest tests/ -q

.gitignore

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
share/python-wheels/
24+
*.egg-info/
25+
.installed.cfg
26+
*.egg
27+
28+
# Pytest / coverage
29+
.pytest_cache/
30+
.tox/
31+
.nox/
32+
.coverage
33+
.coverage.*
34+
.cache
35+
htmlcov/
36+
nosetests.xml
37+
coverage.xml
38+
*.cover
39+
*.log
40+
.hypothesis/
41+
.ruff_cache/
42+
.mypy_cache/
43+
.ipynb_checkpoints/
44+
45+
# Virtual Environments
46+
.venv/
47+
venv/
48+
ENV/
49+
env/
50+
python/
51+
52+
# Streamlit
53+
.streamlit/
54+
.streamlit/secrets.toml
55+
56+
# Local environment files
57+
.env
58+
.env.*
59+
!.env.example
60+
61+
# OS files
62+
.DS_Store
63+
Thumbs.db

CHANGELOG.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Changelog
2+
3+
All notable changes to this project will be documented in this file.
4+
5+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7+
8+
## [1.0.0] - 2026-05-30
9+
10+
### Added
11+
- Standard Git configuration with a new `.gitignore` file.
12+
- MIT open-source software license.
13+
- Rebuilt virtual environment (.venv) using standard Anaconda Python 3.13 configuration, moving away from sandbox-restricted WindowsApps stubs.
14+
- Comprehensive technical roadmap detailing improvements for Scope 2 dual-reporting and zip-code-based grid lookup.
15+
- Factor provenance columns in detailed CSV exports, preserving source names, reference years, database files, and conversion parameters.
16+
- Upgraded bulk batch processor to output dual download files: a facility-level summaries CSV and a transaction-level detailed master ledger CSV.
17+
- Added custom pytest suite evaluating factor details propagation.
18+
- Completely decoupled Scope 3 submodules (`scope3_models.py`, `scope3_factors.py`, `scope3_calculator.py`) isolating spend-based value-chain calculations.
19+
- EPA Supply Chain Factors v1.2 JSON database mapping NAICS categories, 2019 data baselines, 2021 USD baselines, and SEF+MEF coefficients.
20+
- A new 'Scope 3 Supply Chain' interactive tab inside the Streamlit dashboard.
21+
- Traceable detailed Scope 3 calculations ledger download including 15 column metadata parameters.
22+
- Detailed mapping rate metrics displaying mapped spend ($), unmapped spend ($), and percent spend mapped (%) side-by-side with grand total emissions.
23+
- Prominent mapping warning lists alerting users to unmapped categories.
24+
- Dedicated unit test suite `test_scope3.py` verifying model loaders, multiplication math, status mappings, and supplier groupings.
25+
- Scope 3 purchase-ledger example CSV for quick manual testing.
26+
- GitHub Actions workflow that runs the pytest suite on pushes to `main` and pull requests.
27+
- Git attributes file to keep text file line endings predictable across Windows and Linux CI.
28+
29+
### Changed
30+
- Softened documentation claims in `README.md` to clarify prototype status and avoid unsupported certainty.
31+
- Added clear documentation clarifying that Scope 2 electricity factors represent generic national grid averages, highlighting regional eGRID subregions as future roadmap enhancements.
32+
- Refined the operational standards disclosures to strictly communicate the learning/portfolio purpose of the MVP.
33+
- Appended spend-based Scope 3 Category 1 screening methodology boundaries and structural limitations to README.md.
34+
- Tightened README language around framework alignment, factor-library completeness, and formal reporting limitations.
35+
- Added a faster reviewer-oriented README path with quick-start commands and example-data notes.
36+
- Clarified Scope 3 upload messaging so unmapped categories are not implied to be successfully mapped.

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2026 Corey
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
1+
# Framework-Aligned Emissions Calculator (CarbonAware MVP)
2+
3+
A lightweight, testable, local-first greenhouse gas (GHG) accounting tool built to convert facility operational activity data into estimated metric tons of carbon dioxide equivalent ($CO_2e$).
4+
5+
This prototype is designed around the **Greenhouse Gas Protocol Corporate Accounting and Reporting Standard** boundary concepts, separating direct operational emissions (Scope 1), indirect purchased-energy emissions (Scope 2), and an educational spend-based Scope 3 screening workflow. It is not a compliance or certification system.
6+
7+
---
8+
9+
> [!WARNING]
10+
> **Mandatory Disclosure & Compliance Disclaimer**
11+
> “This prototype is intended for learning, portfolio demonstration, and early facility screening. It is not a certified greenhouse gas inventory tool. Emission factors, organizational boundaries, market-based Scope 2 claims, renewable energy certificates, and reporting requirements must be reviewed against current guidance before formal reporting.”
12+
13+
---
14+
15+
## 📖 Table of Contents
16+
1. [Core Features](#-core-features)
17+
2. [Accounting Framework & Methodology](#-accounting-framework--methodology)
18+
3. [Project Directory Architecture](#-project-directory-architecture)
19+
4. [Quick Start](#-quick-start)
20+
5. [Installation & Setup Guide](#-installation--setup-guide)
21+
6. [Running the Application](#-running-the-application)
22+
7. [Executing the Test Suite](#-executing-the-test-suite)
23+
8. [Example Data](#-example-data)
24+
9. [Operational Assumptions & Boundaries](#-operational-assumptions--boundaries)
25+
10. [Emission Factors Reference Guide](#-emission-factors-reference-guide)
26+
11. [Future Roadmap & Architectural Enhancements](#-future-roadmap--architectural-enhancements)
27+
28+
---
29+
30+
## 🌟 Core Features
31+
32+
- **Decoupled Backend Engine**: Calculation math, factor loaders, schema validations, and types are isolated inside a standalone Python package (`src/emissions_calculator`), achieving modular unit-testability outside the GUI.
33+
- **Glassmorphism Metrics Dashboard**: Premium, highly-responsive frontend designed with Streamlit, custom Outfit typography, dynamic card visual transitions, and metric highlights.
34+
- **Interactive Visualizations**: Rich, hover-responsive plotly donut and horizontal bar charts mapping scope shares and resource breakdowns.
35+
- **Bulk CSV Upload & Batch Processing**: Runs carbon accounting formulas instantly across multiple facilities via CSV batch uploads, compiling comparative bar charts and downloadable master inventories.
36+
- **Structured Data Model**: Every conversion factor is loaded from a structured JSON schema detailing year, source, and provenance metadata to support transparent calculations and clear review notes.
37+
38+
---
39+
40+
## 🧮 Accounting Framework & Methodology
41+
42+
The application applies the core operational carbon formulation:
43+
44+
$$\text{Activity Data} \times \text{Emission Factor} = \text{Greenhouse Gas Emissions (MT } CO_2e)$$
45+
46+
### Why Scope Separation Matters
47+
To avoid **double-counting** and establish clear organizational boundaries:
48+
- **Scope 1 (Direct Emissions)**: Generated by onsite combustion owned or controlled directly by the facility. For example, burning **Natural Gas** for commercial heating or consuming **Diesel Fuel** in generators or company-owned fleet vehicles.
49+
- **Scope 2 (Indirect Emissions)**: Generated by utilities consumed by the facility but combusted offsite by the power generator. In this application, this represents **Purchased Electricity** from the regional power grid.
50+
51+
---
52+
53+
## 📂 Project Directory Architecture
54+
55+
The repository is organized following clean, professional python packaging standards:
56+
57+
```text
58+
framework-aligned-emissions-calculator/
59+
├── .github/
60+
│ └── workflows/
61+
│ └── tests.yml # GitHub Actions pytest workflow
62+
├── README.md # Deep technical documentation and user guide
63+
├── requirements.txt # Standard package dependency list
64+
├── app.py # Streamlit dashboard and user interface
65+
├── data/
66+
│ ├── emission_factors.json # Local database of Scope 1/2 conversion factors and citations
67+
│ └── scope3_supply_chain_factors.json # Small educational subset of EPA Supply Chain v1.2 factors
68+
├── src/
69+
│ └── emissions_calculator/
70+
│ ├── __init__.py # Package interfaces exposure
71+
│ ├── calculator.py # Carbon math, input validation, and scope aggregations
72+
│ ├── models.py # Struct data models for factors and results
73+
│ ├── factors.py # JSON factor loader and validator
74+
│ ├── scope3_models.py # Struct data models for Scope 3 spend-based items
75+
│ ├── scope3_factors.py # JSON loader and validator for Scope 3
76+
│ └── scope3_calculator.py # Scope 3 spend-based calculations and warnings
77+
├── tests/
78+
│ ├── test_calculator.py # Pytest coverage for core math, bounds, and scope rules
79+
│ ├── test_factors.py # Pytest coverage for factor parsing and failures
80+
│ └── test_scope3.py # Pytest coverage for Scope 3 loaders and warning models
81+
└── examples/
82+
├── sample_facility_inputs.csv # Reference CSV format for multi-facility uploads
83+
└── sample_scope3_purchases.csv # Reference CSV format for Scope 3 purchase-ledger uploads
84+
```
85+
86+
---
87+
88+
## ⚡ Quick Start
89+
90+
For a fast local check after cloning:
91+
92+
```powershell
93+
python -m venv .venv
94+
.venv\Scripts\Activate.ps1
95+
python -m pip install -r requirements.txt
96+
python -m pytest tests/ -q
97+
python -m streamlit run app.py
98+
```
99+
100+
On Linux/macOS, activate the virtual environment with:
101+
102+
```bash
103+
source .venv/bin/activate
104+
```
105+
106+
---
107+
108+
## ⚙️ Installation & Setup Guide
109+
110+
### Prerequisites
111+
- **Python 3.9+** (Tested with Python 3.13)
112+
- Windows PowerShell, Command Prompt, or Unix Shell
113+
114+
### Step-by-Step Setup
115+
1. **Navigate to the Project Root**:
116+
```powershell
117+
cd framework-aligned-emissions-calculator
118+
```
119+
120+
2. **Initialize a Local Virtual Environment**:
121+
```powershell
122+
python -m venv .venv
123+
```
124+
125+
3. **Activate the Virtual Environment**:
126+
- **Windows (PowerShell)**:
127+
```powershell
128+
.venv\Scripts\Activate.ps1
129+
```
130+
- **Windows (Command Prompt)**:
131+
```cmd
132+
.venv\Scripts\activate.bat
133+
```
134+
- **Linux/macOS**:
135+
```bash
136+
source .venv/bin/activate
137+
```
138+
139+
4. **Install Dependencies**:
140+
```powershell
141+
python -m pip install -r requirements.txt
142+
```
143+
144+
---
145+
146+
## 🚀 Running the Application
147+
148+
Launch the interactive local server using Streamlit:
149+
150+
```powershell
151+
streamlit run app.py
152+
```
153+
154+
Upon launching, the command prompt will output a local network address (typically `http://localhost:8501`). Open your browser to access the dashboard.
155+
156+
---
157+
158+
## 🧪 Executing the Test Suite
159+
160+
Our unit tests cover core math, negative input rejection, missing factor failures, scope boundary checks, and empty input handling.
161+
162+
Execute the tests inside the virtual environment:
163+
164+
```powershell
165+
python -m pytest tests/ -v
166+
```
167+
168+
---
169+
170+
## 🧾 Example Data
171+
172+
Two example files are included for manual testing:
173+
174+
| File | Purpose |
175+
| :--- | :--- |
176+
| `examples/sample_facility_inputs.csv` | Scope 1 and Scope 2 multi-facility utility/fuel upload |
177+
| `examples/sample_scope3_purchases.csv` | Scope 3 Category 1 purchase-ledger upload with one intentionally unmapped row |
178+
179+
The unmapped Scope 3 row is intentional. It demonstrates how the app separates mapped spend from unmapped spend instead of silently treating missing factor coverage as complete.
180+
181+
---
182+
183+
## 📋 Operational Assumptions & Boundaries
184+
185+
- **Stationary Combustion**: Natural gas and diesel factors are calculated under the stationary combustion boundary. Mobile combustion parameters are ignored.
186+
- **Generic Grid-Average Scope 2**: Grid electricity calculations currently utilize a generic US national average factor (Location-based method) as a baseline. This is a simplified approach; true Scope 2 location-based accounting requires regional grid factors reflecting specific geographic subregions (e.g., eGRID subregions). Transitioning to dynamic, regional eGRID subregion lookup is planned as a high-priority future roadmap enhancement. **Market-based methods** (accounting for RECs, green utility purchasing contracts, or local solar attributes) are omitted.
187+
- **Global Warming Potentials**: Equivalence conversions utilize standard IPCC 5th Assessment Report (AR5) 100-year GWP indices ($CO_2 = 1, CH_4 = 28, N_2O = 265$).
188+
- **Spend-Based Scope 3 Screening**: Supply-chain calculations are designed to provide **provenance-friendly, educational screening estimates** utilizing high-level procurement registers and spend indexes. They do not represent supplier-specific primary-data accounting. Procurement amounts are multiplied by standard **SEF+MEF** (Supply Chain Emission Factor + Margins Emission Factor) values to capture complete lifecycle margins. Values utilize 2019 environmental baselines expressed in 2021 USD (model version: EPA Supply Chain Factors v1.2); inflation adjustments and direct supplier primary carbon reporting represent future roadmap items. The included Scope 3 factor file is a small demonstration subset, not the full EPA NAICS factor library.
189+
190+
---
191+
192+
## 📚 Emission Factors Reference Guide
193+
194+
Active Scope 1 and Scope 2 factors are stored in `data/emission_factors.json`:
195+
196+
| Fuel/Activity Type | Boundary | Input Unit | MT $CO_2e$ / Unit | Primary Source Citation |
197+
| :--- | :--- | :--- | :--- | :--- |
198+
| **Natural Gas** | Scope 1 | therms | `0.005306` | EPA Greenhouse Gas Emissions Factors Hub (2023) |
199+
| **Diesel Fuel** | Scope 1 | gallons | `0.010210` | EPA Greenhouse Gas Emissions Factors Hub (2023) |
200+
| **Electricity** | Scope 2 | kWh | `0.000371` | EPA eGRID National Average Grid Rate (2023) |
201+
202+
Scope 3 spend-based factors are stored separately in `data/scope3_supply_chain_factors.json`. The current project includes only a small educational subset of EPA Supply Chain GHG Emission Factors v1.2 categories for demonstration and testing. It should not be treated as a complete supply-chain factor library.
203+
204+
The Scope 1/2 factors currently use 2023-era default values. Before formal reporting, factor versions should be reviewed against the latest available EPA GHG Emission Factors Hub and eGRID releases.
205+
206+
---
207+
208+
## 🗺️ Future Roadmap & Architectural Enhancements
209+
210+
- [ ] **EPA eGRID Regional Subregion Lookup**: Dynamically look up electricity emission factors based on zip codes or eGRID subregion codes rather than national averages.
211+
- [ ] **Market-Based Scope 2 Accounting**: Implement dual-reporting capabilities tracking both location-based grid average factors and custom supplier-specific emission rates or REC purchases.
212+
- [ ] **Monthly Utility Bill Integration**: Transition from annualized activity estimates to monthly tracking calendars to capture seasonality trends.
213+
- [ ] **Expanded Scope 3 Boundaries**: Extend beyond Category 1 purchased goods and services to employee commuting, business travel, and transportation categories.
214+
- [ ] **Source URLs in Factor Metadata**: Add direct source URLs to factor JSON and include them in detailed exports where practical.
215+
- [ ] **Calculation Audit Log**: Automatically append date stamps, user credentials, and active system version tags to exported CSV summaries.
216+
- [ ] **Uncertainty Quantification**: Provide margin-of-error indicators based on factor variations and data quality scores.

0 commit comments

Comments
 (0)