Skip to content

Commit

Permalink
Merge pull request #1 from maasglobal/initial-package
Browse files Browse the repository at this point in the history
Initial package
  • Loading branch information
Markus Shepherd authored Nov 14, 2019
2 parents 0fd8eab + 7ae3bac commit 353a3f9
Show file tree
Hide file tree
Showing 9 changed files with 367 additions and 2 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,6 @@ venv.bak/

# mypy
.mypy_cache/

# IDE
.vscode
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
include README.md LICENSE
12 changes: 12 additions & 0 deletions Pipfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]
twine = "*"

[packages]

[requires]
python_version = "3.6"
128 changes: 128 additions & 0 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 35 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,35 @@
# transport-co2
Library to calculate CO2 (equivalent) emissions for a given transport trip.
# Transport CO2

Calculate CO2 (equivalent) emissions for a given transport trip and provide a simple interpretation of the result.

## Goals

This project is intended to be used to help raise awareness about the cost of transportation choices, so people can make informed decisions.

## Initial focus

We are initially focused on ground (road and rail) transport, as it is the most significant source on transport greenhouse gas emissions.

## API Design

This library intends to provide:

- a statistical estimate of greenhouse gase emissions given information about a trip (origin/destination, mode, and/or distance)
- a simple interpretation of the statistical emissions estimate, in terms such as "high" or "low"

## Research

The carbon estimates produced by this model may be based on the following resources. A full description of the model, including data sources, will be provided as the library takes shape.

- European Environment Agency [CO2 emissions from passenger transport](https://www.eea.europa.eu/media/infographics/co2-emissions-from-passenger-transport/view)

Further improvements to the model may come from other sources, such as the following.

- IPCC AR5 [Chapter 8 - Transport](https://www.ipcc.ch/site/assets/uploads/2018/02/ipcc_wg3_ar5_chapter8.pdf)
- Wikipedia: [Environmental impact of transport](https://en.wikipedia.org/wiki/Environmental_impact_of_transport)

## Attribution

Initial package structure forked from [navdeep-G/setup.py](https://github.com/navdeep-G/setup.py).

Friendly nod to [jamiebull1/transport-carbon](https://github.com/jamiebull1/transport-carbon).
126 changes: 126 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Note: To use the 'upload' functionality of this file, you must:
# $ pipenv install twine --dev

import io
import os
import sys
from shutil import rmtree

from setuptools import find_packages, setup, Command

# Package meta-data.
NAME = "transport-co2"
DESCRIPTION = (
"Library to calculate CO2 (equivalent) emissions for a given transport trip."
)
URL = "https://github.com/maasglobal/transport-co2"
EMAIL = "[email protected], [email protected]"
AUTHOR = "Brylie Christopher Oxley, Markus Schepke"
REQUIRES_PYTHON = ">=3.6.0"
VERSION = "0.1.0"

# What packages are required for this module to be executed?
REQUIRED = []

# What packages are optional?
EXTRAS = {}

# The rest you shouldn't have to touch too much :)
# ------------------------------------------------
# Except, perhaps the License and Trove Classifiers!
# If you do change the License, remember to change the Trove Classifier for that!

here = os.path.abspath(os.path.dirname(__file__))

# Import the README and use it as the long-description.
# Note: this will only work if 'README.md' is present in your MANIFEST.in file!
try:
with io.open(os.path.join(here, "README.md"), encoding="utf-8") as f:
long_description = "\n" + f.read()
except FileNotFoundError:
long_description = DESCRIPTION

# Load the package's __version__.py module as a dictionary.
about = {}
if not VERSION:
project_slug = NAME.lower().replace("-", "_").replace(" ", "_")
with open(os.path.join(here, project_slug, "__version__.py")) as f:
exec(f.read(), about)
else:
about["__version__"] = VERSION


class UploadCommand(Command):
"""Support setup.py upload."""

description = "Build and publish the package."
user_options = []

@staticmethod
def status(s):
"""Prints things in bold."""
print("\033[1m{0}\033[0m".format(s))

def initialize_options(self):
pass

def finalize_options(self):
pass

def run(self):
try:
self.status("Removing previous builds…")
rmtree(os.path.join(here, "dist"))
except OSError:
pass

self.status("Building Source and Wheel (universal) distribution…")
os.system("{0} setup.py sdist bdist_wheel --universal".format(sys.executable))

self.status("Uploading the package to PyPI via Twine…")
os.system("twine upload dist/*")

self.status("Pushing git tags…")
os.system("git tag v{0}".format(about["__version__"]))
os.system("git push --tags")

sys.exit()


# Where the magic happens:
setup(
name=NAME,
version=about["__version__"],
description=DESCRIPTION,
long_description=long_description,
long_description_content_type="text/markdown",
author=AUTHOR,
author_email=EMAIL,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(exclude=["tests", "*.tests", "*.tests.*", "tests.*"]),
# If your package is a single module, use this instead of 'packages':
# py_modules=['mypackage'],
# entry_points={
# 'console_scripts': ['mycli=mymodule:cli'],
# },
install_requires=REQUIRED,
extras_require=EXTRAS,
include_package_data=True,
license="MIT",
classifiers=[
# Trove classifiers
# Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
],
# $ setup.py publish support.
cmdclass={"upload": UploadCommand},
)
2 changes: 2 additions & 0 deletions transport_co2/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .model import Mode
from .estimator import estimate_co2
20 changes: 20 additions & 0 deletions transport_co2/estimator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from typing import Optional, Union
from .model import Mode


def estimate_co2(
mode: Union[str, Mode], distance_in_km: float, occupancy: Optional[float] = None
) -> float:
"""
Estimate CO2 usage for transport mode based on KM and optional vehicle occupancy.
Keyword arguments:
mode -- vehicle mode (limited to allowed values)
distance_in_km -- distance for the trip in kilometers
occupancy -- optional vehicle occupancy (uses average occupancy if falsey)
"""
if isinstance(mode, str):
mode = Mode[mode.upper()]

return mode.estimate_co2(distance_in_km, occupancy)

40 changes: 40 additions & 0 deletions transport_co2/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from enum import Enum
from typing import Optional


class Mode(Enum):
"""
Data structure containing grams of CO2/vehicle KM for several modes of transport
along with average occupancy for each mode.
Source data:
CO2 emissions from passenger transport
from European Environment Agency
https://www.eea.europa.eu/media/infographics/co2-emissions-from-passenger-transport/view
"""

def __init__(self, co2_per_vehicle_km: float, average_occupancy: float):
self.co2_per_vehicle_km = co2_per_vehicle_km
self.average_occupancy = average_occupancy

LIGHT_RAIL = (2184, 156)
SMALL_CAR = (168, 1.5)
LARGE_CAR = (220, 1.5)
SCOOTER = (86.4, 1.2)
BUS = (863, 12.7)

def estimate_co2(
self, distance_in_km: float, occupancy: Optional[float] = None
) -> float:
"""
Estimate CO2 usage for transport mode based on KM and optional vehicle occupancy.
Keyword arguments:
distance_in_km -- distance for the trip in kilometers
occupancy -- optional vehicle occupancy (uses average occupancy if falsey)
"""
# occupancy should be above zero
occupancy = occupancy or self.average_occupancy

return self.co2_per_vehicle_km * distance_in_km / occupancy

0 comments on commit 353a3f9

Please sign in to comment.