Code documentation

Submodules

importer module

Created on Sun Jan 20 15:36:43 2019

@author: cyshi

class importer.DatabaseImporter(c_path='')

Bases: object

A quick and convenient way to import life cycle inventory databases, including commercial and public databases. This object provides an convenient way to download, map and import the SQLite backend to brightway2.

c_path

The absolute path to the current working directory.

Type

string

dirpath

The abolute path to the database directory.

Type

string

ecoinvent_db(download_path=None, store_download=True, **Login_credentials)

A method to log in to ecoinvent user account, downlad and import ecoinvent database to current project based on brightway framework.

Note

Ecoinvent is a commerial databse. Login credential is required before acessing ecoinvent database through Biosteam_lca.

Parameters
  • **Login_credentials (dict) –

    • usernamestr

      Ecoinvent username

    • passwordstr

      Ecoivnent password

    • versionstr

      Avaiable database version

    • system_modelstr

      System models. The ecoinvent version 3 database offers three system models to choose from:

      • Cut-Off: The system model Allocation, cut-off by classification.

      For users new to LCI databases, ecoinvent recommends using the cut-off system model when starting to work with ecoinvent version 3. https://www.ecoinvent.org/database/system-models-in-ecoinvent-3/ system-models-in-ecoinvent-3.html

      • APOS: The system model Allocation at the point of substitution

      • Consequential: The system model substitution, consequential

  • download_path (str, optional) – Default is to download to temporary directory, ‘.7z file’ will be removed after succefful import ecoinvent database. Otherwise user can specify specific download path.

  • store_download (bool, optional) – Default is to store the the ‘.7z file’. Otherwise ‘False’ if no download_path is provided.

Returns

db_name – The name of the ecoinvent_db.

Return type

str

Notes

Ecoinvent is one of the most comprehensive LCI databases based in Europe, with over 14,700 LCI datasets in many areas, such as energy supply, agriculture, transport, biofuels and biomaterials, bulk and specialty chemicals, construction materials, wood, and waste treatment. Current latest version is ecoinvent 3.5, which builds upon all previous versions of the database.

LCI contain only inputs and outputs to and from biosphere and one output to technosphere (the reference product).

References

[1]Wernet, G., Bauer, C., Steubing, B., Reinhard, J., Moreno-Ruiz, E., and Weidema, B., 2016. The ecoinvent database version 3 (part I): overview and methodology. The International Journal of Life Cycle Assessment, [online] 21(9), pp.1218–1230.

[2]Ecoinvent, Allocation cut-off by classification, accessed [Aug 12 2019], available at https://www.ecoinvent.org/database/system-models-in-ecoinvent-3/ cut-off-system-model/allocation-cut-off-by-classification.html

[3]Ecoinvent, What is the structure of the data that ecoinvent offers?, accessed [Aug 13 2019], avaiable at https://www.ecoinvent.org/support/faqs/ first-time-users/what-is-the-structure-of-the-data-that-ecoinvent-offers.html

forwast_db(url='http://lca-net.com/wp-content/uploads/forwast.bw2package.zip')

A method for downloading and installing forwast database.

Parameters

url (string, optional) – The url from which to download the forwast database. Default is to download from http://lca-net.com/wp-content/uploads/forwast.bw2package.zip. may requires updates periodically

Returns

sp – The initialized database.

Return type

obj

Notes

FORWAST is a open source database that developed and managed by <2.-0 LCA consultants>, under the ” EU’s Sixth Framework Programme – European Union”. Forwast database includes “material stocks, waste quantities and environmental indicators based on detailed environmentally extended economic and physical input-output matrices (IO-tables) based on the national accounting systems and other statistics.” The database is also available in SimaPro under “EU and DK Input Output library”.

[1] Schmidt, J. H., Weidema, B. P., & Suh, S. (2010). EU-FORWAST project. Deliverable no. 6.4. Documentation of the final model used for the scenario analyses. In Tech. Rep..

static inspect(sp, db_name)

A static method to check for any unlinked exchange in a given database. If found, it will be the user’s decision to if or not continue writing to SQLite3 backend.

Parameters

sp (obj) – The initialized database.

Returns

  • datasets (int) – The total number of lci datasets extracted.

  • exchanges (int) – The total number of exchanges.

  • unlinked (int) – The total number of unlinked exchanges.

user_customized_db(customized_db_xlsx)

A method for importing user customized lci databases and datasets from an Excel file.

Parameters

customized_db_xlsx (str) – The filename of a .xlsx file in the local directory. For example: example_user_customized_database.xlsx

Returns

sp – The initialized database.

Return type

obj

Notes

Database name will be matched with the ‘name’ field in the excel file.

uslci_db()

A method for initializing the us_lci database. Orignal repository was downloaded from the U.S. Federal LCA Commons|Ag data Commons platform.

Returns

sp – The initialized database.

Return type

obj

Notes

Biosteam_lca leverages ecospold2 importer and excel importer. The Openlca Data Converter is used for converting from json format to ecospold format. Pre-processed databases are saved under biosteam_lca-database directory.

