Пример #1
0
    def adjust_recycled_steel_share(self, dict_act):
        """
        Adjust the supply shares of primary and secondary steel, based on REMIND data.

        :param dict_act: dictionary with REMIND region as keys and datasets as values.
        :type dict_act: dict
        :return: same dictionary, with modified exchanges
        :rtype: dict
        """

        dict_act = self.remove_exchanges(dict_act, ['steel production'])

        for d, act in dict_act.items():
            remind_region = d

            total_production_volume = self.steel_data.sel(region=remind_region, variables='Production|Industry|Steel')
            primary_share = (self.steel_data.sel(region=remind_region, variables='Production|Industry|Steel|Primary') / total_production_volume).values
            secondary_share = 1 - primary_share

            ds = ws.get_one(self.db,
                       ws.equals('reference product', act['reference product']),
                       ws.contains('name', 'steel production'),
                       ws.contains('name', 'converter'),
                        ws.contains('location', 'RoW'))

            act['exchanges'].append(
                {
                    "uncertainty type": 0,
                    "loc": 1,
                    "amount": primary_share,
                    "type": "technosphere",
                    "production volume": 1,
                    "product": ds['reference product'],
                    "name": ds['name'],
                    "unit": ds['unit'],
                    "location": remind_region,
                }
            )

            ds = ws.get_one(self.db,
                       ws.equals('reference product', act['reference product']),
                       ws.contains('name', 'steel production'),
                       ws.contains('name', 'electric'),
                       ws.contains('location', 'RoW'))

            act['exchanges'].append(
                {
                    "uncertainty type": 0,
                    "loc": 1,
                    "amount": secondary_share,
                    "type": "technosphere",
                    "production volume": 1,
                    "product": ds['reference product'],
                    "name": ds['name'],
                    "unit": ds['unit'],
                    "location": remind_region,
                }
            )

        return dict_act
Пример #2
0
    def link_local_electricity_supply(self):
        """Create LDV activities for REMIND regions and relink
        existing electricity exchanges for BEVs and PHEVs
        to REMIND-compatible (regional) market groups.
        """
        print(
            "Re-linking local electricity supply for all EV and FCEV activities"
        )

        for region in self.iam_data.regions:
            try:
                supply = ws.get_one(
                    self.db,
                    ws.equals(
                        "name",
                        "electricity market for fuel preparation, {}".format(
                            self.year)), ws.equals("location", region))

                # replace electricity input
                supply["exchanges"] = [
                    e for e in supply["exchanges"] if e["type"] == "production"
                ]
                supply["exchanges"].append({
                    "amount": 1.0,
                    "location": region,
                    "name": "market group for electricity, low voltage",
                    "product": "electricity, low voltage",
                    "tag": "energy chain",
                    "type": "technosphere",
                    "uncertainty type": 0,
                    "unit": "kilowatt hour",
                })
            except ws.NoResults:
                pass
Пример #3
0
    def create_local_evs(self):
        """Create LDV activities for REMIND regions and relink
        existing electricity exchanges for BEVs and PHEVs
        to REMIND-compatible (regional) market groups.
        """
        print("Creating local BEV and PHEV activities")

        bevs = list(ws.get_many(
            self.db,
            ws.either(
                ws.contains("name", "BEV,"),
                ws.contains("name", "PHEV"))))

        self._delete_non_global(bevs)

        old_supply = ws.get_one(
            self.db,
            ws.startswith(
                "name", "electricity supply for electric vehicles"))

        for region in self.remind_regions:

            # create local electricity supply
            supply = self._create_local_copy(old_supply, region)
            # replace electricity input
            for sup in ws.technosphere(
                    supply, ws.equals("product", "electricity, low voltage")):
                sup.update({
                    "name": "market group for electricity, low voltage",
                    "location": region
                })
            print("Relinking electricity markets for BEVs in {}".format(region))

            for bev in bevs:
                new_bev = self._create_local_copy(bev, region)
                # update fuel market
                oldex = list(ws.technosphere(
                    new_bev,
                    ws.startswith(
                        "name",
                        "electricity supply for electric vehicles")))
                # should only be one
                if len(oldex) != 1:
                    raise ValueError(
                        "Zero or more than one electricity "
                        "markets for fuel production found for {} in {}"
                        .format(new_bev["name"], new_bev["location"]))
                elif len(oldex) == 1:
                    # reference the new supply
                    oldex[0].update({
                        "location": region
                    })
                    self.db.append(new_bev)
            self.db.append(supply)
