Esempio n. 1
0
def test_something_else():
    date_time_index = pd.date_range('1/1/2012', periods=5, freq='H')
    energysystem = solph.EnergySystem(timeindex=date_time_index)
    bel1 = solph.Bus(label='electricity1')
    bel2 = solph.Bus(label='electricity2')
    energysystem.add(bel1, bel2)
    energysystem.add(
        solph.Transformer(
            label='powerline_1_2',
            inputs={bel1: solph.Flow()},
            outputs={
                bel2: solph.Flow(investment=solph.Investment(ep_costs=20))
            }))
    energysystem.add(
        solph.Transformer(
            label='powerline_2_1',
            inputs={bel2: solph.Flow()},
            outputs={
                bel1: solph.Flow(investment=solph.Investment(ep_costs=20))
            }))
    om = solph.Model(energysystem)
    line12 = energysystem.groups['powerline_1_2']
    line21 = energysystem.groups['powerline_2_1']
    solph.constraints.equate_variables(om,
                                       om.InvestmentFlow.invest[line12, bel2],
                                       om.InvestmentFlow.invest[line21, bel1],
                                       name="my_name")
Esempio n. 2
0
def add_transmission_lines_between_electricity_nodes(table_collection, nodes):
    """

    Parameters
    ----------
    table_collection
    nodes

    Returns
    -------

    """
    logging.debug("Add transmission lines to nodes dictionary.")
    power_lines = table_collection["power lines"]
    for idx, values in power_lines.iterrows():
        b1, b2 = idx.split("-")
        lines = [(b1, b2), (b2, b1)]
        for line in lines:
            line_label = Label("line", "electricity", line[0], line[1])
            bus_label_in = Label("bus", "electricity", "all", line[0])
            bus_label_out = Label("bus", "electricity", "all", line[1])
            if bus_label_in not in nodes:
                raise ValueError(
                    "Bus {0} missing for power line from {0} to {1}".format(
                        bus_label_in, bus_label_out
                    )
                )
            if bus_label_out not in nodes:
                raise ValueError(
                    "Bus {0} missing for power line from {0} to {1}".format(
                        bus_label_out, bus_label_in
                    )
                )
            if values.capacity != float("inf"):
                logging.debug(
                    "Line %s has a capacity of %s", line_label, values.capacity
                )
                nodes[line_label] = solph.Transformer(
                    label=line_label,
                    inputs={nodes[bus_label_in]: solph.Flow()},
                    outputs={
                        nodes[bus_label_out]: solph.Flow(
                            nominal_value=values.capacity
                        )
                    },
                    conversion_factors={
                        nodes[bus_label_out]: values.efficiency
                    },
                )
            else:
                logging.debug("Line %s has no capacity limit", line_label)
                nodes[line_label] = solph.Transformer(
                    label=line_label,
                    inputs={nodes[bus_label_in]: solph.Flow()},
                    outputs={nodes[bus_label_out]: solph.Flow()},
                    conversion_factors={
                        nodes[bus_label_out]: values.efficiency
                    },
                )
Esempio n. 3
0
def test_that_the_transformer_warnings_actually_get_raised():
    """ Transformer doesn't warn about potentially erroneous usage.
    """
    look_out = network.Bus()
    msg = "`Transformer` 'no input' constructed without `inputs`."
    with warnings.catch_warnings(record=True) as w:
        solph.Transformer(label='no input', outputs={look_out: "No inputs!"})
        ok_(len(w) == 1)
        eq_(msg, str(w[-1].message))
    msg = "`Transformer` 'no output' constructed without `outputs`."
    with warnings.catch_warnings(record=True) as w:
        solph.Transformer(label='no output', inputs={look_out: "No outputs!"})
        ok_(len(w) == 1)
        eq_(msg, str(w[-1].message))
Esempio n. 4
0
def test_transformer_class():
    transf = solph.Transformer()
    ok_(isinstance(transf.conversion_factors, dict))
    eq_(len(transf.conversion_factors.keys()), 0)
    bus = solph.Bus()
    transf = solph.Transformer(inputs={bus: solph.Flow()})
    eq_(transf.conversion_factors[bus][2], 1)
    transf = solph.Transformer(inputs={bus: solph.Flow()},
                               conversion_factors={bus: 2})
    eq_(transf.conversion_factors[bus][6], 2)
    transf = solph.Transformer(inputs={bus: solph.Flow()},
                               conversion_factors={bus: [2]})
    eq_(len(transf.conversion_factors[bus]), 1)
    with assert_raises(IndexError):
        eq_(transf.conversion_factors[bus][6], 2)
