Chris Mutel avatar Chris Mutel committed f97b90b

3.3: Add group by emission

Comments (0)

Files changed (6)

bw2analyzer/__init__.py

 from .explorer import DatabaseExplorer
 from .report import SerializedLCAReport
 
-__version__ = (0, 3, 2)
+__version__ = (0, 3, 3)

bw2analyzer/tests/__init__.py

 from .econ import EconometricsTestCase
+from .utils import GroupingTest

bw2analyzer/tests/utils.py

+from bw2data.tests import BW2DataTest
+from bw2data import Database, Method
+from ..utils import group_by_emissions
+
+
+class GroupingTest(BW2DataTest):
+    def test_grouping_together(self):
+        biosphere_data = {
+            ("biosphere", 1): {
+                'categories': ['this'],
+                'exchanges': [],
+                'name': 'some bad stuff',
+                'type': 'emission',
+                'unit': 'kg'
+                },
+            ("biosphere", 2): {
+                'categories': ['that'],
+                'exchanges': [],
+                'name': 'some bad stuff',
+                'type': 'emission',
+                'unit': 'kg'
+                },
+        }
+
+        biosphere = Database("biosphere")
+        biosphere.register("Tests", [], len(biosphere_data))
+        biosphere.write(biosphere_data)
+
+        method = Method(("test", "LCIA", "method"))
+        method.register("points", "w00t", 2)
+        method.write([
+            (("biosphere", 1), 1.0, "GLO"),
+            (("biosphere", 2), 1.0, "GLO")
+        ])
+
+        answer = {
+            ('some bad stuff', 'kilogram'): [1.0, 1.0]
+        }
+        self.assertEquals(group_by_emissions(method), answer)
+
+    def test_grouping_separate_name(self):
+        biosphere_data = {
+            ("biosphere", 1): {
+                'categories': ['this'],
+                'exchanges': [],
+                'name': 'some bad stuff',
+                'type': 'emission',
+                'unit': 'kg'
+                },
+            ("biosphere", 2): {
+                'categories': ['that'],
+                'exchanges': [],
+                'name': 'some more bad stuff',
+                'type': 'emission',
+                'unit': 'kg'
+                },
+        }
+
+        biosphere = Database("biosphere")
+        biosphere.register("Tests", [], len(biosphere_data))
+        biosphere.write(biosphere_data)
+
+        method = Method(("test", "LCIA", "method"))
+        method.register("points", "w00t", 2)
+        method.write([
+            (("biosphere", 1), 1.0, "GLO"),
+            (("biosphere", 2), 2.0, "GLO")
+        ])
+
+        answer = {
+            ('some bad stuff', 'kilogram'): [1.0],
+            ('some more bad stuff', 'kilogram'): [2.0]
+        }
+        self.assertEquals(group_by_emissions(method), answer)
+
+    def test_grouping_separate_unit(self):
+        biosphere_data = {
+            ("biosphere", 1): {
+                'categories': ['this'],
+                'exchanges': [],
+                'name': 'some bad stuff',
+                'type': 'emission',
+                'unit': 'kg'
+                },
+            ("biosphere", 2): {
+                'categories': ['that'],
+                'exchanges': [],
+                'name': 'some bad stuff',
+                'type': 'emission',
+                'unit': 'tonne'
+                },
+        }
+
+        biosphere = Database("biosphere")
+        biosphere.register("Tests", [], len(biosphere_data))
+        biosphere.write(biosphere_data)
+
+        method = Method(("test", "LCIA", "method"))
+        method.register("points", "w00t", 2)
+        method.write([
+            (("biosphere", 1), 1.0, "GLO"),
+            (("biosphere", 2), 2.0, "GLO")
+        ])
+
+        answer = {
+            ('some bad stuff', 'kilogram'): [1.0],
+            ('some bad stuff', 'tonne'): [2.0]
+        }
+        self.assertEquals(group_by_emissions(method), answer)

bw2analyzer/utils.py

 from __future__ import division
 from time import time
 from bw2calc import LCA
-from bw2data import Database, methods, databases, mapping
+from bw2data import Database, methods, databases, mapping, Method
 import numpy as np
 import progressbar
 
 
     lca.fix_dictionaries()
     return results, lca.technosphere_dict, time() - start
+
+
+def group_by_emissions(method):
+    """Group characterization factors by name and unit.
+
+    Does not work on regionalized LCIA methods!
+
+    Args:
+        *method* (tuple or Method): LCIA method
+
+    Returns:
+        Dictionary: {(name, unit)}: [cfs... ]
+
+    """
+    if isinstance(method, Method):
+        data = method.load()
+    elif isinstance(method, tuple):
+        data = Method(method).load()
+    else:
+        raise ValueError("Can't interpret %s as a LCIA method" % method)
+
+    biosphere = Database("biosphere").load()
+    grouped = {}
+
+    for key, cf, geo in data:
+        if geo != "GLO":
+            raise ValueError(
+                "`group_by_emissions` doesn't work on regionalized methods"
+            )
+        if key[0] != "biosphere":
+            # Alternative biosphere, e.g. Ecoinvent 3. Add new biosphere DB
+            biosphere.update(**Database(key[0]).load())
+        flow = biosphere[key]
+        label = (flow["name"], flow["unit"])
+        grouped.setdefault(label, []).append(cf)
+
+    return grouped
 # The short X.Y version.
 version = '0.3'
 # The full version, including alpha/beta/rc tags.
-release = '0.3.2'
+release = '0.3.3'
 
 # The language for content autogenerated by Sphinx. Refer to documentation
 # for a list of supported languages.
 
 setup(
     name='bw2analyzer',
-    version="0.3.2",
+    version="0.3.3",
     packages=["bw2analyzer", "bw2analyzer.tests"],
     author="Chris Mutel",
     author_email="cmutel@gmail.com",
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.