Пример #4
0
    def create_local_fcevs(self):
        """Create LDV activities for REMIND regions and relink
        existing electricity exchanges for FCEVs
        to REMIND-compatible (regional) market groups.
        """
        print("Creating local FCEV activities")

        fcevs = list(ws.get_many(
            self.db,
            ws.contains("name", "FCEV,")))

        self._delete_non_global(fcevs)
        old_supply = ws.get_one(
            self.db,
            ws.startswith(
                "name", "fuel supply for hydrogen vehicles"))

        for region in self.remind_regions:
            print("Relinking hydrogen markets for FCEVs in {}".format(region))
            # create local hydrogen supply
            supply = self._create_local_copy(old_supply, region)
            # remove explicit electricity input
            elmark = next(ws.technosphere(supply, ws.startswith(
                "name", "electricity market for fuel preparation")))
            elmark["amount"] = 0
            wurst.delete_zero_amount_exchanges([supply])

            # find hydrogen supply nearby
            h2sups = ws.technosphere(
                supply,
                ws.startswith("product", "Hydrogen"))
            for h2sup in h2sups:
                prod = self._find_local_supplier(region, h2sup["name"])
                h2sup["location"] = prod["location"]
                h2sup["name"] = prod["name"]

            # create local fcev
            for fcev in fcevs:
                # create local fcevs
                local_fcev = self._create_local_copy(fcev, region)
                # link correct market
                fuel_ex = next(ws.technosphere(
                    local_fcev,
                    ws.startswith("name", "fuel supply for hydrogen vehicles")))
                fuel_ex["location"] = region
                self.db.append(local_fcev)
            self.db.append(supply)
Пример #5
0
def add_non_fossil_co2_flows_to_ipcc_method():
    """Add non-fossil CO2 flows to the IPCC 2013 GWP 100a method."""
    ipcc = bw.Method(('IPCC 2013', 'climate change', 'GWP 100a'))
    gwp_data = ipcc.load()

    non_fossil = [
        x for x in ws.get_many(bw.Database("biosphere3"),
                               ws.equals("name", "Carbon dioxide, non-fossil"))
    ]
    print("Adding the following flows:")
    pprint(non_fossil)

    gwp_data.extend([(x.key, 1.) for x in non_fossil])

    co2_in_air = ws.get_one(bw.Database("biosphere3"),
                            ws.equals("name", 'Carbon dioxide, in air'))

    print("Adding {}.".format(co2_in_air))
    gwp_data.append((co2_in_air.key, -1.))

    method = bw.Method(('IPCC 2013', 'climate change', 'GWP 100a', 'Complete'))
    method.register()
    method.write(gwp_data)
    method.process()