Esempio n. 5
0
    def test_transformer(self):
        """Constraint test of a LinearN1Transformer without Investment.
        """
        bgas = solph.Bus(label='gasBus')
        bbms = solph.Bus(label='biomassBus')
        bel = solph.Bus(label='electricityBus')
        bth = solph.Bus(label='thermalBus')

        solph.Transformer(label='powerplantGasCoal',
                          inputs={
                              bbms: solph.Flow(),
                              bgas: solph.Flow()
                          },
                          outputs={
                              bel:
                              solph.Flow(variable_costs=50),
                              bth:
                              solph.Flow(nominal_value=5e10, variable_costs=20)
                          },
                          conversion_factors={
                              bgas: 0.4,
                              bbms: 0.1,
                              bel: 0.3,
                              bth: 0.5
                          })

        self.compare_lp_files('transformer.lp')
Esempio n. 6
0
def check_oemof_installation(silent=False):
    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.Transformer(
        label="pp_gas",
        inputs={bgas: solph.Flow()},
        outputs={bel: solph.Flow(nominal_value=10e10, variable_costs=50)},
        conversion_factors={bel: 0.58})
    om = solph.Model(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"

    if not silent:
        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. 7
0
def auxiliary_transformer(label, input_bus, output_bus):
    r"""
    Get auxiliary transformer for Generic Model energy system.

    Parameters
    ----------
    label : str
        Spezific label to reference transformer.

    input_bus : solph.Bus
        Spezific input bus to reference transformer.

    output_bus : solph.Bus
        Spezific output bus to reference transformer.

    Note
    ----
    Auxiliary transformers are used to represent more complex networks. In
    solph individual busses have to be connected by a componente, in this case
    by 'auxiliary transformer'. In the Generic Model, these are used for the
    solar thermal and storage strand.

    The flow is not transformed, but transferred in an auxiliary way to make
    the calculation feasible.
    """
    auxiliary_transformer = solph.Transformer(
        label=label,
        inputs={input_bus: solph.Flow()},
        outputs={output_bus: solph.Flow(nominal_value=1, max=inf, min=0.0)},
        conversion_factors={output_bus: 1})
    return auxiliary_transformer
Esempio n. 8
0
    def test_transformer_invest_with_existing(self):
        """Constraint test of a LinearN1Transformer with Investment.
        """

        bgas = solph.Bus(label='gasBus')
        bcoal = solph.Bus(label='coalBus')
        bel = solph.Bus(label='electricityBus')
        bth = solph.Bus(label='thermalBus')

        solph.Transformer(label='powerplant_gas_coal',
                          inputs={
                              bgas: solph.Flow(),
                              bcoal: solph.Flow()
                          },
                          outputs={
                              bel:
                              solph.Flow(variable_costs=50,
                                         investment=solph.Investment(
                                             maximum=1000,
                                             ep_costs=20,
                                             existing=200)),
                              bth:
                              solph.Flow(variable_costs=20)
                          },
                          conversion_factors={
                              bgas: 0.58,
                              bcoal: 0.2,
                              bel: 0.3,
                              bth: 0.5
                          })

        self.compare_lp_files('transformer_invest_with_existing.lp')
Esempio n. 9
0
    def test_linear_transformer_chp_invest(self):
        """Constraint test of a Transformer with Investment (two outputs).
        """

        bgas = solph.Bus(label='gasBus')
        bheat = solph.Bus(label='heatBus')
        bel = solph.Bus(label='electricityBus')

        solph.Transformer(label='chp_powerplant_gas',
                          inputs={
                              bgas:
                              solph.Flow(variable_costs=50,
                                         investment=solph.Investment(
                                             maximum=1000, ep_costs=20))
                          },
                          outputs={
                              bel: solph.Flow(),
                              bheat: solph.Flow()
                          },
                          conversion_factors={
                              bel: 0.4,
                              bheat: 0.5
                          })

        self.compare_lp_files('linear_transformer_chp_invest.lp')
    def add_to_oemof_model(self, busses, model):
        """Creates an oemof Transformer component using the information given in
        the CompressorH2 class, to be used in the oemof model

        :param busses: virtual buses used in the energy system
        :type busses: dict
        :param model: current oemof model
        :type model: oemof model
        :return: oemof component
        """
        compressor = solph.Transformer(
            label=self.name,
            inputs={
                busses[self.bus_h2_in]:
                solph.Flow(nominal_value=self.m_flow_max *
                           self.sim_params.interval_time / 60),
                busses[self.bus_el]:
                solph.Flow()
            },
            outputs={busses[self.bus_h2_out]: solph.Flow()},
            conversion_factors={
                busses[self.bus_h2_in]: 1,
                busses[self.bus_el]: self.spec_compression_energy,
                busses[self.bus_h2_out]: 1
            })

        model.add(compressor)
        return compressor
Esempio n. 11
0
def add_power_plants(table_collection, nodes):
    """

    Parameters
    ----------
    table_collection
    nodes

    Returns
    -------

    """
    pp = table_collection["power plants"]

    check_in_out_buses(nodes, pp, table_collection)

    for idx, params in pp.iterrows():
        region = idx[0]

        # Create label for in and out bus:
        fuel_bus = Label(
            "bus", "commodity", params.fuel, params["source region"]
        )
        bus_elec = Label("bus", "electricity", "all", region)

        # Create power plants as 1x1 Transformer if capacity > 0
        if params.capacity > 0:
            # if downtime_factor is in the parameters, use it
            if hasattr(params, "downtime_factor"):
                params.capacity *= 1 - params["downtime_factor"]

            # Define output flow with or without summed_max attribute
            if params.get("annual_limit_electricity", float("inf")) == float(
                "inf"
            ):
                outflow = solph.Flow(nominal_value=params.capacity)
            else:
                smax = params.annual_limit_electricity / params.capacity
                outflow = solph.Flow(
                    nominal_value=params.capacity, summed_max=smax
                )

            # if variable costs are defined add them to the outflow
            if hasattr(params, "variable_costs"):
                vc = params.variable_costs
                outflow.variable_costs = solph.sequence(vc)

            plant_name = idx[1].replace(" - ", "_").replace(".", "")

            trsf_label = Label("trsf", "pp", plant_name, region)

            nodes[trsf_label] = solph.Transformer(
                label=trsf_label,
                inputs={nodes[fuel_bus]: solph.Flow()},
                outputs={nodes[bus_elec]: outflow},
                conversion_factors={nodes[bus_elec]: params.efficiency},
            )
Esempio n. 12
0
def add_mobility(table_collection, nodes):
    """

    Parameters
    ----------
    table_collection
    nodes

    Returns
    -------

    """
    mseries = table_collection["mobility demand series"]
    mtable = table_collection["mobility"]
    for region in mseries.columns.get_level_values(0).unique():
        for fuel in mseries[region].columns:
            source = mtable.loc[(region, fuel), "source"]
            source_region = mtable.loc[(region, fuel), "source region"]
            if mseries[region, fuel].sum() > 0:
                fuel_transformer = Label("process", "fuel", fuel, region)
                fuel_demand = Label("demand", "mobility", fuel, region)
                bus_label = Label("bus", "mobility", fuel, region)
                if fuel != "electricity":
                    com_bus_label = Label(
                        "bus", "commodity", source, source_region
                    )
                else:
                    com_bus_label = Label(
                        "bus", "electricity", "all", source_region
                    )
                if bus_label not in nodes:
                    nodes[bus_label] = solph.Bus(label=bus_label)
                if com_bus_label not in nodes:
                    nodes[com_bus_label] = solph.Bus(label=com_bus_label)
                cf = mtable.loc[(region, fuel), "efficiency"]
                nodes[fuel_transformer] = solph.Transformer(
                    label=fuel_transformer,
                    inputs={nodes[com_bus_label]: solph.Flow()},
                    outputs={nodes[bus_label]: solph.Flow()},
                    conversion_factors={nodes[bus_label]: cf},
                )
                fix_value = mseries[region, fuel]
                nodes[fuel_demand] = solph.Sink(
                    label=fuel_demand,
                    inputs={
                        nodes[bus_label]: solph.Flow(
                            nominal_value=1, fix=fix_value
                        )
                    },
                )
    return nodes
Esempio n. 13
0
    def test_linear_transformer(self):
        """Constraint test of a Transformer without Investment.
        """
        bgas = solph.Bus(label='gas')

        bel = solph.Bus(label='electricity')

        solph.Transformer(
            label='powerplantGas',
            inputs={bgas: solph.Flow()},
            outputs={bel: solph.Flow(nominal_value=10e10, variable_costs=50)},
            conversion_factors={bel: 0.58})

        self.compare_lp_files('linear_transformer.lp')
Esempio n. 14
0
    def test_linear_transformer_chp(self):
        """Constraint test of a Transformer without Investment (two outputs).
        """
        bgas = solph.Bus(label='gasBus')
        bheat = solph.Bus(label='heatBus')
        bel = solph.Bus(label='electricityBus')

        solph.Transformer(
            label='CHPpowerplantGas',
            inputs={bgas: solph.Flow(nominal_value=10e10, variable_costs=50)},
            outputs={bel: solph.Flow(), bheat: solph.Flow()},
            conversion_factors={bel: 0.4, bheat: 0.5})

        self.compare_lp_files('linear_transformer_chp.lp')
Esempio n. 15
0
def connect_electricity_buses(bus1, bus2, es):
    label = berlin_hp.Label
    nodes = deflex.scenario_tools.NodeDict()
    lines = [(bus1, bus2), (bus2, bus1)]
    for line in lines:
        line_label = label("line", "electricity", line[0], line[1])
        bus_label_in = label("bus", "electricity", "all", line[0])
        bus_label_out = label("bus", "electricity", "all", line[1])
        b_in = es.groups[str(bus_label_in)]
        b_out = es.groups[str(bus_label_out)]
        nodes[line_label] = solph.Transformer(
            label=line_label,
            inputs={b_in: solph.Flow(variable_costs=0.0000001)},
            outputs={b_out: solph.Flow()},
        )
    return nodes
Esempio n. 16
0
    def add_to_oemof_model(self, busses, model):
        """Creates an oemof Transformer component from the information given in the
        TrailerH2Delivery class, to be used in the oemof model.

        :param busses: virtual buses used in the energy system
        :type busses: dict
        :param model: current oemof model
        :type model: oemof model
        :return: oemof component
        """
        trailer = solph.Transformer(
            label=self.name,
            outputs={busses[self.bus_out]: solph.Flow(variable_costs=self.current_ac)},
            inputs={busses[self.bus_in]: solph.Flow(nominal_value=self.hydrogen_needed)})

        model.add(trailer)
        return trailer
    def add_to_oemof_model(self, busses, model):
        """Creates an oemof Transformer component from the information given in the
        BiogasConverter class, to be used in the oemof model

        :param busses: virtual buses used in the energy system
        :type busses: dict
        :param model: current oemof model
        :type model: oemof model
        :return: oemof component
        """
        biogas_converter = solph.Transformer(
            label=self.name,
            inputs={busses[self.bg_in]: solph.Flow()},
            outputs={busses[self.bg_out]: solph.Flow()},
            conversion_factors={busses[self.bg_out]: self.conv})
        model.add(biogas_converter)
        return biogas_converter
Esempio n. 18
0
    def create_oemof_model(self, busses, _):
        compressor = solph.Transformer(
            label=self.name,
            inputs={
                busses[self.bus_h2_in]:
                solph.Flow(nominal_value=self.m_flow_max *
                           self.sim_params.interval_time / 60),
                busses[self.bus_el]:
                solph.Flow()
            },
            outputs={busses[self.bus_h2_out]: solph.Flow()},
            conversion_factors={
                busses[self.bus_h2_in]: 1,
                busses[self.bus_el]: self.spec_compression_energy,
                busses[self.bus_h2_out]: 1
            })

        return compressor
    def add_to_oemof_model(self, busses, model):
        """Creates an oemof Transformer component from the information given in the
        TrailerGateCascade class, to be used in the oemof model.

        :param busses: virtual buses used in the energy system
        :type busses: dict
        :param model: current oemof model
        :type model: oemof model
        :return: oemof component
        """
        trailer_gate_cascade = solph.Transformer(
            label=self.name,
            inputs={
                busses[self.bus_in]: solph.Flow(nominal_value=self.max_input)
            },
            outputs={busses[self.bus_out]: solph.Flow()})

        model.add(trailer_gate_cascade)
        return trailer_gate_cascade
def check_oemof_installation(silent=False):
    logging.disable(logging.CRITICAL)

    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(fix=[10, 20, 30, 40, 50], nominal_value=1)},
    )
    solph.Transformer(
        label="pp_gas",
        inputs={bgas: solph.Flow()},
        outputs={bel: solph.Flow(nominal_value=10e10, variable_costs=50)},
        conversion_factors={bel: 0.58},
    )
    om = solph.Model(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"

    if not silent:
        print()
        print("*****************************")
        print("Solver installed with oemof:")
        print()
        for s, t in solver.items():
            print("{0}: {1}".format(s, t))
        print()
        print("*****************************")
        print("oemof successfully installed.")
        print("*****************************")
    def add_to_oemof_model(self, busses, model):
        """Creates an oemof Transformer component from the information given in the
        ElectricHeater class, to be used in the oemof model

        :param busses: virtual buses used in the energy system
        :type busses: dict
        :param model: current oemof model
        :type model: oemof model
        :return: oemof component
        """
        electric_heater = solph.Transformer(
            label=self.name,
            inputs={busses[self.bus_el]: solph.Flow()},
            outputs={
                busses[self.bus_th]: solph.Flow(nominal_value=self.power_max)
            },
            conversion_factors={busses[self.bus_th]: self.efficiency})

        model.add(electric_heater)
        return electric_heater
def run_model(params, wind_invest=False, pv_invest=False, storage_invest=False):
    logging.info('Initialize the energy system')
    energysystem = solph.EnergySystem(timeindex=date_time_index)
    Node.registry = energysystem
    logging.info('Create oemof objects')
    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(nominal_value=params['rgas_nom_val'],
                                                         summed_max=1)})

    solph.Source(label='wind', outputs={bel: solph.Flow(
            actual_value=data['wind'], nominal_value=params['wind_nom_val'], fixed=True)})

    solph.Source(label='pv', outputs={bel: solph.Flow(
           actual_value=data['pv'], nominal_value=params['pv_nom_val'], fixed=True)})

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

    solph.Transformer(
        label="pp_gas",
        inputs={bgas: solph.Flow()},
        outputs={bel: solph.Flow(nominal_value=10e10, variable_costs=50)},
        conversion_factors={bel: 0.58})


    logging.info('Optimise the energy system')

    om = solph.Model(energysystem)

    logging.info('Solve the optimization problem')
    om.solve(solver='cbc')

    energysystem.results['main'] = processing.convert_keys_to_strings(processing.results(om))
    energysystem.results['param'] = processing.convert_keys_to_strings(processing.param_results(energysystem))


    return energysystem, om
