コード例 #1
0
ファイル: cement.py プロジェクト: Loisel/rmnd-lca
    def get_suppliers_of_a_region(
            self, remind_region, ecoinvent_technologies, reference_product
    ):
        """
        Return a list of datasets which location and name correspond to the region, name and reference product given,
        respectively.

        :param remind_region: a REMIND region
        :type remind_region: str
        :param ecoinvent_technologies: list of names of ecoinvent dataset
        :type ecoinvent_technologies: list
        :param reference_product: reference product
        :type reference_product: str
        :return: list of wurst datasets
        :rtype: list
        """
        return ws.get_many(
            self.db,
            *[
                ws.either(
                    *[
                        ws.equals("name", supplier)
                        for supplier in ecoinvent_technologies
                    ]
                ),
                ws.either(
                    *[
                        ws.equals("location", loc)
                        for loc in self.geo.remind_to_ecoinvent_location(remind_region)
                    ]
                ),
                ws.equals("unit", "kilogram"),
                ws.equals("reference product", reference_product),
            ]
        )
コード例 #2
0
ファイル: cement.py プロジェクト: flohump/premise
    def update_pollutant_emissions(self, ds):
        """
        Update pollutant emissions based on GAINS data.
        :return:
        """

        # Update biosphere exchanges according to GAINS emission values
        for exc in ws.biosphere(
                ds,
                ws.either(
                    *[ws.contains("name", x) for x in self.emissions_map])):
            iam_emission_label = self.emissions_map[exc["name"]]

            try:
                iam_emission = self.iam_data.cement_emissions.loc[dict(
                    region=ds["location"],
                    pollutant=iam_emission_label)].values.item(0)
            except KeyError:
                # TODO: fix this.
                # GAINS does not have a 'World' region, hence we use Europe as a temporary fix
                iam_emission = self.iam_data.cement_emissions.loc[dict(
                    region=self.geo.iam_to_GAINS_region("World"),
                    pollutant=iam_emission_label)].values.item(0)

            if exc["amount"] == 0:
                wurst.rescale_exchange(exc,
                                       iam_emission / 1,
                                       remove_uncertainty=True)
            else:
                wurst.rescale_exchange(exc, iam_emission / exc["amount"])
        return ds
コード例 #3
0
        def producer_in_locations(locs):

            possible_producers = list(
                ws.get_many(
                    self.db, ws.equals("name", name),
                    ws.either(*[ws.equals("location", loc) for loc in locs])))

            if len(possible_producers) == 1:
                selected_producer = possible_producers[0]

            elif len(possible_producers) > 1:
                possible_locations = tuple(
                    [p["location"] for p in possible_producers])
                print(
                    ("Multiple potential producers for {} found in {}, "
                     "using activity from {}").format(name, region,
                                                      possible_locations))

                mapping = {
                    ("RAS", "RER"): "RER",
                }
                selected_producer = [
                    p for p in possible_producers
                    if p["location"] == mapping.get(possible_locations, "RER")
                ][0]

                print("We will use the following location: {}".format(
                    selected_producer["location"]))

            else:
                selected_producer = None

            return selected_producer
コード例 #4
0
ファイル: cement.py プロジェクト: flohump/premise
    def get_suppliers_of_a_region(self,
                                  iam_region,
                                  ecoinvent_technologies,
                                  reference_product,
                                  unit="kilogram",
                                  look_for_locations_in="ecoinvent"):
        """
        Return a list of datasets which location and name correspond to the region, name and reference product given,
        respectively.

        :param unit: unit of the dataset. If not specified, "kilogram" is used.
        :param look_for_locations_in: whether it should look for a supplier in ecoinvent locations or IAM locations.
        :param iam_region: an IAM region
        :type iam_region: str
        :param ecoinvent_technologies: list of names of ecoinvent dataset
        :type ecoinvent_technologies: list
        :param reference_product: reference product
        :type reference_product: str
        :return: list of wurst datasets
        :rtype: list
        """
        if look_for_locations_in == "ecoinvent":
            return ws.get_many(
                self.db, *[
                    ws.either(*[
                        ws.contains("name", supplier)
                        for supplier in ecoinvent_technologies
                    ]),
                    ws.either(*[
                        ws.equals("location", loc) for loc in
                        self.geo.iam_to_ecoinvent_location(iam_region)
                    ]),
                    ws.equals("unit", unit),
                    ws.equals("reference product", reference_product),
                ])
        else:
            return ws.get_many(
                self.db, *[
                    ws.either(*[
                        ws.contains("name", supplier)
                        for supplier in ecoinvent_technologies
                    ]),
                    ws.equals("location", look_for_locations_in),
                    ws.equals("unit", unit),
                    ws.equals("reference product", reference_product),
                ])
コード例 #5
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)
コード例 #6
0
 def producer_in_locations(locs):
     prod = None
     producers = list(ws.get_many(
         self.db,
         ws.equals("name", name),
         ws.either(*[
             ws.equals("location", loc) for loc in locs
         ])))
     if len(producers) >= 1:
         prod = producers[0]
         if len(producers) > 1:
             print(("Multiple producers for {} found in {}, "
                    "using activity from {}").format(
                        name, region, prod["location"]))
     return prod
