Import data


In [1]:
from brightway2 import *
from bw2data import Database, get_activity
import numpy as np
import pandas as pd

In [2]:
projects.set_current('Import Quantis OFP - version 4')

In [3]:
bw2setup()


Biosphere database already present!!! No setup is needed

In [4]:
list(databases)


Out[4]:
['MeatDatasets', 'AGs', 'ecoinvent 3.3 cutoff', 'biosphere3']

calculate LCIA

try first sth from ecoinvent


In [6]:
act = Database("MeatDatasets").search('suckler average')[1]
act


Out[6]:
'Suckler beef average, conventional (Quantis, from Agribalyse) UP/DE' (kilogram, None, None)

In [7]:
lca = LCA(
    {act.key: 1}, 
    method=('IPCC 2013', 'climate change', 'GWP 100a'),
)
lca.lci()
lca.lcia()
lca.score


Out[7]:
18.4052599249694

In [74]:
# help(lca.characterized_inventory)
# type(lca.characterized_inventory)
lca.characterized_inventory.shape


Out[74]:
(2156, 14236)

Contribution Analysis


In [8]:
from bw2analyzer import ContributionAnalysis

In [9]:
results = ContributionAnalysis().annotated_top_processes(lca, names=False)
results = [(x[0], x[1], get_activity(x[2]), x[2]) for x in results]
df = pd.DataFrame(results, columns=['lca_score', 'inventory_amount', 'activity', 'process_key'])
# print(df.activity.apply(type)) # peewee objects...
# print(df.activity.apply(len))
# For example
df.activity


Out[9]:
0     [code, filename, type, production amount, sima...
1     [code, filename, type, production amount, sima...
2     [code, filename, type, production amount, sima...
3     [code, filename, type, production amount, sima...
4     [code, filename, type, production amount, sima...
5     [code, filename, type, production amount, sima...
6     [classifications, filename, type, production a...
7     [code, filename, type, production amount, sima...
8     [code, filename, type, production amount, sima...
9     [code, filename, type, production amount, sima...
10    [code, filename, type, production amount, sima...
11    [classifications, filename, type, production a...
12    [code, filename, type, production amount, sima...
13    [classifications, filename, type, production a...
14    [code, filename, type, production amount, sima...
15    [classifications, filename, type, production a...
16    [classifications, filename, type, production a...
17    [classifications, filename, type, production a...
18    [classifications, filename, type, production a...
19    [classifications, filename, type, production a...
20    [classifications, filename, type, production a...
21    [classifications, filename, type, production a...
22    [classifications, filename, type, production a...
23    [code, filename, type, production amount, sima...
24    [classifications, filename, type, production a...
Name: activity, dtype: object

In [10]:
df = lca.to_dataframe()
df.head()


Out[10]:
                                            Activity  \
0  Young suckler bull, conventional, fattening sy...   
1  Young suckler bull, conventional, fattening sy...   
2                            Compost, at plant UP/FR   
3                            Compost, at plant UP/FR   
4                            Compost, at plant UP/FR   

                          Flow Region    Amount  
0  Carbon monoxide, non-fossil   None  3.151814  
1  Carbon monoxide, non-fossil   None  2.527043  
2  Carbon monoxide, non-fossil   None  2.139878  
3  Carbon monoxide, non-fossil   None  1.269280  
4  Carbon monoxide, non-fossil   None  0.985291  

In [11]:
lca.to_dataframe


Out[11]:
<bound method LCA.to_dataframe of <bw2calc.lca.LCA object at 0x7fc5f76dcf98>>

In [85]:
lca.characterized_inventory


Out[85]:
<2156x14236 sparse matrix of type '<class 'numpy.float64'>'
	with 15695 stored elements in Compressed Sparse Row format>

In [34]:
df.sort_values(by='Amount', ascending=False, inplace=True)

In [35]:
lca.top_emissions()


Out[35]:
[(11.653903594071792,
  0.4089088980376071,
  'Methane, non-fossil' (kilogram, None, ('air', 'non-urban air or from high stacks'))),
 (3.3550709038030657,
  0.012670207924730675,
  'Dinitrogen monoxide' (kilogram, None, ('air', 'non-urban air or from high stacks'))),
 (1.5937783154278489,
  1.5937783154278478,
  'Carbon dioxide, fossil' (kilogram, None, ('air', 'non-urban air or from high stacks'))),
 (0.80535814152737173,
  0.80535814152737206,
  'Carbon dioxide, fossil' (kilogram, None, ('air', 'urban air close to ground'))),
 (0.38303347947197897,
  0.38303347947197863,
  'Carbon dioxide, fossil' (kilogram, None, ('air',))),
 (0.32941719902933975,
  0.0012440227122929152,
  'Dinitrogen monoxide' (kilogram, None, ('air', 'urban air close to ground'))),
 (0.14777017123808658,
  0.0049754265132032809,
  'Methane, fossil' (kilogram, None, ('air', 'non-urban air or from high stacks'))),
 (0.065395837196283488,
  0.065395837196283474,
  'Carbon dioxide, from soil or biomass stock' (kilogram, None, ('air', 'non-urban air or from high stacks'))),
 (0.014444745584068384,
  0.00048635505767706869,
  'Methane, fossil' (kilogram, None, ('air', 'urban air close to ground'))),
 (0.012318058909389541,
  0.0030322123181305985,
  'Carbon monoxide, fossil' (kilogram, None, ('air', 'urban air close to ground'))),
 (0.012105180225192779,
  0.0029798101195993997,
  'Carbon monoxide, fossil' (kilogram, None, ('air',))),
 (0.0095237602907574607,
  0.00032066532141781926,
  'Methane, fossil' (kilogram, None, ('air',))),
 (0.0060811114361995055,
  0.0014969258663565508,
  'Carbon monoxide, fossil' (kilogram, None, ('air', 'non-urban air or from high stacks'))),
 (0.0059005777840663723,
  2.2283149758600753e-05,
  'Dinitrogen monoxide' (kilogram, None, ('air',))),
 (0.0055880084716881436,
  2.3771860240564572e-07,
  'Sulfur hexafluoride' (kilogram, None, ('air',))),
 (0.0012117542474372486,
  0.00048645294181285178,
  'Carbon monoxide, non-fossil' (kilogram, None, ('air', 'urban air close to ground'))),
 (0.0011024899872240552,
  1.6639398557237028e-07,
  'Methane, tetrafluoro-, R-14' (kilogram, None, ('air',))),
 (0.00099645971714665119,
  0.00024528843798188554,
  'Carbon monoxide, from soil or biomass stock' (kilogram, None, ('air', 'non-urban air or from high stacks'))),
 (0.00062428273332094648,
  2.1904657309506923e-05,
  'Methane, non-fossil' (kilogram, None, ('air', 'urban air close to ground'))),
 (0.0004765361284285709,
  1.6044987077010674e-05,
  'Methane, from soil or biomass stock' (kilogram, None, ('air', 'non-urban air or from high stacks'))),
 (0.00025954056852454076,
  3.020652494445075e-08,
  'Ethane, 1,2-dichloro-1,1,2,2-tetrafluoro-, CFC-114' (kilogram, None, ('air', 'non-urban air or from high stacks'))),
 (0.00017961464898240214,
  0.00017961464898240211,
  'Carbon dioxide, from soil or biomass stock' (kilogram, None, ('air',))),
 (0.00013736375420147953,
  7.7842829278988598e-08,
  'Methane, chlorodifluoro-, HCFC-22' (kilogram, None, ('air', 'non-urban air or from high stacks'))),
 (0.00013564364362769003,
  1.2194337670597144e-08,
  'Ethane, hexafluoro-, HFC-116' (kilogram, None, ('air',))),
 (0.00013422222247613943,
  2.1333459754130904e-08,
  'Methane, bromotrifluoro-, Halon 1301' (kilogram, None, ('air', 'non-urban air or from high stacks')))]

In [39]:
c_an = ContributionAnalysis().annotated_top_emissions(lca, {'limit': 0, 'limit_type':'percent', 'total':None})
pd.DataFrame(c_an)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-39-ffab247f912c> in <module>()
      1 c_an = ContributionAnalysis().annotated_top_emissions(lca, {'limit': 0, 'limit_type':'percent', 'total':None})
----> 2 pd.DataFrame(c_an)

NameError: name 'pd' is not defined

Create report


In [0]:
from bw2analyzer.report import SerializedLCAReport
test = SerializedLCAReport(
    activity={act.key: 1},
    method=('IPCC 2013', 'climate change', 'GWP 100a'),
    iterations=10,
)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-692a87db3f4b> in <module>()
      1 from bw2analyzer.report import SerializedLCAReport
      2 test = SerializedLCAReport(
----> 3     activity={act.key: 1},
      4     method=('IPCC 2013', 'climate change', 'GWP 100a'),
      5     iterations=10,

NameError: name 'act' is not defined

In [85]:
test.calculate()


---------------------------------------------------------------------------
RemoteTraceback                           Traceback (most recent call last)
RemoteTraceback: 
"""
Traceback (most recent call last):
  File "/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/site-packages/peewee.py", line 3748, in execute_sql
    cursor.execute(sql, params or ())
sqlite3.DatabaseError: database disk image is malformed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/multiprocessing/pool.py", line 119, in worker
    result = (True, func(*args, **kwds))
  File "/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/multiprocessing/pool.py", line 44, in mapstar
    return list(map(*args))
  File "/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/site-packages/bw2calc/monte_carlo.py", line 154, in single_worker
    projects.set_current(project, writable=False)
  File "/d/documents/eaternity/src/bw2data/bw2data/project.py", line 149, in set_current
    self.create_project(name)
  File "/d/documents/eaternity/src/bw2data/bw2data/project.py", line 223, in create_project
    ProjectDataset.name == name).count():
  File "/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/site-packages/peewee.py", line 3141, in count
    return self.aggregate(convert=False) or 0
  File "/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/site-packages/peewee.py", line 3134, in aggregate
    return self._aggregate(aggregation).scalar(convert=convert)
  File "/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/site-packages/peewee.py", line 2901, in scalar
    row = self._execute().fetchone()
  File "/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/site-packages/peewee.py", line 2892, in _execute
    return self.database.execute_sql(sql, params, self.require_commit)
  File "/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/site-packages/playhouse/shortcuts.py", line 210, in execute_sql
    sql, params, require_commit)
  File "/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/site-packages/peewee.py", line 3755, in execute_sql
    self.commit()
  File "/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/site-packages/peewee.py", line 3578, in __exit__
    reraise(new_type, new_type(*exc_args), traceback)
  File "/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/site-packages/peewee.py", line 135, in reraise
    raise value.with_traceback(tb)
  File "/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/site-packages/peewee.py", line 3748, in execute_sql
    cursor.execute(sql, params or ())
peewee.DatabaseError: database disk image is malformed
"""

The above exception was the direct cause of the following exception:

DatabaseError                             Traceback (most recent call last)
<ipython-input-85-6e1508b2d7be> in <module>()
----> 1 test.calculate()

/d/documents/eaternity/src/bw2analyzer/bw2analyzer/report.py in calculate(self)
     48         concentration = concentration_ratio(lca.characterized_inventory.data)
     49         print("MC:")
---> 50         monte_carlo = self.get_monte_carlo()
     51 
     52         activity_data = []

/d/documents/eaternity/src/bw2analyzer/bw2analyzer/report.py in get_monte_carlo(self)
     93             self.method,
     94             iterations=self.iterations,
---> 95             cpus=self.cpus
     96         ).calculate()
     97         print("Converting to array")

/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/site-packages/bw2calc/monte_carlo.py in calculate(self, worker)
    187                 [
    188                     (projects.current, self.demand, self.method, self.chunk_size)
--> 189                     for _ in range(self.num_jobs)
    190                 ]
    191             )

/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/multiprocessing/pool.py in map(self, func, iterable, chunksize)
    258         in a list that is returned.
    259         '''
--> 260         return self._map_async(func, iterable, mapstar, chunksize).get()
    261 
    262     def starmap(self, func, iterable, chunksize=None):

/d/documents/eaternity/bw2-py/envs/bw2/lib/python3.5/multiprocessing/pool.py in get(self, timeout)
    606             return self._value
    607         else:
--> 608             raise self._value
    609 
    610     def _set(self, i, obj):

DatabaseError: database disk image is malformed
FD
CA
hinton
treemap
herfindahl
concentration
MC:
Entered get_monte_carlo

In [0]:
test.report['monte carlo']['histogram']= list(test.report['monte carlo']['histogram'])

In [0]:
test.report['monte carlo']['smoothed'] = list(test.report['monte carlo']['smoothed'])

In [0]:
test.write()

In [0]:
test.report

In [0]:


In [0]:


In [0]:
sorted(str(get_activity(key)) for key, _ in Method(('IPCC 2013', 'climate change', 'GWP 100a')).load())

See all flows with their characterization factors


In [4]:
from brightway2 import *
# method = methods.random()
methods = Method(('IPCC 2013', 'climate change', 'GWP 100a')).load()
for key, cf in methods:
    print(get_activity(key), cf)


---------------------------------------------------------------------------
UnknownObject                             Traceback (most recent call last)
<ipython-input-4-87eaa0f232da> in <module>()
      1 from brightway2 import *
      2 # method = methods.random()
----> 3 methods = Method(('IPCC 2013')).load()
      4 for key, cf in methods:
      5     print(get_activity(key), cf)

/d/documents/eaternity/src/bw2data/bw2data/data_store.py in load(self)
     84         """
     85         if not self.registered:
---> 86             raise UnknownObject("This object is not registered and has no data")
     87         try:
     88             return pickle.load(open(os.path.join(

UnknownObject: This object is not registered and has no data

In [0]:


In [0]:


In [0]:


In [0]:


In [0]:


In [0]:


In [0]:


In [0]:


In [0]:


In [0]:


In [0]:


In [0]: