Esempio n. 1
0
def run_test_example():
    date_time_index = pd.date_range('1/1/2012', periods=5, freq='H')

    energysystem = solph.EnergySystem(timeindex=date_time_index)

    bgas = solph.Bus(label="natural_gas")
    bel = solph.Bus(label="electricity")
    solph.Sink(label='excess_bel', inputs={bel: solph.Flow()})
    solph.Source(label='rgas', outputs={bgas: solph.Flow()})
    solph.Sink(label='demand',
               inputs={
                   bel:
                   solph.Flow(actual_value=[10, 20, 30, 40, 50],
                              fixed=True,
                              nominal_value=1)
               })
    solph.LinearTransformer(
        label="pp_gas",
        inputs={bgas: solph.Flow()},
        outputs={bel: solph.Flow(nominal_value=10e10, variable_costs=50)},
        conversion_factors={bel: 0.58})
    om = solph.OperationalModel(energysystem)

    # check solvers
    solver = dict()
    for s in ['cbc', 'glpk', 'gurobi', 'cplex']:
        try:
            om.solve(solver=s)
            solver[s] = "working"
        except Exception:
            solver[s] = "not working"
    print("*********")
    print('Solver installed with oemof:')
    for s, t in solver.items():
        print("{0}: {1}".format(s, t))
    print("*********")
    print("oemof successfully installed.")
Esempio n. 2
0
def optimise_storage_size(filename="storage_investment.csv",
                          solver='cbc',
                          debug=True,
                          number_timesteps=8760,
                          tee_switch=True):
    logging.info('Initialize the energy system')
    date_time_index = pd.date_range('1/1/2012',
                                    periods=number_timesteps,
                                    freq='H')

    energysystem = solph.EnergySystem(timeindex=date_time_index)

    # Read data file
    full_filename = os.path.join(os.path.dirname(__file__), filename)
    data = pd.read_csv(full_filename, sep=",")

    ##########################################################################
    # Create oemof object
    ##########################################################################

    logging.info('Create oemof objects')
    # create natural gas bus
    bgas = solph.Bus(label="natural_gas")

    # create electricity bus
    bel = solph.Bus(label="electricity")

    # create excess component for the electricity bus to allow overproduction
    solph.Sink(label='excess_bel', inputs={bel: solph.Flow()})

    # create source object representing the natural gas commodity (annual limit)
    solph.Source(label='rgas',
                 outputs={
                     bgas:
                     solph.Flow(nominal_value=194397000 * number_timesteps /
                                8760,
                                summed_max=1)
                 })

    # create fixed source object representing wind power plants
    solph.Source(label='wind',
                 outputs={
                     bel:
                     solph.Flow(actual_value=data['wind'],
                                nominal_value=1000000,
                                fixed=True,
                                fixed_costs=20)
                 })

    # create fixed source object representing pv power plants
    solph.Source(label='pv',
                 outputs={
                     bel:
                     solph.Flow(actual_value=data['pv'],
                                nominal_value=582000,
                                fixed=True,
                                fixed_costs=15)
                 })

    # create simple sink object representing the electrical demand
    solph.Sink(label='demand',
               inputs={
                   bel:
                   solph.Flow(actual_value=data['demand_el'],
                              fixed=True,
                              nominal_value=1)
               })

    # create simple transformer object representing a gas power plant
    solph.LinearTransformer(
        label="pp_gas",
        inputs={bgas: solph.Flow()},
        outputs={bel: solph.Flow(nominal_value=10e10, variable_costs=50)},
        conversion_factors={bel: 0.58})

    # If the period is one year the equivalent periodical costs (epc) of an
    # investment are equal to the annuity. Use oemof's economic tools.
    epc = economics.annuity(capex=1000, n=20, wacc=0.05)

    # create storage object representing a battery
    solph.Storage(
        label='storage',
        inputs={bel: solph.Flow(variable_costs=10e10)},
        outputs={bel: solph.Flow(variable_costs=10e10)},
        capacity_loss=0.00,
        initial_capacity=0,
        nominal_input_capacity_ratio=1 / 6,
        nominal_output_capacity_ratio=1 / 6,
        inflow_conversion_factor=1,
        outflow_conversion_factor=0.8,
        fixed_costs=35,
        investment=solph.Investment(ep_costs=epc),
    )

    ##########################################################################
    # Optimise the energy system and plot the results
    ##########################################################################

    logging.info('Optimise the energy system')

    # initialise the operational model
    om = solph.OperationalModel(energysystem)

    # if debug is true an lp-file will be written
    if debug:
        filename = os.path.join(helpers.extend_basic_path('lp_files'),
                                'storage_invest.lp')
        logging.info('Store lp-file in {0}.'.format(filename))
        om.write(filename, io_options={'symbolic_solver_labels': True})

    # if tee_switch is true solver messages will be displayed
    logging.info('Solve the optimization problem')
    om.solve(solver=solver, solve_kwargs={'tee': tee_switch})

    return energysystem
