Complete Documentation

README, report template, API reference, methodology, and research guidance for AGCM.

📘 Project Overview

AGCM (Adaptive Green Complexity Metric) is a Python-based sustainability-aware algorithm analysis framework. It extends traditional algorithm analysis (Big-O time/space complexity) with energy consumption estimation, CO₂ carbon emission calculation, and a novel composite metric — the AGCM score.

Innovation: AGCM is the first educational framework to combine Big-O complexity, hardware efficiency factors, and regional carbon intensity into a single, comparable, actionable metric.

Project Goals

  • Demonstrate that algorithm choice has measurable environmental impact
  • Provide a practical tool for green software engineering education
  • Introduce a formal metric (AGCM) for comparing algorithm sustainability
  • Support carbon budget mode for sustainability-constrained design
  • Serve as an IEEE-publishable prototype and semester project deliverable
FeatureStatusNotes
Sorting algorithms (4)✅ CompleteBubble, Insertion, Merge, Quick
Fibonacci (2)✅ CompleteNaive + Memoized
Graph traversal (2)✅ CompleteBFS + DFS
Runtime profiler✅ Completetime, psutil, tracemalloc
Energy model✅ CompleteE = P × t
Carbon calculator✅ Complete5 regions supported
AGCM engine✅ CompleteCore formula
Green recommender✅ CompleteRanked output + savings %
Carbon budget mode✅ CompleteFilter by mg CO₂ limit
CLI interface✅ Completemain.py with argparse
Streamlit dashboard✅ Completeapp.py
matplotlib charts✅ Complete5 chart types
Unit tests✅ Completepytest

⚙️ Installation

Prerequisites

  • Python 3.8 or higher
  • pip (Python package installer)
  • Virtual environment (recommended)
  • VS Code or any IDE
bash
# 1. Clone or download the project
git clone https://github.com/yourname/agcm-project.git
cd agcm-project

# 2. Create virtual environment
python -m venv venv
source venv/bin/activate      # macOS/Linux
venv\Scripts\activate         # Windows

# 3. Install dependencies
pip install -r requirements.txt

# 4. Verify installation
python -c "import psutil, pandas, matplotlib; print('All dependencies OK')"
Windows Note: If memory-profiler installation fails, install it with: pip install memory-profiler --no-binary :all:

🚀 Quick Start

Run CLI Analysis

bash
# Basic run — sorting algorithms, n=1000, India, standard hardware
python main.py

# Custom parameters
python main.py --size 500 --region usa --hardware modern_laptop --budget 3.0

# All categories
python main.py --size 1000 --category all --charts

# Fibonacci only (keep n small!)
python main.py --size 25 --category fibonacci

Run Streamlit Dashboard

bash
streamlit run app.py

Use as a Library

python
from algorithms.sorting import merge_sort
from profiler.runtime_profiler import RuntimeProfiler
from agcm.agcm_engine import AGCMEngine
from agcm.recommender import GreenRecommender

# Profile an algorithm
data = list(range(1000, 0, -1))
profiler = RuntimeProfiler()
profile = profiler.profile(merge_sort, data, "Merge Sort", n=1000)

# Compute AGCM
engine = AGCMEngine(region="india", hardware="standard")
result = engine.compute(profile, complexity="O(n log n)", n=1000)
print(result.summary())

📐 AGCM Formula Reference

Core Formula: AGCM(n, h, r) = O(f(n)) × Eunit × Hf × Rc

Symbol Reference

SymbolNameUnitsRangeSource
nInput sizeinteger1 – ∞User input
O(f(n))Complexity multiplierdimensionless1 – 2ⁿAlgorithm metadata
E_unitEnergy per operationnanojoules/op0 – ∞energy_model.py
H_fHardware efficiency factordimensionless0.6 – 1.5config/settings.py
R_cRegional carbon intensitygCO₂/kWh0.028 – 0.700carbon/regions.py
AGCMAdaptive Green Complexity MetricμgCO₂-eq0 – ∞agcm/agcm_engine.py

Interpretation

  • Lower AGCM = Greener algorithm — suitable for ranking and comparison
  • AGCM is context-dependent: the same algorithm has different AGCM scores in different regions
  • AGCM scores are relative — use them for comparison, not absolute carbon quantification
  • For absolute carbon, use carbon_mg field from AGCMResult

