Commits

Chris Mutel committed 27fc0cb

0.3.2: Add utility for contribution analysis

  • Participants
  • Parent commits d302c6d

Comments (0)

Files changed (4)

bw2analyzer/__init__.py

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

bw2analyzer/utils.py

+from __future__ import division
+from time import time
+from bw2calc import LCA
+from bw2data import Database, methods, databases, mapping
+import numpy as np
+import progressbar
+
+
+def contribution_for_all_datasets_one_method(database, method, progress=True):
+    """Calculate contribution analysis (for technosphere processes) for all inventory datasets in one database for one LCIA method.
+
+    Args:
+        *database* (str): Name of database
+        *method* (tuple): Method tuple
+
+    Returns:
+        NumPy array of relative contributions. Each column sums to one.
+        Lookup dictionary, dataset keys to row/column indices
+        Total elapsed time in seconds
+
+    """
+    def get_normalized_scores(lca):
+        scores = np.abs(np.array(
+            lca.characterized_inventory.sum(axis=0)
+        ).ravel())
+        summed = scores.sum()
+        if summed == 0:
+            return np.zeros(scores.shape)
+        else:
+            return scores / summed
+
+    start = time()
+    assert database in databases, "Can't find database %s" % database
+    assert method in methods, "Can't find method %s" % method
+    keys = Database(database).load().keys()
+    assert keys, "Database %s appears to have no datasets" % database
+
+    # Array to store results
+    results = np.zeros((len(keys), len(keys)), dtype=np.float32)
+
+    # Instantiate LCA object
+    lca = LCA({keys[0]: 1}, method=method)
+    lca.lci()
+    lca.decompose_technosphere()
+    lca.lcia()
+
+    if progress:
+        widgets = [
+            'Datasets: ',
+            progressbar.Percentage(),
+            ' ',
+            progressbar.Bar(marker=progressbar.RotatingMarker()),
+            ' ',
+            progressbar.ETA()
+        ]
+        pbar = progressbar.ProgressBar(
+            widgets=widgets,
+            maxval=len(keys)
+        ).start()
+
+    # Actual calculations
+    for index, key in enumerate(keys):
+        lca.redo_lcia({key: 1})
+        col = lca.technosphere_dict[mapping[key]]
+        try:
+            results[:, col] = get_normalized_scores(lca)
+        except:
+            # LCA score is zero
+            pass
+        if progress:
+            pbar.update(index)
+
+    if progress:
+        pbar.finish()
+
+    lca.fix_dictionaries()
+    return results, lca.technosphere_dict, time() - start
 # The short X.Y version.
 version = '0.3'
 # The full version, including alpha/beta/rc tags.
-release = '0.3.1'
+release = '0.3.2'
 
 # The language for content autogenerated by Sphinx. Refer to documentation
 # for a list of supported languages.
 from setuptools import setup
 
 setup(
-  name='bw2analyzer',
-  version="0.3.1.1",
-  packages=["bw2analyzer", "bw2analyzer.tests"],
-  author="Chris Mutel",
-  author_email="cmutel@gmail.com",
-  license=open('LICENSE.txt').read(),
-  install_requires=["brightway2", "scipy", "numpy", "requests"],
-  long_description=open('README.rst').read(),
-  url="https://bitbucket.org/cmutel/brightway2-analyzer",
-  classifiers=[
-    'Development Status :: 4 - Beta',
-    'Intended Audience :: End Users/Desktop',
-    'Intended Audience :: Developers',
-    'Intended Audience :: Science/Research',
-    'License :: OSI Approved :: BSD License',
-    'Operating System :: MacOS :: MacOS X',
-    'Operating System :: Microsoft :: Windows',
-    'Operating System :: POSIX',
-    'Programming Language :: Python',
-    'Programming Language :: Python :: 2.7',
-    'Programming Language :: Python :: 2 :: Only',
-    'Topic :: Scientific/Engineering :: Information Analysis',
-    'Topic :: Scientific/Engineering :: Mathematics',
-    'Topic :: Scientific/Engineering :: Visualization',
+    name='bw2analyzer',
+    version="0.3.2",
+    packages=["bw2analyzer", "bw2analyzer.tests"],
+    author="Chris Mutel",
+    author_email="cmutel@gmail.com",
+    license=open('LICENSE.txt').read(),
+    install_requires=["brightway2", "scipy", "numpy", "requests"],
+    long_description=open('README.rst').read(),
+    url="https://bitbucket.org/cmutel/brightway2-analyzer",
+    classifiers=[
+        'Development Status :: 4 - Beta',
+        'Intended Audience :: End Users/Desktop',
+        'Intended Audience :: Developers',
+        'Intended Audience :: Science/Research',
+        'License :: OSI Approved :: BSD License',
+        'Operating System :: MacOS :: MacOS X',
+        'Operating System :: Microsoft :: Windows',
+        'Operating System :: POSIX',
+        'Programming Language :: Python',
+        'Programming Language :: Python :: 2.7',
+        'Programming Language :: Python :: 2 :: Only',
+        'Topic :: Scientific/Engineering :: Information Analysis',
+        'Topic :: Scientific/Engineering :: Mathematics',
+        'Topic :: Scientific/Engineering :: Visualization',
     ],
 )