Esempio n. 3
0
def heating_systems(esystem, dfull, add_elec, p):
    power_plants = prepare_data.chp_berlin(p)

    time_index = esystem.time_idx
    temperature_path = '/home/uwe/rli-lokal/git_home/demandlib/examples'
    temperature_file = temperature_path + '/example_data.csv'
    temperature = pd.read_csv(temperature_file)['temperature']
    sli = pd.Series(list(temperature.loc[:23]), index=list(range(8760, 8784)))
    temperature = temperature.append(sli)

    temperature = temperature.iloc[0:len(time_index)]
    heatbus = dict()
    hd = dict()
    auxiliary_energy = 0
    print(dfull)
    for h in dfull.keys():
        hd.setdefault(h, 0)
        lsink = 'demand_{0}'.format(h)
        lbus = 'bus_{0}'.format(h)
        ltransf = '{0}'.format(h)
        lres_bus = 'bus_{0}'.format(p.heating2resource[h])

        for b in dfull[h].keys():
            if b.upper() in p.bdew_types:
                bc = 0
                if b.upper() in ['EFH', 'MFH']:
                    bc = 1
                hd[h] += bdew.HeatBuilding(time_index,
                                           temperature=temperature,
                                           shlp_type=b,
                                           building_class=bc,
                                           wind_class=1,
                                           annual_heat_demand=dfull[h][b],
                                           name=h).get_bdew_profile()
                if b.upper() in ['EFH', 'MFH']:
                    print(h, 'in')
                    auxiliary_energy += bdew.HeatBuilding(
                        time_index,
                        temperature=temperature,
                        shlp_type=b,
                        building_class=bc,
                        wind_class=1,
                        annual_heat_demand=add_elec[h][b],
                        name=h).get_bdew_profile()
            elif b in [
                    'i',
            ]:
                hd[h] += pprofiles.IndustrialLoadProfile(
                    time_index).simple_profile(annual_demand=dfull[h][b])
            else:
                logging.error('Demandlib typ "{0}" not found.'.format(b))
        heatbus[h] = solph.Bus(label=lbus)

        solph.Sink(label=lsink,
                   inputs={
                       heatbus[h]:
                       solph.Flow(actual_value=hd[h].div(hd[h].max()),
                                  fixed=True,
                                  nominal_value=hd[h].max())
                   })

        if 'district' not in h:
            if lres_bus not in esystem.groups:
                solph.Bus(label=lres_bus)
            solph.LinearTransformer(
                label=ltransf,
                inputs={esystem.groups[lres_bus]: solph.Flow()},
                outputs={
                    heatbus[h]:
                    solph.Flow(nominal_value=hd[h].max(), variable_costs=0)
                },
                conversion_factors={heatbus[h]: 1})
        else:
            for pp in power_plants[h].index:
                lres_bus = 'bus_' + pp
                if lres_bus not in esystem.groups:
                    solph.Bus(label=lres_bus)
                solph.LinearTransformer(
                    label='pp_chp_{0}_{1}'.format(h, pp),
                    inputs={esystem.groups[lres_bus]: solph.Flow()},
                    outputs={
                        esystem.groups['bus_el']:
                        solph.Flow(
                            nominal_value=power_plants[h]['power_el'][pp]),
                        heatbus[h]:
                        solph.Flow(
                            nominal_value=power_plants[h]['power_th'][pp])
                    },
                    conversion_factors={
                        esystem.groups['bus_el']: 0.3,
                        heatbus[h]: 0.4
                    })
    from matplotlib import pyplot as plt
    hd_df = pd.DataFrame(hd)
    print(hd_df.sum().sum())
    print('z_max:', hd_df['district_z'].max())
    print('dz_max:', hd_df['district_dz'].max())
    print('z_sum:', hd_df['district_z'].sum())
    print('dz_sum:', hd_df['district_dz'].sum())
    hd_df.plot(colormap='Spectral')
    hd_df.to_csv('/home/uwe/hd.csv')
    plt.show()

    solph.Sink(label='auxiliary_energy',
               inputs={
                   esystem.groups['bus_el']:
                   solph.Flow(actual_value=auxiliary_energy.div(
                       auxiliary_energy.max()),
                              fixed=True,
                              nominal_value=auxiliary_energy.max())
               })

    # Create sinks
    # Get normalise demand and maximum value of electricity usage
    electricity_usage = electricity.DemandElec(time_index)
    normalised_demand, max_demand = electricity_usage.solph_sink(
        resample='H', reduce=auxiliary_energy)
    sum_demand = normalised_demand.sum() * max_demand
    print("delec:", "{:.2E}".format(sum_demand))

    solph.Sink(label='elec_demand',
               inputs={
                   esystem.groups['bus_el']:
                   solph.Flow(actual_value=normalised_demand,
                              fixed=True,
                              nominal_value=max_demand)
               })
