Пример #1
0
def get_cdict(my_node):
    my_colors = cfg.get_dict_list("plot_colors", string=True)
    color_dict = {}
    for col in my_node.columns:
        n = 0
        color_keys = list(my_colors.keys())

        try:
            while color_keys[n] not in str(col).lower():
                n += 1
            if len(my_colors[color_keys[n]]) > 1:
                color = "#{0}".format(my_colors[color_keys[n]].pop(0))
            else:
                color = "#{0}".format(my_colors[color_keys[n]][0])
            color_dict[col] = color
        except IndexError:
            n = 0
            try:
                while color_keys[n] not in str(col).lower():
                    n += 1
                if len(my_colors[color_keys[n]]) > 1:
                    color = "#{0}".format(my_colors[color_keys[n]].pop(0))
                else:
                    color = "#{0}".format(my_colors[color_keys[n]][0])
                color_dict[col] = color
            except IndexError:
                color_dict[col] = "#ff00f0"

    return color_dict
Пример #2
0
def test_dicts():
    """Test dictionaries in config file."""
    files = [
        os.path.join(os.path.dirname(__file__), "data", "config_test.ini")
    ]
    config.init(files=files)
    d = config.get_dict("type_tester")
    eq_(d["my_list"], "4,6,7,9")
    d = config.get_dict_list("type_tester")
    eq_(d["my_list"][1], "6")
    eq_(d["my_None"][0], None)
    eq_(d["my_int"][0], 5)
    d = config.get_dict_list("type_tester", string=True)
    eq_(d["my_list"][1], "6")
    eq_(d["my_None"][0], "None")
    eq_(d["my_int"][0], "5")
Пример #3
0
def scenario_transmission(table_collection):
    vs = table_collection['volatile_source']

    # This should be done automatic e.g. if representative point outside the
    # landmass polygon.
    offshore_regions = (cfg.get_dict_list('offshore_regions_set')[cfg.get(
        'init', 'map')])

    elec_trans = deflex.transmission.get_electrical_transmission_deflex()

    # Set transmission capacity of offshore power lines to installed capacity
    # Multiply the installed capacity with 1.1 to get a buffer of 10%.
    for offreg in offshore_regions:
        elec_trans.loc[elec_trans.index.str.contains(offreg),
                       'capacity'] = (vs[offreg].sum().sum() * 1.1)

    elec_trans = (pd.concat([elec_trans], axis=1,
                            keys=['electrical']).sort_index(1))
    general_efficiency = cfg.get('transmission', 'general_efficiency')
    if general_efficiency is not None:
        elec_trans['electrical', 'efficiency'] = general_efficiency
    else:
        msg = ("The calculation of the efficiency by distance is not yet "
               "implemented")
        raise NotImplementedError(msg)
    if cfg.get('init', 'map') == 'de22':
        elec_trans.loc['DE22-DE01', ('electrical', 'efficiency')] = 0.9999
        elec_trans.loc['DE22-DE01', ('electrical', 'capacity')] = 9999999
    return elec_trans
Пример #4
0
def remove_onshore_technology_from_offshore_regions(df):
    """ This filter should be improved. It is slow and has to be adapted
    manually. Anyhow it seems to work this way."""

    logging.info("Removing onshore technology from offshore regions.")
    logging.info("The code is not efficient. So it may take a while.")

    offshore_regions = (cfg.get_dict_list('offshore_regions_set')[cfg.get(
        'init', 'map')])

    coast_regions = {
        'de02': {
            'MV': 'DE01',
            'SH': 'DE01',
            'NI': 'DE01 '
        },
        'de17': {
            'MV': 'DE13',
            'SH': 'DE01',
            'NI': 'DE03'
        },
        'de21': {
            'MV': 'DE01',
            'SH': 'DE13',
            'NI': 'DE14'
        },
        'de22': {
            'MV': 'DE01',
            'SH': 'DE13',
            'NI': 'DE14'
        },
    }
    try:
        dc = coast_regions[cfg.get('init', 'map')]
    except KeyError:
        raise ValueError('Coast regions not defined for {0} model.'.format(
            cfg.get('init', 'map')))

    region_column = '{0}_region'.format(cfg.get('init', 'map'))

    for ttype in ['Solar', 'Bioenergy', 'Wind']:
        for region in offshore_regions:
            logging.debug("Clean {1} from {0}.".format(region, ttype))

            c1 = df['energy_source_level_2'] == ttype
            c2 = df[region_column] == region

            condition = c1 & c2

            if ttype == 'Wind':
                condition = c1 & c2 & (df['technology'] == 'Onshore')

            for i, v in df.loc[condition].iterrows():
                df.loc[i, region_column] = (dc[df.loc[i, 'federal_states']])
    return df
