Commits

Chris Mutel committed 0d63760

Initial commit

Comments (0)

Files changed (10)

+syntax:glob
+dist
+*.pyc
+*~
+MANIFEST
+*.sublime*
+Copyright (c) 2012, Chris Mutel and ETH Zürich
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+Neither the name of ETH Zürich nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Empty file added.
+A python implementation of the Ecoinvent pedigree matrix for estimating uncertainty data for life cycle inventories.

pedigree_matrix/__init__.py

+# -*- coding: utf-8 -*
+from pm import PedigreeMatrix
+from ecoinvent import from_ei_text

pedigree_matrix/data.py

+# -*- coding: utf-8 -*
+from collections import defaultdict
+
+
+basic_uncertainty = {
+    "demand": {
+        "thermal energy, electricity, semi-finished products, working material, waste treatment services":
+            defaultdict(lambda: 1.05),
+        "transport services (tkm)":
+            defaultdict(lambda: 2),
+        "Infrastructure":
+            defaultdict(lambda: 3)
+        },
+    "resources": {
+        "primary energy carriers, metals, salts":
+            defaultdict(lambda: 1.05),
+        "land use, occupation": {
+            "combustion": 1.5,
+            "process": 1.5,
+            "agricultural": 1.1
+            },
+        "land use, transformation": {
+            "combustion": 2,
+            "process": 2,
+            "agricultural": 1.2
+            }
+        },
+    "water": {
+        "BOD, COD, DOC, TOC, inorganic compounds": {
+            "process": 1.5
+            },
+        "individual hydrocarbons, PAH": {
+            "process": 3
+            },
+        "heavy metals": {
+            "process": 1.5,
+            "agricultural": 1.5
+            },
+        "NO3, PO4": {
+            "agricultural": 1.2
+            }
+        },
+    "soil": {
+        "oil, hydrocarbon total": {
+            "process": 1.5
+            },
+        "heavy metals": {
+            "process": 1.5,
+            "agricultural": 1.5
+            },
+        "pesticides": {
+            "agricultural": 1.2
+            }
+        },
+    "air": {
+        "CO2": {
+            "combustion": 1.05,
+            "process": 1.05
+            },
+        "SO2": {
+            "combustion": 1.05
+            },
+        "NMVOC total": {
+            "combustion": 1.5
+            },
+        "NOx, N2O": {
+            "combustion": 1.5,
+            "agricultural": 1.4
+            },
+        "CH4, NH3": {
+            "combustion": 1.5,
+            "agricultural": 1.2
+            },
+        "individual hydrocarbons": {
+            "combustion": 1.5,
+            "process": 2
+            },
+        "PM>10": {
+            "combustion": 1.5,
+            "process": 1.5
+            },
+        "PM10": {
+            "combustion": 2,
+            "process": 2
+            },
+        "PM2.5": {
+            "combustion": 3,
+            "process": 3
+            },
+        "polycyclic aromatic hydrocarbons (PAH)": {
+            "combustion": 3
+            },
+        "CO, heavy metals": {
+            "combustion": 5
+            },
+        "inorganic emissions, others": {
+            "process": 1.5
+            },
+        "radionuclides (e.g., Radon-222)": {
+            "process": 3
+            }
+        }
+    }
+
+version_1 = {
+    "reliability": (1., 1.05, 1.1, 1.2, 1.5),
+    "completeness": (1., 1.02, 1.05, 1.1, 1.2),
+    "temporal correlation": (1., 1.03, 1.1, 1.2, 1.5),
+    "geographical correlation": (1., 1.01, 1.02, 1.02, 1.1),
+    "further technological correlation": (1., 1., 1.2, 1.5, 2),
+    "sample size": (1., 1.02, 1.05, 1.1, 1.2)
+    }
+
+version_2 = {
+    "reliability": (1., 1.54, 1.61, 1.69, 1.69),
+    "completeness": (1., 1.03, 1.04, 1.08, 1.08),
+    "temporal correlation": (1., 1.03, 1.1, 1.19, 1.29),
+    "geographical correlation": (1., 1.04, 1.08, 1.11, 1.11),
+    "further technological correlation": (1., 1.18, 1.65, 2.08, 2.8),
+    "sample size": (1., 1., 1., 1., 1.)
+    }

pedigree_matrix/ecoinvent.py

+from pm import PedigreeMatrix
+import re
+
+
+comment_matcher = re.compile("^\([0-9na, ]*\)")
+
+
+def from_ei_text(comment):
+    """Create PedigreeMatrix from ecoinvent comment text"""
+    factors = comment_matcher.match(comment).group()
+    assert factors, "No formatted comment found"
+    return PedigreeMatrix(factors)

pedigree_matrix/pm.py

+# -*- coding: utf-8 -*
+from data import basic_uncertainty, version_1, version_2
+import math
+
+
+class PedigreeMatrix(object):
+    labels = (
+        "reliability",
+        "completeness",
+        "temporal correlation",
+        "geographical correlation",
+        "further technological correlation",
+        "sample size"
+        )
+
+    def __init__(self, *args):
+        self.pm_factors = version_1
+        self.inputs = self.pad_args(self.parse_args(args))
+        self.args = self.lookup_inputs()
+        self.basic_uncertainty = 1.
+        self.version = 1
+
+    def denester(self, keys, data):
+        keys = list(keys)
+        while keys:
+            data = data[keys.pop(0)]
+        return data
+
+    def use_new_factors(self):
+        self.pm_factors = version_2
+        self.args = self.lookup_inputs()
+
+    def use_old_factors(self):
+        self.pm_factors = version_1
+        self.args = self.lookup_inputs()
+
+    def lookup_inputs(self):
+        return [self.pm_factors[key][index - 1] for key, index in \
+            zip(self.labels, self.inputs)]
+
+    def add_basic_uncertainty(self, *keys):
+        try:
+            self.basic_uncertainty = self.denester(basic_uncertainty, keys)
+        except KeyError:
+            raise ValueError("This basic uncertainty could not be found.")
+
+    def parse_args(self, args):
+        def maybe_int(x):
+            try:
+                return int(x)
+            except:
+                return 1.
+        """
+Parse input into usable form.
+
+``args`` can be one of three data formats:
+
+* "(1,2,3,4,5,6)": A string, e.g. the Ecospold 1 format.
+* (1, 2, 3, 4, 5): A tuple of floats, which require no additional processing.
+* ("1", "2", "3", "4", "5"): A tuple of strings, e.g. input from a web app.
+        """
+        if len(args) == 1 and isinstance(args[0], (tuple, list)):
+            args = args[0]
+        elif len(args) == 1 and isinstance(args[0], basestring):
+            args = args[0].replace("(", "").replace(")", "").split(",")
+        return [maybe_int(x) for x in args]
+
+    def pad_args(self, args):
+        """Pad ``args`` to a length of 6 with zeros (for consistency)."""
+        if len(args) < 6:
+            missing = 6 - len(args)
+            args = args + [1, ] * missing
+        elif len(args) > 6:
+            raise ValueError
+        return args
+
+    def unpack_args(self):
+        return zip(self.labels, self.inputs, self.args)
+
+    def calculate_uncertainty(self, include_basic_uncertainty=True):
+        if include_basic_uncertainty:
+            args = self.args + [self.basic_uncertainty, ]
+        else:
+            args = self.args
+        return math.sqrt(sum([math.log(x) ** 2 for x in args])) / 2
+
+    def geometric_standard_deviation(self, include_basic_uncertainty=True):
+        return math.sqrt(math.exp(
+            self.calculate_uncertainty(include_basic_uncertainty)))

pedigree_matrix/tests.py

+# -*- coding: utf-8 -*
+from . import PedigreeMatrix
+import unittest
+
+
+class InputTest(unittest.TestCase):
+    def test_ecospold_input(self):
+        input_text = "(1, 2, 3)"
+        pm = PedigreeMatrix(1,)
+        self.assertEqual(pm.parse_args((input_text,)), [1, 2, 3])
+
+    def test_float_inputs(self):
+        input_text = (1, 2, 3)
+        pm = PedigreeMatrix(1,)
+        self.assertEqual(pm.parse_args((input_text,)), [1, 2, 3])
+
+    def test_str_inputs(self):
+        input_text = ("1", "2", "3")
+        pm = PedigreeMatrix(1,)
+        self.assertEqual(pm.parse_args((input_text,)), [1, 2, 3])
+
+    def test_padding(self):
+        input_text = [1, 2, 3]
+        pm = PedigreeMatrix(input_text)
+        self.assertEqual(pm.pad_args(input_text),
+            [1, 2, 3, 1, 1, 1])
+
+    def test_complete_parsing_ecospold_input(self):
+        input_text = "(1, 2, 3)"
+        pm = PedigreeMatrix(input_text)
+        self.assertEqual(pm.inputs, [1, 2, 3, 1, 1, 1])
+
+    def test_complete_parsing_float_inputs(self):
+        input_text = (1, 2, 3)
+        pm = PedigreeMatrix(input_text)
+        self.assertEqual(pm.inputs, [1, 2, 3, 1, 1, 1])
+
+    def test_complete_parsing_str_inputs(self):
+        input_text = ("1", "2", "3")
+        pm = PedigreeMatrix(input_text)
+        self.assertEqual(pm.inputs, [1, 2, 3, 1, 1, 1])
+
+    def test_denester(self):
+        input_dict = {1: {2: {3: 4}}}
+        pm = PedigreeMatrix(1,)
+        self.assertEqual(pm.denester((1, 2, 3), input_dict), 4)
+        input_dict = {1: 2}
+        pm = PedigreeMatrix(1,)
+        self.assertEqual(pm.denester((1, ), input_dict), 2)
+from distutils.core import setup
+
+setup(
+  name='pedigree_matrix',
+  version="0.1",
+  packages=["pedigree_matrix"],
+  author="Chris Mutel",
+  author_email="cmutel@gmail.com",
+  license=open('LICENSE.txt').read(),
+  long_description=open('README.txt').read(),
+)