Skip to content

Instantly share code, notes, and snippets.

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
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:
PRODUCT = 'robe'
MASS = '0.3'
EXPORT_PATH = 'output/'
TODAY ='%Y-%m-%d')
def get_all_materials():
Call Ecobalyse API to get all materials
r = requests.get('')
materials = r.json()
return [material['id'] for material in materials]
def get_all_countries():
Call Ecobalyse API to get all countries
r = requests.get('')
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(
'', params=payload)
print(f"requesting {r.url}")
data = r.json()
result = _handle_detailed_wikicarbone_response(payload, data)
print(f"error on {r.url}")
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['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)
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