Example #1
0
def setup_fixtures(request):

    print('RUNNING SETUP FIXTURE')

    if TEST_MODEL_NAME in bw2.projects:
        bw2.projects.delete_project(name=TEST_MODEL_NAME, delete_dir=True)

    bw2.projects.set_current(TEST_MODEL_NAME)
    bw2.bw2setup()

    script_path = os.path.dirname(os.path.realpath(__file__))
    ecospold_folder = os.path.join("tests", "assets", "datasets")
    ecospold_path = os.path.join(script_path, ecospold_folder)
    print(ecospold_path)

    ei = bw2.SingleOutputEcospold2Importer(ecospold_path,
                                           "Ecoinvent3_3_cutoff")
    ei.apply_strategies()
    ei.statistics()
    ei.write_database()

    bw2.projects.set_current('default')

    def teardown_fixtures():
        print('TEAR IT DOWN!!')
        bw2.projects.set_current('default')

        if TEST_MODEL_NAME in bw2.projects:
            bw2.projects.delete_project(name=TEST_MODEL_NAME, delete_dir=True)

    request.addfinalizer(teardown_fixtures)
Example #2
0
def lcopt_bw2_setup(ecospold_path, overwrite=False, db_name=DEFAULT_DB_NAME):  # pragma: no cover

    """
    Utility function to set up brightway2 to work correctly with lcopt.

    It requires the path to the ecospold files containing the Ecoinvent 3.3 cutoff database.

    If you don't have these files, log into `ecoinvent.org  <http://www.ecoinvent.org/login-databases.html>`_ and go to the Files tab

    Download the file called ``ecoinvent 3.3_cutoff_ecoSpold02.7z``

    Extract the file somewhere sensible on your machine, you might need to download `7-zip <http://www.7-zip.org/download.html>`_ to extract the files.

    Make a note of the path of the folder that contains the .ecospold files, its probably ``<path/extracted/to>/datasets/``

    Use this path (as a string) as the first parameter in this function

    To overwrite an existing version, set overwrite=True
    """

    if db_name in bw2.projects:
        if overwrite:                                           
            bw2.projects.delete_project(name=db_name, delete_dir=True)
        else:
            print('Looks like bw2 is already set up - if you want to overwrite the existing version, use overwrite = True')
            return False

    bw2.projects.set_current(db_name)
    bw2.bw2setup()
    ei = bw2.SingleOutputEcospold2Importer(ecospold_path, "Ecoinvent3_3_cutoff")
    ei.apply_strategies()
    ei.statistics()
    ei.write_database()

    return True
Example #3
0
def get_ecoinvent(db_name=None,
                  auto_write=False,
                  download_path=None,
                  store_download=True,
                  **kwargs):
    """
    Download and import ecoinvent to current brightway2 project
    Optional kwargs:
        db_name: name to give imported database (string) default is downloaded filename
        auto_write: automatically write database if no unlinked processes (boolean) default is False (i.e. prompt yes or no)
        download_path: path to download .7z file to (string) default is download to temporary directory (.7z file is deleted after import)
        store_download: store the .7z file for later reuse, default is True, only takes effect if no download_path is provided
        username: ecoinvent username (string)
        password: ecoivnent password (string)
        version: ecoinvent version (string), eg '3.5'
        system_model: ecoinvent system model (string), one of {'cutoff', 'apos', 'consequential'}
    """
    with tempfile.TemporaryDirectory() as td:
        if download_path is None:
            if store_download:
                download_path = eidlstorage.eidl_dir
            else:
                download_path = td

        downloader = EcoinventDownloader(outdir=download_path, **kwargs)
        downloader.run()
        downloader.extract(target_dir=td)

        if not db_name:
            db_name = downloader.file_name.replace('.7z', '')
        datasets_path = os.path.join(td, 'datasets')
        importer = bw.SingleOutputEcospold2Importer(datasets_path, db_name)

    if 'biosphere3' not in bw.databases:
        if auto_write:
            bw.bw2setup()
        else:
            print('No biosphere database present in your current ' +
                  'project: {}'.format(bw.projects.current))
            print(
                'You can run "bw2setup()" if this is a new project. Run it now?'
            )
            if input('[y]/n ') in {'y', ''}:
                bw.bw2setup()
            else:
                return

    importer.apply_strategies()
    datasets, exchanges, unlinked = importer.statistics()

    if auto_write and not unlinked:
        print('\nWriting database {} in project {}'.format(
            db_name, bw.projects.current))
        importer.write_database()
    else:
        print('\nWrite database {} in project {}?'.format(
            db_name, bw.projects.current))
        if input('[y]/n ') in {'y', ''}:
            importer.write_database()
Example #4
0
def setup_fixtures(request):

    print('RUNNING SETUP FIXTURE')

    if FULL_SETUP:
        bw2.projects.purge_deleted_directories()
        if bw2_project_exists(IMPORT_PROJECT_NAME):
            bw2.projects.delete_project(name=IMPORT_PROJECT_NAME,
                                        delete_dir=True)
        if bw2_project_exists(TEST_BW_PROJECT_NAME):
            bw2.projects.delete_project(name=TEST_BW_PROJECT_NAME,
                                        delete_dir=True)

        if bw2_project_exists(DEFAULT_BIOSPHERE_PROJECT):
            bw2.projects.set_current(DEFAULT_BIOSPHERE_PROJECT)
            bw2.projects.copy_project(IMPORT_PROJECT_NAME, switch=True)
        else:
            bw2.projects.set_current(IMPORT_PROJECT_NAME)
            bw2.bw2setup()

        script_path = os.path.dirname(os.path.realpath(__file__))
        ecospold_folder = os.path.join("tests", "assets", "datasets")
        ecospold_path = os.path.join(script_path, ecospold_folder)
        print(ecospold_path)

        ei = bw2.SingleOutputEcospold2Importer(ecospold_path,
                                               "Ecoinvent3_3_cutoff")
        ei.apply_strategies()
        ei.statistics()
        ei.write_database()

        bw2.projects.copy_project(TEST_BW_PROJECT_NAME, switch=True)

        test_db = bw2.Database(TEST_BW_DB_NAME)
        test_db.write(TEST_MODEL_DATABASE)

        bw2.projects.set_current('default')

    def teardown_fixtures():
        print('TEAR IT DOWN!!')

        print('cleaning up brightway')

        bw2.projects.set_current('default')

        if bw2_project_exists(TEST_BW_PROJECT_NAME):
            bw2.projects.delete_project(
                name=TEST_BW_PROJECT_NAME)  #, delete_dir=True)
            #bw2.projects.purge_deleted_directories()

        if bw2_project_exists(IMPORT_PROJECT_NAME):
            bw2.projects.delete_project(name=IMPORT_PROJECT_NAME)

        shutil.rmtree(os.path.join(script_path, "tests", TEST_FOLDER))

    request.addfinalizer(teardown_fixtures)
def create_project(project_name, ecoinvent_path,
                   years, scenario, remind_data_path, from_scratch=True):
    """
    Create and prepare a brightway2 project with updated
    inventories for electricity markets according to
    REMIND data.

    Relies on `premise.NewDatabase`. Existing databases are
    deleted.

    :param str project_name: name of the brightway2 project to modify
    :param str ecoinvent_path: path to the ecoinvent db, at present
        this has to be ecoinvent version 3.6
    :param list years: range of years to create inventories for
    :param str scenario: the scenario to create inventories for
    :param bool from_scratch: should all databases be deleted and recreated?

    """
    bw.projects.set_current(project_name)

    if(from_scratch):
        print("Clean existing databases.")
        dbstr = list(bw.databases)
        for db in dbstr:
            del(bw.databases[db])
            bw.methods.clear()

        bw.bw2setup()

    print("Import Ecoinvent.")
    if 'ecoinvent 3.6 cutoff' in bw.databases:
        print("Database has already been imported")
    else:
        ei36 = bw.SingleOutputEcospold2Importer(
            fpei36, 'ecoinvent 3.6 cutoff')
        ei36.apply_strategies()
        ei36.statistics()
        ei36.write_database()

    for year in years:
        print("Create modified database for scenario {} and year {}"
              .format(scenario, year))
        ndb = premise.NewDatabase(
            scenario=scenario,
            year=year,
            source_db='ecoinvent 3.6 cutoff',
            source_version=3.6,
            filepath_to_iam_files=remind_data_path)
        ndb.update_all()
        ndb.write_db_to_brightway()
Example #6
0
def lcopt_bw2_setup(ecospold_path, overwrite = False):
	if DEFAULT_DB_NAME in bw2.projects:
		if overwrite:
			bw2.projects.delete_project(name=DEFAULT_DB_NAME, delete_dir=True)
		else:
			print('Looks like bw2 is already set up - if you want to overwrite the existing version, use overwrite = True')
			return False

	bw2.projects.set_current(DEFAULT_DB_NAME)
	bw2.bw2setup()
	ei = bw2.SingleOutputEcospold2Importer(ecospold_path, "Ecoinvent3_3_cutoff")
	ei.apply_strategies()
	ei.statistics()
	ei.write_database()

	return True
