<jupyter_start><jupyter_text>Testing Rome2Rio APIGoal of this notebook, calculate co2 emission and offset costs. Example site: https://co2.myclimate.org/en/offset_further_emissions  SearchExample request and explanation of resposne in [docs](https://www.rome2rio.com/documentation/1-4/search/)<jupyter_code>import os
from dotenv import load_dotenv
import pandas as pd
import requests

load_dotenv()
ROME2RIO_KEY = os.getenv("ROME2RIO_KEY")

S = requests.Session()
Origin = "Bern"
Destination = "Zurich"

URL = "http://free.rome2rio.com/api/1.4/json/Search"

PARAMS = {
    "key": ROME2RIO_KEY,
    "oName": Origin,
    "dName": Destination,
    "noRideshare": True,
    "currencyCode": "EUR"
}

R = S.get(url=URL, params=PARAMS)
DATA = R.json()
# print(DATA)<jupyter_output><empty_output><jupyter_text>Print available routes, transit time and estimated costs<jupyter_code>fields = ['name', 'distance', 'totalTransitDuration', 'totalDuration', 'indicativePrices']
routes = [
    {k: route[k] for k in fields}
    for route in DATA['routes']
]
# routes<jupyter_output><empty_output><jupyter_text>Now calculate CO2 emmission.Need some baseline metrics for different transport modes. Taken from this [bbc blog](https://www.bbc.com/news/science-environment-493495660)<jupyter_code>emissions_pp = {
    "flight_domestic": 254,
    "flight_longhaul": 195,
    "car_1pax": 171,
    "bus": 104,
    "car_4pax": 43,
    "rail": 41,
    "coach": 27,
    "eurostar": 6,
}<jupyter_output><empty_output><jupyter_text>Aggregating it to the Rome2Rio categories we have:<jupyter_code>from statistics import mean 

emissions_pp_r2r = {
    "Drive": mean([emissions_pp['car_1pax'], emissions_pp['car_4pax']]),
    "Bus": mean([emissions_pp['bus'], emissions_pp['coach']]),
    "Train": mean([emissions_pp['rail'], emissions_pp['eurostar']]),
}<jupyter_output><empty_output><jupyter_text>So for the above 3 routes, the CO2 emission (in grams) for each option is:<jupyter_code># add co2 for each route
for route in routes:
    route.update(
        {"co2Emission": emissions_pp_r2r[route['name']] * route['distance']}
    )
[
    {k: route[k] for k in ['name', 'co2Emission']}
    for route in routes
]<jupyter_output><empty_output><jupyter_text>Now translate into how many trees you will need to compensate a gram of CO2. Using the calculation they make on [Trees for the Future](https://www.tfaforms.com/4666774)> Trees for the Future's agroforestry projects in Sub-Saharan Africa sequester CO2 through tree planting and land restoration at a cost of USD 6.91 per metric tonne of CO2. Therefore, the total cost to offset your annual CO2 emissions is: $ 0.00So we need to convert the grams to metric tonnes of CO2 first: 1 tonne is 1_000_000 grams.<jupyter_code># conver to EUR
offset_costs = 6.91 * 0.82

# add co2 compensation costs for each route
for route in routes:
    route.update(
        {"co2CompensationCost": round(route["co2Emission"] / 1_000_000 * offset_costs, 2)}
    )

[
    {k: route[k] for k in ['name', 'co2CompensationCost']}
    for route in routes
]<jupyter_output><empty_output><jupyter_text>Note: this only gives us an estimate of the cost to compensate. It doesn't tell us how many trees will be planted.Estimates vary on how much CO2 one tree will offset:- 0.2 tonne per tree. [This calculator](http://www.carbonify.com/carbon-calculator.htm) claims that 5 trees will need to be planted to ensure that at least one lives 40 years equalling 1 tonne of CO2 absorbtion. - 1 tonne per 100 years according to [here](https://www.viessmann.co.uk/heating-advice/how-much-co2-does-tree-absorb:~:text=Over%20a%20lifetime%20of%20100,to%20offset%20the%20emissions%20created.)- 7 tonnes according to [this site](https://ythakker.medium.com/how-many-new-trees-would-it-take-to-offset-our-carbon-emissions-13c78ccb09ab)<jupyter_code># add nr of trees to be planted
for route in routes:
    route.update(
        {"co2CompensationTrees": round(route["co2Emission"] / 1_000_000 * 5, 2)}
    )

[
    {k: route[k] for k in ['name', 'co2CompensationTrees']}
    for route in routes
]
print(f"Details for trip {Origin} to {Destination}:")
(
    pd.DataFrame(routes)
    [['name', 'totalDuration', 'co2Emission', 'co2CompensationCost', 'co2CompensationTrees']]
    .rename({
        "totalDuration": "totalDuration (min)",
        "co2Emission": "co2Emission (grams)",
        "co2CompensationCost": "co2CompensationCost (EUR)",
        "co2CompensationTrees": "co2CompensationTrees (# Trees)"}, axis=1)
)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12538699690402477, 'fraction_numerical': 0.03494029190623618, 'mean_word_length': 4.904699738903394, 'pattern_counts': {'":': 23, '<': 29, '<?xml version=': 0, '>': 30, 'https://': 6, 'lorem ipsum': 0, 'www.': 5, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '373346', 'license': 'MIT', 'n_tokens_mistral': 1673, 'n_tokens_neox': 1543, 'n_words': 423, 'path': 'notebooks/api/rome2rio-co2-compensator.ipynb', 'repo_name': 'stevennooijen/stairwaytotravel-backend', 'size': '4522'}