Esempio n. 23
0
    def add_to_oemof_model(self, busses, model):
        """Creates an oemof Transformer component from information given in
        the Gate class, to be used in the oemof model

        :param busses: virtual buses used in the energy system
        :type busses: dict
        :param model: current oemof model
        :type model: oemof model
        :return: oemof component
        """
        gate = solph.Transformer(
            label=self.name,
            inputs={
                busses[self.bus_in]:
                solph.Flow(variable_costs=self.artificial_costs,
                           nominal_value=self.max_input)
            },
            outputs={busses[self.bus_out]: solph.Flow()},
            conversion_factors={busses[self.bus_out]: self.efficiency})

        model.add(gate)
        return gate
    def add_to_oemof_model(self, busses, model):
        """Creates an oemof Transformer component from information given in
        the AirSourceHeatPump class, to be used in the oemof model

        :param busses: virtual buses used in the energy system
        :type busses: dict
        :param model: current oemof model
        :type model: oemof model
        :return: oemof component
        """
        air_source_heat_pump = solph.Transformer(
            label=self.name,
            inputs={busses[self.bus_el]: solph.Flow(variable_costs=0)},
            outputs={
                busses[self.bus_th]:
                solph.Flow(nominal_value=self.power_max, variable_costs=0)
            },
            conversion_factors={
                busses[self.bus_th]: self.cops[self.sim_params.i_interval]
            })

        model.add(air_source_heat_pump)
        return air_source_heat_pump
