-
Notifications
You must be signed in to change notification settings - Fork 124
/
_flow.py
601 lines (513 loc) · 22.4 KB
/
_flow.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# -*- coding: utf-8 -*-
"""
solph version of oemof.network.Edge including base constraints
SPDX-FileCopyrightText: Uwe Krien <krien@uni-bremen.de>
SPDX-FileCopyrightText: Simon Hilpert
SPDX-FileCopyrightText: Cord Kaldemeyer
SPDX-FileCopyrightText: Stephan Günther
SPDX-FileCopyrightText: Birgit Schachler
SPDX-FileCopyrightText: jnnr
SPDX-FileCopyrightText: jmloenneberga
SPDX-License-Identifier: MIT
"""
from warnings import warn
from oemof.network import network as on
from oemof.tools import debugging
from pyomo.core import BuildAction
from pyomo.core import Constraint
from pyomo.core import NonNegativeIntegers
from pyomo.core import Set
from pyomo.core import Var
from pyomo.core import Expression
from pyomo.core import quicksum
from pyomo.core.base.block import SimpleBlock
from oemof.solph._plumbing import sequence
class Flow(on.Edge):
r"""Defines a flow between two nodes.
Keyword arguments are used to set the attributes of this flow. Parameters
which are handled specially are noted below.
For the case where a parameter can be either a scalar or an iterable, a
scalar value will be converted to a sequence containing the scalar value at
every index. This sequence is then stored under the paramter's key.
Parameters
----------
nominal_value : numeric, :math:`P_{nom}`
The nominal value of the flow. If this value is set the corresponding
optimization variable of the flow object will be bounded by this value
multiplied with min(lower bound)/max(upper bound).
max : numeric (iterable or scalar), :math:`f_{max}`
Normed maximum value of the flow. The flow absolute maximum will be
calculated by multiplying :attr:`nominal_value` with :attr:`max`
min : numeric (iterable or scalar), :math:`f_{min}`
Normed minimum value of the flow (see :attr:`max`).
fix : numeric (iterable or scalar), :math:`f_{actual}`
Normed fixed value for the flow variable. Will be multiplied with the
:attr:`nominal_value` to get the absolute value. If :attr:`fixed` is
set to :obj:`True` the flow variable will be fixed to `fix
* nominal_value`, i.e. this value is set exogenous.
positive_gradient : :obj:`dict`, default: `{'ub': None, 'costs': 0}`
A dictionary containing the following two keys:
* `'ub'`: numeric (iterable, scalar or None), the normed *upper
bound* on the positive difference (`flow[t-1] < flow[t]`) of
two consecutive flow values.
* `'costs``: numeric (scalar or None), the gradient cost per
unit.
negative_gradient : :obj:`dict`, default: `{'ub': None, 'costs': 0}`
A dictionary containing the following two keys:
* `'ub'`: numeric (iterable, scalar or None), the normed *upper
bound* on the negative difference (`flow[t-1] > flow[t]`) of
two consecutive flow values.
* `'costs``: numeric (scalar or None), the gradient cost per
unit.
summed_max : numeric, :math:`f_{sum,max}`
Specific maximum value summed over all timesteps. Will be multiplied
with the nominal_value to get the absolute limit.
summed_min : numeric, :math:`f_{sum,min}`
see above
variable_costs : numeric (iterable or scalar)
The costs associated with one unit of the flow. If this is set the
costs will be added to the objective expression of the optimization
problem.
fixed : boolean
Boolean value indicating if a flow is fixed during the optimization
problem to its ex-ante set value. Used in combination with the
:attr:`fix`.
investment : :class:`Investment <oemof.solph.options.Investment>`
Object indicating if a nominal_value of the flow is determined by
the optimization problem. Note: This will refer all attributes to an
investment variable instead of to the nominal_value. The nominal_value
should not be set (or set to None) if an investment object is used.
nonconvex : :class:`NonConvex <oemof.solph.options.NonConvex>`
If a nonconvex flow object is added here, the flow constraints will
be altered significantly as the mathematical model for the flow
will be different, i.e. constraint etc. from
:class:`NonConvexFlowBlock <oemof.solph.blocks.NonConvexFlowBlock>`
will be used instead of
:class:`FlowBlock <oemof.solph.blocks.FlowBlock>`.
Note: at the moment this does not work if the investment attribute is
set .
Notes
-----
The following sets, variables, constraints and objective parts are created
* :py:class:`~oemof.solph..flows.flow.FlowBlock`
* :py:class:`~oemof.solph..flows.investment_flow.InvestmentFlowBlock`
(additionally if Investment object is present)
* :py:class:`~oemof.solph..flows.non_convex_flow.NonConvexFlowBlock`
(If nonconvex object is present, CAUTION: replaces
:py:class:`~oemof.solph.flows.flow.FlowBlock`
class and a MILP will be build)
Examples
--------
Creating a fixed flow object:
>>> f = Flow(fix=[10, 4, 4], variable_costs=5)
>>> f.variable_costs[2]
5
>>> f.fix[2]
4
Creating a flow object with time-depended lower and upper bounds:
>>> f1 = Flow(min=[0.2, 0.3], max=0.99, nominal_value=100)
>>> f1.max[1]
0.99
"""
def __init__(self, **kwargs):
# TODO: Check if we can inherit from pyomo.core.base.var _VarData
# then we need to create the var object with
# pyomo.core.base.IndexedVarWithDomain before any FlowBlock is created.
# E.g. create the variable in the energy system and populate with
# information afterwards when creating objects.
super().__init__()
scalars = [
"nominal_value",
"summed_max",
"summed_min",
"investment",
"nonconvex",
"integer",
]
sequences = ["fix", "variable_costs", "min", "max"]
dictionaries = ["positive_gradient", "negative_gradient"]
defaults = {
"variable_costs": 0,
"positive_gradient": {"ub": None, "costs": 0},
"negative_gradient": {"ub": None, "costs": 0},
}
keys = [k for k in kwargs if k != "label"]
if "fixed_costs" in keys:
raise AttributeError(
"The `fixed_costs` attribute has been removed" " with v0.2!"
)
if "actual_value" in keys:
raise AttributeError(
"The `actual_value` attribute has been renamed"
" to `fix` with v0.4. The attribute `fixed` is"
" set to True automatically when passing `fix`."
)
if "fixed" in keys:
msg = (
"The `fixed` attribute is deprecated.\nIf you have defined "
"the `fix` attribute the flow variable will be fixed.\n"
"The `fixed` attribute does not change anything."
)
warn(msg, debugging.SuspiciousUsageWarning)
# It is not allowed to define min or max if fix is defined.
if kwargs.get("fix") is not None and (
kwargs.get("min") is not None or kwargs.get("max") is not None
):
raise AttributeError(
"It is not allowed to define min/max if fix is defined."
)
# Set default value for min and max
if kwargs.get("min") is None:
if "bidirectional" in keys:
defaults["min"] = -1
else:
defaults["min"] = 0
if kwargs.get("max") is None:
defaults["max"] = 1
for attribute in set(scalars + sequences + dictionaries + keys):
value = kwargs.get(attribute, defaults.get(attribute))
if attribute in dictionaries:
setattr(
self,
attribute,
{"ub": sequence(value["ub"]), "costs": value["costs"]},
)
else:
setattr(
self,
attribute,
sequence(value) if attribute in sequences else value,
)
# Checking for impossible attribute combinations
if self.investment and self.nominal_value is not None:
raise ValueError(
"Using the investment object the nominal_value"
" has to be set to None."
)
if self.investment and self.nonconvex:
raise ValueError(
"Investment flows cannot be combined with "
+ "nonconvex flows!"
)
# Checking for impossible gradient combinations
if self.nonconvex:
if self.nonconvex.positive_gradient["ub"][0] is not None and (
self.positive_gradient["ub"][0] is not None
or self.negative_gradient["ub"][0] is not None
):
raise ValueError(
"You specified a positive gradient in your nonconvex "
"option. This cannot be combined with a positive or a "
"negative gradient for a standard flow!"
)
if self.nonconvex:
if self.nonconvex.negative_gradient["ub"][0] is not None and (
self.positive_gradient["ub"][0] is not None
or self.negative_gradient["ub"][0] is not None
):
raise ValueError(
"You specified a negative gradient in your nonconvex "
"option. This cannot be combined with a positive or a "
"negative gradient for a standard flow!"
)
class FlowBlock(SimpleBlock):
r""" FlowBlock block with definitions for standard flows.
**The following variables are created**:
negative_gradient :
Difference of a flow in consecutive timesteps if flow is reduced
indexed by NEGATIVE_GRADIENT_FLOWS, TIMESTEPS.
positive_gradient :
Difference of a flow in consecutive timesteps if flow is increased
indexed by NEGATIVE_GRADIENT_FLOWS, TIMESTEPS.
**The following sets are created:** (-> see basic sets at :class:`.Model` )
SUMMED_MAX_FLOWS
A set of flows with the attribute :attr:`summed_max` being not None.
SUMMED_MIN_FLOWS
A set of flows with the attribute :attr:`summed_min` being not None.
NEGATIVE_GRADIENT_FLOWS
A set of flows with the attribute :attr:`negative_gradient` being not
None.
POSITIVE_GRADIENT_FLOWS
A set of flows with the attribute :attr:`positive_gradient` being not
None
INTEGER_FLOWS
A set of flows where the attribute :attr:`integer` is True (forces flow
to only take integer values)
**The following constraints are build:**
FlowBlock max sum :attr:`om.FlowBlock.summed_max[i, o]`
.. math::
\sum_t flow(i, o, t) \cdot \tau
\leq summed\_max(i, o) \cdot nominal\_value(i, o), \\
\forall (i, o) \in \textrm{SUMMED\_MAX\_FLOWS}.
FlowBlock min sum :attr:`om.FlowBlock.summed_min[i, o]`
.. math::
\sum_t flow(i, o, t) \cdot \tau
\geq summed\_min(i, o) \cdot nominal\_value(i, o), \\
\forall (i, o) \in \textrm{SUMMED\_MIN\_FLOWS}.
Negative gradient constraint
:attr:`om.FlowBlock.negative_gradient_constr[i, o]`:
.. math::
flow(i, o, t-1) - flow(i, o, t) \geq \
negative\_gradient(i, o, t), \\
\forall (i, o) \in \textrm{NEGATIVE\_GRADIENT\_FLOWS}, \\
\forall t \in \textrm{TIMESTEPS}.
Positive gradient constraint
:attr:`om.FlowBlock.positive_gradient_constr[i, o]`:
.. math:: flow(i, o, t) - flow(i, o, t-1) \geq \
positive\__gradient(i, o, t), \\
\forall (i, o) \in \textrm{POSITIVE\_GRADIENT\_FLOWS}, \\
\forall t \in \textrm{TIMESTEPS}.
**The following parts of the objective function are created:**
If :attr:`variable_costs` are set by the user:
.. math::
\sum_{(i,o)} \sum_t flow(i, o, t) \cdot variable\_costs(i, o, t)
The expression can be accessed by :attr:`om.FlowBlock.variable_costs` and
their value after optimization by :meth:`om.FlowBlock.variable_costs()` .
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _create(self, group=None):
r"""Creates sets, variables and constraints for all standard flows.
Parameters
----------
group : list
List containing tuples containing flow (f) objects and the
associated source (s) and target (t)
of flow e.g. groups=[(s1, t1, f1), (s2, t2, f2),..]
"""
if group is None:
return None
m = self.parent_block()
# ########################## SETS #################################
# set for all flows with an global limit on the flow over time
self.SUMMED_MAX_FLOWS = Set(
initialize=[
(g[0], g[1])
for g in group
if g[2].summed_max is not None
and g[2].nominal_value is not None
]
)
self.SUMMED_MIN_FLOWS = Set(
initialize=[
(g[0], g[1])
for g in group
if g[2].summed_min is not None
and g[2].nominal_value is not None
]
)
self.NEGATIVE_GRADIENT_FLOWS = Set(
initialize=[
(g[0], g[1])
for g in group
if g[2].negative_gradient["ub"][0] is not None
]
)
self.POSITIVE_GRADIENT_FLOWS = Set(
initialize=[
(g[0], g[1])
for g in group
if g[2].positive_gradient["ub"][0] is not None
]
)
self.INTEGER_FLOWS = Set(
initialize=[(g[0], g[1]) for g in group if g[2].integer]
)
# ######################### Variables ################################
self.positive_gradient = Var(self.POSITIVE_GRADIENT_FLOWS, m.TIMESTEPS)
self.negative_gradient = Var(self.NEGATIVE_GRADIENT_FLOWS, m.TIMESTEPS)
self.integer_flow = Var(
self.INTEGER_FLOWS, m.TIMESTEPS, within=NonNegativeIntegers
)
# set upper bound of gradient variable
for i, o, f in group:
if m.flows[i, o].positive_gradient["ub"][0] is not None:
for t in m.TIMESTEPS:
self.positive_gradient[i, o, t].setub(
f.positive_gradient["ub"][t] * f.nominal_value
)
if m.flows[i, o].negative_gradient["ub"][0] is not None:
for t in m.TIMESTEPS:
self.negative_gradient[i, o, t].setub(
f.negative_gradient["ub"][t] * f.nominal_value
)
# ######################### CONSTRAINTS ###############################
# def _fix_value_rule(model):
# """"""
# for inp, out in m.FIRSTSTAGE_FLOWS:
# for t in m.TIMESTEPS:
# self.fix_value_constr.add(
# (inp, out, t),
# m.flow[inp, out, t] ==
# m.flows[inp, out].fix[t] * m.flows[inp, out].nominal_value)
#
# self.fix_value_constr = Constraint(m.FIRSTSTAGE_FLOWS, m.TIMESTEPS, noruleinit=True)
# self.fix_value_build = BuildAction(rule=_fix_value_rule)
def _flow_summed_max_rule(model):
"""Rule definition for build action of max. sum flow constraint."""
for inp, out in self.SUMMED_MAX_FLOWS:
lhs = sum(
m.flow[inp, out, ts] * m.timeincrement[ts]
for ts in m.TIMESTEPS
)
rhs = (
m.flows[inp, out].summed_max
* m.flows[inp, out].nominal_value
)
self.summed_max.add((inp, out), lhs <= rhs)
self.summed_max = Constraint(self.SUMMED_MAX_FLOWS, noruleinit=True)
self.summed_max_build = BuildAction(rule=_flow_summed_max_rule)
def _flow_summed_min_rule(model):
"""Rule definition for build action of min. sum flow constraint."""
for inp, out in self.SUMMED_MIN_FLOWS:
lhs = sum(
m.flow[inp, out, ts] * m.timeincrement[ts]
for ts in m.TIMESTEPS
)
rhs = (
m.flows[inp, out].summed_min
* m.flows[inp, out].nominal_value
)
self.summed_min.add((inp, out), lhs >= rhs)
self.summed_min = Constraint(self.SUMMED_MIN_FLOWS, noruleinit=True)
self.summed_min_build = BuildAction(rule=_flow_summed_min_rule)
def _positive_gradient_flow_rule(model):
"""Rule definition for positive gradient constraint."""
for inp, out in self.POSITIVE_GRADIENT_FLOWS:
for ts in m.TIMESTEPS:
if ts > 0:
lhs = m.flow[inp, out, ts] - m.flow[inp, out, ts - 1]
rhs = self.positive_gradient[inp, out, ts]
self.positive_gradient_constr.add(
(inp, out, ts), lhs <= rhs
)
else:
pass # return(Constraint.Skip)
self.positive_gradient_constr = Constraint(
self.POSITIVE_GRADIENT_FLOWS, m.TIMESTEPS, noruleinit=True
)
self.positive_gradient_build = BuildAction(
rule=_positive_gradient_flow_rule
)
def _negative_gradient_flow_rule(model):
"""Rule definition for negative gradient constraint."""
for inp, out in self.NEGATIVE_GRADIENT_FLOWS:
for ts in m.TIMESTEPS:
if ts > 0:
lhs = m.flow[inp, out, ts - 1] - m.flow[inp, out, ts]
rhs = self.negative_gradient[inp, out, ts]
self.negative_gradient_constr.add(
(inp, out, ts), lhs <= rhs
)
else:
pass # return(Constraint.Skip)
self.negative_gradient_constr = Constraint(
self.NEGATIVE_GRADIENT_FLOWS, m.TIMESTEPS, noruleinit=True
)
self.negative_gradient_build = BuildAction(
rule=_negative_gradient_flow_rule
)
def _integer_flow_rule(block, ii, oi, ti):
"""Force flow variable to NonNegativeInteger values."""
return self.integer_flow[ii, oi, ti] == m.flow[ii, oi, ti]
self.integer_flow_constr = Constraint(
self.INTEGER_FLOWS, m.TIMESTEPS, rule=_integer_flow_rule
)
def _objective_expression(self):
r"""Objective expression for all standard flows with fixed costs
and variable costs.
"""
m = self.parent_block()
self.variable_costs = quicksum(
m.flow[i, o, t]
* m.objective_weighting[t]
* m.flows[i, o].variable_costs[t]
for t in m.TIMESTEPS
for i, o in m.FLOWS
if m.flows[i, o].variable_costs[0] is not None
)
self.gradient_costs = quicksum(
self.positive_gradient[i, o, t]
* m.flows[i, o].positive_gradient["costs"]
for t in m.TIMESTEPS
for (i, o) in m.FLOWS
if m.flows[i, o].positive_gradient["ub"][0] is not None
)
self.gradient_costs += quicksum(
self.positive_gradient[i, o, t]
* m.flows[i, o].negative_gradient["costs"]
for t in m.TIMESTEPS
for (i, o) in m.FLOWS
if m.flows[i, o].negative_gradient["ub"][0] is not None
)
return (
self.variable_costs
+ self.gradient_costs
)
def _stochastic_objective_expression(self):
r"""First stage objective expression for all stochastic flows
"""
m = self.parent_block()
self.variable_costs = quicksum(
m.flow[i, o, t]
* m.objective_weighting[t]
* m.flows[i, o].variable_costs[t]
for t in m.TIMESTEPS
for i, o in m.FLOWS - m.FIRSTSTAGE_FLOWS
if m.flows[i, o].variable_costs[0] is not None
)
self.gradient_costs = quicksum(
self.positive_gradient[i, o, t]
* m.flows[i, o].positive_gradient["costs"]
for t in m.TIMESTEPS
for (i, o) in m.FLOWS - m.FIRSTSTAGE_FLOWS
if m.flows[i, o].positive_gradient["ub"][0] is not None
)
self.gradient_costs += quicksum(
self.positive_gradient[i, o, t]
* m.flows[i, o].negative_gradient["costs"]
for t in m.TIMESTEPS
for (i, o) in m.FLOWS - m.FIRSTSTAGE_FLOWS
if m.flows[i, o].negative_gradient["ub"][0] is not None
)
self.firststage_variable_costs = quicksum(
m.flow[i, o, t]
* m.objective_weighting[t]
* m.flows[i, o].variable_costs[t]
for t in m.TIMESTEPS
for i, o in m.FIRSTSTAGE_FLOWS
if m.flows[i, o].variable_costs[0] is not None
)
self.firststage_gradient_costs = quicksum(
self.positive_gradient[i, o, t]
* m.flows[i, o].positive_gradient["costs"]
for t in m.TIMESTEPS
for (i, o) in m.FIRSTSTAGE_FLOWS
if m.flows[i, o].positive_gradient["ub"][0] is not None
)
self.firststage_gradient_costs += quicksum(
self.negative_gradient[i, o, t]
* m.flows[i, o].positive_gradient["costs"]
for t in m.TIMESTEPS
for (i, o) in m.FIRSTSTAGE_FLOWS
if m.flows[i, o].negative_gradient["ub"][0] is not None
)
return (
self.variable_costs +
self.gradient_costs +
self.firststage_variable_costs
+ self.firststage_gradient_costs
)
self.gradient_costs += quicksum(
self.positive_gradient[i, o, t]
* m.flows[i, o].negative_gradient["costs"]
for t in m.TIMESTEPS
for (i, o) in m.FLOWS
if m.flows[i, o].negative_gradient["ub"][0] is not None
)
return (
self.variable_costs
+ self.first_stage_variable_costs
+ self.gradient_costs
+ self.first_stage_gradient_costs
)