Esempio n. 4
0
def optimise_storage_size(energysystem,
                          filename="variable_chp.csv",
                          solver='cbc',
                          debug=True,
                          tee_switch=True):

    # Read data file with heat and electrical demand (192 hours)
    full_filename = os.path.join(os.path.dirname(__file__), filename)
    data = pd.read_csv(full_filename, sep=",")

    ##########################################################################
    # Create oemof.solph objects
    ##########################################################################

    logging.info('Create oemof.solph objects')

    # create natural gas bus
    bgas = solph.Bus(label="natural_gas")

    # create commodity object for gas resource
    solph.Source(label='rgas', outputs={bgas: solph.Flow(variable_costs=50)})

    # create two electricity buses and two heat buses
    bel = solph.Bus(label="electricity")
    bel2 = solph.Bus(label="electricity_2")
    bth = solph.Bus(label="heat")
    bth2 = solph.Bus(label="heat_2")

    # create excess components for the elec/heat bus to allow overproduction
    solph.Sink(label='excess_bth_2', inputs={bth2: solph.Flow()})
    solph.Sink(label='excess_therm', inputs={bth: solph.Flow()})
    solph.Sink(label='excess_bel_2', inputs={bel2: solph.Flow()})
    solph.Sink(label='excess_elec', inputs={bel: solph.Flow()})

    # create simple sink object for electrical demand for each electrical bus
    solph.Sink(label='demand_elec',
               inputs={
                   bel:
                   solph.Flow(actual_value=data['demand_el'],
                              fixed=True,
                              nominal_value=1)
               })
    solph.Sink(label='demand_el_2',
               inputs={
                   bel2:
                   solph.Flow(actual_value=data['demand_el'],
                              fixed=True,
                              nominal_value=1)
               })

    # create simple sink object for heat demand for each thermal bus
    solph.Sink(label='demand_therm',
               inputs={
                   bth:
                   solph.Flow(actual_value=data['demand_th'],
                              fixed=True,
                              nominal_value=741000)
               })
    solph.Sink(label='demand_th_2',
               inputs={
                   bth2:
                   solph.Flow(actual_value=data['demand_th'],
                              fixed=True,
                              nominal_value=741000)
               })

    # This is just a dummy transformer with a nominal input of zero
    solph.LinearTransformer(label='fixed_chp_gas',
                            inputs={bgas: solph.Flow(nominal_value=0)},
                            outputs={
                                bel: solph.Flow(),
                                bth: solph.Flow()
                            },
                            conversion_factors={
                                bel: 0.3,
                                bth: 0.5
                            })

    # create a fixed transformer to distribute to the heat_2 and elec_2 buses
    solph.LinearTransformer(label='fixed_chp_gas_2',
                            inputs={bgas: solph.Flow(nominal_value=10e10)},
                            outputs={
                                bel2: solph.Flow(),
                                bth2: solph.Flow()
                            },
                            conversion_factors={
                                bel2: 0.3,
                                bth2: 0.5
                            })

    # create a fixed transformer to distribute to the heat and elec buses
    solph.VariableFractionTransformer(
        label='variable_chp_gas',
        inputs={bgas: solph.Flow(nominal_value=10e10)},
        outputs={
            bel: solph.Flow(),
            bth: solph.Flow()
        },
        conversion_factors={
            bel: 0.3,
            bth: 0.5
        },
        conversion_factor_single_flow={bel: 0.5})

    ##########################################################################
    # Optimise the energy system and plot the results
    ##########################################################################

    logging.info('Optimise the energy system')

    om = solph.OperationalModel(energysystem)

    if debug:
        filename = os.path.join(helpers.extend_basic_path('lp_files'),
                                'variable_chp.lp')
        logging.info('Store lp-file in {0}.'.format(filename))
        om.write(filename, io_options={'symbolic_solver_labels': True})

    logging.info('Solve the optimization problem')
    om.solve(solver=solver, solve_kwargs={'tee': tee_switch})

    return energysystem
Esempio n. 5
0
def optimise_storage_size(filename="storage_invest.csv", solvername='cbc',
                          debug=True, number_timesteps=8760, tee_switch=True):
    logging.info('Initialize the energy system')
    date_time_index = pd.date_range('1/1/2012', periods=number_timesteps,
                                    freq='H')

    energysystem = solph.EnergySystem(timeindex=date_time_index)

    # Read data file
    full_filename = os.path.join(os.path.dirname(__file__), filename)
    data = pd.read_csv(full_filename, sep=",")

    ##########################################################################
    # Create oemof object
    ##########################################################################

    logging.info('Create oemof objects')
    # create gas bus
    bgas = solph.Bus(label="natural_gas")

    # create electricity bus
    bel = solph.Bus(label="electricity")

    # create excess component for the electricity bus to allow overproduction
    solph.Sink(label='excess_bel', inputs={bel: solph.Flow()})

    # create commodity object for gas resource
    solph.Source(label='rgas', outputs={bgas: solph.Flow(
        nominal_value=194397000 * number_timesteps / 8760, summed_max=1)})

    # create fixed source object for wind
    solph.Source(label='wind', outputs={bel: solph.Flow(
        actual_value=data['wind'], nominal_value=1000000, fixed=True,
        fixed_costs=20)})

    # create fixed source object for pv
    solph.Source(label='pv', outputs={bel: solph.Flow(
        actual_value=data['pv'], nominal_value=582000, fixed=True,
        fixed_costs=15)})

    # create simple sink object for demand
    solph.Sink(label='demand', inputs={bel: solph.Flow(
        actual_value=data['demand_el'], fixed=True, nominal_value=1)})

    # create simple transformer object for gas powerplant
    solph.LinearTransformer(
        label="pp_gas",
        inputs={bgas: solph.Flow()},
        outputs={bel: solph.Flow(nominal_value=10e10, variable_costs=50)},
        conversion_factors={bel: 0.58})

    # Calculate ep_costs from capex to compare with old solph
    capex = 1000
    lifetime = 20
    wacc = 0.05
    epc = capex * (wacc * (1 + wacc) ** lifetime) / ((1 + wacc) ** lifetime - 1)

    # create storage transformer object for storage
    solph.Storage(
        label='storage',
        inputs={bel: solph.Flow(variable_costs=10e10)},
        outputs={bel: solph.Flow(variable_costs=10e10)},
        capacity_loss=0.00, initial_capacity=0,
        nominal_input_capacity_ratio=1/6,
        nominal_output_capacity_ratio=1/6,
        inflow_conversion_factor=1, outflow_conversion_factor=0.8,
        fixed_costs=35,
        investment=solph.Investment(ep_costs=epc),
    )

    ##########################################################################
    # Optimise the energy system and plot the results
    ##########################################################################

    logging.info('Optimise the energy system')

    om = solph.OperationalModel(energysystem)

    if debug:
        filename = os.path.join(
            helpers.extend_basic_path('lp_files'), 'storage_invest.lp')
        logging.info('Store lp-file in {0}.'.format(filename))
        om.write(filename, io_options={'symbolic_solver_labels': True})

    logging.info('Solve the optimization problem')
    om.solve(solver=solvername, solve_kwargs={'tee': tee_switch})

    return energysystem