References

[1] USDA National Agricultural Library. (2015). LCA Commons. Ag Data Commons. https://doi.org/10.15482/USDA.ADC/1173236. Accessed 2020-03-23.

[2] Michael Srocka, Juliane Franze, Andreas Ciroth, January 2010. Documentation openLCA format converter V2. Data Conversion from EcoSpold02 to ILCD. GreenDeltaTC GmbH Berlin

importer.Importer

alias of importer.DatabaseImporter

importer.listDir(dir)

multilca module

Created on Sun Jan 20 15:36:43 2019

@author: cyshi

class multilca.MultiLCA(inventory_inputs)

Bases: object

A means of conducting life cycle assessment calculations with multiple inventory inputs profiles, life cycle impact assessment methods, and variable amounts inherited from each unit. Pre-selection of database is required, if not specify, default database would be chosen.

inventory_inputs

Inventory profile and amount for process inputs.

Type

dict

Note

Call .run () to generate results. Results return a numpy array with multiple impact results, calculate up to 800+ impact categories for each unit simultaneously. Call``.timer ()`` to see simulation time.

ia_methods = [('TRACI', 'environmental impact', 'acidification'), ('TRACI', 'environmental impact', 'ecotoxicity'), ('TRACI', 'environmental impact', 'eutrophication'), ('TRACI', 'environmental impact', 'global warming'), ('TRACI', 'environmental impact', 'ozone depletion'), ('TRACI', 'environmental impact', 'photochemical oxidation'), ('TRACI', 'human health', 'carcinogenics'), ('TRACI', 'human health', 'non-carcinogenics'), ('TRACI', 'human health', 'respiratory effects, average')]
static multi_impact(flow, amount, methods, factorize=False, table=False)

A method to calculate the life cycle impact assessment results for selected processes and multiple methods.

Parameters
  • flow (dict) – The flow to apply.

  • amount (int) – Unit demand.

  • methods – The methods to apply.

  • factorize (bool, optional) – Factorize results. Default is False.

  • table (bool, optional) – Return results in tabular form. Default is False.

Returns

multi_impact_result – The flow, and its associated scoresum.

Return type

tuple

Notes

LCIAmethods is an inclusive list of all candidate LCIA methods that need to be tested.

multi_process(single_impact)

A method to calculate the impact score of multiple process using selected lcia method.

Parameters

simgle_impact – The single impact to consider.

Returns

multi_process_result – A tuple containing numpy array of impact scores for each input.

Return type

tuple

Raises
  • ValueError – If flow is not a dict.

  • ValueError – If flow dict is empty.

multi_process_calc(activities, single_impact)

A method to calculate the impact score of multiple process using selected lcia method.

Parameters
  • activities (list) – The activities to apply.

  • single_impact – The single impact to consider.

Returns

multi_process_calc_result – A tuple containing a numpy array of impact scores for each input.

Return type

tuple

scores(timer=False, table=False, method=None)

A method to run multi impact LCA calculation by taking inputs, methods and amounts of each input.

Parameters
  • timer (boolean, optional) – Set to True to print() time taken to process. Default is False.

  • table (boolean, optional) – Set to True to print tabulated results.

  • method (tuple, optional) – LCIA Method; e.g. (‘TRACI’, ‘human health’, ‘carcinogenics’)

Returns

results_dic – A dict containing numpy arrays with multiple impact results.

Return type

dict

Note

User can choose one or more impact categories. If not specified, IPCC glowbal warming potencial is the default method.

classmethod set_ia_methods(set_methods)

A @classmethod to set user defined impact assessment method(s).

Parameters

set_methods – The methods to be set to ia_methods.

Returns

cls.ia_methods – The newly set ia_methods.

Return type

dict

timer()

A method to record the time of running analysis

Returns

end_time – The difference between the start time and the end time of the process as expressed in seconds.

Return type

float

multilca.export_matrix_to_excel(row_names, col_names, matrix, filepath='export.xlsx', sheetname='Export')

A method to export inventory input matrix to excel.

Parameters
  • row_names (list) – A list of the row names to write to the Excel sheet.

  • col_names (list) – The column names to write to the Excel sheet.

  • matrix – The matrix from which to write.

  • filepath (str, optional) – The name of the file to write to. Default value is export.xlsx.

  • sheetname (str, optional) – The name of the Excel sheet. Default value is Export.

multilca.static_calc(flow, amount, methods, factorize=False)

Establish static lca basis. By default no factorization.

reset_lcia module

setup module

Created on Sun Jan 20 15:36:43 2019

@author: cyshi

setup.SetUp

alias of setup.SetUpDatabase

class setup.SetUpDatabase(database_name)

Bases: object

A means of setting up lci databases with brightway backend. Inventory data can be exported to excel. This class enables importing, managing, and manipulating the databases and activities and exchanges in the database.

database_name

Name of the lci databases or datasets

Type

str

db

An instance of the database to be set up.

Type

obj

activities()

A method for getting a list of all activities in a self.db.

Returns

