greenops

package
v0.3.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 31, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package greenops provides carbon emission equivalency calculations.

It converts abstract carbon footprint values (kg CO2e) into relatable real-world equivalencies like "miles driven" or "smartphones charged" using EPA-published conversion factors.

Index

Constants

View Source
const (
	// EPAMilesDrivenFactor is kg CO2e per mile for average passenger vehicle.
	// Source: EPA GHG Equivalencies Calculator (2024 edition).
	// Reference: https://www.epa.gov/energy/greenhouse-gas-equivalencies-calculator-calculations-and-references
	//
	// Derivation from EPA 2024 data:
	//   - CO2 per gallon gasoline: 8.89 kg (8.89 × 10⁻³ metric tons)
	//   - Average fuel economy: 22.8 miles per gallon
	//   - GHG adjustment (CH4 + N2O): 1/0.994 = 1.006
	//   - Result: 8.89 ÷ 22.8 × 1.006 = 0.392 ≈ 0.393 kg CO2e/mile
	//   - EPA reference: 3.93 × 10⁻⁴ metric tons/mile = 0.393 kg/mile
	//
	// Note: This is the divisor used in the equivalency formula (kg_CO2e / factor).
	EPAMilesDrivenFactor = 0.393

	// EPASmartphoneChargeFactor is kg CO2e per smartphone charge.
	// Based on average smartphone battery capacity and grid carbon intensity.
	EPASmartphoneChargeFactor = 0.00822

	// EPATreeSeedlingFactor is kg CO2e absorbed per tree seedling over 10 years.
	// Based on urban tree carbon sequestration rates.
	EPATreeSeedlingFactor = 60.0

	// EPAHomeDayFactor is kg CO2e per day of average US home electricity.
	// Based on average residential electricity consumption and grid intensity.
	EPAHomeDayFactor = 18.3
)

EPA Formula Constants (2024 Edition) Source: https://www.epa.gov/energy/greenhouse-gas-equivalencies-calculator

These constants represent the kg CO2e equivalent for each activity. To calculate the equivalency, divide the carbon value by the factor:

equivalency = kg_CO2e / factor
View Source
const (
	// GramsToKg converts grams to kilograms.
	GramsToKg = 0.001

	// KgToKg is the identity conversion for kilograms.
	KgToKg = 1.0

	// TonsToKg converts metric tons to kilograms.
	TonsToKg = 1000.0

	// PoundsToKg converts pounds to kilograms.
	PoundsToKg = 0.453592
)

Unit Conversion Constants for normalizing carbon values to kilograms.

View Source
const (
	// MinDisplayThresholdKg is the minimum kg CO2e for any display.
	// Values below this are effectively zero and not displayed.
	MinDisplayThresholdKg = 0.001

	// MinEquivalencyThresholdKg is the minimum kg CO2e for showing equivalencies.
	// Below this threshold, raw values are shown without equivalencies
	// because the equivalencies become meaninglessly small.
	MinEquivalencyThresholdKg = 1.0

	// LargeNumberThreshold is the threshold for using abbreviated display.
	// Values at or above this threshold use "~X.X million" format.
	LargeNumberThreshold = 1_000_000

	// BillionThreshold is the threshold for billion-scale display.
	BillionThreshold = 1_000_000_000
)

Display Threshold Constants control when equivalencies are shown.

View Source
const (
	// CarbonMetricKey is the canonical key for carbon footprint in sustainability maps.
	CarbonMetricKey = "carbon_footprint"

	// DeprecatedCarbonKey is the legacy key (deprecated, for backward compatibility).
	DeprecatedCarbonKey = "gCO2e"
)

Metric Keys for sustainability maps.

Variables

View Source
var (
	// ErrInvalidUnit indicates an unrecognized carbon unit.
	// This error is returned when NormalizeToKg receives an unknown unit string.
	ErrInvalidUnit = constError("invalid carbon unit")

	// ErrNegativeValue indicates a negative carbon value.
	// Carbon emissions cannot be negative.
	ErrNegativeValue = constError("negative carbon value")

	// ErrCalculationOverflow indicates a value too large to calculate safely.
	// This is a safety check to prevent floating point overflow.
	ErrCalculationOverflow = constError("calculation overflow")
)

Error types for equivalency calculations. These are sentinel errors that can be compared with errors.Is().

Functions

func FormatFloat

func FormatFloat(f float64, precision int) string

FormatFloat formats a float with the specified precision and thousand separators. FormatFloat formats f rounded to precision decimal places and returns a string with English-style thousand separators applied to the integer part when possible. If precision is 0 the value is formatted via FormatNumber. The function rounds to the requested precision, preserves the decimal portion, and preserves the sign for negative values. If applying thousand separators to the integer portion fails, the plain decimal-formatted string is returned.

func FormatLarge

func FormatLarge(n float64) string

FormatLarge formats large numbers with abbreviated notation.

Values below LargeNumberThreshold (1 million) use comma-separated format. Values at or above LargeNumberThreshold use "~X.X million" format. Values at or above BillionThreshold use "~X.X billion" format.

FormatLarge abbreviates large floating-point numbers using million and billion units. If n is greater than or equal to BillionThreshold it returns a string like "~X.X billion" with one decimal place. If n is greater than or equal to LargeNumberThreshold it returns a string like "~X.X million" with one decimal place. For values below those thresholds it returns a comma-separated integer representation of n rounded to the nearest integer.

func FormatNumber

func FormatNumber(n int64) string

FormatNumber formats an integer with thousand separators. FormatNumber formats n with comma thousand separators using the package's English-locale printer.

func IsRecognizedUnit

func IsRecognizedUnit(unit string) bool

IsRecognizedUnit returns true if the unit string is valid for carbon values. IsRecognizedUnit reports whether the provided unit string is a supported carbon unit. It accepts "g", "kg", "t", "lb" and their "CO2e" variants (for example "gCO2e", "kgCO2e"), matching case-insensitively. It returns true if the unit is recognized, false otherwise.

func NormalizeToKg

func NormalizeToKg(value float64, unit string) (float64, error)

NormalizeToKg converts a carbon value in any recognized unit to kilograms.

Recognized units: g, kg, t, lb, gCO2e, kgCO2e, tCO2e, lbCO2e Unit matching is case-insensitive.

Returns ErrNegativeValue if value is negative. Returns ErrInvalidUnit if the unit is not recognized. NormalizeToKg converts a carbon quantity from the provided unit to kilograms. Supported units are "g", "kg", "t", "lb" and their "CO2e" variants (case-insensitive). Returns the converted value in kilograms. It returns ErrNegativeValue if value is less than zero, ErrInvalidUnit if the unit is not recognized, and ErrCalculationOverflow if the input is Inf or NaN or if the multiplication results in an overflow.

Types

type CarbonInput

type CarbonInput struct {
	// Value is the numeric carbon emission amount.
	Value float64 `json:"value"`

	// Unit is the measurement unit (g, kg, t, gCO2e, kgCO2e, tCO2e, lb, lbCO2e).
	Unit string `json:"unit"`
}

CarbonInput represents carbon emission data for equivalency calculation.

type EquivalencyOutput

type EquivalencyOutput struct {
	// InputKg is the normalized input value in kilograms CO2e.
	InputKg float64 `json:"input_kg"`

	// Results contains calculated equivalencies in priority order.
	Results []EquivalencyResult `json:"results"`

	// DisplayText is the full prose format for CLI/TUI output.
	// Example: "Equivalent to driving ~781 miles or charging ~18,248 smartphones"
	DisplayText string `json:"display_text"`

	// CompactText is the abbreviated format for constrained outputs.
	// Example: "(≈ 781 mi, 18,248 phones)"
	CompactText string `json:"compact_text"`

	// IsEmpty returns true if no equivalencies were calculated.
	IsEmpty bool `json:"is_empty"`
}

EquivalencyOutput contains all equivalency results for display.

func Calculate

func Calculate(ctx context.Context, input CarbonInput) (EquivalencyOutput, error)

Calculate computes carbon equivalencies for the given carbon input.

It normalizes the input value to kilograms, then calculates equivalencies using EPA formulas for miles driven and smartphones charged.

Returns an empty output if the input is below MinEquivalencyThresholdKg. Returns an error for invalid units or negative values.

Example:

input := CarbonInput{Value: 150.0, Unit: "kg"}
output, err := Calculate(input)

Calculate converts a CarbonInput to kilograms and computes EPA-based equivalencies expressed as miles driven and smartphones charged.

If normalization to kilograms fails, Calculate returns an empty EquivalencyOutput (IsEmpty = true) and the normalization error. If the normalized kilogram value is below MinEquivalencyThresholdKg, Calculate returns an empty EquivalencyOutput with InputKg set to the normalized value and no error. If numeric overflow or invalid results occur during equivalency calculation, Calculate returns an empty EquivalencyOutput with ErrCalculationOverflow.

On success, the returned EquivalencyOutput contains InputKg, a Results slice with EquivalencyMilesDriven and EquivalencySmartphonesCharged entries (each containing the raw and formatted values and a label), a human-readable DisplayText of the form "Equivalent to driving ~{miles} miles or charging ~{phones} smartphones", a CompactText for diagnostics "(≈ {miles} mi, {phones} phones)", and IsEmpty = false.

The ctx parameter enables trace ID propagation for contextual logging in callers.

func CalculateFromMap

func CalculateFromMap(ctx context.Context, metrics map[string]SustainabilityMetric) EquivalencyOutput

CalculateFromMap extracts carbon data from a sustainability metrics map and calculates equivalencies.

It looks for the "carbon_footprint" key first (canonical), then falls back to the deprecated "gCO2e" key for backward compatibility.

Returns an empty output if no carbon metric is found or if the value is below the threshold.

Example:

metrics := map[string]SustainabilityMetric{
    "carbon_footprint": {Value: 150.0, Unit: "kg"},
}

CalculateFromMap extracts a carbon metric from the provided metrics map and computes equivalencies.

If the map is nil or contains neither the canonical key "carbon_footprint" nor the deprecated key "gCO2e", the function returns an empty EquivalencyOutput with IsEmpty set to true. The function prefers the canonical key; if only the deprecated key is present a deprecation warning is logged. If equivalency computation fails for a found metric, a warning is logged and an empty EquivalencyOutput is returned.

Parameters:

  • ctx: context for trace ID propagation and contextual logging.
  • metrics: a map of metric keys to SustainabilityMetric values from which a carbon metric may be read.

Returns:

  • EquivalencyOutput containing computed equivalencies when successful, or an empty EquivalencyOutput with IsEmpty = true on missing data or computation failure.

type EquivalencyResult

type EquivalencyResult struct {
	// Type identifies the equivalency category.
	Type EquivalencyType `json:"type"`

	// Value is the raw calculated equivalency value.
	Value float64 `json:"value"`

	// FormattedValue is the display-ready string with separators/scaling.
	FormattedValue string `json:"formatted_value"`

	// Label is the descriptive phrase (e.g., "miles driven").
	Label string `json:"label"`
}

EquivalencyResult represents a single calculated equivalency.

type EquivalencyType

type EquivalencyType int

EquivalencyType represents a category of carbon emission equivalency.

const (
	// EquivalencyMilesDriven converts CO2e to miles driven in an average passenger vehicle.
	EquivalencyMilesDriven EquivalencyType = iota

	// EquivalencySmartphonesCharged converts CO2e to smartphone full charges.
	EquivalencySmartphonesCharged

	// EquivalencyTreeSeedlings converts CO2e to tree seedlings grown for 10 years.
	// Note: Optional/future use per spec assumptions.
	EquivalencyTreeSeedlings

	// EquivalencyHomeDays converts CO2e to days of average US home electricity use.
	// Note: Optional/future use.
	EquivalencyHomeDays
)

func (EquivalencyType) String

func (e EquivalencyType) String() string

String returns a human-readable representation of the EquivalencyType.

type SustainabilityMetric

type SustainabilityMetric struct {
	Value float64 `json:"value"`
	Unit  string  `json:"unit"`
}

SustainabilityMetric mirrors engine.SustainabilityMetric for interface compatibility.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL