-
Notifications
You must be signed in to change notification settings - Fork 52
/
optimization_container.jl
1777 lines (1605 loc) · 59.1 KB
/
optimization_container.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
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Optimization Container construction stage
"""
abstract type ConstructStage end
struct ArgumentConstructStage <: ConstructStage end
struct ModelConstructStage <: ConstructStage end
struct OptimizationContainerMetadata
container_key_lookup::Dict{String, <:OptimizationContainerKey}
end
function OptimizationContainerMetadata()
return OptimizationContainerMetadata(Dict{String, OptimizationContainerKey}())
end
function deserialize_metadata(
::Type{OptimizationContainerMetadata},
output_dir::String,
model_name,
)
filename = _make_metadata_filename(model_name, output_dir)
return Serialization.deserialize(filename)
end
function deserialize_key(metadata::OptimizationContainerMetadata, name::AbstractString)
!haskey(metadata.container_key_lookup, name) && error("$name is not stored")
return metadata.container_key_lookup[name]
end
add_container_key!(x::OptimizationContainerMetadata, key, val) =
x.container_key_lookup[key] = val
get_container_key(x::OptimizationContainerMetadata, key) = x.container_key_lookup[key]
has_container_key(x::OptimizationContainerMetadata, key) =
haskey(x.container_key_lookup, key)
struct PrimalValuesCache
variables_cache::Dict{VariableKey, AbstractArray}
expressions_cache::Dict{ExpressionKey, AbstractArray}
end
function PrimalValuesCache()
return PrimalValuesCache(
Dict{VariableKey, AbstractArray}(),
Dict{ExpressionKey, AbstractArray}(),
)
end
function Base.isempty(pvc::PrimalValuesCache)
return isempty(pvc.variables_cache) && isempty(pvc.expressions_cache)
end
mutable struct ObjectiveFunction
invariant_terms::JuMP.AbstractJuMPScalar
variant_terms::GAE
synchronized::Bool
sense::MOI.OptimizationSense
function ObjectiveFunction(invariant_terms::JuMP.AbstractJuMPScalar,
variant_terms::GAE,
synchronized::Bool,
sense::MOI.OptimizationSense = MOI.MIN_SENSE)
new(invariant_terms, variant_terms, synchronized, sense)
end
end
get_invariant_terms(v::ObjectiveFunction) = v.invariant_terms
get_variant_terms(v::ObjectiveFunction) = v.variant_terms
function get_objective_expression(v::ObjectiveFunction)
if iszero(v.variant_terms)
return v.invariant_terms
else
return JuMP.add_to_expression!(v.variant_terms, v.invariant_terms)
end
end
get_sense(v::ObjectiveFunction) = v.sense
is_synchronized(v::ObjectiveFunction) = v.synchronized
set_synchronized_status(v::ObjectiveFunction, value) = v.synchronized = value
reset_variant_terms(v::ObjectiveFunction) = v.variant_terms = zero(JuMP.AffExpr)
has_variant_terms(v::ObjectiveFunction) = !iszero(v.variant_terms)
set_sense!(v::ObjectiveFunction, sense::MOI.OptimizationSense) = v.sense = sense
function ObjectiveFunction()
return ObjectiveFunction(
zero(JuMP.GenericAffExpr{Float64, JuMP.VariableRef}),
zero(JuMP.AffExpr),
true,
)
end
mutable struct OptimizationContainer <: AbstractModelContainer
JuMPmodel::JuMP.Model
time_steps::UnitRange{Int}
resolution::Dates.TimePeriod
settings::Settings
settings_copy::Settings
variables::Dict{VariableKey, AbstractArray}
aux_variables::Dict{AuxVarKey, AbstractArray}
duals::Dict{ConstraintKey, AbstractArray}
constraints::Dict{ConstraintKey, AbstractArray}
objective_function::ObjectiveFunction
expressions::Dict{ExpressionKey, AbstractArray}
parameters::Dict{ParameterKey, ParameterContainer}
primal_values_cache::PrimalValuesCache
initial_conditions::Dict{ICKey, Vector{<:InitialCondition}}
initial_conditions_data::InitialConditionsData
infeasibility_conflict::Dict{Symbol, Array}
pm::Union{Nothing, PM.AbstractPowerModel}
base_power::Float64
optimizer_stats::OptimizerStats
built_for_recurrent_solves::Bool
metadata::OptimizationContainerMetadata
default_time_series_type::Type{<:PSY.TimeSeriesData}
end
function OptimizationContainer(
sys::PSY.System,
settings::Settings,
jump_model::Union{Nothing, JuMP.Model},
::Type{T},
) where {T <: PSY.TimeSeriesData}
resolution = PSY.get_time_series_resolution(sys)
if isabstracttype(T)
error("Default Time Series Type $V can't be abstract")
end
if jump_model !== nothing && get_direct_mode_optimizer(settings)
throw(
IS.ConflictingInputsError(
"Externally provided JuMP models are not compatible with the direct model keyword argument. Use JuMP.direct_model before passing the custom model",
),
)
end
return OptimizationContainer(
jump_model === nothing ? JuMP.Model() : jump_model,
1:1,
IS.time_period_conversion(resolution),
settings,
copy_for_serialization(settings),
Dict{VariableKey, AbstractArray}(),
Dict{AuxVarKey, AbstractArray}(),
Dict{ConstraintKey, AbstractArray}(),
Dict{ConstraintKey, AbstractArray}(),
ObjectiveFunction(),
Dict{ExpressionKey, AbstractArray}(),
Dict{ParameterKey, ParameterContainer}(),
PrimalValuesCache(),
Dict{ICKey, Vector{InitialCondition}}(),
InitialConditionsData(),
Dict{Symbol, Array}(),
nothing,
PSY.get_base_power(sys),
OptimizerStats(),
false,
OptimizationContainerMetadata(),
T,
)
end
built_for_recurrent_solves(container::OptimizationContainer) =
container.built_for_recurrent_solves
get_aux_variables(container::OptimizationContainer) = container.aux_variables
get_base_power(container::OptimizationContainer) = container.base_power
get_constraints(container::OptimizationContainer) = container.constraints
function cost_function_unsynch(container::OptimizationContainer)
obj_func = PSI.get_objective_expression(container)
if has_variant_terms(obj_func) && PSI.is_synchronized(container)
PSI.set_synchronized_status(obj_func, false)
PSI.reset_variant_terms(obj_func)
end
return
end
function get_container_keys(container::OptimizationContainer)
return Iterators.flatten(keys(getfield(container, f)) for f in STORE_CONTAINERS)
end
get_default_time_series_type(container::OptimizationContainer) =
container.default_time_series_type
get_duals(container::OptimizationContainer) = container.duals
get_expressions(container::OptimizationContainer) = container.expressions
get_infeasibility_conflict(container::OptimizationContainer) =
container.infeasibility_conflict
get_initial_conditions(container::OptimizationContainer) = container.initial_conditions
get_initial_conditions_data(container::OptimizationContainer) =
container.initial_conditions_data
get_initial_time(container::OptimizationContainer) = get_initial_time(container.settings)
get_jump_model(container::OptimizationContainer) = container.JuMPmodel
get_metadata(container::OptimizationContainer) = container.metadata
get_optimizer_stats(container::OptimizationContainer) = container.optimizer_stats
get_parameters(container::OptimizationContainer) = container.parameters
get_resolution(container::OptimizationContainer) = container.resolution
get_settings(container::OptimizationContainer) = container.settings
get_time_steps(container::OptimizationContainer) = container.time_steps
get_variables(container::OptimizationContainer) = container.variables
set_initial_conditions_data!(container::OptimizationContainer, data) =
container.initial_conditions_data = data
get_objective_expression(container::OptimizationContainer) = container.objective_function
is_synchronized(container::OptimizationContainer) =
container.objective_function.synchronized
set_time_steps!(container::OptimizationContainer, time_steps::UnitRange{Int64}) =
container.time_steps = time_steps
function has_container_key(
container::OptimizationContainer,
::Type{T},
::Type{U},
meta = CONTAINER_KEY_EMPTY_META,
) where {T <: ExpressionType, U <: Union{PSY.Component, PSY.System}}
key = ExpressionKey(T, U, meta)
return haskey(container.expressions, key)
end
function has_container_key(
container::OptimizationContainer,
::Type{T},
::Type{U},
meta = CONTAINER_KEY_EMPTY_META,
) where {T <: VariableType, U <: Union{PSY.Component, PSY.System}}
key = VariableKey(T, U, meta)
return haskey(container.variables, key)
end
function has_container_key(
container::OptimizationContainer,
::Type{T},
::Type{U},
meta = CONTAINER_KEY_EMPTY_META,
) where {T <: AuxVariableType, U <: Union{PSY.Component, PSY.System}}
key = AuxVarKey(T, U, meta)
return haskey(container.aux_variables, key)
end
function has_container_key(
container::OptimizationContainer,
::Type{T},
::Type{U},
meta = CONTAINER_KEY_EMPTY_META,
) where {T <: ConstraintType, U <: Union{PSY.Component, PSY.System}}
key = ConstraintKey(T, U, meta)
return haskey(container.constraints, key)
end
function has_container_key(
container::OptimizationContainer,
::Type{T},
::Type{U},
meta = CONTAINER_KEY_EMPTY_META,
) where {T <: ParameterType, U <: Union{PSY.Component, PSY.System}}
key = ParameterKey(T, U, meta)
return haskey(container.parameters, key)
end
function has_container_key(
container::OptimizationContainer,
::Type{T},
::Type{U},
meta = CONTAINER_KEY_EMPTY_META,
) where {T <: InitialConditionType, U <: Union{PSY.Component, PSY.System}}
key = ICKey(T, U, meta)
return haskey(container.initial_conditions, key)
end
function is_milp(container::OptimizationContainer)::Bool
!supports_milp(container) && return false
if !isempty(
JuMP.all_constraints(
PSI.get_jump_model(container),
JuMP.VariableRef,
JuMP.MOI.ZeroOne,
),
)
return true
end
return false
end
function supports_milp(container::OptimizationContainer)
jump_model = get_jump_model(container)
return supports_milp(jump_model)
end
function _validate_warm_start_support(JuMPmodel::JuMP.Model, warm_start_enabled::Bool)
!warm_start_enabled && return warm_start_enabled
solver_supports_warm_start =
MOI.supports(JuMP.backend(JuMPmodel), MOI.VariablePrimalStart(), MOI.VariableIndex)
if !solver_supports_warm_start
solver_name = JuMP.solver_name(JuMPmodel)
@warn("$(solver_name) does not support warm start")
end
return solver_supports_warm_start
end
function _finalize_jump_model!(container::OptimizationContainer, settings::Settings)
@debug "Instantiating the JuMP model" _group = LOG_GROUP_OPTIMIZATION_CONTAINER
if built_for_recurrent_solves(container) && get_optimizer(settings) === nothing
throw(
IS.ConflictingInputsError(
"Optimizer can not be nothing when building for recurrent solves",
),
)
end
if get_direct_mode_optimizer(settings)
optimizer = () -> MOI.instantiate(get_optimizer(settings))
container.JuMPmodel = JuMP.direct_model(optimizer())
elseif get_optimizer(settings) === nothing
@debug "The optimization model has no optimizer attached" _group =
LOG_GROUP_OPTIMIZATION_CONTAINER
else
JuMP.set_optimizer(PSI.get_jump_model(container), get_optimizer(settings))
end
JuMPmodel = PSI.get_jump_model(container)
warm_start_enabled = get_warm_start(settings)
solver_supports_warm_start = _validate_warm_start_support(JuMPmodel, warm_start_enabled)
set_warm_start!(settings, solver_supports_warm_start)
JuMP.set_string_names_on_creation(JuMPmodel, get_store_variable_names(settings))
@debug begin
JuMP.set_string_names_on_creation(JuMPmodel, true)
end
if get_optimizer_solve_log_print(settings)
JuMP.unset_silent(JuMPmodel)
@debug "optimizer unset to silent" _group = LOG_GROUP_OPTIMIZATION_CONTAINER
else
JuMP.set_silent(JuMPmodel)
@debug "optimizer set to silent" _group = LOG_GROUP_OPTIMIZATION_CONTAINER
end
return
end
function init_optimization_container!(
container::OptimizationContainer,
::Type{T},
sys::PSY.System,
) where {T <: PM.AbstractPowerModel}
PSY.set_units_base_system!(sys, "SYSTEM_BASE")
# The order of operations matter
settings = get_settings(container)
if get_initial_time(settings) == UNSET_INI_TIME
if get_default_time_series_type(container) <: PSY.AbstractDeterministic
set_initial_time!(settings, PSY.get_forecast_initial_timestamp(sys))
elseif get_default_time_series_type(container) <: PSY.SingleTimeSeries
ini_time, _ = PSY.check_time_series_consistency(sys, PSY.SingleTimeSeries)
set_initial_time!(settings, ini_time)
end
end
if get_horizon(settings) == UNSET_HORIZON
set_horizon!(settings, PSY.get_forecast_horizon(sys))
end
container.time_steps = 1:get_horizon(settings)
if T <: CopperPlatePowerModel || T <: AreaBalancePowerModel
total_number_of_devices = length(get_available_components(PSY.Device, sys))
else
total_number_of_devices = length(get_available_components(PSY.Device, sys))
total_number_of_devices += length(get_available_components(PSY.ACBranch, sys))
end
# The 10e6 limit is based on the sizes of the lp benchmark problems http://plato.asu.edu/ftp/lpcom.html
# The maximum numbers of constraints and variables in the benchmark problems is 1,918,399 and 1,259,121,
# respectively. See also https://prod-ng.sandia.gov/techlib-noauth/access-control.cgi/2013/138847.pdf
variable_count_estimate = length(container.time_steps) * total_number_of_devices
if variable_count_estimate > 10e6
@warn(
"The lower estimate of total number of variables that will be created in the model is $(variable_count_estimate). \\
The total number of variables might be larger than 10e6 and could lead to large build or solve times."
)
end
stats = get_optimizer_stats(container)
stats.detailed_stats = get_detailed_optimizer_stats(settings)
_finalize_jump_model!(container, settings)
return
end
function reset_optimization_model!(container::OptimizationContainer)
for field in [:variables, :aux_variables, :constraints, :expressions, :duals]
empty!(getfield(container, field))
end
container.initial_conditions_data = InitialConditionsData()
container.objective_function = ObjectiveFunction()
container.primal_values_cache = PrimalValuesCache()
JuMP.empty!(PSI.get_jump_model(container))
return
end
function check_parameter_multiplier_values(multiplier_array::DenseAxisArray)
return !all(isnan.(multiplier_array.data))
end
function check_parameter_multiplier_values(multiplier_array::SparseAxisArray)
return !all(isnan.(values(multiplier_array.data)))
end
function check_optimization_container(container::OptimizationContainer)
for (k, param_container) in container.parameters
valid = check_parameter_multiplier_values(param_container.multiplier_array)
if !valid
error("The model container has invalid values in $(encode_key_as_string(k))")
end
end
return
end
function get_problem_size(container::OptimizationContainer)
model = get_jump_model(container)
vars = JuMP.num_variables(model)
cons = 0
for (exp, c_type) in JuMP.list_of_constraint_types(model)
cons += JuMP.num_constraints(model, exp, c_type)
end
return "The current total number of variables is $(vars) and total number of constraints is $(cons)"
end
function _make_container_array(ax...)
return remove_undef!(DenseAxisArray{GAE}(undef, ax...))
end
function _make_system_expressions!(
container::OptimizationContainer,
subnetworks::Dict{Int, Set{Int}},
dc_bus_numbers::Vector{Int},
::Type{<:PM.AbstractPowerModel},
bus_reduction_map::Dict{Int64, Set{Int64}},
)
time_steps = get_time_steps(container)
if isempty(bus_reduction_map)
ac_bus_numbers = collect(Iterators.flatten(values(subnetworks)))
else
ac_bus_numbers = collect(keys(bus_reduction_map))
end
container.expressions = Dict(
ExpressionKey(ActivePowerBalance, PSY.ACBus) =>
_make_container_array(ac_bus_numbers, time_steps),
ExpressionKey(ActivePowerBalance, PSY.DCBus) =>
_make_container_array(dc_bus_numbers, time_steps),
ExpressionKey(ReactivePowerBalance, PSY.ACBus) =>
_make_container_array(ac_bus_numbers, time_steps),
)
return
end
function _make_system_expressions!(
container::OptimizationContainer,
subnetworks::Dict{Int, Set{Int}},
dc_bus_numbers::Vector{Int},
::Type{<:PM.AbstractActivePowerModel},
bus_reduction_map::Dict{Int64, Set{Int64}},
)
time_steps = get_time_steps(container)
if isempty(bus_reduction_map)
ac_bus_numbers = collect(Iterators.flatten(values(subnetworks)))
else
ac_bus_numbers = collect(keys(bus_reduction_map))
end
container.expressions = Dict(
ExpressionKey(ActivePowerBalance, PSY.ACBus) =>
_make_container_array(ac_bus_numbers, time_steps),
ExpressionKey(ActivePowerBalance, PSY.DCBus) =>
_make_container_array(dc_bus_numbers, time_steps),
)
return
end
function _make_system_expressions!(
container::OptimizationContainer,
subnetworks::Dict{Int, Set{Int}},
::Vector{Int},
::Type{CopperPlatePowerModel},
bus_reduction_map::Dict{Int64, Set{Int64}},
)
time_steps = get_time_steps(container)
subnetworks_ref_buses = collect(keys(subnetworks))
container.expressions = Dict(
ExpressionKey(ActivePowerBalance, PSY.System) =>
_make_container_array(subnetworks_ref_buses, time_steps),
)
return
end
function _make_system_expressions!(
container::OptimizationContainer,
subnetworks::Dict{Int, Set{Int}},
dc_bus_numbers::Vector{Int},
::Type{T},
bus_reduction_map::Dict{Int64, Set{Int64}},
) where {T <: Union{PTDFPowerModel, StandardPTDFModel}}
time_steps = get_time_steps(container)
if isempty(bus_reduction_map)
ac_bus_numbers = collect(Iterators.flatten(values(subnetworks)))
else
ac_bus_numbers = collect(keys(bus_reduction_map))
end
subnetworks = collect(keys(subnetworks))
container.expressions = Dict(
ExpressionKey(ActivePowerBalance, PSY.System) =>
_make_container_array(subnetworks, time_steps),
ExpressionKey(ActivePowerBalance, PSY.DCBus) =>
_make_container_array(dc_bus_numbers, time_steps),
ExpressionKey(ActivePowerBalance, PSY.ACBus) =>
# Bus numbers are sorted to guarantee consistency in the order between the
# containers
_make_container_array(sort!(ac_bus_numbers), time_steps),
)
return
end
function initialize_system_expressions!(
container::OptimizationContainer,
::Type{T},
subnetworks::Dict{Int, Set{Int}},
system::PSY.System,
bus_reduction_map::Dict{Int64, Set{Int64}},
) where {T <: PM.AbstractPowerModel}
dc_bus_numbers = [PSY.get_number(b) for b in PSY.get_components(PSY.DCBus, system)]
_make_system_expressions!(container, subnetworks, dc_bus_numbers, T, bus_reduction_map)
return
end
function build_impl!(
container::OptimizationContainer,
template::ProblemTemplate,
sys::PSY.System,
)
transmission = get_network_formulation(template)
transmission_model = get_network_model(template)
initialize_system_expressions!(
container,
transmission,
transmission_model.subnetworks,
sys,
transmission_model.radial_network_reduction.bus_reduction_map)
# Order is required
for device_model in values(template.devices)
@debug "Building Arguments for $(get_component_type(device_model)) with $(get_formulation(device_model)) formulation" _group =
LOG_GROUP_OPTIMIZATION_CONTAINER
TimerOutputs.@timeit BUILD_PROBLEMS_TIMER "$(get_component_type(device_model))" begin
if validate_available_devices(device_model, sys)
construct_device!(
container,
sys,
ArgumentConstructStage(),
device_model,
transmission_model,
)
end
@debug "Problem size:" get_problem_size(container) _group =
LOG_GROUP_OPTIMIZATION_CONTAINER
end
end
TimerOutputs.@timeit BUILD_PROBLEMS_TIMER "Services" begin
construct_services!(
container,
sys,
ArgumentConstructStage(),
get_service_models(template),
get_device_models(template),
)
end
for branch_model in values(template.branches)
@debug "Building Arguments for $(get_component_type(branch_model)) with $(get_formulation(branch_model)) formulation" _group =
LOG_GROUP_OPTIMIZATION_CONTAINER
TimerOutputs.@timeit BUILD_PROBLEMS_TIMER "$(get_component_type(branch_model))" begin
if validate_available_devices(branch_model, sys)
construct_device!(
container,
sys,
ArgumentConstructStage(),
branch_model,
transmission_model,
)
end
@debug "Problem size:" get_problem_size(container) _group =
LOG_GROUP_OPTIMIZATION_CONTAINER
end
end
TimerOutputs.@timeit BUILD_PROBLEMS_TIMER "Services" begin
construct_services!(
container,
sys,
ModelConstructStage(),
get_service_models(template),
get_device_models(template),
)
end
for device_model in values(template.devices)
@debug "Building Model for $(get_component_type(device_model)) with $(get_formulation(device_model)) formulation" _group =
LOG_GROUP_OPTIMIZATION_CONTAINER
TimerOutputs.@timeit BUILD_PROBLEMS_TIMER "$(get_component_type(device_model))" begin
if validate_available_devices(device_model, sys)
construct_device!(
container,
sys,
ModelConstructStage(),
device_model,
transmission_model,
)
end
@debug "Problem size:" get_problem_size(container) _group =
LOG_GROUP_OPTIMIZATION_CONTAINER
end
end
# This function should be called after construct_device ModelConstructStage
TimerOutputs.@timeit BUILD_PROBLEMS_TIMER "$(transmission)" begin
@debug "Building $(transmission) network formulation" _group =
LOG_GROUP_OPTIMIZATION_CONTAINER
construct_network!(container, sys, transmission_model, template)
@debug "Problem size:" get_problem_size(container) _group =
LOG_GROUP_OPTIMIZATION_CONTAINER
end
for branch_model in values(template.branches)
@debug "Building Model for $(get_component_type(branch_model)) with $(get_formulation(branch_model)) formulation" _group =
LOG_GROUP_OPTIMIZATION_CONTAINER
TimerOutputs.@timeit BUILD_PROBLEMS_TIMER "$(get_component_type(branch_model))" begin
if validate_available_devices(branch_model, sys)
construct_device!(
container,
sys,
ModelConstructStage(),
branch_model,
transmission_model,
)
end
@debug "Problem size:" get_problem_size(container) _group =
LOG_GROUP_OPTIMIZATION_CONTAINER
end
end
TimerOutputs.@timeit BUILD_PROBLEMS_TIMER "Objective" begin
@debug "Building Objective" _group = LOG_GROUP_OPTIMIZATION_CONTAINER
update_objective_function!(container)
end
@debug "Total operation count $(PSI.get_jump_model(container).operator_counter)" _group =
LOG_GROUP_OPTIMIZATION_CONTAINER
check_optimization_container(container)
return
end
function update_objective_function!(container::OptimizationContainer)
JuMP.@objective(
get_jump_model(container),
get_sense(container.objective_function),
get_objective_expression(container.objective_function)
)
return
end
"""
Default solve method for OptimizationContainer
"""
function solve_impl!(container::OptimizationContainer, system::PSY.System)
optimizer_stats = get_optimizer_stats(container)
jump_model = get_jump_model(container)
_,
optimizer_stats.timed_solve_time,
optimizer_stats.solve_bytes_alloc,
optimizer_stats.sec_in_gc = @timed JuMP.optimize!(jump_model)
model_status = JuMP.primal_status(jump_model)
if model_status != MOI.FEASIBLE_POINT::MOI.ResultStatusCode
@error "Optimizer returned $model_status"
if get_calculate_conflict(get_settings(container))
compute_conflict!(container)
end
return RunStatus.FAILED
end
status = RunStatus.SUCCESSFUL
_, optimizer_stats.timed_calculate_aux_variables =
@timed calculate_aux_variables!(container, system)
# Needs to be called here to avoid issues when getting duals from MILPs
write_optimizer_stats!(container)
_, optimizer_stats.timed_calculate_dual_variables =
@timed calculate_dual_variables!(container, system, is_milp(container))
return status
end
function compute_conflict!(container::OptimizationContainer)
jump_model = get_jump_model(container)
JuMP.unset_silent(jump_model)
jump_model.is_model_dirty = false
conflict = container.infeasibility_conflict
try
JuMP.compute_conflict!(jump_model)
if MOI.get(jump_model, MOI.ConflictStatus()) != MOI.CONFLICT_FOUND
@error "No conflict could be found for the model. $(MOI.get(jump_model, MOI.ConflictStatus()))"
end
for (key, field_container) in get_constraints(container)
conflict_indices = check_conflict_status(jump_model, field_container)
if isempty(conflict_indices)
@info "Conflict Index returned empty for $key"
continue
else
conflict[encode_key(key)] = conflict_indices
end
end
@error "$(conflict)"
catch e
jump_model.is_model_dirty = true
if isa(e, MethodError)
@info "Can't compute conflict, check that your optimizer supports conflict refining/IIS"
else
@error "Can't compute conflict" exception = (e, catch_backtrace())
end
end
return
end
function write_optimizer_stats!(container::OptimizationContainer)
write_optimizer_stats!(get_optimizer_stats(container), get_jump_model(container))
return
end
"""
Exports the OpModel JuMP object in MathOptFormat
"""
function serialize_optimization_model(container::OptimizationContainer, save_path::String)
serialize_jump_optimization_model(get_jump_model(container), save_path)
return
end
const _CONTAINER_METADATA_FILE = "optimization_container_metadata.bin"
_make_metadata_filename(model_name::Symbol, output_dir) =
joinpath(output_dir, string(model_name), _CONTAINER_METADATA_FILE)
_make_metadata_filename(output_dir) = joinpath(output_dir, _CONTAINER_METADATA_FILE)
function serialize_metadata!(container::OptimizationContainer, output_dir::String)
for key in Iterators.flatten((
keys(container.constraints),
keys(container.duals),
keys(container.parameters),
keys(container.variables),
keys(container.aux_variables),
keys(container.expressions),
))
encoded_key = encode_key_as_string(key)
if has_container_key(container.metadata, encoded_key)
# Constraints and Duals can store the same key.
IS.@assert_op key == get_container_key(container.metadata, encoded_key)
end
add_container_key!(container.metadata, encoded_key, key)
end
filename = _make_metadata_filename(output_dir)
Serialization.serialize(filename, container.metadata)
@debug "Serialized container keys to $filename" _group = IS.LOG_GROUP_SERIALIZATION
end
function deserialize_metadata!(
container::OptimizationContainer,
output_dir::String,
model_name,
)
merge!(
container.metadata.container_key_lookup,
deserialize_metadata(OptimizationContainerMetadata, output_dir, model_name),
)
return
end
function _assign_container!(container::Dict, key::OptimizationContainerKey, value)
if haskey(container, key)
@error "$(encode_key(key)) is already stored" sort!(encode_key.(keys(container)))
throw(IS.InvalidValue("$key is already stored"))
end
container[key] = value
@debug "Added container entry $(typeof(key)) $(encode_key(key))" _group =
LOG_GROUP_OPTIMZATION_CONTAINER
return
end
####################################### Variable Container #################################
function _add_variable_container!(
container::OptimizationContainer,
var_key::VariableKey{T, U},
sparse::Bool,
axs...,
) where {T <: VariableType, U <: Union{PSY.Component, PSY.System}}
if sparse
var_container = sparse_container_spec(JuMP.VariableRef, axs...)
else
var_container = container_spec(JuMP.VariableRef, axs...)
end
_assign_container!(container.variables, var_key, var_container)
return var_container
end
function add_variable_container!(
container::OptimizationContainer,
::T,
::Type{U},
axs...;
sparse = false,
meta = CONTAINER_KEY_EMPTY_META,
) where {T <: VariableType, U <: Union{PSY.Component, PSY.System}}
var_key = VariableKey(T, U, meta)
return _add_variable_container!(container, var_key, sparse, axs...)
end
function add_variable_container!(
container::OptimizationContainer,
::T,
::Type{U},
meta::String,
axs...;
sparse = false,
) where {T <: VariableType, U <: Union{PSY.Component, PSY.System}}
var_key = VariableKey(T, U, meta)
return _add_variable_container!(container, var_key, sparse, axs...)
end
function _get_pwl_variables_container()
contents = Dict{Tuple{String, Int, Int}, Any}()
return SparseAxisArray(contents)
end
function add_variable_container!(
container::OptimizationContainer,
::T,
::Type{U};
meta = CONTAINER_KEY_EMPTY_META,
) where {T <: PieceWiseLinearCostVariable, U <: Union{PSY.Component, PSY.System}}
var_key = VariableKey(T, U, meta)
_assign_container!(container.variables, var_key, _get_pwl_variables_container())
return container.variables[var_key]
end
function get_variable_keys(container::OptimizationContainer)
return collect(keys(container.variables))
end
function get_variable(container::OptimizationContainer, key::VariableKey)
var = get(container.variables, key, nothing)
if var === nothing
name = encode_key(key)
keys = encode_key.(get_variable_keys(container))
throw(IS.InvalidValue("variable $name is not stored. $keys"))
end
return var
end
function get_variable(
container::OptimizationContainer,
::T,
::Type{U},
meta::String = CONTAINER_KEY_EMPTY_META,
) where {T <: VariableType, U <: Union{PSY.Component, PSY.System}}
return get_variable(container, VariableKey(T, U, meta))
end
##################################### AuxVariable Container ################################
function add_aux_variable_container!(
container::OptimizationContainer,
::T,
::Type{U},
axs...;
sparse = false,
meta = CONTAINER_KEY_EMPTY_META,
) where {T <: AuxVariableType, U <: PSY.Component}
var_key = AuxVarKey(T, U, meta)
if sparse
aux_variable_container = sparse_container_spec(Float64, axs...)
else
aux_variable_container = container_spec(Float64, axs...)
end
_assign_container!(container.aux_variables, var_key, aux_variable_container)
return aux_variable_container
end
function get_aux_variable_keys(container::OptimizationContainer)
return collect(keys(container.aux_variables))
end
function get_aux_variable(container::OptimizationContainer, key::AuxVarKey)
aux = get(container.aux_variables, key, nothing)
if aux === nothing
name = encode_key(key)
keys = encode_key.(get_variable_keys(container))
throw(IS.InvalidValue("Auxiliary variable $name is not stored. $keys"))
end
return aux
end
function get_aux_variable(
container::OptimizationContainer,
::T,
::Type{U},
meta::String = CONTAINER_KEY_EMPTY_META,
) where {T <: AuxVariableType, U <: PSY.Component}
return get_aux_variable(container, AuxVarKey(T, U, meta))
end
##################################### DualVariable Container ################################
function add_dual_container!(
container::OptimizationContainer,
::Type{T},
::Type{U},
axs...;
sparse = false,
meta = CONTAINER_KEY_EMPTY_META,
) where {T <: ConstraintType, U <: Union{PSY.Component, PSY.System}}
if is_milp(container)
@warn("The model has resulted in a MILP, \\
dual value retrieval requires solving an additional Linear Program \\
which increases simulation time and the results could be innacurate.")
end
const_key = ConstraintKey(T, U, meta)
if sparse
dual_container = sparse_container_spec(Float64, axs...)
else
dual_container = container_spec(Float64, axs...)
end
_assign_container!(container.duals, const_key, dual_container)
return dual_container
end
function get_dual_keys(container::OptimizationContainer)
return collect(keys(container.duals))
end
##################################### Constraint Container #################################
function _add_constraints_container!(
container::OptimizationContainer,
cons_key::ConstraintKey,
axs...;
sparse = false,
)
if sparse
cons_container = sparse_container_spec(JuMP.ConstraintRef, axs...)
else
cons_container = container_spec(JuMP.ConstraintRef, axs...)
end
_assign_container!(container.constraints, cons_key, cons_container)
return cons_container
end
function add_constraints_container!(
container::OptimizationContainer,
::T,
::Type{U},
axs...;
sparse = false,
meta = CONTAINER_KEY_EMPTY_META,
) where {T <: ConstraintType, U <: Union{PSY.Component, PSY.System}}
cons_key = ConstraintKey(T, U, meta)
return _add_constraints_container!(container, cons_key, axs...; sparse = sparse)
end
function get_constraint_keys(container::OptimizationContainer)
return collect(keys(container.constraints))
end
function get_constraint(container::OptimizationContainer, key::ConstraintKey)
var = get(container.constraints, key, nothing)
if var === nothing
name = encode_key(key)
keys = encode_key.(get_constraint_keys(container))
throw(IS.InvalidValue("constraint $name is not stored. $keys"))
end
return var
end
function get_constraint(
container::OptimizationContainer,
::T,
::Type{U},
meta::String = CONTAINER_KEY_EMPTY_META,
) where {T <: ConstraintType, U <: Union{PSY.Component, PSY.System}}
return get_constraint(container, ConstraintKey(T, U, meta))
end
function read_duals(container::OptimizationContainer)
return Dict(k => to_dataframe(jump_value.(v), k) for (k, v) in get_duals(container))
end