Skip to content

Instantly share code, notes, and snippets.

@martindaniel4
Created February 27, 2023 10:45
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
A script to run simulations on top of Ecobalyse API.
import pandas as pd
import requests
from datetime import date
"""
This script is used to run mass simulations from the Ecobalyse API. Documentation is available here: https://ecobalyse.beta.gouv.fr/#/api
"""
PRODUCT = 'robe'
MASS = '0.3'
EXPORT_PATH = 'output/'
TODAY = date.today().strftime('%Y-%m-%d')
def get_all_materials():
"""
Call Ecobalyse API to get all materials
"""
r = requests.get('https://ecobalyse.beta.gouv.fr/api/textile/materials')
materials = r.json()
return [material['id'] for material in materials]
def get_all_countries():
"""
Call Ecobalyse API to get all countries
"""
r = requests.get('https://ecobalyse.beta.gouv.fr/api/textile/countries')
countries = r.json()
return [country['code'] for country in countries]
def run_simulations(product, mass, materials, countries):
"""
For a given product and mass, iterate over materials, countries and returns a dataframe with the results of the simulations.
"""
simulations = []
for country in countries:
for material in materials:
payload = {'mass': mass,
'product': product,
'materials[]': f"{material};1",
'countryFabric': country,
'countryDyeing': country,
'countryMaking': country}
r = requests.get(
' https://ecobalyse.beta.gouv.fr/api/textile/simulator/detailed', params=payload)
print(f"requesting {r.url}")
try:
data = r.json()
result = _handle_detailed_wikicarbone_response(payload, data)
simulations.append(result)
except:
print(f"error on {r.url}")
print(r.text)
continue
df = pd.concat(simulations, axis=0)
df.to_csv('{}simulations_{}.csv'.format(EXPORT_PATH, TODAY), index=False)
return df
def _handle_detailed_wikicarbone_response(payload, response):
"""
Transform the response JSON returned by Ecobalyse detailed API simulator into a useable DataFrame
"""
array = []
lca = response['lifeCycle']
for step in lca:
df = pd.DataFrame()
impacts = pd.Series(step['impacts'])
df['impact'] = impacts
df.reset_index(inplace=True)
df['mass'] = payload['mass']
df['materials[]'] = payload['materials[]']
df['product'] = payload['product']
df['countryFabric'] = payload['countryFabric']
df['countryDyeing'] = payload['countryDyeing']
df['countryMaking'] = payload['countryMaking']
df['label'] = step['label']
df = df[['mass', 'materials[]', 'product',
'countryFabric', 'countryDyeing', 'countryMaking',
'label', 'index', 'impact']]
df.rename(columns={'impact': 'value', 'index': 'impact',
'materials[]': 'materials'}, inplace=True)
array.append(df)
return pd.concat(array, axis=0)
run_simulations(PRODUCT, MASS, get_all_materials(), get_all_countries())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment