Beispiel #1
0
def create_ecoinvent_33_project(ei33_path, ei33_name="ecoinvent 3.3 cutoff"):
    current_project = deepcopy(bd.projects.current)
    bd.projects.set_current(
        ei33_name)  # Temporarily switch to ecoinvent 3.3 project
    bi.bw2setup()
    import_ecoinvent(ei33_path, ei33_name)
    bd.projects.set_current(current_project)  # Switch back
Beispiel #2
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 = SingleOutputEcospold2Importer(datasets_path, db_name)

    if 'biosphere3' not in databases:
        if auto_write:
            bw2setup()
        else:
            print('No biosphere database present in your current ' +
                  'project: {}'.format(projects.current))
            print(
                'You can run "bw2setup()" if this is a new project. Run it now?'
            )
            if input('[y]/n ') in {'y', ''}:
                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, projects.current))
        importer.write_database()
    else:
        print('\nWrite database {} in project {}?'.format(
            db_name, projects.current))
        if input('[y]/n ') in {'y', ''}:
            importer.write_database()
Beispiel #3
0
    def write_database(self, project, name, overwrite=False):

        if project not in projects:
            warn("The project '{}' doesn't exist, it will be created".format(
                project))

        if projects.current != project:
            projects.set_current(project)

        if 'biosphere3' not in databases:
            bw2setup()

        if name in databases:
            if not overwrite:
                assert 0, 'Database already exists, either use overwrite=True, or use another name'
            else:
                print('Deleting existing database {}'.format(name))
                del databases[name]

        w.write_brightway2_database(self.db, name)
Beispiel #4
0
    def get_ecoinvent(self,
                      db_name=None,
                      download_path=None,
                      store_download=True,
                      **kwargs):
        """
        Download and import ecoinvent to FuturaDatabase. Sets :attr:`~db` directly

        Optional kwargs:

        :param db_name: name to give imported database. Default is downloaded filename
        :type db_name: str, optional

        :param download_path: path to download .7z file to default is download to temporary directory
            (.7z file is deleted after import)
        :type download_path: str, optional

        :param store_download: store the .7z file for later reuse, default is True, only takes effect if
            no download_path is provided
        :type store_download: bool, optional

        :param username: ecoinvent username
        :type username: str, optional

        :param password: ecoinvent password
        :type password: str, optional

        :param version: ecoinvent version, eg '3.5'
        :type version: str, optional

        :param system_model: ecoinvent system model, one of {'cutoff', 'apos', 'consequential'}
        :type system_model: str, optional

        :return: None
        :rtype: None
        """
        username = kwargs.get('username')
        password = kwargs.get('password')
        version = str(kwargs.get('version'))
        system_model = kwargs.get('system_model')
        write_config = False

        if version and system_model:
            print(
                "Attempting to find stored version of ecoinvent {} {})".format(
                    version, system_model))

            check_database_name = "ecoinvent_{}{}".format(
                system_model,
                str(version).replace('.', ''))

            check = check_database(DEFAULT_SETUP_PROJECT, check_database_name)

            if check:
                print("Found an existing version - extracting that")
                self.extract_bw2_database(DEFAULT_SETUP_PROJECT,
                                          check_database_name)
                return

        if not username or not password:
            config = storage.config
            ecoinvent = config.get('ecoinvent')
        if not username:
            if ecoinvent:
                username = ecoinvent.get('username')

        if not password:
            if ecoinvent:
                password = ecoinvent.get('password')

        if not username:
            username = input('ecoinvent username: '******'username'] = username
            write_config = True

        if not password:
            password = getpass.getpass('ecoinvent password: '******'password'] = password
            write_config = True

        if write_config:
            storage.write_config(config)

        with tempfile.TemporaryDirectory() as td:
            if download_path is None:
                if store_download:
                    download_path = storage.ecoinvent_dir
                else:
                    download_path = td

            downloader = EcoinventDownloader(outdir=download_path,
                                             username=username,
                                             password=password,
                                             version=version,
                                             system_model=system_model)
            downloader.run()
            print('Extracting datasets to temporary directory {}'.format(td))
            downloader.extract(target_dir=td)

            if not db_name:
                db_name = "ecoinvent_{}".format(
                    downloader.file_name.replace('.7z', ''))
            datasets_path = os.path.join(td, 'datasets')
            importer = SingleOutputEcospold2Importer(datasets_path, db_name)

        current_project = projects.current

        projects.set_current(DEFAULT_SETUP_PROJECT)

        if 'biosphere3' not in databases:
            bw2setup()

        if not migrations:
            create_core_migrations()

        importer.apply_strategies()
        datasets, exchanges, unlinked = importer.statistics()
        if not unlinked:
            importer.write_database()

        projects.set_current(current_project)

        for ds in importer.data:
            if 'parameters' in ds.keys():
                parameters, parameters_full = convert_parameters_to_wurst_style(
                    ds['parameters'])
                ds['parameters'] = parameters
                ds['parameters full'] = parameters_full

        add_input_info_for_indigenous_exchanges(importer.data, [db_name])

        if not unlinked:
            self.db.extend(importer.data)
            self.database_names.append(db_name)
Beispiel #5
0
 def create_db(self):
     bw2setup()
     create_climate_methods()
     data = {
         ("clima", "co2"): {
             'name':
             "co2",
             'exchanges': [
                 {
                     'amount':
                     1,
                     'input':
                     (db_bio.name, '349b29d1-3e58-4c66-98b9-9d1a076efd2e'
                      ),  #fossil fuel carbon dioxide thus normal CF
                     'type':
                     'biosphere'
                 },
             ],
             'type':
             'process',
         },
         ('clima', 'ch4'): {
             'name':
             "ch4",
             'exchanges': [
                 {
                     'amount':
                     1,
                     'input':
                     (db_bio.name, 'da1157e2-7593-4dfd-80dd-a3449b37a4d8'
                      ),  #Methane non fossil thus normal CF
                     'type':
                     'biosphere'
                 },
             ],
             'type':
             'process',
         },
         ('clima', 'ch4_fossil'): {
             'name':
             "ch4_fossil",
             'exchanges': [
                 {
                     'amount':
                     1,
                     'input':
                     (db_bio.name, '0795345f-c7ae-410c-ad25-1845784c75f5'
                      ),  #Methane fossil thus consider conversion to co2
                     'type':
                     'biosphere'
                 },
             ],
             'type':
             'process',
         },
         ('clima', 'co2bio_test'): {
             'name':
             "co2bio_test",
             'exchanges': [
                 {
                     'amount':
                     1,
                     'input':
                     (db_bio.name, 'cc6a1abb-b123-4ca6-8f16-38209df609be'
                      ),  #biogenic carbon dioxide 
                     'type':
                     'biosphere'
                 },
             ],
             'type':
             'process',
         }
     }
     db = Database('clima')
     db.write(data)