⚠️ Brightway Learn is in Public Beta ⚠️

Brightway2 for Beginners#

Authors

This page was created by Karin Treyer, Anish Koyamparambath and Michael Weinold in September 2023 as part of the BrightCon 2023 hackathon.

License

This page is licensed under a Creative Commons Attribution 4.0 International License (CC BY 4.0).
You can give credit or cite this page as:
Chapter "Brightway2 for Beginners" from the "Learn Brightway" Online Book (https://learn.brightway.dev/) by Brightway Contributors (2023)

Note

In this chapter, you will learn how to:

  1. Install Anaconda (and why you need it)

  2. Install Brightway

  3. How to load Brightway in Jupyter Notebook

  4. How to create, copy, delete a Brightway project

  5. How to load databases (eg. Ecoinvent)

Installing Anaconda#

Anaconda is a python distribution comes with the useful conda package manager. The distribution is available in two forms:

  1. Anaconda is a full fledged distribution with multiple packages installed. It comes with a wide range of data analysis, machine learning, and scientific computing libraries pre-installed, making it a comprehensive package for data scientists. Anaconda can be installed from the Anaconda download page.

  2. Miniconda is a minimal distribution that only includes python and conda. This allows you to create a lightweight and customized Python environment. With Miniconda, you have more control over which packages you want to install, making it a good choice for users who want to build their own Python environments tailored to their specific needs. Miniconda can be installed from the Anaconda download page.

Both Anaconda and Miniconda can be used to download Brightway into your computer.

Using Conda to download the brightway2 package#

There are different versions of Brightway (1, 2 & 2.5) and the differences between them are explained in this page.

This notebook will demonstrate the use of Brightway version 2.

A documentation explaining how to install brightway is available in the documentation which is the same as explained below.

Once you install Anaconda or Miniconda, you can access the Anaconda Navigator (See option 1, only if you download the Anaconda distribution) or you can access the Anaconda prompt (See option 2, available in both Anaconda & Miniconda distribution).

  1. Anaconda Navigator is a Graphical User Inteface to download the required packages. It is recommended to create an environment where you will install brightway. An environment allows you to have different versions of installed packages. For instance, brightway 2 requires a specific version of background libraries that are necessary to run brightway smoothly.

If you install all your projects in the same environment, you might run into issues. Creating an environment avoids such issues. More information on how to handle environments are explained below.

To create environment, click on the Environments tab in the left and below you will find an option called Create which will create a new environment with your desired name.

Note: An environment name cannot be repeated.

Once you create an environment, on the top right corner in the search bar search for brightway2 and install (all the necessary libraries are automatically installed).

To run jupyter notebook, click on Home from the top left corner of the navigator (Ensure the correnct environment is selected i.e bw) and then click on Launch under Jupyterlab or Jupter notebook.

To deactivate an environment after work, simply click on the base or another environment from the Anaconda Navigator.

Note: The notebook launches in the default directory i.e., the home directory. Changing it is complicated that to use Anaconda prompt to install jupyter which is explained below.

  1. Anaconda prompt is a console environment that is available in both Anaconda and Miniconda distributions. Copy the following code into the anaconda prompt.

conda create -n bw -c conda-forge brightway2 jupyterlab

This code creates an environment named ‘bw’ that can be changed and it also installs jupyterlab that allows to use a web based interface to execute python code.

In order to use brightway, you must activate the environment using the following code:

conda activate bw

Note: If you are using another editor or an Integrated Development Environment (IDE) such as pycharm, VSCode, spyder or others remember to select/setup the appropriate environment before executing the code.

To use jupter notebook such as this file, after activating the environment run the following code:

jupyter notebook

Note: Remember to navigate to the desired folder before executing the above code as it is complicated to go out of the folder to save your notebook after it starts.

To deactivate the environment after working on your project use the following code:

conda deactivate

Note: In order to deactivate, you must first save and close the jupyter notebook. Save your work before quitting. Go to the home page of the notebook (the page that shows you the directory and different files and click on quit.

Imp Note: Clicking on logout will not quit the jupyter notebook and you cannot provide an input into the terminal. In such cases, press CTR+C(Windows & Mac) to quit jupyter notebook which allows you to then deactivate the environment.

After working with brightway, remember to deactivate the environment either using Anaconda Navigator or Anaconda prompt.

Working with environments#

Setting up an environment#

You will work with environments in conda, see the official conda page.

“A conda environment is a directory that contains a specific collection of conda packages that you have installed.” When you install Brightway, they will be installed in a specific environment which will contain all necessary packages. You can e.g. have one environment for brightway2, and one for brightway25.

When you will install e.g. Brightway2, you will execute this line:

conda create -n bw brightway2 jupyterlab

This is the conda command for creating a new environment, which is called “bw”. Only running ‘’‘“conda create -n bw”’’’ would simply set up a new env, but empty without any packages in it. Adding “brightway2” or “jupyterlab” or “python” will install the respective package. You can also specify the version number of the package, e.g. “python =3.10”. This is sometimes useful, when packages are not yet aligned well in terms of versions, i.e. bw is not yet adapted to use the very latest version of python. You can add as many packages as you want to the conda create command. See below for an explanation how conda knows where to fetch the packages.

By default, environments are installed into the envs directory in your conda directory. If you want to know more, this page explains more on the management of environments:

“If you change one environment, your other environments are not affected.” However, the environments on your computer talk to each other. When you will create a new environment, and a new project in it, you will be able to see that new project in Activity browser (a graphical user interface for brightway for more information click here. You can create as many projects as you want in one environment.

You can easily activate or deactivate environments, which is how you switch between them. You can also share your environment with someone by giving them a copy of your environment.yaml file (see below). For more information, see Managing environments.

Opening an environment#

Once you have created your environment, you can open it with conda activate envname

Channels#

A “channel” is the location where packages are stored. By default, packages are installed from the “conda-forge” channel, which is maintained by a community of open source developers. brightway2 has been added to the conda-forge channel. brightway25 has not been added to conda-forge yet. brightway25 needs to be installed from the conda channel “cmutel”. This is to avoid users “accidentally” installing the more advanced brightway25, which is not yet compatible with the activity browser.

Here is a nice explanation what channels are.

This is not very relevant for you as a beginner, but it can help you understand e.g. the installation line for Activity Browser, which looks like this: conda create -n ab -c conda-forge activity-browser

You have already seen above that the “create -n ab” creates the environment named “ab”, and “activity browser” is the package which is fetched. Here, “-c conda-forge” is just an explicitly added link to the channel “conda-forge”.

Maintaining an environment#

We recommend you do not “update” the packages in your environment. Updating individual brightway packages (or other Python packages that Brightway uses, like “scipy”, ‘numpy’ etc.) could introduce “breaking changes”. A “breaking change” is a change in the source code of Brightway. This includes the exact syntax of Brightway commands. In other words, just changing the version number of numpy might not be enough, because it depends itself on other packages, which would have to be aligned with the new numpy version.

Instead, best create a new environment, and install e.g. bw2 again. bw2 always strives to use the latest versions of the packages it uses wherever it makes sense.

Saving, sharing and restoring an environment#

As explained here, you can save your environment in order to re-create it at any time later.

This is necessary if you want to make sure that you can re-calculate a project few months or even years later. All you need is are the following three files:

  1. The yml. file of the environment.

  2. The jupyter notebook

  3. Any excel file in case you have used one

It is important that these three files are e.g. labelled in their filename with the same date, or are stored in the same folder, so that you can easily find the relevant combination.

So the steps you need to do are:#

  1. Save your environment as .yml file:

    conda list -n YOURENVNAME –export SAVINGPATH/<FILE_NAME>.yml

Example:

conda list -n syn39 –export C:\Users\syn39_20230917.yml

You can name your yml file as you want. It seems to make sense to include the environment name and time stamp in the name. You can save your yml in the folder you want. Your project folder, and/or a dedicated backup folder, whatever.

Five years later, you want to recreate your environment.

  1. conda env create -f C:\Users\syn39_20230917.yml

It is possible to only use the filename in case you are in the same folder, but as this is not always obvious, using the full path is on the safe side.

Recap: Installing brightway2 on your computer#

You may already have installed bw2 and ab while reading above.

In case not, or in case you want this to be summarised, here’s how to get these two packages on your computer:

Brightway2: Follow the setup instruction from bw2 here.

Namely: conda create -n bw brightway2 jupyterlab creates the environment AND fetches the two packages brightway2 and jupyterlab from the channel conda-forge. And with conda activate bw, you access the environment so that you can make use of all the packages which are included in it, such as LCA calculations, handling of LCA databases, etc.

Preparing the Notebook#

The Jupyter Notebook is a web-based interactive computing platform. The notebook combines live code, equations, narrative text, visualizations.
In the notebook, each cell executes code either single line or multiple line.
Contrary to other tools such as a text editor or an IDE where the code is executed line by line untill the end of the script, in a notebook, each cell can be executed individually without a particular order.
However, in order to maintin coherency and to harmonize the flow of code, it is recommended to code each step in a linear fashion i.e., Cell 1 will execute the first line or group of code and then Cell 1 will execute the second line or group and so on.

INFO: Refer to Jupter notebook documentation or videos to better understand what and how to use Jupyter notebook.

Using Brightway#

To use brightway2 (referred to as bw here on), you must first import brightway libraries from the package. brightway2 is the name of the package that contains multiple sub packages such as bw2io, bw2calc and others. Importing brightway2 will automatically import all the subpackages thereby all the modules and functions within them. This is discouraged by the developers as it is not easy to identify which function is a part of which subpackage which would be difficult in debugging.

The objective of this notebook is however to quickly show you how to use different functions of brightway2.

Import brightway into the notebook#

#This code is used to import the brightway2 package with an alias i.e., 'bw'. 
#Using an alias helps us manage the code easily. (Its like a nick name)
import brightway2 as bw 

List the project names stored in the current brightway environment#

bw.projects #The prefix "bw" shows that "projects" is taken from the brightway2 package.
Brightway2 projects manager with 4 objects:
	ElectricMachine
	default
	demo
	demopingpong
Use `projects.report()` to get a report on all projects.
list(bw.projects)#Show the project names as a list
[Project: default,
 Project: ElectricMachine,
 Project: demopingpong,
 Project: demo]
print(bw.projects)#use this code if you are not using jupyternotebook but a text editor or an IDE
Brightway2 projects manager with 4 objects:
	ElectricMachine
	default
	demo
	demopingpong
Use `projects.report()` to get a report on all projects.

Access the saved project#

#If you want to know, where the project is saved on your computer (directory, you can do this)
bw.projects.dir
#The set current function loads the project and all the databases attached to the project if previously stored
bw.projects.set_current('demo')

Note: If the name of the project does not exist previously, brightway automatically creates a new project with the provided name
Note: You cannot rename the name of the project once created. Inorder to rename the project, you must copy it using .copyproject where you can provide a new name.
INFO: Remember to delete the old project with the wrong name using .delete_project.

bw.projects.copy_project('Brightway4dummies')#.copy_project only copies the current project that you have set before
bw.projects.delete_project('demo', delete_dir=True)#Deletes the projectb
'demo'

Note: You must provide the argument delete_dir and set it as True. Failing this step will not delete the directory and you will never be able to reuse the name in the current brightway environment.

Set up the project#

Load the biosphere flows and Impact assessment methods into the project#

Brightway comes with default set of biosphere flows and impact assessment methods that can be loaded into the project.

*Note: Each project created must load these flows and methods to do an assessment. Once loaded it stays with the project which will be loaded along with the project every time .set_current(“Name of the project”) is used.

bw.bw2setup()#This code loads all the biosphere flows and LCIA methods
Creating default biosphere
Writing activities to SQLite3 database:
Applying strategy: normalize_units
Applying strategy: drop_unspecified_subcategories
Applying strategy: ensure_categories_are_tuples
Applied 3 strategies in 0.01 seconds
0% [##############################] 100% | ETA: 00:00:00
Total time elapsed: 00:00:00
Title: Writing activities to SQLite3 database:
  Started: 09/17/2023 15:35:38
  Finished: 09/17/2023 15:35:38
  Total time elapsed: 00:00:00
  CPU %: 13.00
  Memory %: 1.34
Created database: biosphere3
Creating default LCIA methods

Wrote 762 LCIA methods with 227223 characterization factors
Creating core data migrations

Loading external databases into brightway#

Since most of the LCA practitioners use Ecoinvent to model their processes, in this example we show how to import Ecoinvent database into brightway. Please note same steps can be adopted to import any other database into brightway.
Note: Brightway can load in different data formats such as ‘ecospold’, ‘excel’. If using ecoinvent ecospold format, provide the directory where the extracted datasets are available
Imp Note: Always assign a variable to load all the data which is later used to perform other functions.

Note: .SingleOutputEcospold2Importer is a function that loads all the datasets that are in ecospold or .spold format. It takes two main arguments, the path to the file and the name of the dataset you would like to save it as in the project.

Imp Note: If you are using an older version of ecospold, use .SingleOutputEcospold1Importer.

ei = bw.SingleOutputEcospold2Importer(r"D:\Projects\Brightway\Documentation\Ecoinvent\datasets", "ev391cutoff")
Extracting XML data from 21238 datasets
Extracted 21238 datasets in 107.22 seconds

Note: The format needs to be converted and brightway strategies are applied. .apply_stretegies() function is applied to the variable that loaded the database

ei.apply_strategies()
Applying strategy: normalize_units
Applying strategy: update_ecoinvent_locations
Applying strategy: remove_zero_amount_coproducts
Applying strategy: remove_zero_amount_inputs_with_no_activity
Applying strategy: remove_unnamed_parameters
Applying strategy: es2_assign_only_product_with_amount_as_reference_product
Applying strategy: assign_single_product_as_activity
Applying strategy: create_composite_code
Applying strategy: drop_unspecified_subcategories
Applying strategy: fix_ecoinvent_flows_pre35
Applying strategy: drop_temporary_outdated_biosphere_flows
Applying strategy: link_biosphere_by_flow_uuid
Applying strategy: link_internal_technosphere_by_composite_code
Applying strategy: delete_exchanges_missing_activity
Applying strategy: delete_ghost_exchanges
Applying strategy: remove_uncertainty_from_negative_loss_exchanges
Applying strategy: fix_unreasonably_high_lognormal_uncertainties
Applying strategy: set_lognormal_loc_value
Applying strategy: convert_activity_parameters_to_list
Applying strategy: add_cpc_classification_from_single_reference_product
Applying strategy: delete_none_synonyms
Applied 21 strategies in 7.43 seconds

In order to view how many datastates and exchanges are loaded can be viewed using .statistics()

ei.statistics()
21238 datasets
674593 exchanges
0 unlinked exchanges
  
(21238, 674593, 0)

The above functions only loaded/imported the database into the brightway but still has to be written to the project inorder to access it again when using the project. This is possible using .write_database()

ei.write_database()
Writing activities to SQLite3 database:
0% [##############################] 100% | ETA: 00:00:00
Total time elapsed: 00:00:47
Title: Writing activities to SQLite3 database:
  Started: 09/17/2023 16:21:27
  Finished: 09/17/2023 16:22:14
  Total time elapsed: 00:00:47
  CPU %: 42.10
  Memory %: 18.98
Created database: ev391cutoff
Brightway2 SQLiteBackend: ev391cutoff

Now lets see what databases are existing in our project. Use .databases to bw variable.

list(bw.databases)
['biosphere3', 'ev391cutoff']

You can also load a custom processes created by you that includes a combination of ecoinvent processes and biosphere. You can find the documentation on how to format the excel file here.

Note: The database name in the database column in the excel sheet must match the name provided while importing. For example, ecoinvent is saved as ‘ev391cutoff’ which should be the exact same name used while referring inside the excel file.

Load the excel file using .ExcelImporter by providing the path to the file.

imp = bw.ExcelImporter(r'D:\Projects\Brightway\Documentation\lci_rawdata_import.xlsx')
imp.apply_strategies()
Extracted 1 worksheets in 0.03 seconds
Applying strategy: csv_restore_tuples
Applying strategy: csv_restore_booleans
Applying strategy: csv_numerize
Applying strategy: csv_drop_unknown
Applying strategy: csv_add_missing_exchanges_section
Applying strategy: normalize_units
Applying strategy: normalize_biosphere_categories
Applying strategy: normalize_biosphere_names
Applying strategy: strip_biosphere_exc_locations
Applying strategy: set_code_by_activity_hash
Applying strategy: link_iterable_by_fields
Applying strategy: assign_only_product_as_production
Applying strategy: link_technosphere_by_activity_hash
Applying strategy: drop_falsey_uncertainty_fields_but_keep_zeros
Applying strategy: convert_uncertainty_types_to_integers
Applying strategy: convert_activity_parameters_to_list
Applied 16 strategies in 15.06 seconds

Next step is to match the processes in the excel file to the ecoinvent database (which is the only database referred to)

imp.match_database("ev391cutoff", fields=('name','unit','location'))
Applying strategy: link_iterable_by_fields
imp.statistics()#Lets see how many datasets are loaded
2 datasets
43 exchanges
0 unlinked exchanges
  
(2, 43, 0)
imp.write_database()#Write the imported database into the project
Writing activities to SQLite3 database:
0% [##] 100% | ETA: 00:00:00
Total time elapsed: 00:00:00
Title: Writing activities to SQLite3 database:
  Started: 09/17/2023 16:39:23
  Finished: 09/17/2023 16:39:23
  Total time elapsed: 00:00:00
  CPU %: 0.00
  Memory %: 20.53
Created database: hydrogen_demo
imp.unlinked#Print any unlinked processes
<generator object ImportBase.unlinked at 0x000001861DDE0840>