Esempio n. 25
0
    def add_to_oemof_model(self, busses, model):
        """Creates an oemof Transformer component using the information given in
        the BiogasSteamReformer class, to be used in the oemof model

        :param busses: buses used in the energy system
        :type busses: dict
        :param model: current oemof model
        :type model: oemof model
        :return: oemof component
        """
        biogas_smr_psa = solph.Transformer(
            label=self.name,
            inputs={
                busses[self.bus_bg]: solph.Flow(variable_costs=0),
                busses[self.bus_el]: solph.Flow(variable_costs=0)
            },
            outputs={busses[self.bus_h2]: solph.Flow()},
            conversion_factors={
                busses[self.bus_h2]: self.smr_psa_eff,
                busses[self.bus_el]: self.energy_cnsmp_1kg_bg
            })
        model.add(biogas_smr_psa)
        return biogas_smr_psa
Esempio n. 26
0
                                 nominal_value=600000)
                  })

# create simple sink object representing the electrical demand
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
pp_gas = solph.Transformer(
    label="pp_gas",
    inputs={bgas: solph.Flow()},
    outputs={bel: solph.Flow(nominal_value=10e10, variable_costs=0)},
    conversion_factors={bel: 0.58})

# create storage object representing a battery
storage = solph.components.GenericStorage(
    label='storage',
    inputs={bel: solph.Flow(variable_costs=0.0001)},
    outputs={bel: solph.Flow()},
    loss_rate=0.00,
    initial_storage_level=0,
    invest_relation_input_capacity=1 / 6,
    invest_relation_output_capacity=1 / 6,
    inflow_conversion_factor=1,
    outflow_conversion_factor=0.8,
    investment=solph.Investment(ep_costs=epc_storage),
                                  param_value['eta_solar_th'] *
                                  0.000001),  # [MWh/m²]
                    nominal_value=param_value['area_solar_th'] * 10000,  # [m²]
                    fixed=True)
            }))