Пример #5
0
def get_mileage_by_type_and_fuel(year=2018):
    """
    Get mileage by type and fuel from mileage table and other sources.

    See mobility.ini file for more information.
    """
    # get km per year and type
    total = (get_sheet_from_mileage_table("VK 1.1").loc[
        "Jahresfahrleistung in 1.000 km",
        str(year)].mul(1000))
    passenger = (get_sheet_from_mileage_table("VK 1.7").loc[
        "Jahresfahrleistung in 1.000 km",
        str(year)].mul(1000))
    small_trucks = (get_sheet_from_mileage_table("VK 1.17").loc[
        "Jahresfahrleistung in 1.000 km",
        str(year)].mul(1000))
    medium_trucks = (get_sheet_from_mileage_table("VK 1.20").loc[
        "Jahresfahrleistung in 1.000 km",
        str(year)].mul(1000))
    big_trucks_diesel = (get_sheet_from_mileage_table("VK 1.23").loc[
        "Jahresfahrleistung in 1.000 km",
        str(year)].mul(1000).sum())
    df = pd.DataFrame(index=total.index, columns=["diesel", "petrol", "other"])

    vt_dict = cfg.get_dict("vehicle_types_dictionary")
    df.rename(vt_dict, axis=0, inplace=True)
    total.rename(vt_dict, axis=0, inplace=True)

    dc = cfg.get_dict("fuel_dictionary")

    # add km by fuel for passenger cars
    df.loc["passenger car"] = passenger.rename(dc, axis=0)

    # add km by fuel for small trucks (<= 3.5 tons)
    df.loc["small truck (max. 3.5 tons)"] = small_trucks.rename(dc, axis=0)

    # add km by fuel for medium trucks (3.5 < weight <= 7.5 tons)
    df.loc["medium truck (3.5 to 7.5 tons)"] = medium_trucks.rename(dc, axis=0)

    # add km by fuel for big trucks (> 7.5 tons)
    # assuming that non-diesel engines are 50% petrol and 50% other
    n = "big truck (over 7.5 tons)"
    df.loc[n, "diesel"] = big_trucks_diesel
    df.loc[n, ["petrol", "other"]] = (total[n] - big_trucks_diesel) / 2

    fuel_share = pd.DataFrame(cfg.get_dict_list("fuel share"),
                              index=["diesel", "petrol",
                                     "other"]).astype(float)

    for col in fuel_share.columns:
        df.loc[col] = fuel_share[col].mul(total[col])

    return df
Пример #6
0
def calculate_mobility_energy_use(year):
    """

    Parameters
    ----------
    year

    Returns
    -------

    Examples
    --------
    >>> mobility_balance = get_traffic_fuel_energy(2017)
    >>> energy_use = calculate_mobility_energy_use(2017)
    >>> p = "Petrol usage [TJ]"
    >>> d = "Diesel usage [TJ]"
    >>> o = "Overall fuel usage [TJ]"
    >>> print(p, "(energy balance):", int(mobility_balance["Ottokraftstoffe"]))
    Petrol usage [TJ] (energy balance): 719580
    >>> print(p, "(calculated):", int(energy_use["petrol"].sum()))
    Petrol usage [TJ] (calculated): 803603
    >>> print(d, "(energy balance):",
    ...     int(mobility_balance["Dieselkraftstoffe"]))
    Diesel usage [TJ] (energy balance): 1425424
    >>> print(d, "(calculated):", int(energy_use["diesel"].sum()))
    Diesel usage [TJ] (calculated): 1636199
    >>> print(o, "(energy balance):", int(mobility_balance.sum()))
    Overall fuel usage [TJ] (energy balance): 2275143
    >>> print(o, "(calculated):", int(energy_use.sum().sum()))
    Overall fuel usage [TJ] (calculated): 2439803
    """
    # fetch table of mileage by fuel and vehicle type
    mileage = get_mileage_by_type_and_fuel(year)

    # fetch table of specific demand by fuel and vehicle type (from 2011)
    spec_demand = (pd.DataFrame(
        cfg.get_dict_list("fuel consumption"),
        index=["diesel", "petrol", "other"],
    ).astype(float).transpose())

    # fetch the energy content of the different fuel types
    energy_content = pd.Series(
        cfg.get_dict("energy_per_liter"))[["diesel", "petrol", "other"]]

    return mileage.mul(spec_demand).mul(energy_content) / 10**6