🧩 Module Reference

profiler.RuntimeProfiler

python
profiler = RuntimeProfiler(repetitions=5, warmup=2)
result = profiler.profile(func, input_data, algo_name, n)

# result.time_s      → float  (seconds)
# result.cpu_percent → float  (%)
# result.memory_kb   → float  (KB)

energy.EnergyModel

python
model = EnergyModel(cpu_watt=65, hardware="standard")
result = model.estimate(time_s=0.01)

# result.energy_mj          → raw mJ
# result.energy_mj_adjusted → mJ × H_f (hardware-adjusted)
# result.H_f                → hardware factor applied

carbon.CarbonCalculator

python
calc = CarbonCalculator(region="india")
result = calc.calculate(energy_mj=0.05)

# result.carbon_mg  → CO₂ in milligrams
# result.R_c        → regional factor used

agcm.AGCMEngine

python
engine = AGCMEngine(region="india", hardware="standard", cpu_watt=65)
result = engine.compute(profile, complexity="O(n log n)", n=1000)

# result.agcm_score  → The AGCM score
# result.carbon_mg   → CO₂ in mg
# result.energy_mj   → Energy in mJ
# result.summary()   → Human-readable string

agcm.GreenRecommender

python
rec = GreenRecommender()
ranked = rec.rank(results_list)         # Sort by AGCM ascending
report = rec.generate_report(ranked)    # Text report string
saving = rec.carbon_saving_percent(best, other)  # % reduction

agcm.CarbonBudgetMode

python
budget = CarbonBudgetMode(budget_mg=5.0)
report = budget.analyze(results_list)

# report.compliant    → List within budget
# report.exceeded     → List over budget
# report.recommended  → Best compliant option
print(budget.format_report(report))

💰 Carbon Budget Mode

Carbon Budget Mode allows you to define a maximum acceptable CO₂ emission per algorithm run. The system filters algorithms that exceed this budget and highlights compliant ones.

How It Works

  1. Set a budget in milligrams of CO₂ (e.g., 5.0 mg)
  2. Run all algorithms via CarbonBudgetMode.analyze(results)
  3. Each result is marked within_budget = True/False
  4. The system recommends the lowest-AGCM algorithm that stays within budget
  5. Over-budget algorithms are flagged with their excess amount
Research Application: Carbon Budget Mode can be used to define "green SLAs" (Service Level Agreements) for algorithm selection in sustainable software systems.

Budget Interpretation Guide

Budget (mg CO₂)ContextSorting @ n=1000, India
0.001Extremely strict (IoT/edge)Only Quick Sort passes
0.1Strict (mobile app)Quick + Merge pass
5.0Standard (desktop app)Quick + Merge pass
50.0Relaxed (batch job)All algorithms pass

🌍 Region Configuration

AGCM simulates real-world regional carbon grids. Each region has a carbon intensity factor (R_c) in gCO₂/kWh.

python — carbon/regions.py
REGIONS = {
    "india":   {"label": "India",   "intensity_g_per_kwh": 700, "R_c": 0.700},
    "usa":     {"label": "USA",     "intensity_g_per_kwh": 450, "R_c": 0.450},
    "germany": {"label": "Germany", "intensity_g_per_kwh": 350, "R_c": 0.350},
    "eu":      {"label": "EU Avg",  "intensity_g_per_kwh": 275, "R_c": 0.275},
    "norway":  {"label": "Norway",  "intensity_g_per_kwh": 28,  "R_c": 0.028},
}

# To add a new region, simply add an entry:
REGIONS["australia"] = {"label":"Australia","intensity_g_per_kwh":650,"R_c":0.650}
These are representative values based on IEA and national grid data (2023). Actual values change seasonally and vary by energy source mix.

🔬 Experimental Methodology

Experiment Setup

  • Warmup: 2 runs discarded before measurement
  • Repetitions: 5 runs per algorithm; median time used
  • Input generation: Worst-case reverse-sorted arrays for sorting; fixed n for Fibonacci
  • Isolation: Sequential execution, not parallel
  • Timing: time.perf_counter() for microsecond precision

Validity Threats

  • Energy model simplification: E = P × t assumes 100% CPU utilization, which overestimates energy for light workloads
  • GIL impact: Python's Global Interpreter Lock may affect CPU measurements
  • System load: Background processes affect timing and CPU metrics
  • DRAM ignored: Memory energy consumption not modeled
For stronger research: Replace E = P × t with Intel RAPL (Running Average Power Limit) hardware counters for ground-truth energy measurements.

📄 IEEE Paper Writing Guide

I. Introduction

Motivate green software engineering. Cite growing data center energy consumption (IEA 2023). State that algorithm selection lacks sustainability metrics. Introduce AGCM as a solution. State research questions (RQ1–RQ3).

II. Related Work

Review: Green Software Foundation (GSF), Software Carbon Intensity (SCI) specification, RAPL-based energy profiling papers, GreenSort benchmark, Energy-Aware Computing surveys.

III. AGCM Framework Design

Present the AGCM formula with full mathematical derivation. Explain each variable. Show unit analysis. Present the system architecture diagram. Describe module responsibilities.

IV. Experimental Evaluation

Describe experiment setup (hardware, Python version, OS). Present 4 tables: sorting AGCM results, Fibonacci comparison, regional variation, hardware variation. Include 5 charts.

V. Results and Discussion

Answer each research question with data. Discuss AGCM score differences. Highlight the fibonacci memoization finding. Discuss regional impact. Discuss hardware factor significance.

VI. Conclusion & Future Work

Summarize AGCM's contribution. State limitations (simplified energy model). Future work: RAPL integration, cloud-native AGCM, ML-predicted complexity order, multi-language support.

Research Questions

  1. RQ1: How much does algorithm choice affect carbon emissions for equivalent computational tasks?
  2. RQ2: How significantly does regional carbon intensity affect the AGCM ranking of algorithms?
  3. RQ3: Can AGCM-guided algorithm selection meaningfully reduce software carbon footprint?

🎓 Viva Preparation Q&A

Q: What is AGCM and what problem does it solve?

AGCM (Adaptive Green Complexity Metric) is a novel composite metric that extends traditional algorithm complexity analysis with energy consumption, hardware efficiency, and regional carbon intensity. It solves the problem that Big-O notation provides no guidance on the environmental impact of algorithm choice.

Q: Why is Big-O not enough?

Big-O tells us how an algorithm scales, but not its actual energy cost. Two O(n²) algorithms can have vastly different real-world energy profiles. Additionally, Big-O ignores hardware efficiency (an ARM chip runs the same algorithm using 60% less energy than a legacy desktop) and the carbon intensity of the power grid.

Q: How is the energy model validated?

The simplified model E = P × t is a lower bound approximation. For educational purposes, it provides relative comparisons. For research validation, one would compare against RAPL (Intel) or PowerTOP measurements. The model's accuracy increases when algorithm execution dominates CPU time.

Q: What are the limitations of AGCM?

  • Simplified energy model (doesn't account for memory, I/O, or idle power)
  • Regional carbon intensity values are averages (not real-time)
  • Doesn't model multi-core or parallel execution
  • Python-specific — C/Java implementations would show different profiles

Q: What is the most surprising finding?

The Fibonacci comparison: Memoized Fibonacci (n=28) achieves 99.9998% carbon reduction over Naive Fibonacci. Traditional analysis would label both as "recursive functions" — AGCM reveals a catastrophic 450,000× difference in sustainability score. This demonstrates AGCM's unique value.

Q: How can AGCM be extended for real-world use?

By integrating with (1) Intel RAPL for hardware-level power measurement, (2) real-time carbon intensity APIs (Electricity Maps API), (3) CI/CD pipelines as a "green quality gate", and (4) cloud provider sustainability APIs (AWS Carbon Footprint Tool).

🚀 Future Work & Extensions

RAPL Integration

Replace E = P × t with Intel RAPL hardware counters for ground-truth energy measurement. Requires Linux + root access.

🌐

Real-Time Carbon API

Integrate Electricity Maps API to use live carbon intensity data instead of fixed regional averages.

🤖

ML Complexity Predictor

Use machine learning to predict algorithm complexity class from source code AST, automating AGCM for arbitrary functions.

🔧

CI/CD Green Gate

Integrate AGCM as a GitHub Actions step that fails PRs exceeding a carbon budget threshold.