Chris Mutel avatar Chris Mutel committed 15adfc0

0.4.1: Working LCA process select and calculation

Comments (0)

Files changed (5)

 
 app = Flask(__name__)
 
+###########################
+### Basic functionality ###
+###########################
+
 
 @app.errorhandler(404)
 def page_not_found(e):
     # Log error?
     return render_template('500.html'), 500
 
+############
+### Jobs ###
+############
+
 
 @app.route("/status/<job>")
 def job_status(job):
     except InvalidJob:
         abort(500)
 
+###################
+### Basic views ###
+###################
+
 
 @app.route('/')
 def index():
     return render_template("index.html", **context)
 
 
+@app.route('/start', methods=["GET", "POST"])
+def start_bw():
+    """Start Brightway"""
+    job_id = get_job_id()
+    if request.method == "GET":
+        pass
+    elif not request.form["confirm"] == "false":
+        return redirect(url_for(index) + "?temp_dir_ok=True")
+    # Starting Brightway
+    # If POST[action] = "get_biosphere":
+    set_job_status(job_id, {"action": "biosphere-import", "finished": False})
+    # Download file to disk
+    DatabaseImporter().importer(biosphere)
+    set_job_status(job_id, {"action": "biosphere-import", "finished": True})
+
+    # Step two
+    # Import IA methods
+    # Can also be from dropbox
+
+    # Step three
+    # Import Ecoinvent or other LCI database
+
+    # Step four
+    # There is no step four!
+    # Actually, there is: go to the normal homepage
+
+
+###########
+### LCA ###
+###########
+
+
 @app.route('/database/<name>/names')
 def activity_names(name):
     if name not in databases:
         return "---"
 
 
-@app.route('/select')
-def process_selector():
-    return render_template("select.html",
-        db_names=[x for x in databases.list if x != "biosphere"],
-        lcia_methods=[{
-            "l1": get_tuple_index(key, 0),
-            "l2": get_tuple_index(key, 1),
-            "l3": get_tuple_index(key, 2),
-            "u": value["unit"],
-            "n": value["num_cfs"],
-            "k": key
-        } for key, value in methods.data.iteritems() if value.get("num_cfs", 1)])
-
-
-@app.route('/hinton')
-def hinton():
-    return render_template("hinton.html")
-
-
 @app.route('/lca', methods=["GET", "POST"])
 def lca():
     if request.method == "GET":
-        return render_template("lca-select.html")
+        return render_template("select.html",
+            db_names=[x for x in databases.list if x != "biosphere"],
+            lcia_methods=[{
+                "l1": get_tuple_index(key, 0),
+                "l2": get_tuple_index(key, 1),
+                "l3": get_tuple_index(key, 2),
+                "u": value["unit"],
+                "n": value["num_cfs"],
+            } for key, value in methods.data.iteritems() if value.get("num_cfs", 1)])
     else:
-        fu = eval(request.form["activity"])
-        method = eval(request.form["method"])
+        fu = dict([
+            (tuple(x[0]), x[1]) for x in JsonWrapper.loads(request.form["activity"])
+            ])
+        method = tuple(JsonWrapper.loads(request.form["method"]))
         context = {}
         lca = LCA(fu, method)
         lca.lci()
         return render_template("lca.html", **context)
 
 
+#############
+### Tests ###
+#############
+
+
+@app.route('/hinton')
+def hinton():
+    return render_template("hinton.html")
+
+
 @app.route('/progress')
 def progress_test():
     job_id = get_job_id()
     set_job_status(status_id, {"status": "Starting..."})
     return render_template("hist.html", **{"job": job_id, 'status': status_id})
 
+#########################
+### Database explorer ###
+#########################
+
 
 def filter_sort_process_database(data, filter=None, order=None):
     if order:
         name=name, data=JsonWrapper.dumps(data))
 
 
-@app.route("/method-json/<name1>/<name2>/<name3>")
-def method_json(name1, name2, name3):
-    name = (name1, name2, name3)
-    print name, name in methods
-    if name not in methods:
-        abort(404)
-    biosphere = Database("biosphere").load()
-    print "Biosphere loaded", len(biosphere)
-    cfs = [{"n": biosphere[x[0]]["name"],
-        "c": str(biosphere[x[0]]["categories"]),
-        "a": x[1]
-        } for x in Method(name).load().iteritems()]
-    cfs.sort()
-    return json_response(cfs)
-
-
-@app.route("/method/<name1>")
-@app.route("/method/<name1>/<name2>")
-@app.route("/method/<name1>/<name2>/<name3>")
-def method_explorer(name1, name2=None, name3=None):
-    return
-
-
 def short_name(name):
     return " ".join(name.split(" ")[:3])[:25]
 
         activity=data[(name, code)]["name"],
         direction=direction.title())
 
+#######################
+### Method explorer ###
+#######################
 
-@app.route('/start', methods=["GET", "POST"])
-def start_bw():
-    """Start Brightway"""
-    job_id = get_job_id()
-    if request.method == "GET":
-        pass
-    elif not request.form["confirm"] == "false":
-        return redirect(url_for(index) + "?temp_dir_ok=True")
-    # Starting Brightway
-    # If POST[action] = "get_biosphere":
-    set_job_status(job_id, {"action": "biosphere-import", "finished": False})
-    # Download file to disk
-    DatabaseImporter().importer(biosphere)
-    set_job_status(job_id, {"action": "biosphere-import", "finished": True})
 
