Skip to content

Instantly share code, notes, and snippets.

@cmutel
Last active March 16, 2017 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmutel/a408e3a62f35519065cee125d7821d4d to your computer and use it in GitHub Desktop.
Save cmutel/a408e3a62f35519065cee125d7821d4d to your computer and use it in GitHub Desktop.
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):
pass
application = Flask(__name__)
LCI_DTYPE = [
('input', np.uint32),
('output', np.uint32),
('row', np.uint32),
('col', np.uint32),
('type', np.uint8),
('amount', np.float32),
]
LCIA_DTYPE = [
('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)
np.save(os.path.join(dirpath, "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)
np.save(os.path.join(dirpath, "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)
lca.lci()
lca.lcia()
return jsonify({'score': lca.score})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment