Ejemplo n.º 1
0
def compute(es=None, **arguments):
    """Creates the optimization model, solves it and writes back results to
    energy system object

    Parameters
    ----------
    es : :class:`oemof.solph.network.EnergySystem` object
        Energy system holding nodes, grouping functions and other important
        information.
    **arguments : key word arguments
        Arguments passed from command line
    """

    if es.temporal is not None:
        m = Model(es, objective_weighting=es.temporal['weighting'])
    else:
        m = Model(es)

    logging.info('Model creation time: ' + stopwatch())

    m.receive_duals()

    if arguments['--debug']:
        filename = 'renpass_model.lp'
        logging.info('Writing lp-file to {}.'.format(filename))
        m.write(filename, io_options={'symbolic_solver_labels': True})

    m.solve(solver=arguments['--solver'], solve_kwargs={'tee': True})

    logging.info('Optimization time: ' + stopwatch())

    return m
Ejemplo n.º 2
0
def optimize(input_data_dir, results_data_dir, solver='cbc', debug=False):
    r"""
    Takes the specified datapackage, creates an energysystem and solves the
    optimization problem.
    """
    # create energy system object
    logging.info("Creating EnergySystem from datapackage")
    es = EnergySystem.from_datapackage(
        os.path.join(input_data_dir, "datapackage.json"),
        attributemap={},
        typemap=TYPEMAP,
    )

    # create model from energy system (this is just oemof.solph)
    logging.info("Creating the optimization model")
    m = Model(es)

    # if you want dual variables / shadow prices uncomment line below
    # m.receive_duals()

    # save lp file together with optimization results
    if debug:
        lp_file_dir = os.path.join(results_data_dir, 'model.lp')
        logging.info(f"Saving the lp-file to {lp_file_dir}")
        m.write(lp_file_dir, io_options={'symbolic_solver_labels': True})

    # select solver 'gurobi', 'cplex', 'glpk' etc
    logging.info(f'Solving the problem using {solver}')
    m.solve(solver=solver)

    # get the results from the the solved model(still oemof.solph)
    es.results = m.results()
    es.params = outputlib.processing.parameter_as_dict(es)

    # now we use the write results method to write the results in oemof-tabular
    # format
    logging.info(f'Writing the results to {results_data_dir}')
    es.dump(results_data_dir)
Ejemplo n.º 3
0
pwltf = solph.custom.PiecewiseLinearTransformer(
    label='pwltf',
    inputs={b_gas: solph.Flow(nominal_value=100, variable_costs=1)},
    outputs={b_el: solph.Flow()},
    in_breakpoints=in_breakpoints,
    conversion_function=conv_func,
    pw_repn='CC')  # 'CC', 'DCC', 'INC', 'MC'

# DCC TODO: Solve problem in outputlib with DCC

energysystem.add(pwltf)

# create and solve the optimization model
optimization_model = Model(energysystem)
optimization_model.write('/home/jann/Desktop/my_model.lp',
                         io_options={'symbolic_solver_labels': True})
optimization_model.solve(solver=solver,
                         solve_kwargs={
                             'tee': False,
                             'keepfiles': False
                         })

results = outputlib.processing.results(optimization_model)
string_results = outputlib.processing.convert_keys_to_strings(results)
df = outputlib.processing.create_dataframe(optimization_model)
sequences = {k: v['sequences'] for k, v in string_results.items()}
df = pd.concat(sequences, axis=1)
df[('efficiency', None, None)] = df[('pwltf', 'electricity',
                                     'flow')].divide(df[('gas', 'pwltf',
                                                         'flow')])
Ejemplo n.º 4
0
ext = fc.ExtractionTurbine(label='ext',
                           carrier=gas,
                           tech='ext',
                           commitable=False,
                           electricity_bus=el1,
                           heat_bus=heat,
                           capacity=10,
                           thermal_efficiency=0.4,
                           electric_efficiency=0.4,
                           condensing_efficiency=0.5)

conv = fc.Conversion('conv',
                     from_bus=el2,
                     to_bus=heat,
                     efficiency=0.95,
                     capacity=2)

load = fc.Load('load', bus=el1, amount=1000, profile=[0.005, 0.00034, 0.0434])

# Connection
conn = fc.Connection('conn', from_bus=el1, to_bus=el2, loss=0.07, capacity=100)

es.add(el1, el2, heat, biomass, bp, st, wind, sto, conv, load, conn, gas, ext)

m = Model(es)

m.pprint()

m.write('model.lp', io_options={'symbolic_solver_labels': True})
Ejemplo n.º 5
0
es = EnergySystem()

el0 = elec.ElectricalBus('el0')
el1 = elec.ElectricalBus('el1')
el2 = elec.ElectricalBus('el2')

line0 = elec.Line(from_bus=el0, to_bus=el1, capacity=60, reactance=0.0001)
line1 = elec.Line(from_bus=el1, to_bus=el2, capacity=60, reactance=0.0001)
line2 = elec.Line(from_bus=el2, to_bus=el0, capacity=60, reactance=0.0001)

gen0 = fc.Dispatchable("gen0",
                       capacity=100,
                       bus=el0,
                       marginal_cost=50,
                       carrier='coal')
gen1 = fc.Dispatchable("gen1",
                       capacity=100,
                       bus=el1,
                       marginal_cost=25,
                       carrier='gas')

load0 = fc.Load("load0", bus=el2, amount=100, profile=[1])

es.add(el0, el1, el2, line0, line1, line2, gen0, gen1, load0)

m = Model(es)

m.solve()

m.write('lopf-model.lp')
    nominal_storage_capacity=nominal_storage_capacity,
    min_storage_level=input_data['min_storage_level'],
    max_storage_level=input_data['max_storage_level'],
    loss_rate=loss_rate,
    fixed_losses_relative=fixed_losses_relative,
    fixed_losses_absolute=fixed_losses_absolute,
    inflow_conversion_factor=1.0,
    outflow_conversion_factor=1.0,
)

energysystem.add(bus_heat, heat_source, shortage, excess, heat_demand,
                 thermal_storage)

# create and solve the optimization model
optimization_model = Model(energysystem)
optimization_model.write('storage_model.lp',
                         io_options={'symbolic_solver_labels': True})
optimization_model.solve(solver=solver,
                         solve_kwargs={
                             'tee': False,
                             'keepfiles': False
                         })
# get results
results = outputlib.processing.results(optimization_model)
string_results = outputlib.processing.convert_keys_to_strings(results)
sequences = {k: v['sequences'] for k, v in string_results.items()}
df = pd.concat(sequences, axis=1)

# plot results
fig, (ax1, ax2) = plt.subplots(2, 1)

df[[('shortage', 'bus_heat', 'flow'), ('heat_source', 'bus_heat', 'flow'),
Ejemplo n.º 7
0
    fname = os.path.join('data', 'sequences', f)
    df = pd.read_csv(fname, sep=';')
    df = df.iloc[:timesteps]
    df.to_csv(fname, index=False, sep=';')

config = building.read_build_config('config.toml')

es = EnergySystem.from_datapackage(
    "datapackage.json",
    attributemap={},
    typemap=facades.TYPEMAP,
)

m = Model(es)

m.write('tmp.lp', io_options={"symbolic_solver_labels": True})

m.receive_duals()

m.solve('gurobi')

m.results = m.results()

if os.path.exists('results'):
    shutil.rmtree('results')
os.mkdir('results')

pp.write_results(m, 'results', scalars=False)

# create short summary
supply_sum = (pp.supply_results(
Ejemplo n.º 8
0
es.add(
    fc.Excess(label="excess_heat_SDE",
              bus=heat_bus_SDE,
              tech="grid",
              carrier="heat",
              marginal_cost=costs.at["vom", "excess_heat"]))

print("Demand data have been read.")

# OEMoF Model Creation
m = Model(es)

print("OSeEM-DE is ready to solve.")

# LP File
m.write(os.path.join(results_path, "investment.lp"),
        io_options={"symbolic_solver_labels": True})

# Shadow Price
m.receive_duals()

# Solve
m.solve("cbc")
m.results = m.results()

print("OSeEM-DE solved the optimization problem. :)")

# Results
pp.write_results(m, results_path)

print("Results have been written. Results are available in {}.".format(
    results_path))
Ejemplo n.º 9
0
    label='powerplant_2',
    outputs={
        el_bus: Flow(
            nominal_value=12.5,
            variable_costs=10
        )
    }
)

es.add(el_bus, demand, pp1, pp2)

om = Model(es)

lp_file_dir = 'dispatch.lp'

om.write(lp_file_dir, io_options={'symbolic_solver_labels': True})

om.solve()

results = om.results()

string_results = outputlib.processing.convert_keys_to_strings(results)

string_results = outputlib.processing.convert_keys_to_strings(results)

# collect all timeseries in a DataFrame
sequences = {k: v['sequences'] for k, v in string_results.items()}
sequences = pd.concat(sequences, axis=1)

print(sequences)
Ejemplo n.º 10
0
class Scenario:
    """
    Definition of a deflex scenario object.
    """
    def __init__(self, **kwargs):
        """

        Parameters
        ----------
        kwargs
        """
        self.name = kwargs.get("name", "unnamed_scenario")
        self.table_collection = kwargs.get("table_collection", {})
        self.year = kwargs.get("year", None)
        self.ignore_errors = kwargs.get("ignore_errors", False)
        self.round_values = kwargs.get("round_values", 0)
        self.model = kwargs.get("model", None)
        self.es = kwargs.get("es", None)
        self.results = None
        self.results_fn = kwargs.get("results_fn", None)
        self.debug = kwargs.get("debug", None)
        self.location = None
        self.map = None
        self.meta = kwargs.get("meta", None)

    def initialise_energy_system(self):
        if self.debug is True:
            number_of_time_steps = 3
        else:
            try:
                if calendar.isleap(self.year):
                    number_of_time_steps = 8784
                else:
                    number_of_time_steps = 8760
            except TypeError:
                msg = ("You cannot create an EnergySystem with self.year={0}, "
                       "of type {1}.")
                raise TypeError(msg.format(self.year, type(self.year)))

        date_time_index = pd.date_range("1/1/{0}".format(self.year),
                                        periods=number_of_time_steps,
                                        freq="H")
        return EnergySystem(timeindex=date_time_index)

    def load_excel(self, filename=None):
        """Load scenario from an excel-file."""
        if filename is not None:
            self.location = filename
        xls = pd.ExcelFile(self.location)
        for sheet in xls.sheet_names:
            self.table_collection[sheet] = xls.parse(sheet,
                                                     index_col=[0],
                                                     header=[0, 1])
        return self

    def load_csv(self, path=None):
        """Load scenario from a csv-collection."""
        if path is not None:
            self.location = path
        for file in os.listdir(self.location):
            if file[-4:] == ".csv":
                filename = os.path.join(self.location, file)
                self.table_collection[file[:-4]] = pd.read_csv(filename,
                                                               index_col=[0],
                                                               header=[0, 1])
        return self

    def to_excel(self, filename):
        """Dump scenario into an excel-file."""
        # create path if it does not exist
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        writer = pd.ExcelWriter(filename)
        for name, df in sorted(self.table_collection.items()):
            df.to_excel(writer, name)
        writer.save()
        logging.info("Scenario saved as excel file to {0}".format(filename))

    def to_csv(self, path):
        """Dump scenario into a csv-collection."""
        if os.path.isdir(path):
            shutil.rmtree(os.path.join(path))
        os.makedirs(path)

        for name, df in self.table_collection.items():
            name = name.replace(" ", "_") + ".csv"
            filename = os.path.join(path, name)
            df.to_csv(filename)
        logging.info("Scenario saved as csv-collection to {0}".format(path))

    def check_table(self, table_name):
        if self.table_collection[table_name].isnull().values.any():
            c = []
            for column in self.table_collection[table_name].columns:
                if self.table_collection[table_name][column].isnull().any():
                    c.append(column)
            msg = "Nan Values in the {0} table (columns: {1})."
            raise ValueError(msg.format(table_name, c))
        return self

    def create_nodes(self):
        pass

    def initialise_es(self, year=None):
        if year is not None:
            self.year = year
        self.es = self.initialise_energy_system()
        return self

    def add_nodes(self, nodes):
        """

        Parameters
        ----------
        nodes : dict
            Dictionary with a unique key and values of type oemof.network.Node.

        Returns
        -------
        self

        """
        if self.es is None:
            self.initialise_es()
        self.es.add(*nodes.values())
        return self

    def table2es(self):
        if self.es is None:
            self.es = self.initialise_energy_system()
        nodes = self.create_nodes()
        self.es.add(*nodes.values())
        return self

    def create_model(self):
        self.model = Model(self.es)
        return self

    def dump_es(self, filename):
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        f = open(filename, "wb")
        if self.meta is None:
            if self.es.results is not None and "Meta" in self.es.results:
                self.meta = self.es.results["meta"]
        pickle.dump(self.meta, f)
        pickle.dump(self.es.__dict__, f)
        f.close()
        logging.info("Results dumped to {0}.".format(filename))

    def restore_es(self, filename=None):
        if filename is None:
            filename = self.results_fn
        else:
            self.results_fn = filename
        if self.es is None:
            self.es = EnergySystem()
        f = open(filename, "rb")
        self.meta = pickle.load(f)
        self.es.__dict__ = pickle.load(f)
        f.close()
        self.results = self.es.results["main"]
        logging.info("Results restored from {0}.".format(filename))

    def scenario_info(self, solver_name):
        sc_info = {
            "name": self.name,
            "datetime": datetime.datetime.now(),
            "year": self.year,
            "solver": solver_name,
        }
        return sc_info

    def solve(self, with_duals=False, tee=True, logfile=None, solver=None):
        logging.info("Optimising using {0}.".format(solver))

        if with_duals:
            self.model.receive_duals()

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

        self.model.solve(solver=solver,
                         solve_kwargs={
                             "tee": tee,
                             "logfile": logfile
                         })
        self.es.results["main"] = processing.results(self.model)
        self.es.results["meta"] = processing.meta_results(self.model)
        self.es.results["param"] = processing.parameter_as_dict(self.es)
        self.es.results["meta"]["scenario"] = self.scenario_info(solver)
        self.es.results["meta"]["in_location"] = self.location
        self.es.results["meta"]["file_date"] = datetime.datetime.fromtimestamp(
            os.path.getmtime(self.location))
        self.es.results["meta"]["oemof_version"] = logger.get_version()
        self.results = self.es.results["main"]

    def plot_nodes(self, show=None, filename=None, **kwargs):

        rm_nodes = kwargs.get("remove_nodes_with_substrings")

        g = graph.create_nx_graph(self.es,
                                  filename=filename,
                                  remove_nodes_with_substrings=rm_nodes)
        if show is True:
            draw_graph(g, **kwargs)
        return g