Example #7
0
def get_ecoinvent(db_name=None, auto_write=False, *args, **kwargs):
    """
    Download and import ecoinvent to current brightway2 project
    Optional kwargs:
        db_name: name to give imported database (string) default is downloaded filename
        auto_write: automatically write database if no unlinked processes (boolean) default is False (i.e. prompt yes or no)
        download_path: path to download .7z file to (string) default is download to temporary directory (.7z file is deleted after import)
    """
    if check_requirements(auto_write=auto_write):

        with tempfile.TemporaryDirectory() as td:

            if 'download_path' in kwargs:
                download_path = kwargs['download_path']
            else:
                download_path = td

            print("downloading to {}".format(download_path))

            downloader = EcoinventDownloader(*args,
                                             outdir=download_path,
                                             **kwargs)

            extract = '7za x {} -o{}'.format(downloader.out_path, td)
            subprocess.call(extract.split())
            if not db_name:
                db_name = downloader.file_name.replace('.7z', '')
            datasets_path = os.path.join(td, 'datasets')
            importer = bw.SingleOutputEcospold2Importer(datasets_path, db_name)

        importer.apply_strategies()
        datasets, exchanges, unlinked = importer.statistics()

        if auto_write and not unlinked:
            print('\nWriting database {} in project {}'.format(
                db_name, bw.projects.current))
            importer.write_database()
        else:
            print('\nWrite database {} in project {}?'.format(
                db_name, bw.projects.current))
            if input('[y]/n ') in {'y', ''}:
                importer.write_database()
activity_data = pd.read_excel(
    r"E:\tencent files\chrome Download\Research\DEA\DEA_transport\Data_input\data.xlsx",
    sheet_name="activity_data",
    index_col=0,
)

# 不同运输模型的LCA名称
activity_eidb_df = pd.read_excel(
    r"E:\tencent files\chrome Download\Research\DEA\DEA_transport\Data_input\data.xlsx",
    sheet_name="lca_EF",
    index_col=0,
)

if "ecoinvent 3.6" not in bw.databases:
    link = r"E:\ecoinvent3.6cutoffecoSpold02\datasets"
    ei36 = bw.SingleOutputEcospold2Importer(link, "ecoinvent 3.6", use_mp=False)
    ei36.apply_strategies()
    ei36.statistics()
    ei36.write_database()

eidb = bw.Database("ecoinvent 3.6")
structured_array = np.load(eidb.filepath_processed())
transport_modes = list(activity_data.columns)[1:]
years = list(range(2013, 2018))

fu_value_dict = {}
for year in years:
    fu_subdict = {}
    for transport_mode in transport_modes:
        fu_subdict[transport_mode] = value(activity_data, year, transport_mode)
    fu_value_dict[year] = fu_subdict
import brightway2 as bw
import pandas as pd

bw.projects.set_current('Comparative static LCA')
bw.bw2setup()

# Importing the LCI database
fpei36 = 'C:/Users/muuuuggle/Desktop/ecoinvent 3.6_apos_ecoSpold02/datasets'

if 'ecoinvent3.6apos' in bw.databases:
    print('Database has already been imported')
else:
    eiapos36 = bw.SingleOutputEcospold2Importer(fpei36,
                                                'ecoinvent3.6apos',
                                                use_mp=False)
    eiapos36.apply_strategies()
    eiapos36.statistics()
    eiapos36.write_database()

bioDB = bw.Database('biosphere3')
ecoinDB = bw.Database('ecoinvent3.6apos')
print('The ecoinvnet DB type is', type(ecoinDB), 'The biosphere DB type is ',
      type(bioDB), 'just you know')

# Finding my two products
ecoinDB.make_searchable()
dairy = ecoinDB.search('dairy')
print(dairy)

Milk1 = dairy[1]
Milk2 = dairy[5]
@author: massimo
"""

import brightway2 as bw

# If you want to make a new project OR import the database into a specific project
# Use these commands below
# Otherwsie skip them
list(bw.projects)
bw.projects.current
bw.projects.set_current("<your project  name here>")

# Import the biosphere3 database

bw.bw2setup()  # This will take some time

# Import ecoinvent

# You need to chenge the line below with the directory wher eyou have saved ecoinvent
fpei34 = "/Users/massimo/Documents/AAU/Research/Databases/ecoinvent v3.4/datasets"

bw.databases
if 'ecoinvent 3.4 conseq' in bw.databases:
    print("Database has already been imported")
else:
    ei34 = bw.SingleOutputEcospold2Importer(fpei34, 'ecoinvent 3.4 conseq')
    ei34.apply_strategies()
    ei34.statistics()

ei34.write_database()  # This will take some time.