# Combined heat and power plant
if param_value['number_of_chps'] > 0:
    energysystem.add(
        solph.Transformer(
            label='chp',
            inputs={bgas: solph.Flow()},
            outputs={
                bth:
                solph.Flow(nominal_value=param_value['number_of_chps'] *
                           param_value['chp_heat_output']),  # [MW]
                bel:
                solph.Flow()
            },
            conversion_factors={
                bth: param_value['conversion_factor_bth_chp'],
                bel: param_value['conversion_factor_bel_chp']
            }))

# Boiler
if param_value['number_of_boilers'] > 0:
    energysystem.add(
        solph.Transformer(
            label='boiler',
            inputs={bgas: solph.Flow()},
            outputs={
                bth:
Esempio n. 28
0
                              outputs={
                                bel: solph.Flow(nominal_value=100,
                                                variable_costs=10,
                                                emission_factor=0.01,
                                                actual_value=[0.1, 0.2, 0.3],
                                                fixed=True)}))

energysystem.add(solph.Source(label='gas-source',
                              outputs={
                                bel: solph.Flow(variable_costs=10,
                                                emission_factor=0.2)}))

energysystem.add(solph.Transformer(
    label="pp_gas",
    inputs={
        bgas: solph.Flow()},
    outputs={
        bel: solph.Flow(nominal_value=200)},
    conversion_factors={
        bel: 0.58}))


model = solph.Model(energysystem)

# add the emission constraint
constraints.emission_limit(model, limit=100)

model.total_emissions.pprint()

model.solve()

print(model.total_emissions())
temp_threshold_icing = 2

# Pre-Calculate COPs
cops_ASHP = cmpr_hp_chiller.calc_cops(
    temp_high=[40],
    temp_low=data['ambient_temperature'],
    quality_grade=0.4,
    mode='heat_pump',
    consider_icing=True,
    temp_threshold_icing=temp_threshold_icing,
    factor_icing=0.8)

# Air-Source Heat Pump
energysystem.add(solph.Transformer(
    label="ASHP",
    inputs={b_el: solph.Flow()},
    outputs={b_heat: solph.Flow(nominal_value=25, variable_costs=5)},
    conversion_factors={b_heat: cops_ASHP}))

model = solph.Model(energysystem)

model.solve(solver=solver, solve_kwargs={'tee': solver_verbose})

energysystem.results['main'] = outputlib.processing.results(model)
energysystem.results['meta'] = outputlib.processing.meta_results(model)

energysystem.dump(dpath=None, filename=None)

# ****************************************************************************
# ********** PART 2 - Processing the results *********************************
# ****************************************************************************
Esempio n. 30
0
def run_model_thermal(config_path, var_number):

    with open(config_path, 'r') as ymlfile:
        cfg = yaml.load(ymlfile)

    if cfg['debug']:
        number_of_time_steps = 3
    else:
        number_of_time_steps = cfg['number_timesteps']

    solver = cfg['solver']
    debug = cfg['debug']
    solver_verbose = cfg['solver_verbose']  # show/hide solver output

    ### Read data and parameters ###

    # define the used directories
    abs_path = os.path.dirname(os.path.abspath(os.path.join(__file__, '..')))
    results_path = abs_path + '/results'
    data_ts_path = abs_path + '/data/data_confidential/'
    data_param_path = abs_path + '/data/data_public/'

    # Read parameter values from parameter file
    filename_param = data_param_path + cfg['parameters_file_name'][var_number]
    param_df = pd.read_csv(filename_param, index_col=1, sep=';')  # uses second column of csv-file for indexing
    param_value = param_df['value']

    # Import  PV and demand data
    data = pd.read_csv((data_ts_path + cfg['time_series_file_name']), sep=';')

    # redefine ep_costs_function:
    def ep_costs_f(capex, n, opex):
        return ep_costs_func(capex, n, opex, param_value['wacc'])

    # initiate the logger
    logger.define_logging(logfile='Oman_thermal_{0}_{1}.log'.format(cfg['exp_number'], var_number),
                          logpath=results_path + '/logs',
                          screen_level=logging.INFO,
                          file_level=logging.DEBUG)

    date_time_index = pd.date_range('1/1/2017', periods=(2 if debug is True else number_of_time_steps), freq='H')

    # Initialise the energysystem
    logging.info('Initialize the energy system')

    energysystem = solph.EnergySystem(timeindex=date_time_index)

    #######################
    # Build up the system #
    #######################

    # Busses

    bth = solph.Bus(label='thermal')
    bco = solph.Bus(label="cool")
    bwh = solph.Bus(label="waste")
    bel = solph.Bus(label="electricity")
    bga = solph.Bus(label="gas")
    bam = solph.Bus(label="ambient")

    energysystem.add(bth, bco, bwh, bel, bga, bam)

    # Sinks and sources

    ambience = solph.Sink(label='ambience', inputs={bam: solph.Flow()})

    grid_ga = solph.Source(label='naturalgas', outputs={bga: solph.Flow(variable_costs=param_value['price_gas'])})

    grid_el = solph.Source(label='grid_el', outputs={bel: solph.Flow(variable_costs=param_value['price_electr'])})

    collector = solph.Source(label='collector', outputs={bth: solph.Flow(
        fixed=True, actual_value=data['solar gain kWprom2'],
        investment=solph.Investment(ep_costs=ep_costs_f(param_value['invest_costs_collect_output_th'],
                                                        param_value['lifetime_collector'],
                                                        param_value['opex_collector'])))})        # Has to be developed

    pv = solph.Source(label='pv', outputs={bel: solph.Flow(
        fixed=True, actual_value=data['solar gain relativ'],
        investment=solph.Investment(ep_costs=ep_costs_f(param_value['invest_costs_pv_output_th'],
                                                        param_value['lifetime_pv'],
                                                        param_value['opex_pv'])))})  # Einheit: 0,7616 kWpeak

    demand = solph.Sink(label='demand', inputs={bco: solph.Flow(
        fixed=True, actual_value=data['Cooling load kW'], nominal_value=1)})

    excess = solph.Sink(label='excess_thermal', inputs={bth: solph.Flow()})

    excess_el = solph.Sink(label='excess_el', inputs={bel: solph.Flow()})

    energysystem.add(ambience, grid_ga, grid_el, collector, pv, demand, excess, excess_el)

    # Transformers

    if param_value['nominal_value_boiler_output_thermal'] == 0:
        boil = solph.Transformer(
            label='boiler',
            inputs={bga: solph.Flow()},
            outputs={bth: solph.Flow(investment=solph.Investment(
                ep_costs=ep_costs_f(param_value['invest_costs_boiler_output_th'], param_value['lifetime_boiler'],
                                    param_value['opex_boiler'])))},
            conversion_factors={bth: param_value['conv_factor_boiler_output_thermal']})
    else:
        boil = solph.Transformer(
            label='boiler',
            inputs={bga: solph.Flow()},
            outputs={bth: solph.Flow(nominal_value=param_value['nominal_value_boiler_output_thermal'])},
            conversion_factors={bth: param_value['conv_factor_boiler_output_thermal']})

    chil = solph.Transformer(
        label='absorption_chiller',
        inputs={bth: solph.Flow()},
        outputs={bco: solph.Flow(investment=solph.Investment(
                    ep_costs=ep_costs_f(param_value['invest_costs_absorption_output_cool'],
                                        param_value['lifetime_absorption'], param_value['opex_absorption']))),
                 bwh: solph.Flow()},
        conversion_factors={bco: param_value['conv_factor_absorption_output_cool'],
                            bwh: param_value['conv_factor_absorption_output_waste']})

    aqui = solph.Transformer(
        label='aquifer',
        inputs={bwh: solph.Flow(investment=solph.Investment(
                    ep_costs=ep_costs_f(param_value['invest_costs_aqui_input_th'], param_value['lifetime_aqui'],
                                        param_value['opex_aqui']))),
                bel: solph.Flow()},
        outputs={bam: solph.Flow()},
        conversion_factors={bwh: param_value['conv_factor_aquifer_input_waste'],
                            bel: param_value['conv_factor_aquifer_input_el']})

    towe = solph.Transformer(
        label='cooling_tower',
        inputs={bwh: solph.Flow(investment=solph.Investment(
                    ep_costs=ep_costs_f(param_value['invest_costs_tower_input_th'], param_value['lifetime_tower'],
                                        param_value['opex_tower']))),
                bel: solph.Flow()},
        outputs={bam: solph.Flow()},
        conversion_factors={bwh: param_value['conv_factor_tower_input_waste'],
                            bel: param_value['conv_factor_tower_input_el']})

    energysystem.add(chil, boil, aqui, towe)

    # storages

    if param_value['nominal_capacitiy_stor_cool'] == 0:
        stor_co = solph.components.GenericStorage(
            label='storage_cool',
            inputs={bco: solph.Flow()},
            outputs={bco: solph.Flow()},
            capacity_loss=param_value['capac_loss_stor_cool'],
            # invest_relation_input_capacity=1 / 6,
            # invest_relation_output_capacity=1 / 6,
            inflow_conversion_factor=param_value['conv_factor_stor_cool_input'],
            outflow_conversion_factor=param_value['conv_factor_stor_cool_output'],
            investment=solph.Investment(
                ep_costs=ep_costs_f(param_value['invest_costs_stor_cool_capacity'], param_value['lifetime_stor_cool'],
                                    param_value['opex_stor_cool'])))
    else:
        stor_co = solph.components.GenericStorage(
            label='storage_cool',
            inputs={bco: solph.Flow()},
            outputs={bco: solph.Flow()},
            capacity_loss=param_value['capac_loss_stor_cool'],
            # invest_relation_input_capacity=1 / 6,
            # invest_relation_output_capacity=1 / 6,
            inflow_conversion_factor=param_value['conv_factor_stor_cool_input'],
            outflow_conversion_factor=param_value['conv_factor_stor_cool_output'],
            nominal_capacity=param_value['nominal_capacitiy_stor_cool'])

    if param_value['nominal_capacitiy_stor_thermal'] == 0:
        stor_th = solph.components.GenericStorage(
            label='storage_thermal',
            inputs={bth: solph.Flow()},
            outputs={bth: solph.Flow()},
            capacity_loss=param_value['capac_loss_stor_thermal'],
            # invest_relation_input_capacity=1 / 6,
            # invest_relation_output_capacity=1 / 6,
            inflow_conversion_factor=param_value['conv_factor_stor_thermal_input'],
            outflow_conversion_factor=param_value['conv_factor_stor_thermal_output'],
            investment=solph.Investment(
                ep_costs=ep_costs_f(param_value['invest_costs_stor_thermal_capacity'],
                                    param_value['lifetime_stor_thermal'], param_value['opex_stor_thermal'])))
    else:
        stor_th = solph.components.GenericStorage(
            label='storage_thermal',
            inputs={bth: solph.Flow()},
            outputs={bth: solph.Flow()},
            capacity_loss=param_value['capac_loss_stor_thermal'],
            # invest_relation_input_capacity=1 / 6,
            # invest_relation_output_capacity=1 / 6,
            inflow_conversion_factor=param_value['conv_factor_stor_thermal_input'],
            outflow_conversion_factor=param_value['conv_factor_stor_thermal_output'],
            nominal_capacity=param_value['nominal_capacitiy_stor_thermal'])

    if param_value['nominal_capacitiy_stor_el'] == 0:
        stor_el = solph.components.GenericStorage(
            label='storage_electricity',
            inputs={bel: solph.Flow()},
            outputs={bel: solph.Flow()},
            capacity_loss=param_value['capac_loss_stor_el'],
            # invest_relation_input_capacity=1 / 6,
            # invest_relation_output_capacity=1 / 6,
            inflow_conversion_factor=param_value['conv_factor_stor_el_input'],
            outflow_conversion_factor=param_value['conv_factor_stor_el_output'],
            investment=solph.Investment(
                ep_costs=ep_costs_f(param_value['invest_costs_stor_el_capacity'], param_value['lifetime_stor_el'],
                                    param_value['opex_stor_el'])))

    else:
        stor_el = solph.components.GenericStorage(
            label='storage_electricity',
            inputs={bel: solph.Flow()},
            outputs={bel: solph.Flow()},
            capacity_loss=param_value['capac_loss_stor_el'],
            # invest_relation_input_capacity=1 / 6,
            # invest_relation_output_capacity=1 / 6,
            inflow_conversion_factor=param_value['conv_factor_stor_el_input'],
            outflow_conversion_factor=param_value['conv_factor_stor_el_output'],
            nominal_capacity=param_value['nominal_capacitiy_stor_el'])

    energysystem.add(stor_co, stor_th, stor_el)

    ########################################
    # Create a model and solve the problem #
    ########################################

    # Initialise the operational model (create the problem) with constrains
    model = solph.Model(energysystem)

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

    if cfg['debug']:
        filename = results_path + '/lp_files/' + 'Oman_thermal_{0}_{1}.lp'.format(cfg['exp_number'], var_number)
        logging.info('Store lp-file in {0}.'.format(filename))
        model.write(filename, io_options={'symbolic_solver_labels': True})

    logging.info('Store the energy system with the results.')

    energysystem.results['main'] = outputlib.processing.results(model)
    energysystem.results['meta'] = outputlib.processing.meta_results(model)
    energysystem.results['param'] = outputlib.processing.parameter_as_dict(model)

    energysystem.dump(dpath=(results_path + '/dumps'),
                      filename='oman_thermal_{0}_{1}.oemof'.format(cfg['exp_number'], var_number))