db_activities_list – A list of all activities in this database.

Return type

list

Raises

TypeError – If dict keys being iterated over cannot be interpreted as an activity.

all_exchanges()

A method to get all exchanges in self.db

Returns

exchanges_description – A statement of the total number of exchanges in the db.

Return type

str

c_path = ''
check_dir()

A method to check that path is a directory, and that the system has write permissions.

Parameters

dirpath (str) – The filepath to the directory in question.

Returns

  • True (bool) – If the input path is a directory and writeable.

  • False (bool) – If the input path is either not a directory or is not writeable

data()

A method to load the db.

delete()

A method to delete a previously installed database.

delete_activity(activity)

A method to delete a flow from database.

Parameters

activity (str) – The flow to be deleted.

download_path = None
size()

A method to get the number of total activities in the imported database, if the database is not empty

Returns

db_activities – A count of the total activities in the db.

Return type

str

Raises

ImportError – If the db fails to load.

statistics()

A method to get the number of activities and exchanges in the database.

Returns

activities_and_num_of_exchanges – A count of all datasets and exchanges in self.db.

Return type

str

store_download = True
uncertainty()

A method to get the most common uncertainty type for self.db.

Returns

most_common_uncertainty – The most common uncertainty type in the db.

Return type

str

setup.db_write_toExcel(lci_data, db_name)

A function to write inventory database to an Excel file.

Parameters
  • lci_data

  • db_name (str) – The name of the database.

Returns

fp – The filepath to the spreadsheet file.

Return type

string

Module contents

Utilities needed to emulate Python’s interactive interpreter.

class code.InteractiveConsole(locals=None, filename='<console>')

Bases: code.InteractiveInterpreter

Closely emulate the behavior of the interactive Python interpreter.

This class builds on InteractiveInterpreter and adds prompting using the familiar sys.ps1 and sys.ps2, and input buffering.

interact(banner=None, exitmsg=None)

Closely emulate the interactive Python console.

The optional banner argument specifies the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real interpreter – since it’s so close!).

The optional exitmsg argument specifies the exit message printed when exiting. Pass the empty string to suppress printing an exit message. If exitmsg is not given or None, a default message is printed.

push(line)

Push a line to the interpreter.

The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter’s runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended. The return value is 1 if more input is required, 0 if the line was dealt with in some way (this is the same as runsource()).

raw_input(prompt='')

Write a prompt and read a line.

The returned line does not include the trailing newline. When the user enters the EOF key sequence, EOFError is raised.

The base implementation uses the built-in function input(); a subclass may replace this with a different implementation.

resetbuffer()

Reset the input buffer.

class code.InteractiveInterpreter(locals=None)

Bases: object

Base class for InteractiveConsole.

This class deals with parsing and interpreter state (the user’s namespace); it doesn’t deal with input buffering or prompting or input file naming (the filename is always passed in explicitly).

runcode(code)

Execute a code object.

When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised.

A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal with it.

runsource(source, filename='<input>', symbol='single')

Compile and run some source in the interpreter.

Arguments are as for compile_command().

One of several things can happen:

1) The input is incorrect; compile_command() raised an exception (SyntaxError or OverflowError). A syntax traceback will be printed by calling the showsyntaxerror() method.

2) The input is incomplete, and more input is required; compile_command() returned None. Nothing happens.

3) The input is complete; compile_command() returned a code object. The code is executed by calling self.runcode() (which also handles run-time exceptions, except for SystemExit).

The return value is True in case 2, False in the other cases (unless an exception is raised). The return value can be used to decide whether to use sys.ps1 or sys.ps2 to prompt the next line.

showsyntaxerror(filename=None)

Display the syntax error that just occurred.

This doesn’t display a stack trace because there isn’t one.

If a filename is given, it is stuffed in the exception instead of what was there before (because Python’s parser always uses “<string>” when reading from a string).

The output is written by self.write(), below.

showtraceback()

Display the exception that just occurred.

We remove the first stack item because it is our own code.

The output is written by self.write(), below.

write(data)

Write a string.

The base implementation writes to sys.stderr; a subclass may replace this with a different implementation.

code.compile_command(source, filename='<input>', symbol='single')

Compile a command and determine whether it is incomplete.

Arguments:

source – the source string; may contain n characters filename – optional filename from which source was read; default

“<input>”

symbol – optional grammar start symbol; “single” (default) or “eval”

Return value / exceptions raised:

  • Return a code object if the command is complete and valid

  • Return None if the command is incomplete

  • Raise SyntaxError, ValueError or OverflowError if the command is a syntax error (OverflowError and ValueError can be produced by malformed literals).

code.interact(banner=None, readfunc=None, local=None, exitmsg=None)

Closely emulate the interactive Python interpreter.

This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readline module to enable GNU readline if it is available.

Arguments (all optional, all default to None):

banner – passed to InteractiveConsole.interact() readfunc – if not None, replaces InteractiveConsole.raw_input() local – passed to InteractiveInterpreter.__init__() exitmsg – passed to InteractiveConsole.interact()