Instantly share code, notes, and snippets.

What would you like to do?
MVP for a server that runs Brightway2-calc calculations
from bw2calc import IndepentLCAMixin, LCA as _LCA
from flask import request, Flask, jsonify
from io import TextIOWrapper
import csv
import numpy as np
import os
import tempfile
"""Run bw2calc without using a backend - instead, send LCI/A data as CSV files in a web request.
To run: Install dependencies, and gunicorn, then do `gunicorn bw2calc_alone:application`."""
class LCA(IndepentLCAMixin, _LCA):
application = Flask(__name__)
('input', np.uint32),
('output', np.uint32),
('row', np.uint32),
('col', np.uint32),
('type', np.uint8),
('amount', np.float32),
('flow', np.uint32),
('geo', np.uint32),
('row', np.uint32),
('amount', np.float32),
MAX_INT_32 = 4294967295
@application.route("/", methods=['POST'])
def lca_calculation():
with tempfile.TemporaryDirectory() as dirpath:
arr = np.array([
(int(inp), int(outp), MAX_INT_32, MAX_INT_32, int(typ), float(amnt))
for inp, outp, typ, amnt in csv.reader(TextIOWrapper(request.files['lci']))
], dtype=LCI_DTYPE), "lci.npy"), arr, allow_pickle=False)
arr = np.array([
(int(flow), 1, MAX_INT_32, float(amnt))
for flow, amnt in csv.reader(TextIOWrapper(request.files['lcia']))
], dtype=LCIA_DTYPE), "lcia.npy"), arr, allow_pickle=False)
config = {'demand': {
int(request.form['activity']): float(request.form['amount'])},
'database_filepath': [os.path.join(dirpath, "lci.npy")],
'method': [os.path.join(dirpath, "lcia.npy")],
lca = LCA(**config)
return jsonify({'score': lca.score})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment