Coder Social home page Coder Social logo

pledge4future / co2calculator Goto Github PK

View Code? Open in Web Editor NEW
12.0 12.0 5.0 10.92 MB

Python package to calculate work related CO2 emissions from heating and electricity consumption as well as business trips and commuting.

Home Page: https://pledge4future.github.io/co2calculator/

License: GNU General Public License v3.0

Python 100.00%
climate-change co2-emissions paris-agreement research

co2calculator's People

Contributors

akokam avatar alexbercik avatar codingfabi avatar dependabot[bot] avatar fabiankneissl avatar han16nah avatar nkrasovec avatar redfrexx avatar sarahmadeleine avatar veitu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

co2calculator's Issues

Calculate distance of a train trip

If the user does not know how many kilometers a train ride contained, is there a way to calculate this for the user if they provide us with the start and end point?

Warnings

Transform existing print statements with "Warning" to actual warnings:

import warnings
warnings.warn("Warning message")

and add new warnings for the case that the user did not provide certain parameters and a default value is used.
(see issue #43 )

Car transport: Use custom fuel consumption

Instead of using one of the predefined emission factors, users can also put in their specific fuel consumption (e.g., if they track it themselves).
We should implement this.

  • get manufacturing emissions separately
  • calculate emission from the exact fuel combustion (needed: emission factors for the fuel combustion)

Uncertainty Score

Desgin an uncertainty score for the data put in by the users. Were average values used all the time or were more specific values (e.g., fuel type, size class, etc.) used?

Figure out which data should be retained in the database so that the score could be recalculated later. Right now we try to store as less data as possible so that we don't run into data privacy issues

Separate distance calculation from emission calculation

Most of the business logic is designed to calculate distance and emissions from relatively low-level functions in one go. This makes it really hard to test and maintain. Also, it is prone to human error when editing code.

Calculating distance and calculating emissions should be clearly separated. Function names should be as precise as possible. All emission calculation functions should only accept distance, no stops etc.

Accepted when:

  • Functional testing of backend calls is implemented (to ensure integration safety with backend)
  • Dedicated functions to calculate distance from stops, start-destination, .. are implemented (and tested)
  • Used interfaces of backend code is refactored to use new distance-functions, then call emission calculation

Side effect:

  • Code is refactored to DRY principle

Emission factor for hybrid cars

We do not have emission factors for hybrid cars. Would we awesome if we find any, because there are quite a lot of plug-in-hybrids in Germany.
Alternative: use gasoline emission factors for plug-in hybrids?

Implement calc_co2e_businesstrip

Implement the function calc_co2e_businesstrip:

def calc_co2_businesstrip(transportation_mode, start=None, destination=None, distance=None,
car_size=None, car_fuel_type=None, bus_size=None, bus_fuel_type=None,
capacity=None, occupancy=None, passengers=None, roundtrip=None):
"""
Calculate co2 emissions for a business trip (not implemented yet)
:param start:
:param destination:
:param distance:
:return:
"""
pass
return 999

Travel emissions - Air travel

We still need a methodology for air travel emissions.

Here some references:

Implement calc_co2_commuting

def calc_co2_commuting_per_mode(transportation_mode, distance=None,
                          size=None, fuel_type=None, occupancy=None, passengers=None, work_weeks=None):
    """
    Calculate co2 emissions for commuting per mode of transport (not implemented yet)
    :param transportation_mode: [car, bus, train, bicycle, pedelec, motorcycle, tram]
    :param distance: distance in km per week
    :param size: size of car or bus if applicable
    :param fuel_type: fuel type of car, bus or train if applicable
    :param occupancy: occupancy, if applicable/known (only for bus)
    :param passengers: number of passengers, if applicable (only for car)
    :param work_weeks: number of working weeks per year,
                e.g., 52 (weeks per year) - 4 (paid leave) - 2 (public holidays) = 42
    :return: total emissions for the respective mode of transport
    """
    pass
    return 999

Might have to be adapted, if calculating on a monthly instead of yearly basis..

Interface improvements

Some things discovered when writing unit tests so far:

  • A lot of repeated code for distance and emission calculation (hurting DRY principle)
  • Methods often have too many arguments
  • Arguments are often not validated inside a method (hence, likely to crash)

Mitigations:

  • Use enums instead of lists of strings to declare types (e.g., transportation_mode)
  • Implement models for input and output including validators (with the help of pydantic)
  • Implement models for complex arguments including validators (like stop)

Building emissions

Often, electricity and heating consumption will only be available on the building level. Therefore, it is important to know what area the lab occupies to obtain the lab's consumption.

heating emissions = energy consumption for heating of building * share of floorspace of lab * emission factor

The user can then either directly provide the share of floorspace or both the floorspace of the lab and the entire floorspace of the building.

Find good solution for pelias geocoding for routing

Currently, our geocoding function looks like this:

def geocoding(address):
    """
    Function to obtain coordinates for a given address
    :param address: Location/Address to be searched
            user should give address in the form:
            <adress>, <locality>, <country>
            e.g. Hauptbahnhof, Heidelberg, Germany
            e.g. Im Neuenheimer Feld 348, Heidelberg, Germany
            e.g. Heidelberg, Germany
    :return: Name, country and coordinates of the found location
    """

    clnt = openrouteservice.Client(key=ors_api_key)

    call = pelias_search(clnt, address)
    for feature in call["features"]:
        name = feature["properties"]["name"]
        country = feature["properties"]["country"]
        coords = feature["geometry"]["coordinates"]
        break

    return name, country, coords

->

def geocoding(address):

This means that from a (potentially very long) results list, we simply choose the first one, which will often be wrong.
Here, we need a good solution, e.g.

Return value of `calc_co2e_commuting`is inconsistent

For transport_mode=car calc_co2_commuting returns a tuple (emissions, distance),

co2e = calc_co2_commuting(transportation_mode="car",
                                     weekly_distance=distance,
                                     passengers=1,
                                     size="medium",
                                     fuel_type="gasoline")

but for transport_mode=bike a float value emissions.

co2e = calc_co2_commuting(transportation_mode="bicycle",
                          weekly_distance=distance)

I guess it would be best, if it always returns a tuple (emissions, distance).

Prepare for going public

  • Fix currently open issues - (see milestone)
  • update documentation
  • merge dev into main
  • go public :)