Пример #6
0
    def link_local_liquid_fuel_markets(self):
        """
        Use IAM fuel markets to update the mix of bio-, syn-
        and fossil liquids in gasoline and diesel.

        """
        new_producers = {
            "diesel": {
                # biodiesel is only from cooking oil from RER,
                # as this is not the focus for now
                # to be improved!
                "Biomass": ws.get_one(
                    self.db,
                    ws.equals(
                        "name", "Biodiesel, from used cooking oil, at fuelling station"
                    ),
                )
            },
            "gasoline": {
                # only ethanol from European wheat straw as biofuel
                "Biomass": ws.get_one(
                    self.db,
                    ws.equals(
                        "name", "Ethanol, from wheat straw pellets, at fuelling station"
                    ),
                    ws.equals("location", "RER"),
                )
            },
        }

        for region in self.iam_data.regions:
            try:
                supply = {
                    ftype: ws.get_one(
                        self.db,
                        ws.equals("location", region),
                        ws.equals(
                            "name",
                            "fuel supply for {} vehicles, {}".format(ftype, self.year),
                        ),
                    )
                    for ftype in ["gasoline", "diesel"]
                }

                # two regions for gasoline and diesel production
                if region in ("EUR", "NEU", "WEU", "CEU"):
                    new_producers["gasoline"]["Fossil"] = ws.get_one(
                        self.db,
                        ws.equals("name", "market for petrol, low-sulfur"),
                        ws.equals("location", "Europe without Switzerland"),
                    )
                    new_producers["diesel"]["Fossil"] = ws.get_one(
                        self.db,
                        ws.equals("name", "market group for diesel"),
                        ws.equals("location", "RER"),
                    )
                else:
                    new_producers["gasoline"]["Fossil"] = ws.get_one(
                        self.db,
                        ws.equals("name", "market for petrol, low-sulfur"),
                        ws.equals("location", "RoW"),
                    )
                    new_producers["diesel"]["Fossil"] = ws.get_one(
                        self.db,
                        ws.equals("name", "market group for diesel"),
                        ws.equals("location", "GLO"),
                    )

                # local syndiesel
                new_producers["diesel"]["Hydrogen"] = self._find_local_supplier(
                    region,
                    "Diesel, synthetic, from electrolysis-based hydrogen, energy allocation, at fuelling station",
                )

                new_producers["gasoline"]["Hydrogen"] = self._find_local_supplier(
                    region,
                    "Gasoline, synthetic, from MTG, hydrogen from electrolysis, energy allocation, at fuelling station",
                )

                supply_search = {
                    "gasoline": {
                        "Hydrogen": "gasoline, synthetic, vehicle grade",
                        "Fossil": "petrol, low-sulfur",
                    },
                    "diesel": {
                        "Hydrogen": "diesel, synthetic, vehicle grade",
                        "Fossil": "diesel",
                    },
                }

                print("Relinking fuel markets for ICEVs in {}".format(region))
                for ftype in supply_search:
                    for subtype in supply_search[ftype]:

                        ex = list(
                            ws.technosphere(
                                supply[ftype],
                                ws.equals("product", supply_search[ftype][subtype]),
                            )
                        )

                        if len(ex) > 0:
                            ex[0].update(
                                {
                                    "location": new_producers[ftype][subtype][
                                        "location"
                                    ],
                                    "name": new_producers[ftype][subtype]["name"],
                                }
                            )

            except ws.NoResults:
                pass
Пример #7
0
    def fetch_proxies(self, name, ref_prod):
        """
        Fetch dataset proxies, given a dataset `name` and `reference product`.
        Store a copy for each REMIND region.
        If a REMIND region does not find a fitting ecoinvent location,
        fetch a dataset with a "RoW" location.
        Delete original datasets from the database.

        :return:
        """
        d_map = {
            self.geo.ecoinvent_to_remind_location(d['location']): d['location']
            for d in ws.get_many(
                self.db,
                ws.equals("name", name),
                ws.equals("reference product", ref_prod)
            )
        }

        list_remind_regions = [
            c[1] for c in self.geo.geo.keys()
            if type(c) == tuple and c[0] == "REMIND"
        ]

        d_remind_to_eco = {r: d_map.get(r, "RoW") for r in list_remind_regions}

        d_act = {}

        for d in d_remind_to_eco:
            try:
                ds = ws.get_one(
                    self.db,
                    ws.equals("name", name),
                    ws.equals("reference product", ref_prod),
                    ws.equals("location", d_remind_to_eco[d]),
                )

                d_act[d] = copy.deepcopy(ds)
                d_act[d]["location"] = d
                d_act[d]["code"] = str(uuid.uuid4().hex)
            except ws.NoResults:
                print('No dataset {} found for the REMIND region {}'.format(name, d))
                continue

            for prod in ws.production(d_act[d]):
                prod['location'] = d

        deleted_markets = [
            (act['name'], act['reference product'], act['location']) for act in self.db
                   if (act["name"], act['reference product']) == (name, ref_prod)
        ]

        with open(DATA_DIR / "logs/log deleted cement datasets.csv", "a") as csv_file:
                writer = csv.writer(csv_file,
                                    delimiter=';',
                                    lineterminator='\n')
                for line in deleted_markets:
                    writer.writerow(line)

        # Remove old datasets
        self.db = [act for act in self.db
                   if (act["name"], act['reference product']) != (name, ref_prod)]


        return d_act
