Commits

Chris Mutel  committed 40e7a81

Compatibility with 0.12 bw2data and 0.11 bw2calc

  • Participants
  • Parent commits f5bb5e0
  • Tags 0.5

Comments (0)

Files changed (8)

+Changelog
+*********
+
+0.5 (2014-01-29)
+================
+

File bw2analyzer/__init__.py

 from .sc_graph import GTManipulator
 from .report import SerializedLCAReport
 
-__version__ = (0, 4)
+__version__ = (0, 5)

File bw2analyzer/report.py

 # -*- coding: utf-8 -*-
 from __future__ import division
 from . import ContributionAnalysis, GTManipulator
+from .econ import herfindahl_index, concentration_ratio
 from brightway2 import JsonWrapper, methods, config
 from bw2calc import ParallelMonteCarlo, LCA, GraphTraversal
 from scipy.stats import gaussian_kde
 
 class SerializedLCAReport(object):
     """A complete LCA report (i.e. LCA score, Monte Carlo uncertainty analysis, contribution analysis) that can be serialized to a defined standard."""
-    version = 1
+    version = 2
 
     def __init__(self, activity, method, iterations=10000, cpus=None,
             outliers=0.025):
         lca.fix_dictionaries()
         rt, rb = lca.reverse_dict()
 
+        gt = GraphTraversal().calculate(self.activity, method=self.method)
+        force_directed = self.get_force_directed(gt['nodes'], gt['edges'], lca)
         ca = ContributionAnalysis()
         hinton = ca.hinton_matrix(lca)
-        treemap = ca.d3_treemap(lca.characterized_inventory, rb, rt)
-        herfindahl = ca.herfindahl_index(
-            lca.characterized_inventory, lca.score)
-        concentration = ca.concentration_ratio(
-            lca.characterized_inventory, lca.score)
+        treemap = self.get_treemap(gt['nodes'], gt['edges'], lca)
+        herfindahl = herfindahl_index(lca.characterized_inventory.data)
+        concentration = concentration_ratio(lca.characterized_inventory.data)
 
         self.report = {
             "activity": [(ca.get_name(k), "%.2g" % v, ca.db_names[k[0]][k][
                 "herfindahl": herfindahl,
                 "concentration": concentration
                 },
-            "force_directed": self.get_force_directed(),
+            "force_directed": force_directed,
             "monte carlo": self.get_monte_carlo(),
             "metadata": {
                 "type": "Brightway2 serialized LCA report",
                 },
             }
 
+    def get_treemap(self, nodes, edges, lca, unroll_cutoff=0.01,
+                simplify_limit=0.1):
+        nodes, edges, links = GTManipulator.unroll_graph(nodes, edges, lca.score, cutoff=unroll_cutoff)
+        nodes, edges = GTManipulator.simplify(nodes, edges, lca.score, limit=simplify_limit)
+        return GTManipulator.d3_treemap(nodes, edges, lca)
+
     def get_monte_carlo(self):
         """Get Monte Carlo results"""
         if not self.iterations:
             iterations=self.iterations,
             cpus=self.cpus
             ).calculate())
+        # mc_data = np.random.lognormal(size=self.iterations)
         mc_data.sort()
         if np.unique(mc_data).shape[0] == 1:
             # No uncertainty in database
                 }
             }
 
-    def get_force_directed(self):
+    def get_force_directed(self, nodes, edges, lca):
         """Get graph traversal results"""
-        gt = GraphTraversal()
-        traversal = gt.calculate(self.activity, self.method)
         nodes, edges = GTManipulator.simplify_naive(
-            traversal['nodes'],
-            traversal['edges'],
-            traversal['lca'].score
+            nodes,
+            edges,
+            lca.score
         )
-        nodes = GTManipulator.add_metadata(nodes, traversal['lca'])
-        return GTManipulator.reformat_d3(nodes, edges, traversal['lca'].score)
+        nodes = GTManipulator.add_metadata(nodes, lca)
+        return GTManipulator.d3_force_directed(nodes, edges, lca.score)
 
     def write(self):
         """Write report data to file"""

File bw2analyzer/sc_graph.py

 import copy
 import itertools
 from heapq import heappush, heappop
-from bw2data import Database
+from bw2data import Database, config
 
 
 def tupify(o):
 
         child_nodes = lambda node, edges: [e['from'] for e in edges if e['to'] == node]
 
+        counter = itertools.count(1)
+
         def format_node(node_key, node_data, rt):
             if node_key == -1:
                 return {
                     'name': 'Functional unit',
                     'unit': 'unit',
-                    'location': 'GLO',
+                    'location': config.global_location,
                     'categories': "",
-                    'id': node_key,
+                    'id': counter.next(),
                     'amount': 1.
                 }
 
                 'unit': ds['unit'],
                 'location': ds['location'],
                 'categories': ", ".join(ds['categories']),
-                'id': node_key,
+                'id': counter.next(),
                 'amount': node_data['amount']
             }
 

File bw2analyzer/utils.py

 
     if progress:
         widgets = [
-            'Datasets: ',
-            progressbar.Percentage(),
-            ' ',
-            progressbar.Bar(marker=progressbar.RotatingMarker()),
-            ' ',
+            progressbar.SimpleProgress(sep="/"), " (",
+            progressbar.Percentage(), ') ',
+            progressbar.Bar(marker=progressbar.RotatingMarker()), ' ',
             progressbar.ETA()
         ]
         pbar = progressbar.ProgressBar(
     grouped = {}
 
     for key, cf, geo in data:
-        if geo != "GLO":
+        if geo != config.global_location:
             raise ValueError(
                 "`group_by_emissions` doesn't work on regionalized methods"
             )
-        if key[0] != "biosphere":
+        if key[0] != config.biosphere:
             # Alternative biosphere, e.g. Ecoinvent 3. Add new biosphere DB
             biosphere.update(**Database(key[0]).load())
         flow = biosphere[key]

File docs/conf.py

 # Note that not all possible configuration values are present in this
 # autogenerated file.
 #
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+version = '0.5'
+# The full version, including alpha/beta/rc tags.
+release = '0.5'
+
 # All configuration values have a default; values that are commented out
 # serve to show the default.
 
 project = u'bw2analyzer'
 copyright = u'2013, Chris Mutel'
 
-# The version info for the project you're documenting, acts as replacement for
-# |version| and |release|, also used in various other places throughout the
-# built documents.
-#
-# The short X.Y version.
-version = '0.4'
-# The full version, including alpha/beta/rc tags.
-release = '0.4'
-
 # The language for content autogenerated by Sphinx. Refer to documentation
 # for a list of supported languages.
 #language = None

File requirements.txt

 numpy>=1.6
 requests>=1.1.0
 scipy
-brightway2>=0.10
-bw2calc>=0.10.1
-bw2data>=0.10.1
+brightway2
+bw2calc
+bw2data
 
 setup(
     name='bw2analyzer',
-    version="0.4",
+    version="0.5",
     packages=["bw2analyzer", "bw2analyzer.tests"],
     author="Chris Mutel",
     author_email="cmutel@gmail.com",
     long_description=open('README.rst').read(),
     url="https://bitbucket.org/cmutel/brightway2-analyzer",
     classifiers=[
-        'Development Status :: 4 - Beta',
+        'Development Status :: 5 - Production/Stable',
         'Intended Audience :: End Users/Desktop',
         'Intended Audience :: Developers',
         'Intended Audience :: Science/Research',