コード例 #7
0
ファイル: renewables.py プロジェクト: romainsacchi/premise
    def update_efficiency_of_solar_PV(self):
        """
        Update the efficiency of solar PV modules.
        We look at how many square meters are needed per kilowatt of installed capacity
        to obtain the current efficiency.
        Then we update the surface needed according to the projected efficiency.
        :return:
        """

        ds = ws.get_many(
            self.db, *[
                ws.contains("name", "photovoltaic"),
                ws.either(
                    ws.contains("name", "installation"),
                    ws.contains("name", "construction"),
                ),
                ws.doesnt_contain_any("name", ["market", "factory"]),
                ws.equals("unit", "unit"),
            ])

        for d in ds:
            power = float(re.findall("\d+", d["name"])[0])

            for exc in ws.technosphere(
                    d, *[
                        ws.contains("name", "photovoltaic"),
                        ws.equals("unit", "square meter"),
                    ]):

                surface = float(exc["amount"])
                max_power = surface  # in kW, since we assume a constant 1,000W/m^2
                current_eff = power / max_power
                new_eff = get_efficiency_ratio_solar_PV(self.year,
                                                        power).values

                # We only update the efficiency if it is higher than the current one.
                if new_eff > current_eff:
                    exc["amount"] *= float(current_eff / new_eff)
                    d["parameters"] = {"efficiency": new_eff}

        return self.db
コード例 #8
0
def add_modified_tags(original_db, scenarios):
    """
    Add a `modified` label to any activity that is new
    Also add a `modified` label to any exchange that has been added
    or that has a different value than the source database.
    :return:
    """

    # Class `Export` to which the original database is passed
    exp = Export(original_db)
    # Collect a dictionary of activities {row/col index in A matrix: code}
    rev_ind_A = rev_index(create_codes_index_of_A_matrix(original_db))
    # Retrieve list of coordinates [activity, activity, value]
    coords_A = exp.create_A_matrix_coordinates()
    # Turn it into a dictionary {(code of receiving activity, code of supplying activity): value}
    original = {(rev_ind_A[x[0]], rev_ind_A[x[1]]): x[2] for x in coords_A}
    # Collect a dictionary with activities' names and correponding codes
    codes_names = create_codes_and_names_of_A_matrix(original_db)
    # Collect list of substances
    rev_ind_B = rev_index(create_codes_index_of_B_matrix())
    # Retrieve list of coordinates of the B matrix [activity index, substance index, value]
    coords_B = exp.create_B_matrix_coordinates()
    # Turn it into a dictionary {(activity code, substance code): value}
    original.update({(rev_ind_A[x[0]], rev_ind_B[x[1]]): x[2] for x in coords_B})

    for s, scenario in enumerate(scenarios):
        print(f"Looking for differences in database {s + 1} ...")
        rev_ind_A = rev_index(create_codes_index_of_A_matrix(scenario["database"]))
        exp = Export(scenario["database"], scenario["model"], scenario["pathway"], scenario["year"], "")
        coords_A = exp.create_A_matrix_coordinates()
        new = {(rev_ind_A[x[0]], rev_ind_A[x[1]]): x[2] for x in coords_A}

        rev_ind_B = rev_index(create_codes_index_of_B_matrix())
        coords_B = exp.create_B_matrix_coordinates()
        new.update({(rev_ind_A[x[0]], rev_ind_B[x[1]]): x[2] for x in coords_B})

        list_new = set(i[0] for i in original.keys()) ^ set(i[0] for i in new.keys())

        ds = (d for d in scenario["database"] if d["code"] in list_new)

        # Tag new activities
        for d in ds:
            d["modified"] = True

        # List codes that belong to activities that contain modified exchanges
        list_modified = (i[0] for i in new if i in original and new[i] != original[i])
        #
        # Filter for activities that have modified exchanges
        for ds in ws.get_many(
                scenario["database"],
                ws.either(*[ws.equals("code", c) for c in set(list_modified)])
        ):
            # Loop through biosphere exchanges and check if
            # the exchange also exists in the original database
            # and if it has the same value
            # if any of these two conditions is False, we tag the exchange
            excs = (exc for exc in ds["exchanges"] if exc["type"] == "biosphere")
            for exc in excs:
                if (ds["code"], exc["input"][0]) not in original or new[(ds["code"], exc["input"][0])] != original[(ds["code"], exc["input"][0])]:
                    exc["modified"] = True
            # Same thing for technosphere exchanges,
            # except that we first need to look up the provider's code first
            excs = (exc for exc in ds["exchanges"] if exc["type"] == "technosphere")
            for exc in excs:
                if (exc["name"], exc["product"], exc["unit"], exc["location"]) in codes_names:
                    exc_code = codes_names[(exc["name"], exc["product"], exc["unit"], exc["location"])]
                    if new[(ds["code"], exc_code)] != original[(ds["code"], exc_code)]:
                        exc["modified"] = True
                else:
                    exc["modified"] = True

    return scenarios
コード例 #9
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