Пример #8
0
    def create_local_icevs(self):
        """
        Use REMIND fuel markets to update the mix of bio-, syn-
        and fossil liquids in gasoline and diesel.
        """
        print("Creating local ICEV activities")
        icevs = list(ws.get_many(
            self.db,
            ws.either(
                ws.contains("name", "ICEV-"),
                ws.contains("name", "HEV-"))
            ))

        old_suppliers = {
            fuel: ws.get_one(
                self.db,
                ws.startswith(
                    "name", "fuel supply for {} vehicles".format(fuel)))
            for fuel in ["diesel", "gasoline"]}

        new_producers = {
            "diesel": {
                # biodiesel is only from cooking oil from RER,
                # as this is not the focus for now
                # to be improved!
                "Biomass": ws.get_one(
                    self.db,
                    ws.equals("name", "Biodiesel from cooking oil"))
            },
            "gasoline": {
                # only ethanol from European wheat straw as biofuel
                "Biomass": ws.get_one(
                    self.db,
                    ws.equals("name", "Ethanol from wheat straw pellets"),
                    ws.equals("location", "RER"))
            }
        }

        data = self.rmd.get_remind_fuel_mix_for_ldvs()
        for region in self.remind_regions:
            # two regions for gasoline and diesel production
            if region == "EUR":
                new_producers["gasoline"]["Fossil"] = ws.get_one(
                    self.db,
                    ws.equals("name", "market for petrol, low-sulfur"),
                    ws.equals("location", "Europe without Switzerland"))
                new_producers["diesel"]["Fossil"] = ws.get_one(
                    self.db,
                    ws.equals("name", "market group for diesel"),
                    ws.equals("location", "RER"))
            else:
                new_producers["gasoline"]["Fossil"] = ws.get_one(
                    self.db,
                    ws.equals("name", "market for petrol, low-sulfur"),
                    ws.equals("location", "RoW"))
                new_producers["diesel"]["Fossil"] = ws.get_one(
                    self.db,
                    ws.equals("name", "market group for diesel"),
                    ws.equals("location", "GLO"))

            # local syndiesel
            new_producers["diesel"]["Hydrogen"] = self._find_local_supplier(
                region, "Diesel production, synthetic, Fischer Tropsch process")

            new_producers["gasoline"]["Hydrogen"] = self._find_local_supplier(
                region, "Gasoline production, synthetic, from methanol")

            print("Relinking fuel markets for ICEVs in {}".format(region))
            for ftype in new_producers:
                new_supp = self._create_local_copy(
                    old_suppliers[ftype], region)

                new_supp["exchanges"] = [{
                    "amount": data.loc[region, suptype].values.item(),
                    "name": new_producers[ftype][suptype]["name"],
                    "location": new_producers[ftype][suptype]["location"],
                    "unit": "kilogram",
                    "type": "technosphere",
                    "reference product": new_producers[ftype][suptype]["reference product"],
                    "product": new_producers[ftype][suptype]["reference product"]
                } for suptype in new_producers[ftype]]

                new_supp["exchanges"].append({
                    "amount": 1,
                    "name": new_supp["name"],
                    "location": region,
                    "unit": "kilogram",
                    "type": "production",
                    "reference product": "fuel",
                    "product": "fuel"
                })

                self.db.append(new_supp)

            shortcuts = {
                "diesel": "EV-d",
                "gasoline": "EV-p"
            }

            for ftype in shortcuts:
                # diesel cars
                cars = list(ws.get_many(
                    icevs, ws.contains("name", shortcuts[ftype])))
                for car in cars:
                    # some local activities might already exist
                    local_dcar = self._get_local_act_or_copy(
                        cars, car, region)
                    # replace diesel supplier
                    fuel_ex = next(ws.technosphere(
                        local_dcar,
                        ws.startswith(
                            "name",
                            "fuel supply for {} vehicles".format(ftype))))
                    fuel_ex["location"] = region