-
Notifications
You must be signed in to change notification settings - Fork 25
/
stochasticprogram.jl
378 lines (361 loc) · 17.1 KB
/
stochasticprogram.jl
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
# MIT License
#
# Copyright (c) 2018 Martin Biel
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
StochasticProgram
An instance of a stochastic optimization problem.
"""
struct StochasticProgram{N, S <: NTuple{N, Stage}, ST <: AbstractStochasticStructure{N}}
stages::S
decisions::Decisions{N}
structure::ST
generator::Dict{Symbol, Function}
problemcache::Dict{Symbol, JuMP.Model}
solutioncache::Dict{Symbol, SolutionCache}
optimizer::StochasticProgramOptimizer
function StochasticProgram(stages::NTuple{N, Stage},
scenario_types::ScenarioTypes{M},
instantiation::StochasticInstantiation,
optimizer_constructor) where {N, M}
N >= 2 || error("Stochastic program needs at least two stages.")
M == N - 1 || error("Inconsistent number of stages $N and number of scenario types $M")
S = typeof(stages)
decisions = Decisions(Val(N))
optimizer = StochasticProgramOptimizer(optimizer_constructor)
structure = StochasticStructure(decisions, scenario_types, default_structure(instantiation, optimizer.optimizer))
ST = typeof(structure)
return new{N, S, ST}(stages,
decisions,
structure,
Dict{Symbol, Function}(),
Dict{Symbol, JuMP.Model}(),
Dict{Symbol, SolutionCache}(),
optimizer)
end
function StochasticProgram(stages::NTuple{N, Stage},
scenarios::NTuple{M, Vector{<:AbstractScenario}},
instantiation::StochasticInstantiation,
optimizer_constructor) where {N, M}
N >= 2 || error("Stochastic program needs at least two stages.")
M == N - 1 || error("Inconsistent number of stages $N and number of scenario types $M")
S = typeof(stages)
decisions = Decisions(Val(N))
optimizer = StochasticProgramOptimizer(optimizer_constructor)
structure = StochasticStructure(decisions, scenarios, default_structure(instantiation, optimizer.optimizer))
ST = typeof(structure)
return new{N, S, ST}(stages,
decisions,
structure,
Dict{Symbol, Function}(),
Dict{Symbol, JuMP.Model}(),
Dict{Symbol, SolutionCache}(),
optimizer)
end
end
TwoStageStochasticProgram{S <: Tuple{Stage, Stage}, ST <: AbstractStochasticStructure{2}} = StochasticProgram{2, S, ST}
# Constructors #
# ========================== #
# Two-stage
# ========================== #
"""
StochasticProgram(first_stage_params::Any,
second_stage_params::Any,
instantiation::StochasticInstantiation,
optimizer_constructor=nothing) where T <: AbstractFloat
Create a new two-stage stochastic program with stage data given by `first_stage_params` and `second_stage_params`. After construction, scenarios of type `Scenario` can be added through `add_scenario!`. Optionally, a capable `optimizer_constructor` can be supplied to later optimize the stochastic program. If multiple Julia processes are available, the resulting stochastic program will automatically be memory-distributed on these processes. This can be avoided by setting `procs = [1]`.
"""
function StochasticProgram(first_stage_params::Any,
second_stage_params::Any,
instantiation::StochasticInstantiation,
optimizer_constructor = nothing)
stages = (Stage(first_stage_params), Stage(second_stage_params))
return StochasticProgram(stages, (Scenario,), instantiation, optimizer_constructor)
end
"""
StochasticProgram(first_stage_params::Any,
second_stage_params::Any,
::Type{Scenario},
instantiation::StochasticInstantiation,
optimizer_constructor=nothing) where Scenario <: AbstractScenario
Create a new two-stage stochastic program with stage data given by `first_stage_params` and `second_stage_params`. After construction, scenarios of type `S` can be added through `add_scenario!`. Optionally, a capable `optimizer_constructor` can be supplied to later optimize the stochastic program. If multiple Julia processes are available, the resulting stochastic program will automatically be memory-distributed on these processes. This can be avoided by setting `procs = [1]`.
"""
function StochasticProgram(first_stage_params::Any,
second_stage_params::Any,
::Type{Scenario},
instantiation::StochasticInstantiation,
optimizer_constructor = nothing) where Scenario <: AbstractScenario
stages = (Stage(first_stage_params), Stage(second_stage_params))
return StochasticProgram(stages, (Scenario,), instantiation, optimizer_constructor)
end
"""
StochasticProgram(::Type{Scenario},
instantiation::StochasticInstantiation,
optimizer_constructor=nothing) where Scenario <: AbstractScenario
Create a new two-stage stochastic program with scenarios of type `Scenario` and no stage data. Optionally, a capable `optimizer_constructor` can be supplied to later optimize the stochastic program.
"""
function StochasticProgram(::Type{Scenario},
instantiation::StochasticInstantiation,
optimizer_constructor = nothing) where Scenario <: AbstractScenario
stages = (Stage(nothing), Stage(nothing))
return StochasticProgram(stages, (Scenario,), instantiation, optimizer_constructor; procs = procs)
end
"""
StochasticProgram(first_stage_params::Any,
second_stage_params::Any,
scenarios::Vector{<:AbstractScenario},
instantiation::StochasticInstantiation,
optimizer_constructor = nothing)
Create a new two-stage stochastic program with a given collection of `scenarios`. Optionally, a capable `optimizer_constructor` can be supplied to later optimize the stochastic program. If multiple Julia processes are available, the resulting stochastic program will automatically be memory-distributed on these processes. This can be avoided by setting `procs = [1]`.
"""
function StochasticProgram(first_stage_params::Any,
second_stage_params::Any,
scenarios::Vector{<:AbstractScenario},
instantiation::StochasticInstantiation,
optimizer_constructor = nothing)
stages = (Stage(first_stage_params), Stage(second_stage_params))
return StochasticProgram(stages, (scenarios,), instantiation, optimizer_constructor)
end
"""
StochasticProgram(scenarios::Vector{<:AbstractScenario},
instantiation::StochasticInstantiation,
optimizer_constructor = nothing)
Create a new two-stage stochastic program with a given collection of `scenarios` and no stage data. Optionally, a capable `optimizer_constructor` can be supplied to later optimize the stochastic program. If multiple Julia processes are available, the resulting stochastic program will automatically be memory-distributed on these processes. This can be avoided by setting `procs = [1]`.
"""
function StochasticProgram(scenarios::Vector{<:AbstractScenario},
instantiation::StochasticInstantiation,
optimizer_constructor = nothing)
stages = (Stage(nothing), Stage(nothing))
return StochasticProgram(stages, (scenarios,), instantiation, optimizer_constructor)
end
function Base.copy(src::StochasticProgram{N}; instantiation = UnspecifiedInstantiation(), optimizer = nothing) where N
stages = ntuple(Val(N)) do i
Stage(stage_parameters(src, i))
end
scenario_types = ntuple(Val(N-1)) do i
scenario_type(src, i+1)
end
dest = StochasticProgram(stages, scenario_types, instantiation, optimizer)
merge!(dest.generator, src.generator)
return dest
end
# Printing #
# ========================== #
function Base.show(io::IO, stochasticprogram::StochasticProgram{N}) where N
plural(n) = (n == 1 ? "" : "s")
stage(sp, s) = begin
stage_key = Symbol(:stage_,s)
ndecisions = num_decisions(sp, s)
nscenarios = num_scenarios(sp, s)
if s == 1
if N == 2
return " * $(ndecisions) decision variable$(plural(ndecisions))"
else
return " * Stage $s:\n * $(ndecisions) decision variable$(plural(ndecisions))"
end
elseif s == 2 && N == 2
stype = typename(scenario_type(stochasticprogram))
return " * $(ndecisions) recourse variables\n * $(nscenarios) scenario$(plural(nscenarios)) of type $stype"
else
stype = typename(scenario_type(stochasticprogram, s))
if distributed(stochasticprogram, s)
if s == N
return " * Distributed stage $s:\n * $(ndecisions) recourse variables\n * $(nscenarios) scenario$(plural(nscenarios)) of type $stype"
else
return " * Distributed stage $s:\n * $(ndecisions) decision variable$(plural(ndecisions))\n * $(nscenarios) scenario$(plural(nscenarios)) of type $stype"
end
else
if s == N
return " * Stage $s:\n * $(ndecisions) recourse variables\n * $(nscenarios) scenario$(plural(nscenarios)) of type $stype"
else
return " * Stage $s:\n * $(ndecisions) decision variable$(plural(ndecisions))\n * $(nscenarios) scenario$(plural(nscenarios)) of type $stype"
end
end
end
end
if deferred(stochasticprogram)
n = num_scenarios(stochasticprogram)
if n == 0
return print(io, "Deferred stochastic program")
else
return print(io, "Deferred stochastic program with $n scenario$(plural(n))")
end
end
if N == 2 && distributed(stochasticprogram)
println(io, "Distributed stochastic program with:")
else
println(io, "Stochastic program with:")
end
print(io, stage(stochasticprogram, 1))
for s = 2:N
println(io,"")
print(io, stage(stochasticprogram, s))
end
println(io,"")
print(io, "Structure: ")
print(io, structure_name(stochasticprogram))
println(io,"")
print(io, "Solver name: ")
print(io, optimizer_name(stochasticprogram))
end
function Base.print(io::IO, stochasticprogram::StochasticProgram)
if !deferred(stochasticprogram)
# Delegate printing according to stochastic structure
print(io, structure(stochasticprogram))
print(io, "Solver name: ")
print(io, optimizer_name(stochasticprogram))
else
# Just give summary if the stochastic program has not been initialized yet
show(io, stochasticprogram)
end
end
# ========================== #
# MOI #
# ========================== #
function MOI.get(stochasticprogram::StochasticProgram, attr::Union{MOI.TerminationStatus, MOI.PrimalStatus, MOI.DualStatus})
# Check if there is a cached solution
cache = solutioncache(stochasticprogram)
if haskey(cache, :solution)
# Returned cached solution if possible
try
return MOI.get(cache[:solution], attr)
catch
end
end
if haskey(cache, :node_solution_1)
# Value was possibly only cached in first-stage solution
try
return MOI.get(cache[:node_solution_1], attr)
catch
end
end
return MOI.get(optimizer(stochasticprogram), attr)
end
function MOI.get(stochasticprogram::StochasticProgram, attr::MOI.AbstractModelAttribute)
if MOI.is_set_by_optimize(attr)
# Check if there is a cached solution
cache = solutioncache(stochasticprogram)
if haskey(cache, :solution)
# Returned cached solution if possible
try
return MOI.get(cache[:solution], attr)
catch
end
end
if haskey(cache, :node_solution_1)
# Value was possibly only cached in first-stage solution
try
return MOI.get(cache[:node_solution_1], attr)
catch
end
end
check_provided_optimizer(stochasticprogram.optimizer)
if MOI.get(stochasticprogram, MOI.TerminationStatus()) == MOI.OPTIMIZE_NOT_CALLED
throw(OptimizeNotCalled())
end
return MOI.get(optimizer(stochasticprogram), attr)
else
if is_structure_independent(attr)
# Get attribute from first stage of proxy if structure independent
return MOI.get(proxy(stochasticprogram, 1), attr)
else
# Handle in structure otherwise
return MOI.get(structure(stochasticprogram), attr)
end
end
end
function MOI.get(stochasticprogram::StochasticProgram, attr::ScenarioDependentModelAttribute)
if MOI.is_set_by_optimize(attr)
# Check if there is a cached solution
cache = solutioncache(stochasticprogram)
key = Symbol(:node_solution_, attr.stage, :_, attr.scenario_index)
if haskey(cache, key)
try
return MOI.get(cache[key], attr.attr)
catch
end
end
check_provided_optimizer(stochasticprogram.optimizer)
# Return statuses without checks
if typeof(attr.attr) <: Union{MOI.TerminationStatus, MOI.PrimalStatus, MOI.DualStatus}
try
# Try to get scenario-dependent value directly
return MOI.get(optimizer(stochasticprogram), attr)
catch
# Fallback to resolving scenario-dependence in structure if
# not supported natively by optimizer
return MOI.get(structure(stochasticprogram), attr)
end
end
if MOI.get(stochasticprogram, MOI.TerminationStatus()) == MOI.OPTIMIZE_NOT_CALLED
throw(OptimizeNotCalled())
end
try
# Try to get scenario-dependent value directly
return MOI.get(optimizer(stochasticprogram), attr)
catch
# Fallback to resolving scenario-dependence in structure if
# not supported natively by optimizer
MOI.get(structure(stochasticprogram), attr)
end
else
if is_structure_independent(attr)
# Get attribute from first stage of proxy if structure independent
return MOI.get(proxy(stochasticprogram, 1), attr)
else
# Handle in structure otherwise
return MOI.get(structure(stochasticprogram), attr)
end
end
end
function MOI.get(stochasticprogram::StochasticProgram, attr::MOI.AbstractOptimizerAttribute)
MOI.get(optimizer(stochasticprogram), attr)
end
function MOI.set(sp::StochasticProgram, attr::MOI.AbstractOptimizerAttribute, value)
MOI.set(optimizer(sp), attr, value)
return nothing
end
function MOI.set(sp::StochasticProgram, attr::MOI.AbstractModelAttribute, value)
if is_structure_independent(attr)
MOI.set(proxy(sp, attr.stage), attr, value)
end
MOI.set(structure(sp), attr, value)
return nothing
end
function MOI.set(sp::StochasticProgram, attr::ScenarioDependentModelAttribute, value)
if is_structure_independent(attr)
MOI.set(proxy(sp, attr.stage), attr, value)
end
MOI.set(structure(sp), attr, value)
return nothing
end
function MOI.set(sp::StochasticProgram, attr::MOI.Silent, flag)
# Ensure that Silent is always passed
MOI.set(structure(sp), attr, flag)
# Pass to optimizer anyway
MOI.set(optimizer(sp), attr, flag)
return nothing
end
function JuMP.check_belongs_to_model(con_ref::ConstraintRef{<:StochasticProgram}, stochasticprogram::StochasticProgram)
if owner_model(con_ref) !== model
throw(ConstraintNotOwned(con_ref))
end
end
Base.broadcastable(sp::StochasticProgram) = Ref(sp)