Documentation of methodology

Document the methodology in the markfown file

How to account for emissions of externals (events, lectures, guests, etc.)

In many (esp. academic) institutions, there will be lectures, events, hosted conferences, etc., which can often produce high amounts of emissions but also include external people.

We should include such events in the calculator (consider in completeness score?), and think about how to account for it:

  • Do we distribute it on all participants (incl. externals) and then only count the emissions of internals to the institution's emissions?
  • Do we also store such "external/guest's emissions" for each institute (separately for the other emissions)?

Calculation of emissions from vehicles operated from a lab

There might be transport emissions which are covered by neither of the categories "business trips" and "commuting".
Those include the emissions related to vehicles operated by the lab. This may usually be an institute car or bus, but depending on research area could also be a ship or helicopter.

General formula:
Emission of a vehicle operated by the lab = annual quantity consumed of the energy source used * emission factor of the source concerned.

The quantity consumed may be expressed in km traveled, flight hours, liter consumed or sea-days.

See also: https://labos1point5.org/ges-1point5 -> La méthodologie -> Méthods de calculs

How to consider emissions when in Home Office

Since 2020, many people are working in home office. Therefore, some electricity consumption will not be accounted for if only using the institution's building electricity consumption.

We should have an option to also count emissions in home office.

This may be calculated by the device(s) used in home office and the duration of daily/weekly usage. Lighting is also important and heating (you usually don't heat your home while you are at work).

The heating emissions in home office could be estimated in the following way: monthly heating consumption / number of people in the household * share of the month spent working at home

Overhaul distance calculation

Context:

  • Streamline different methods of distance calculations
  • Avoid loading DataFrame|s as global vars
  • Make it a "Service"
  • Define clear interfaces

Check mandatory and optional arguments

The following code fails with unsupported operand type(s) for /: 'float' and 'NoneType' when the argument passenger is not given.

co2e = calc_co2_commuting(transportation_mode="car",
                                 weekly_distance=20,
                                 size="medium,
                                 fuel_type="gasoline")

I think it would be good to either set a default value (e.g. 1) or raise an AssertionError at the beginning of the function. Would be good to check if other combinations of arguments cause similar errors.

Extension: Devices and paper

We could add a section for

  • electronic/research devices (new acquisitions, inventory)
  • paper (office paper, possibly also toilet paper etc.)

doesn't contribute massively to emissions, but maybe add water consumption as well

Travel emissions - occupancy bus

Emissions from bus travels highly depend on the occupancy (i.e. what % of seats are occupied).
Below are some figures demonstrating this (data downloaded from probas database, can be found in data/probas/bus.
We should therefore also ask the user for an estimate on bus size (3,5-18 t or 18-30 t) and occupancy (i.e. almost empty (20%), half full (50%), almost full (80%), full (100%)). Most will not be able to answer this, where we can use the one with average size and occupancy of 50 %.

bus_co2-emissions
bus_small_co2-emissions
bus_small_co2-emissions_nach_auslastung

Improve testing of distance-calculating methods

Some of the tests are actively calling openrouteservice - which is not really a good practice for unit or functional testing.
Those interfaces shall be mocked. If - for any reason - those calls are really wanted, those tests should be moved to proper integration tests.

Write unit tests

We currently have tests in calculate.py using data from external .csv-files.

We should rewrite them to unit test into a file "testing.py".

Add emission factors for other modes of transport

For computing the commuting emissions, we need emission factors for:

  • E-bike (currently only: Pedelec)
  • Hybrid cars
  • Scooter
  • Motorcycle
  • Tram
  • Urban bus
  • Local train
  • Metro

For business trips, we might add:

  • boats/ships (e.g. ferries) -> find out detour coefficient??
  • different types of planes?

Find database for train stations

Background:

Users will not know the adress of the stations, but currently our geocoding service needs an address. Check if there is an API that links the train stations to the addresses.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.