-    # Step two
-    # Import IA methods
-    # Can also be from dropbox
+@app.route("/method-json/<name1>/<name2>/<name3>")
+def method_json(name1, name2, name3):
+    name = (name1, name2, name3)
+    print name, name in methods
+    if name not in methods:
+        abort(404)
+    biosphere = Database("biosphere").load()
+    print "Biosphere loaded", len(biosphere)
+    cfs = [{"n": biosphere[x[0]]["name"],
+        "c": str(biosphere[x[0]]["categories"]),
+        "a": x[1]
+        } for x in Method(name).load().iteritems()]
+    cfs.sort()
+    return json_response(cfs)
 
-    # Step three
-    # Import Ecoinvent or other LCI database
 
-    # Step four
-    # There is no step four!
-    # Actually, there is: go to the normal homepage
+@app.route("/method/<name1>")
+@app.route("/method/<name1>/<name2>")
+@app.route("/method/<name1>/<name2>/<name3>")
+def method_explorer(name1, name2=None, name3=None):
+    return
 
-# Normal homepage:
-# Think of what should be here
-# At a minimum, a table of databases
-# and IA methods
-# A quick entry to LCA (define function units)
 
 # use werkzeug.utils.secure_filename to check uploaded file names
 # http://werkzeug.pocoo.org/docs/utils/

bw2ui/web/templates/index.html

 <a href="/hist">
     <button>Dynamic hist</button>
 </a>
-<a href="/progress">
-    <button>Dynamic progress update</button>
+<a href="/lca">
+    <button>LCA calculation</button>
 </a>
 <a href="/hinton">
     <button>Hinton demo</button>

bw2ui/web/templates/lca-select.html

-{% extends "base.html" %}
-
-{% block body %}
-<form action="/lca" method="POST">
-  <fieldset>
-    <legend>LCA report setup</legend>
-        <p>Activity: <input type="text" name="activity"></p>
-        <p>Method: <input type="text" name="method"></p>
-        <p><input type="submit" name="submit"></p>
-  </fieldset>
-</form>
-{% endblock %}

bw2ui/web/templates/select.html

 <div class="span-16 last">
     <h3>Selected activities:</h3>
     <p>(click to change amounts)</p>
-    <table id="selected_activities">
+    <table id="selected-activities">
         <thead>
             <tr>
                 <th>Amount</th>
         </tbody>
     </table>
 </div>
+<hr>
 <div class="clear span-24">
     <h1>Chose the LCIA method</h1>
     <h3>Chosen method: <span id="chosen-method">(click below to chose a method)</span></h3>
                 <th>Level 3</th>
                 <th># CFs</th>
                 <th>Unit</th>
-                <th>Key</th>
             </tr>
         </thead>
         <tbody>{% for m in lcia_methods %}
                 <td>{{m.l3}}</td>
                 <td>{{m.n}}</td>
                 <td>{{m.u}}</td>
-                <td>{{m.k}}</td>
             </tr>{% endfor %}
         </tbody>
     </table>
 </div>
+<hr>
+<div>
+    <form action="/lca" method="post">
+        <input type="hidden" name="activity" value="" id="hidden-activity">
+        <input type="hidden" name="method" value="" id="hidden-method">
+        <button type="submit">Calculate!</button>
+    </form>
+</div>
 <script>
 $(document).ready(function() {
-    var selected_method = null;
     $("#activity-input").prop('disabled', true);
-    $('#selected_activities').dataTable();
+    $('#selected-activities').dataTable();
     $('#lcia_methods').dataTable();
-    $('#selected_activities').dataTable().fnSetColumnVis(4, false);
-    $('#lcia_methods').dataTable().fnSetColumnVis(5, false);
+    $('#selected-activities').dataTable().fnSetColumnVis(4, false);
 
     $('input[name=database-select]:radio').change(function () {
         $("#activity-input").prop('disabled', false);
         });
     });
 
+    var method_builder = function (row) {
+        var m = [row.cells[0].textContent];
+        for (var i = 1; i <= 2; i++) {
+            if (row.cells[i].textContent !== "---") {
+                m.push(row.cells[i].textContent);
+            };
+        };
+        return m;
+    }
+
+    var get_selected_activities = function () {
+        var data = $('#selected-activities').dataTable().fnGetData(),
+            value = [];
+        for (var i = data.length - 1; i >= 0; i--) {
+            value.push([data[i][4], data[i][0]]);
+        };
+        console.log(value);
+        return value;
+    }
+
     $("#activity-input").autocomplete({
         disabled: true,
         source: ["foo", "bar", "baz"],
         select: function( event, ui ) {
-            var table = $("#selected_activities").dataTable();
+            var table = $("#selected-activities").dataTable();
             table.fnAddData([
                 1.0, ui.item.value.u, ui.item.value.n, ui.item.value.l, ui.item.value.k
             ]);
             if (table.fnGetData(0)[0] === "Not yet!") {
                 table.fnDeleteRow(0);
             };
-            $("#activity-input").html("");
+            $("#activity-input").val("");
+            $("#hidden-activity").val(JSON.stringify(get_selected_activities()));
             return false;
         },
         focus: function( event, ui ) { return false; }
             $(this).addClass('row_selected');
         }
         $("#chosen-method").html(this.cells[0].textContent + " : " + this.cells[1].textContent + " : " + this.cells[2].textContent);
-        console.log(this);
-        selected_method = this.cells[4].textContent;
-        console.log(selected_method);
+        $("#hidden-method").val(JSON.stringify(method_builder(this)));
     });
-
 });
 </script>
 {% endblock %}
 
 setup(
   name='bw2ui',
-  version="0.4",
+  version="0.4.1",
   packages=["bw2ui", "bw2ui.web"],
   package_data={'bw2ui.web': [
     "static/blueprint/*.css",
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.