-
Notifications
You must be signed in to change notification settings - Fork 87
/
model.jl
638 lines (556 loc) · 25.2 KB
/
model.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
const C{F, S} = Tuple{CI{F, S}, F, S}
const EMPTYSTRING = ""
# Implementation of MOI for vector of constraint
function _addconstraint!(constrs::Vector{C{F, S}}, ci::CI, f::F, s::S) where {F, S}
push!(constrs, (ci, f, s))
length(constrs)
end
function _delete!(constrs::Vector, ci::CI, i::Int)
deleteat!(constrs, i)
@view constrs[i:end] # will need to shift it in constrmap
end
_getindex(ci::CI, f::MOI.AbstractFunction, s::MOI.AbstractSet) = ci
function _getindex(constrs::Vector, ci::CI, i::Int)
_getindex(constrs[i]...)
end
_getfun(ci::CI, f::MOI.AbstractFunction, s::MOI.AbstractSet) = f
function _getfunction(constrs::Vector, ci::CI, i::Int)
@assert ci.value == constrs[i][1].value
_getfun(constrs[i]...)
end
_gets(ci::CI, f::MOI.AbstractFunction, s::MOI.AbstractSet) = s
function _getset(constrs::Vector, ci::CI, i::Int)
@assert ci.value == constrs[i][1].value
_gets(constrs[i]...)
end
_modifyconstr(ci::CI{F, S}, f::F, s::S, change::F) where {F, S} = (ci, change, s)
_modifyconstr(ci::CI{F, S}, f::F, s::S, change::S) where {F, S} = (ci, f, change)
_modifyconstr(ci::CI{F, S}, f::F, s::S, change::MOI.AbstractFunctionModification) where {F, S} = (ci, modifyfunction(f, change), s)
function _modify!(constrs::Vector{C{F, S}}, ci::CI{F}, i::Int, change) where {F, S}
constrs[i] = _modifyconstr(constrs[i]..., change)
end
_getnoc(constrs::Vector{C{F, S}}, noc::MOI.NumberOfConstraints{F, S}) where {F, S} = length(constrs)
# Might be called when calling NumberOfConstraint with different coefficient type than the one supported
_getnoc(constrs::Vector, noc::MOI.NumberOfConstraints) = 0
function _getloc(constrs::Vector{C{F, S}})::Vector{Tuple{DataType, DataType}} where {F, S}
isempty(constrs) ? [] : [(F, S)]
end
_getlocr(constrs::Vector{C{F, S}}, ::MOI.ListOfConstraintIndices{F, S}) where {F, S} = map(constr -> constr[1], constrs)
_getlocr(constrs::Vector{<:C}, ::MOI.ListOfConstraintIndices{F, S}) where {F, S} = CI{F, S}[]
# Implementation of MOI for AbstractModel
abstract type AbstractModel{T} <: MOI.ModelLike end
getconstrloc(model::AbstractModel, ci::CI) = model.constrmap[ci.value]
# Variables
MOI.get(model::AbstractModel, ::MOI.NumberOfVariables) = length(model.varindices)
function MOI.addvariable!(model::AbstractModel)
v = VI(model.nextvariableid += 1)
push!(model.varindices, v)
v
end
function MOI.addvariables!(model::AbstractModel, n::Integer)
[MOI.addvariable!(model) for i in 1:n]
end
"""
removevariable(f::MOI.AbstractFunction, s::MOI.AbstractSet, vi::MOI.VariableIndex)
Return a tuple `(g, t)` representing the constraint `f`-in-`s` with the
variable `vi` removed. That is, the terms containing the variable `vi` in the
function `f` are removed and the dimension of the set `s` is updated if
needed (e.g. when `f` is a `VectorOfVariables` with `vi` being one of the
variables).
"""
removevariable(f, s, vi::VI) = removevariable(f, vi), s
function removevariable(f::MOI.VectorOfVariables, s, vi::VI)
g = removevariable(f, vi)
if length(g.variables) != length(f.variables)
t = updatedimension(s, length(g.variables))
else
t = s
end
return g, t
end
function _removevar!(constrs::Vector, vi::VI)
for i in eachindex(constrs)
ci, f, s = constrs[i]
constrs[i] = (ci, removevariable(f, s, vi)...)
end
return []
end
function _removevar!(constrs::Vector{<:C{MOI.SingleVariable}}, vi::VI)
# If a variable is removed, the SingleVariable constraints using this variable
# need to be removed too
rm = []
for (ci, f, s) in constrs
if f.variable == vi
push!(rm, ci)
end
end
rm
end
function MOI.delete!(model::AbstractModel, vi::VI)
if !MOI.isvalid(model, vi)
throw(MOI.InvalidIndex(vi))
end
model.objective = removevariable(model.objective, vi)
rm = broadcastvcat(constrs -> _removevar!(constrs, vi), model)
for ci in rm
MOI.delete!(model, ci)
end
delete!(model.varindices, vi)
if haskey(model.varnames, vi)
delete!(model.namesvar, model.varnames[vi])
delete!(model.varnames, vi)
end
end
function MOI.isvalid(model::AbstractModel, ci::CI{F, S}) where {F, S}
if ci.value > length(model.constrmap)
false
else
loc = getconstrloc(model, ci)
if iszero(loc) # This means that it has been deleted
false
elseif loc > MOI.get(model, MOI.NumberOfConstraints{F, S}())
false
else
ci == _getindex(model, ci, getconstrloc(model, ci))
end
end
end
MOI.isvalid(model::AbstractModel, vi::VI) = in(vi, model.varindices)
function MOI.get(model::AbstractModel, ::MOI.ListOfVariableIndices)
vis = collect(model.varindices)
sort!(vis, by=vi->vi.value) # It needs to be sorted by order of creation
vis
end
# Names
MOI.supports(::AbstractModel, ::MOI.Name) = true
function MOI.set!(model::AbstractModel, ::MOI.Name, name::String)
model.name = name
end
MOI.canget(model::AbstractModel, ::MOI.Name) = true
MOI.get(model::AbstractModel, ::MOI.Name) = model.name
"""
check_can_assign_name(model::MOI.ModelLike, IndexType::Type{<:MOI.Index}, idx::MOI.Index, name::String)
Return a `Bool` indicating whether `name` is available to be used by an
index of type `IndexType` (i.e., it is not already used). type `IndexType`.
If it is already used and the index using this name is not `idx` then it throws
an error.
"""
function check_can_assign_name(model::MOI.ModelLike, IndexType::Type{<:MOI.Index}, idx::MOI.Index, name::String)
if !isempty(name) && MOI.canget(model, IndexType, name)
other_idx = MOI.get(model, IndexType, name)
if other_idx != idx
error("$(IndexType == VI ? :Variable : :Constraint) name $name is already used by $other_idx)")
end
return false
else
return true
end
end
"""
setname(index_to_names::Dict{<:MOI.Index, String}, names_to_index::Dict{String, <:MOI.Index}, idx::MOI.Index, name::String, idxtype::Symbol)
Sets the name of the index `idx` to the name `name` in the maps `index_to_names` and `names_to_index`.
If `name` is empty, and `idx` already has a name, it is removed.
"""
function setname(index_to_names::Dict{<:MOI.Index, String}, names_to_index::Dict{String, <:MOI.Index}, idx::MOI.Index, name::String)
if haskey(index_to_names, idx)
delete!(names_to_index, index_to_names[idx])
end
index_to_names[idx] = name
if !isempty(name)
names_to_index[name] = idx
end
return
end
MOI.supports(::AbstractModel, ::MOI.VariableName, vi::Type{VI}) = true
function MOI.set!(model::AbstractModel, ::MOI.VariableName, vi::VI, name::String)
if check_can_assign_name(model, VI, vi, name)
setname(model.varnames, model.namesvar, vi, name)
end
end
MOI.canget(::AbstractModel, ::MOI.VariableName, ::Type{VI}) = true
MOI.get(model::AbstractModel, ::MOI.VariableName, vi::VI) = get(model.varnames, vi, EMPTYSTRING)
MOI.canget(model::AbstractModel, ::Type{VI}, name::String) = haskey(model.namesvar, name)
MOI.get(model::AbstractModel, ::Type{VI}, name::String) = model.namesvar[name]
MOI.canget(::AbstractModel, ::MOI.ListOfVariableAttributesSet) = true
function MOI.get(model::AbstractModel, ::MOI.ListOfVariableAttributesSet)::Vector{MOI.AbstractVariableAttribute}
isempty(model.varnames) ? [] : [MOI.VariableName()]
end
MOI.supports(model::AbstractModel, ::MOI.ConstraintName, ::Type{<:CI}) = true
function MOI.set!(model::AbstractModel, ::MOI.ConstraintName, ci::CI, name::String)
if check_can_assign_name(model, CI, ci, name)
setname(model.connames, model.namescon, ci, name)
end
end
MOI.canget(model::AbstractModel, ::MOI.ConstraintName, ::Type{<:CI}) = true
MOI.get(model::AbstractModel, ::MOI.ConstraintName, ci::CI) = get(model.connames, ci, EMPTYSTRING)
MOI.canget(model::AbstractModel, CT::Type{<:CI}, name::String) = haskey(model.namescon, name) && model.namescon[name] isa CT
MOI.get(model::AbstractModel, ::Type{<:CI}, name::String) = model.namescon[name]
MOI.canget(::AbstractModel, ::MOI.ListOfConstraintAttributesSet) = true
function MOI.get(model::AbstractModel, ::MOI.ListOfConstraintAttributesSet)::Vector{MOI.AbstractConstraintAttribute}
isempty(model.connames) ? [] : [MOI.ConstraintName()]
end
# Objective
MOI.canget(model::AbstractModel, ::MOI.ObjectiveSense) = model.senseset
MOI.get(model::AbstractModel, ::MOI.ObjectiveSense) = model.sense
MOI.supports(model::AbstractModel, ::MOI.ObjectiveSense) = true
function MOI.set!(model::AbstractModel, ::MOI.ObjectiveSense, sense::MOI.OptimizationSense)
model.senseset = true
model.sense = sense
end
MOI.canget(model::AbstractModel, ::MOI.ObjectiveFunction{T}) where T = model.objectiveset && typeof(model.objective) == T
function MOI.get(model::AbstractModel, ::MOI.ObjectiveFunction{T})::T where T
if typeof(model.objective) != T
throw(InexactError())
end
model.objective
end
MOI.supports(model::AbstractModel, ::MOI.ObjectiveFunction) = true
function MOI.set!(model::AbstractModel, ::MOI.ObjectiveFunction, f::MOI.AbstractFunction)
model.objectiveset = true
# f needs to be copied, see #2
model.objective = deepcopy(f)
end
function MOI.modify!(model::AbstractModel, obj::MOI.ObjectiveFunction, change::MOI.AbstractFunctionModification)
model.objective = modifyfunction(model.objective, change)
end
MOI.canget(::AbstractModel, ::MOI.ListOfOptimizerAttributesSet) = true
MOI.get(::AbstractModel, ::MOI.ListOfOptimizerAttributesSet) = MOI.AbstractOptimizerAttribute[]
MOI.canget(::AbstractModel, ::MOI.ListOfModelAttributesSet) = true
function MOI.get(model::AbstractModel, ::MOI.ListOfModelAttributesSet)::Vector{MOI.AbstractModelAttribute}
listattr = MOI.AbstractModelAttribute[]
if model.senseset
push!(listattr, MOI.ObjectiveSense())
end
if model.objectiveset
push!(listattr, MOI.ObjectiveFunction{typeof(model.objective)}())
end
if !isempty(model.name)
push!(listattr, MOI.Name())
end
listattr
end
# Constraints
function MOI.addconstraint!(model::AbstractModel, f::F, s::S) where {F<:MOI.AbstractFunction, S<:MOI.AbstractSet}
if MOI.supportsconstraint(model, F, S)
# We give the index value `nextconstraintid + 1` to the new constraint.
# As the same counter is used for all pairs of F-in-S constraints,
# the index value is unique across all constraint types as mentionned in `@model`'s doc.
ci = CI{F, S}(model.nextconstraintid += 1)
# f needs to be copied, see #2
push!(model.constrmap, _addconstraint!(model, ci, deepcopy(f), deepcopy(s)))
return ci
else
throw(MOI.UnsupportedConstraint{F, S}())
end
end
function MOI.delete!(model::AbstractModel, ci::CI)
if !MOI.isvalid(model, ci)
throw(MOI.InvalidIndex(ci))
end
for (ci_next, _, _) in _delete!(model, ci, getconstrloc(model, ci))
model.constrmap[ci_next.value] -= 1
end
model.constrmap[ci.value] = 0
if haskey(model.connames, ci)
delete!(model.namescon, model.connames[ci])
delete!(model.connames, ci)
end
end
function MOI.modify!(model::AbstractModel, ci::CI, change::MOI.AbstractFunctionModification)
_modify!(model, ci, getconstrloc(model, ci), change)
end
MOI.supports(::AbstractModel, ::MOI.ConstraintFunction, ::Type{<:CI}) = true
function MOI.set!(model::AbstractModel, ::MOI.ConstraintFunction, ci::CI, change::MOI.AbstractFunction)
_modify!(model, ci, getconstrloc(model, ci), change)
end
MOI.supports(::AbstractModel, ::MOI.ConstraintSet, ::Type{<:CI}) = true
function MOI.set!(model::AbstractModel, ::MOI.ConstraintSet, ci::CI, change::MOI.AbstractSet)
_modify!(model, ci, getconstrloc(model, ci), change)
end
MOI.get(model::AbstractModel, noc::MOI.NumberOfConstraints) = _getnoc(model, noc)
function MOI.get(model::AbstractModel, loc::MOI.ListOfConstraints)
broadcastvcat(_getloc, model)
end
function MOI.get(model::AbstractModel, loc::MOI.ListOfConstraintIndices)
broadcastvcat(constrs -> _getlocr(constrs, loc), model)
end
MOI.canget(model::AbstractModel, ::Union{MOI.NumberOfVariables,
MOI.ListOfVariableIndices,
MOI.NumberOfConstraints,
MOI.ListOfConstraints,
MOI.ListOfConstraintIndices,
MOI.ObjectiveSense}) = true
function MOI.get(model::AbstractModel, ::MOI.ConstraintFunction, ci::CI)
_getfunction(model, ci, getconstrloc(model, ci))
end
function MOI.get(model::AbstractModel, ::MOI.ConstraintSet, ci::CI)
_getset(model, ci, getconstrloc(model, ci))
end
function MOI.isempty(model::AbstractModel)
isempty(model.name) && !model.senseset && !model.objectiveset &&
isempty(model.objective.terms) && iszero(model.objective.constant) &&
iszero(model.nextvariableid) && iszero(model.nextconstraintid)
end
MOI.copy!(dest::AbstractModel, src::MOI.ModelLike; copynames=true) = defaultcopy!(dest, src, copynames)
# Allocate-Load Interface
# Even if the model does not need it and use defaultcopy!, it could be used by a layer that needs it
needsallocateload(model::AbstractModel) = false
allocatevariables!(model::AbstractModel, nvars) = MOI.addvariables!(model, nvars)
allocate!(model::AbstractModel, attr...) = MOI.set!(model, attr...)
canallocate(model::AbstractModel, attr::MOI.AnyAttribute) = MOI.supports(model, attr)
canallocate(model::AbstractModel, attr::MOI.AnyAttribute, IndexType::Type{<:MOI.Index}) = MOI.supports(model, attr, IndexType)
allocateconstraint!(model::AbstractModel, f::MOI.AbstractFunction, s::MOI.AbstractSet) = MOI.addconstraint!(model, f, s)
function loadvariables!(::AbstractModel, nvars) end
function load!(::AbstractModel, attr...) end
canload(model::AbstractModel, attr::MOI.AnyAttribute) = MOI.supports(model, attr)
canload(model::AbstractModel, attr::MOI.AnyAttribute, IndexType::Type{<:MOI.Index}) = MOI.supports(model, attr, IndexType)
function loadconstraint!(::AbstractModel, ::CI, ::MOI.AbstractFunction, ::MOI.AbstractSet) end
# Can be used to access constraints of a model
"""
broadcastcall(f::Function, model::AbstractModel)
Calls `f(contrs)` for every vector `constrs::Vector{ConstraintIndex{F, S}, F, S}` of the model.
# Examples
To add all constraints of the model to a solver `solver`, one can do
```julia
_addcon(solver, ci, f, s) = MOI.addconstraint!(solver, f, s)
function _addcon(solver, constrs::Vector)
for constr in constrs
_addcon(solver, constr...)
end
end
MOIU.broadcastcall(constrs -> _addcon(solver, constrs), model)
```
"""
function broadcastcall end
"""
broadcastvcat(f::Function, model::AbstractModel)
Calls `f(contrs)` for every vector `constrs::Vector{ConstraintIndex{F, S}, F, S}` of the model and concatenate the results with `vcat` (this is used internally for `ListOfConstraints`).
# Examples
To get the list of all functions:
```julia
_getfun(ci, f, s) = f
_getfun(cindices::Tuple) = _getfun(cindices...)
_getfuns(constrs::Vector) = _getfun.(constrs)
MOIU.broadcastvcat(_getfuns, model)
```
"""
function broadcastvcat end
# Macro to generate Model
abstract type Constraints{F} end
abstract type SymbolFS end
struct SymbolFun <: SymbolFS
s::Symbol
typed::Bool
cname::Symbol
end
struct SymbolSet <: SymbolFS
s::Symbol
typed::Bool
end
# QuoteNode prevents s from being interpolated and keeps it as a symbol
# Expr(:., MOI, s) would be MOI.s
# Expr(:., MOI, $s) would be Expr(:., MOI, EqualTo)
# Expr(:., MOI, :($s)) would be Expr(:., MOI, :EqualTo)
# Expr(:., MOI, :($(QuoteNode(s)))) is Expr(:., MOI, :(:EqualTo)) <- what we want
# (MOI, :Zeros) -> :(MOI.Zeros)
_mod(m::Module, s::Symbol) = Expr(:., m, :($(QuoteNode(s))))
# (:Zeros) -> :(MOI.Zeros)
_moi(s::Symbol) = _mod(MOI, s)
_set(s::SymbolSet) = _moi(s.s)
_fun(s::SymbolFun) = _moi(s.s)
function _typedset(s::SymbolSet)
if s.typed
:($(_set(s)){T})
else
_set(s)
end
end
function _typedfun(s::SymbolFun)
if s.typed
:($(_fun(s)){T})
else
_fun(s)
end
end
# Base.lowercase is moved to Unicode.lowercase in Julia v0.7
if VERSION >= v"0.7.0-DEV.2813"
using Unicode
end
_field(s::SymbolFS) = Symbol(lowercase(string(s.s)))
_getC(s::SymbolSet) = :($MOIU.C{F, $(_typedset(s))})
_getC(s::SymbolFun) = _typedfun(s)
_getCV(s::SymbolSet) = :($(_getC(s))[])
_getCV(s::SymbolFun) = :($(s.cname){T, $(_getC(s))}())
_callfield(f, s::SymbolFS) = :($f(model.$(_field(s))))
_broadcastfield(b, s::SymbolFS) = :($b(f, model.$(_field(s))))
"""
macro model(modelname, scalarsets, typedscalarsets, vectorsets, typedvectorsets, scalarfunctions, typedscalarfunctions, vectorfunctions, typedvectorfunctions)
Creates a type `modelname` implementing the MOI model interface and containing `scalarsets` scalar sets `typedscalarsets` typed scalar sets, `vectorsets` vector sets, `typedvectorsets` typed vector sets, `scalarfunctions` scalar functions, `typedscalarfunctions` typed scalar functions, `vectorfunctions` vector functions and `typedvectorfunctions` typed vector functions.
To give no set/function, write `()`, to give one set `S`, write `(S,)`.
This implementation of the MOI model certifies that the constraint indices, in addition to being different between constraints `F`-in-`S` for the same types `F` and `S`,
are also different between constraints for different types `F` and `S`.
This means that for constraint indices `ci1`, `ci2` of this model, `ci1 == ci2` if and only if `ci1.value == ci2.value`.
This fact can be used to use the the value of the index directly in a dictionary representing a mapping between constraint indices and something else.
### Examples
The model describing an linear program would be:
```julia
@model LPModel () (EqualTo, GreaterThan, LessThan, Interval) (Zeros, Nonnegatives, Nonpositives) () (SingleVariable,) (ScalarAffineFunction,) (VectorOfVariables,) (VectorAffineFunction,)
```
Let `MOI` denote `MathOptInterface`, `MOIU` denote `MOI.Utilities` and `MOIU.C{F, S}` be defined as `MOI.Tuple{CI{F, S}, F, S}`.
The macro would create the types:
```julia
struct LPModelScalarConstraints{T, F <: MOI.AbstractScalarFunction} <: MOIU.Constraints{F}
equalto::Vector{MOIU.C{F, MOI.EqualTo{T}}}
greaterthan::Vector{MOIU.C{F, MOI.GreaterThan{T}}}
lessthan::Vector{MOIU.C{F, MOI.LessThan{T}}}
interval::Vector{MOIU.C{F, MOI.Interval{T}}}
end
struct LPModelVectorConstraints{T, F <: MOI.AbstractVectorFunction} <: MOIU.Constraints{F}
zeros::Vector{MOIU.C{F, MOI.Zeros}}
nonnegatives::Vector{MOIU.C{F, MOI.Nonnegatives}}
nonpositives::Vector{MOIU.C{F, MOI.Nonpositives}}
end
mutable struct LPModel{T} <: MOIU.AbstractModel{T}
name::String
sense::MOI.OptimizationSense
objective::Union{MOI.SingleVariable, MOI.ScalarAffineFunction{T}, MOI.ScalarQuadraticFunction{T}}
nextvariableid::Int64
varindices::Set{MOI.VariableIndex}
varnames::Dict{MOI.VariableIndex, String}
namesvar::Dict{String, MOI.VariableIndex}
nextconstraintid::Int64
connames::Dict{MOI.ConstraintIndex, String}
namescon::Dict{String, MOI.ConstraintIndex}
constrmap::Vector{Int}
singlevariable::LPModelScalarConstraints{T, MOI.SingleVariable}
scalaraffinefunction::LPModelScalarConstraints{T, MOI.ScalarAffineFunction{T}}
vectorofvariables::LPModelVectorConstraints{T, MOI.VectorOfVariables}
vectoraffinefunction::LPModelVectorConstraints{T, MOI.VectorAffineFunction{T}}
end
```
The type `LPModel` implements the MathOptInterface API except methods specific to solver models like `optimize!` or `getattribute` with `VariablePrimal`.
"""
macro model(modelname, ss, sst, vs, vst, sf, sft, vf, vft)
scalarsets = [SymbolSet.(ss.args, false); SymbolSet.(sst.args, true)]
vectorsets = [SymbolSet.(vs.args, false); SymbolSet.(vst.args, true)]
scname = Symbol(string(modelname) * "ScalarConstraints")
vcname = Symbol(string(modelname) * "VectorConstraints")
scalarfuns = [SymbolFun.(sf.args, false, scname); SymbolFun.(sft.args, true, scname)]
vectorfuns = [SymbolFun.(vf.args, false, vcname); SymbolFun.(vft.args, true, vcname)]
funs = [scalarfuns; vectorfuns]
scalarconstraints = :(struct $scname{T, F<:$MOI.AbstractScalarFunction} <: $MOIU.Constraints{F}; end)
vectorconstraints = :(struct $vcname{T, F<:$MOI.AbstractVectorFunction} <: $MOIU.Constraints{F}; end)
for (c, sets) in ((scalarconstraints, scalarsets), (vectorconstraints, vectorsets))
for s in sets
field = _field(s)
push!(c.args[3].args, :($field::Vector{$(_getC(s))}))
end
end
modeldef = quote
mutable struct $modelname{T} <: $MOIU.AbstractModel{T}
name::String
senseset::Bool
sense::$MOI.OptimizationSense
objectiveset::Bool
objective::Union{$MOI.SingleVariable, $MOI.ScalarAffineFunction{T}, $MOI.ScalarQuadraticFunction{T}}
nextvariableid::Int64
varindices::Set{$VI}
varnames::Dict{$VI, String}
namesvar::Dict{String, $VI}
nextconstraintid::Int64
connames::Dict{$CI, String}
namescon::Dict{String, $CI}
constrmap::Vector{Int} # Constraint Reference value ci -> index in array in Constraints
end
end
for f in funs
cname = f.cname
field = _field(f)
push!(modeldef.args[2].args[3].args, :($field::$cname{T, $(_getC(f))}))
end
code = quote
function $MOIU.broadcastcall(f::Function, model::$modelname)
$(Expr(:block, _broadcastfield.(Ref(:($MOIU.broadcastcall)), funs)...))
end
function $MOIU.broadcastvcat(f::Function, model::$modelname)
vcat($(_broadcastfield.(Ref(:($MOIU.broadcastvcat)), funs)...))
end
function $MOI.empty!(model::$modelname{T}) where T
model.name = ""
model.senseset = false
model.sense = $MOI.FeasibilitySense
model.objectiveset = false
model.objective = $SAF{T}(MOI.ScalarAffineTerm{T}[], zero(T))
model.nextvariableid = 0
empty!(model.varindices)
empty!(model.varnames)
empty!(model.namesvar)
model.nextconstraintid = 0
empty!(model.connames)
empty!(model.namescon)
empty!(model.constrmap)
$(Expr(:block, _callfield.(Ref(:($MOI.empty!)), funs)...))
end
end
for (cname, sets) in ((scname, scalarsets), (vcname, vectorsets))
code = quote
$code
function $MOIU.broadcastcall(f::Function, model::$cname)
$(Expr(:block, _callfield.(:f, sets)...))
end
function $MOIU.broadcastvcat(f::Function, model::$cname)
vcat($(_callfield.(:f, sets)...))
end
function $MOI.empty!(model::$cname)
$(Expr(:block, _callfield.(Ref(:(Base.empty!)), sets)...))
end
end
end
for (func, T) in ((:_addconstraint!, CI), (:_modify!, CI), (:_delete!, CI), (:_getindex, CI), (:_getfunction, CI), (:_getset, CI), (:_getnoc, MOI.NumberOfConstraints))
funct = _mod(MOIU, func)
for (c, sets) in ((scname, scalarsets), (vcname, vectorsets))
for s in sets
set = _set(s)
field = _field(s)
code = quote
$code
$funct(model::$c, ci::$T{F, <:$set}, args...) where F = $funct(model.$field, ci, args...)
end
end
end
for f in funs
fun = _fun(f)
field = _field(f)
code = quote
$code
$funct(model::$modelname, ci::$T{<:$fun}, args...) = $funct(model.$field, ci, args...)
end
end
end
return esc(quote
$scalarconstraints
function $scname{T, F}() where {T, F}
$scname{T, F}($(_getCV.(scalarsets)...))
end
$vectorconstraints
function $vcname{T, F}() where {T, F}
$vcname{T, F}($(_getCV.(vectorsets)...))
end
$modeldef
function $modelname{T}() where T
$modelname{T}("", false, $MOI.FeasibilitySense, false, $SAF{T}($MOI.ScalarAffineTerm{T}[], zero(T)),
0, Set{$VI}(), Dict{$VI, String}(), Dict{String, $VI}(),
0, Dict{$CI, String}(), Dict{String, $CI}(), Int[],
$(_getCV.(funs)...))
end
$MOI.canget(model::$modelname{T}, ::Union{MOI.ConstraintFunction,
MOI.ConstraintSet}, ::Type{$CI{F, S}}) where {T, F<:Union{$(_typedfun.(scalarfuns)...)},
S<:Union{$(_typedset.(scalarsets)...)}} = true
$MOI.canget(model::$modelname{T}, ::Union{MOI.ConstraintFunction,
MOI.ConstraintSet}, ::Type{$CI{F, S}}) where {T, F<:Union{$(_typedfun.(vectorfuns)...)},
S<:Union{$(_typedset.(vectorsets)...)}} = true
$MOI.supportsconstraint(model::$modelname{T}, ::Type{<:Union{$(_typedfun.(scalarfuns)...)}}, ::Type{<:Union{$(_typedset.(scalarsets)...)}}) where T = true
$MOI.supportsconstraint(model::$modelname{T}, ::Type{<:Union{$(_typedfun.(vectorfuns)...)}}, ::Type{<:Union{$(_typedset.(vectorsets)...)}}) where T = true
$code
end)
end