Пример #7
0
def scenario_mobility(year, table):
    """

    Parameters
    ----------
    year
    table

    Returns
    -------

    Examples
    --------
    >>> my_table = scenario_mobility(2015, {})
    >>> my_table["mobility_mileage"]["DE"].sum()
    diesel    3.769021e+11
    petrol    3.272263e+11
    other     1.334462e+10
    dtype: float64
    >>> my_table["mobility_spec_demand"]["DE"].loc["passenger car"]
    diesel    0.067
    petrol    0.079
    other     0.000
    Name: passenger car, dtype: float64
    >>> my_table["mobility_energy_content"]["DE"]["diesel"]
    energy_per_liter [MJ/l]    34.7
    Name: diesel, dtype: float64
    """
    if calendar.isleap(year):
        hours_of_the_year = 8784
    else:
        hours_of_the_year = 8760

    try:
        other = cfg.get("creator", "mobility_other")
    except configparser.NoSectionError:
        other = cfg.get("general", "mobility_other")

    mobility_mileage = mobility.get_mileage_by_type_and_fuel(year)

    # fetch table of specific demand by fuel and vehicle type (from 2011)
    mobility_spec_demand = (pd.DataFrame(
        cfg.get_dict_list("fuel consumption"),
        index=["diesel", "petrol", "other"],
    ).astype(float).transpose())

    mobility_spec_demand["other"] = mobility_spec_demand[other]
    fuel_usage = mobility_spec_demand.mul(mobility_mileage).sum()

    # fetch the energy content of the different fuel types
    mobility_energy_content = pd.DataFrame(cfg.get_dict("energy_per_liter"),
                                           index=["energy_per_liter [MJ/l]"])[[
                                               "diesel", "petrol", "other"
                                           ]]

    mobility_energy_content["other"] = mobility_energy_content[other]

    # Convert to MW????? BITTE GENAU!!!
    energy_usage = fuel_usage.mul(mobility_energy_content).div(3600)

    s = energy_usage.div(
        hours_of_the_year).transpose()["energy_per_liter [MJ/l]"]
    table["mobility demand series"] = pd.DataFrame(
        index=range(hours_of_the_year), columns=energy_usage.columns).fillna(1)

    table["mobility demand series"] = table["mobility demand series"].mul(
        s, axis=1)

    table["mobility demand series"][other] += table["mobility demand series"][
        "other"]
    table["mobility demand series"].drop("other", axis=1, inplace=True)

    table["mobility demand series"] = (
        table["mobility demand series"].astype(float).round().astype(int))

    table["mobility"] = pd.DataFrame(
        index=["diesel", "petrol", "electricity"],
        columns=["efficiency", "source", "source region"],
    )

    for col in table["mobility"].columns:
        for idx in table["mobility"].index:
            section = "mobility: " + idx
            table["mobility"].loc[idx, col] = cfg.get(section, col)

    # Add "DE" as region level to be consistent to other tables
    table["mobility"].index = pd.MultiIndex.from_product(
        [["DE"], table["mobility"].index])
    table["mobility demand series"].columns = pd.MultiIndex.from_product(
        [["DE"], table["mobility demand series"].columns])
    return table