-
Notifications
You must be signed in to change notification settings - Fork 126
/
simplex.pl
1379 lines (1136 loc) · 45.1 KB
/
simplex.pl
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
/*
Author: Markus Triska
E-mail: [email protected]
WWW: http://www.metalevel.at
Copyright (C): 2005-2022, Markus Triska
Part of Scryer Prolog. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
:- module(simplex,
[
assignment/2,
constraint/3,
constraint/4,
constraint_add/4,
gen_state/1,
maximize/3,
minimize/3,
objective/2,
shadow_price/3,
transportation/4,
variable_value/3
]).
:- use_module(library(assoc)).
:- use_module(library(pio)).
:- use_module(library(lists)).
:- use_module(library(dcgs)).
:- use_module(library(charsio)).
:- use_module(library(format)).
:- use_module(library(between)).
:- use_module(library(atts)).
:- use_module(library(arithmetic)).
/** library(simplex): Solve linear programming problems
This library provides several predicates for solving linear
programming problems with the simplex algorithm, and also includes
efficient algorithms for transportation and assignment problems.
Efficiency could be improved significantly by changing the
implementation to the revised simplex method, benefiting from sparse
matrices.
If you are interested in cooperating on such improvements, please
contact me! Enhancing the performance of this library would be a great
thesis project, for example.
## Introduction {#simplex-intro}
A *linear programming problem* or simply *linear program* (LP)
consists of:
- a set of _linear_ *constraints*
- a set of *variables*
- a _linear_ *objective function*.
The goal is to assign values to the variables so as to _maximize_ (or
minimize) the value of the objective function while satisfying all
constraints.
Many optimization problems can be modeled in this way. As one basic
example, consider a knapsack with fixed capacity C, and a number of
items with sizes `s(i)` and values `v(i)`. The goal is to put as many
items as possible in the knapsack (not exceeding its capacity) while
maximizing the sum of their values.
As another example, suppose you are given a set of _coins_ with
certain values, and you are to find the minimum number of coins such
that their values sum up to a fixed amount. Instances of these
problems are solved below.
Rational arithmetic is used throughout solving linear programs. In
the current implementation, all variables are implicitly constrained
to be _non-negative_. This may change in future versions, and
non-negativity constraints should therefore be stated explicitly.
## Example 1 {#simplex-ex-1}
This is the "radiation therapy" example, taken from _Introduction to
Operations Research_ by Hillier and Lieberman.
[*Prolog DCG notation*](https://www.metalevel.at/prolog/dcg) is
used to _implicitly_ thread the state through posting the constraints:
```
:- use_module(library(simplex)).
:- use_module(library(dcgs)).
radiation(S) :-
gen_state(S0),
post_constraints(S0, S1),
minimize([0.4*x1, 0.5*x2], S1, S).
post_constraints -->
constraint([0.3*x1, 0.1*x2] =< 2.7),
constraint([0.5*x1, 0.5*x2] = 6),
constraint([0.6*x1, 0.4*x2] >= 6),
constraint([x1] >= 0),
constraint([x2] >= 0).
```
An example query:
```
?- radiation(S), variable_value(S, x1, Val1),
variable_value(S, x2, Val2).
S = solved(...), Val1 = 15 rdiv 2, Val2 = 9 rdiv 2.
```
## Example 2 {#simplex-ex-2}
Here is an instance of the knapsack problem described above, where `C
= 8`, and we have two types of items: One item with value 7 and size
6, and 2 items each having size 4 and value 4. We introduce two
variables, `x(1)` and `x(2)` that denote how many items to take of
each type.
```
:- use_module(library(simplex)).
knapsack(S) :-
knapsack_constraints(S0),
maximize([7*x(1), 4*x(2)], S0, S).
knapsack_constraints(S) :-
gen_state(S0),
constraint([6*x(1), 4*x(2)] =< 8, S0, S1),
constraint([x(1)] =< 1, S1, S2),
constraint([x(2)] =< 2, S2, S).
```
An example query yields:
```
?- knapsack(S), variable_value(S, x(1), X1),
variable_value(S, x(2), X2).
S = solved(...), X1 = 1 rdiv 1, X2 = 1 rdiv 2.
```
That is, we are to take the one item of the first type, and half of one of
the items of the other type to maximize the total value of items in the
knapsack.
If items can not be split, integrality constraints have to be imposed:
```
knapsack_integral(S) :-
knapsack_constraints(S0),
constraint(integral(x(1)), S0, S1),
constraint(integral(x(2)), S1, S2),
maximize([7*x(1), 4*x(2)], S2, S).
```
Now the result is different:
```
?- knapsack_integral(S), variable_value(S, x(1), X1),
variable_value(S, x(2), X2).
X1 = 0
X2 = 2
```
That is, we are to take only the _two_ items of the second type.
Notice in particular that always choosing the remaining item with best
performance (ratio of value to size) that still fits in the knapsack
does not necessarily yield an optimal solution in the presence of
integrality constraints.
## Example 3 {#simplex-ex-3}
We are given:
- 3 coins each worth 1 unit
- 20 coins each worth 5 units and
- 10 coins each worth 20 units.
The task is to find a _minimal_ number of these coins that amount to
111 units in total. We introduce variables `c(1)`, `c(5)` and `c(20)`
denoting how many coins to take of the respective type:
```
:- use_module(library(simplex)).
coins(S) :-
gen_state(S0),
coins(S0, S).
coins -->
constraint([c(1), 5*c(5), 20*c(20)] = 111),
constraint([c(1)] =< 3),
constraint([c(5)] =< 20),
constraint([c(20)] =< 10),
constraint([c(1)] >= 0),
constraint([c(5)] >= 0),
constraint([c(20)] >= 0),
constraint(integral(c(1))),
constraint(integral(c(5))),
constraint(integral(c(20))),
minimize([c(1), c(5), c(20)]).
```
An example query:
```
?- coins(S), variable_value(S, c(1), C1),
variable_value(S, c(5), C5),
variable_value(S, c(20), C20).
S = solved(...), C1 = 1 rdiv 1, C5 = 2 rdiv 1, C20 = 5 rdiv 1.
```
@author [Markus Triska](https://www.metalevel.at)
*/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
General Simplex Algorithm
Structures used:
tableau(Objective, Variables, Indicators, Constraints)
*) objective function, represented as row
*) list of variables corresponding to columns
*) indicators denoting which variables are still active
*) constraints as rows
row(Var, Left, Right)
*) the basic variable corresponding to this row
*) coefficients of the left-hand side of the constraint
*) right-hand side of the constraint
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
find_row(Variable, [Row|Rows], R) :-
Row = row(V, _, _),
( V == Variable -> R = Row
; find_row(Variable, Rows, R)
).
%% variable_value(+State, +Variable, -Value)
%
% Value is unified with the value obtained for Variable. State must
% correspond to a solved instance.
variable_value(State, Variable, Value) :-
functor(State, F, _),
( F == solved ->
solved_tableau(State, Tableau),
tableau_rows(Tableau, Rows),
( find_row(Variable, Rows, Row) -> Row = row(_, _, Value)
; Value = 0
)
; F == clpr_solved -> no_clpr
).
no_clpr :- throw(clpr_not_supported).
var_zero(State, _Coeff*Var) :- variable_value(State, Var, 0).
list_first(Ls, F, Index) :- once(nth0(Index, Ls, F)).
%% shadow_price(+State, +Name, -Value)
%
% Unifies Value with the shadow price corresponding to the linear
% constraint whose name is Name. State must correspond to a solved
% instance.
shadow_price(State, Name, Value) :-
functor(State, F, _),
( F == solved ->
solved_tableau(State, Tableau),
tableau_objective(Tableau, row(_,Left,_)),
tableau_variables(Tableau, Variables),
solved_names(State, Names),
memberchk(user(Name)-Var, Names),
list_first(Variables, Var, Nth0),
nth0(Nth0, Left, Value)
; F == clpr_solved -> no_clpr
).
%% objective(+State, -Objective)
%
% Unifies Objective with the result of the objective function at the
% obtained extremum. State must correspond to a solved instance.
objective(State, Obj) :-
functor(State, F, _),
( F == solved ->
solved_tableau(State, Tableau),
tableau_objective(Tableau, Objective),
Objective = row(_, _, Obj)
; no_clpr
).
% interface functions that access tableau components
tableau_objective(tableau(Obj, _, _, _), Obj).
tableau_rows(tableau(_, _, _, Rows), Rows).
tableau_indicators(tableau(_, _, Inds, _), Inds).
tableau_variables(tableau(_, Vars, _, _), Vars).
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
interface functions that access and modify state components
state is a structure of the form
state(Num, Names, Cs, Is)
Num: used to obtain new unique names for slack variables in a side-effect
free way (increased by one and threaded through)
Names: list of Name-Var, correspondence between constraint-names and
names of slack/artificial variables to obtain shadow prices later
Cs: list of constraints
Is: list of integer variables
constraints are initially represented as c(Name, Left, Op, Right),
and after normalizing as c(Var, Left, Right). Name of unnamed constraints
is 0. The distinction is important for merging constraints (mainly in
branch and bound) with existing ones.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
constraint_name(c(Name, _, _, _), Name).
constraint_op(c(_, _, Op, _), Op).
constraint_left(c(_, Left, _, _), Left).
constraint_right(c(_, _, _, Right), Right).
%% gen_state(-State)
%
% Generates an initial state corresponding to an empty linear program.
gen_state(state(0,[],[],[])).
state_add_constraint(C, S0, S) :-
( constraint_name(C, 0), constraint_left(C, [_Coeff*_Var]) ->
state_merge_constraint(C, S0, S)
; state_add_constraint_(C, S0, S)
).
state_add_constraint_(C, state(VID,Ns,Cs,Is), state(VID,Ns,[C|Cs],Is)).
state_merge_constraint(C, S0, S) :-
constraint_left(C, [Coeff0*Var0]),
constraint_right(C, Right0),
constraint_op(C, Op),
( Coeff0 =:= 0 ->
( Op == (=) -> Right0 =:= 0, S0 = S
; Op == (=<) -> S0 = S
; Op == (>=) -> Right0 =:= 0, S0 = S
)
; Coeff0 < 0 -> state_add_constraint_(C, S0, S)
; Right is Right0 rdiv Coeff0,
state_constraints(S0, Cs),
( select(c(0, [1*Var0], Op, CRight), Cs, RestCs) ->
( Op == (=) -> CRight =:= Right, S0 = S
; Op == (=<) ->
NewRight is min(Right, CRight),
NewCs = [c(0, [1*Var0], Op, NewRight)|RestCs],
state_set_constraints(NewCs, S0, S)
; Op == (>=) ->
NewRight is max(Right, CRight),
NewCs = [c(0, [1*Var0], Op, NewRight)|RestCs],
state_set_constraints(NewCs, S0, S)
)
; state_add_constraint_(c(0, [1*Var0], Op, Right), S0, S)
)
).
state_add_name(Name, Var), [state(VID,[Name-Var|Ns],Cs,Is)] -->
[state(VID,Ns,Cs,Is)].
state_add_integral(Var, state(VID,Ns,Cs,Is), state(VID,Ns,Cs,[Var|Is])).
state_constraints(state(_, _, Cs, _), Cs).
state_names(state(_,Names,_,_), Names).
state_integrals(state(_,_,_,Is), Is).
state_set_constraints(Cs, state(VID,Ns,_,Is), state(VID,Ns,Cs,Is)).
state_set_integrals(Is, state(VID,Ns,Cs,_), state(VID,Ns,Cs,Is)).
state_next_var(VarID0), [state(VarID1,Names,Cs,Is)] -->
[state(VarID0,Names,Cs,Is)],
{ VarID1 is VarID0 + 1 }.
solved_tableau(solved(Tableau, _, _), Tableau).
solved_names(solved(_, Names,_), Names).
solved_integrals(solved(_,_,Is), Is).
% User-named constraints are wrapped with user/1 to also allow "0" in
% constraint names.
%% constraint(+Constraint, +S0, -S)
%
% Adds a linear or integrality constraint to the linear program
% corresponding to state S0. A linear constraint is of the form =|Left
% Op C|=, where `Left` is a list of `Coefficient*Variable` terms
% (variables in the context of linear programs can be atoms or
% compound terms) and `C` is a non-negative numeric constant. The list
% represents the sum of its elements. `Op` can be `=`, `=<` or `>=`.
% The coefficient `1` can be omitted. An integrality constraint is of
% the form integral(Variable) and constrains Variable to an integral
% value.
constraint(C, S0, S) :-
functor(S0, F, _),
( F == state ->
( C = integral(Var) -> state_add_integral(Var, S0, S)
; constraint_(0, C, S0, S)
)
; F == clpr_state -> no_clpr
).
%% constraint(+Name, +Constraint, +S0, -S)
%
% Like constraint/3, and attaches the name Name (an atom or compound
% term) to the new constraint.
constraint(Name, C, S0, S) :- constraint_(user(Name), C, S0, S).
constraint_(Name, C, S0, S) :-
functor(S0, F, _),
( F == state ->
( C = integral(Var) -> state_add_integral(Var, S0, S)
; C =.. [Op, Left0, Right0],
coeff_one(Left0, Left),
Right0 >= 0,
number_to_rational(Right0, Right),
state_add_constraint(c(Name, Left, Op, Right), S0, S)
)
; F == clpr_state -> no_clpr
).
%% constraint_add(+Name, +Left, +S0, -S)
%
% Left is a list of `Coefficient*Variable` terms. The terms are added
% to the left-hand side of the constraint named Name. S is unified
% with the resulting state.
constraint_add(Name, A, S0, S) :-
functor(S0, F, _),
( F == state ->
state_constraints(S0, Cs),
add_left(Cs, user(Name), A, Cs1),
state_set_constraints(Cs1, S0, S)
; F == clpr_state -> no_clpr
).
add_left([c(Name,Left0,Op,Right)|Cs], V, A, [c(Name,Left,Op,Right)|Rest]) :-
( Name == V -> append(A, Left0, Left), Rest = Cs
; Left0 = Left, add_left(Cs, V, A, Rest)
).
branching_variable(State, Variable) :-
solved_integrals(State, Integrals),
member(Variable, Integrals),
variable_value(State, Variable, Value),
\+ integer(Value).
worth_investigating(ZStar0, _, _) :- var(ZStar0).
worth_investigating(ZStar0, AllInt, Z) :-
nonvar(ZStar0),
( AllInt =:= 1 -> Z1 is floor(Z)
; Z1 = Z
),
Z1 > ZStar0.
branch_and_bound(Objective, Solved, AllInt, ZStar0, ZStar, S0, S, Found) :-
objective(Solved, Z),
( worth_investigating(ZStar0, AllInt, Z) ->
( branching_variable(Solved, BrVar) ->
variable_value(Solved, BrVar, Value),
Value1 is floor(Value),
Value2 is Value1 + 1,
constraint([BrVar] =< Value1, S0, SubProb1),
( maximize_(Objective, SubProb1, SubSolved1) ->
Sub1Feasible = 1,
objective(SubSolved1, Obj1)
; Sub1Feasible = 0
),
constraint([BrVar] >= Value2, S0, SubProb2),
( maximize_(Objective, SubProb2, SubSolved2) ->
Sub2Feasible = 1,
objective(SubSolved2, Obj2)
; Sub2Feasible = 0
),
( Sub1Feasible =:= 1, Sub2Feasible =:= 1 ->
( Obj1 >= Obj2 ->
First = SubProb1,
Second = SubProb2,
FirstSolved = SubSolved1,
SecondSolved = SubSolved2
; First = SubProb2,
Second = SubProb1,
FirstSolved = SubSolved2,
SecondSolved = SubSolved1
),
branch_and_bound(Objective, FirstSolved, AllInt, ZStar0, ZStar1, First, Solved1, Found1),
branch_and_bound(Objective, SecondSolved, AllInt, ZStar1, ZStar2, Second, Solved2, Found2)
; Sub1Feasible =:= 1 ->
branch_and_bound(Objective, SubSolved1, AllInt, ZStar0, ZStar1, SubProb1, Solved1, Found1),
Found2 = 0
; Sub2Feasible =:= 1 ->
Found1 = 0,
branch_and_bound(Objective, SubSolved2, AllInt, ZStar0, ZStar2, SubProb2, Solved2, Found2)
; Found1 = 0, Found2 = 0
),
( Found1 =:= 1, Found2 =:= 1 -> S = Solved2, ZStar = ZStar2
; Found1 =:= 1 -> S = Solved1, ZStar = ZStar1
; Found2 =:= 1 -> S = Solved2, ZStar = ZStar2
; S = S0, ZStar = ZStar0
),
Found is max(Found1, Found2)
; S = Solved, ZStar = Z, Found = 1
)
; ZStar = ZStar0, S = S0, Found = 0
).
%% maximize(+Objective, +S0, -S)
%
% Maximizes the objective function, stated as a list of
% `Coefficient*Variable` terms that represents the sum of its
% elements, with respect to the linear program corresponding to state
% S0. \arg{S} is unified with an internal representation of the solved
% instance.
maximize(Z0, S0, S) :-
coeff_one(Z0, Z1),
functor(S0, F, _),
( F == state -> maximize_mip(Z1, S0, S)
; F == clpr_state -> no_clpr
).
maximize_mip(Z, S0, S) :-
maximize_(Z, S0, Solved),
state_integrals(S0, Is),
( Is == [] -> S = Solved
; % arrange it so that branch and bound branches on variables
% in the same order the integrality constraints were stated in
reverse(Is, Is1),
state_set_integrals(Is1, S0, S1),
( all_integers(Z, Is1) -> AllInt = 1
; AllInt = 0
),
branch_and_bound(Z, Solved, AllInt, _, _, S1, S, 1)
).
all_integers([], _).
all_integers([Coeff*V|Rest], Is) :-
integer(Coeff),
memberchk(V, Is),
all_integers(Rest, Is).
%% minimize(+Objective, +S0, -S)
%
% Analogous to maximize/3.
minimize(Z0, S0, S) :-
coeff_one(Z0, Z1),
functor(S0, F, _),
( F == state ->
maplist(linsum_negate, Z1, Z2),
maximize_mip(Z2, S0, S1),
solved_tableau(S1, tableau(Obj, Vars, Inds, Rows)),
solved_names(S1, Names),
Obj = row(z, Left0, Right0),
all_times(Left0, -1, Left),
Right is -Right0,
Obj1 = row(z, Left, Right),
state_integrals(S0, Is),
S = solved(tableau(Obj1, Vars, Inds, Rows), Names, Is)
; F == clpr_state -> no_clpr
).
op_pendant(>=, =<).
op_pendant(=<, >=).
constraints_collapse([]) --> [].
constraints_collapse([C|Cs]) -->
{ C = c(Name, Left, Op, Right) },
( { Name == 0, Left = [1*Var], op_pendant(Op, P) } ->
{ Pendant = c(0, [1*Var], P, Right) },
( { select(Pendant, Cs, Rest) } ->
[c(0, Left, (=), Right)],
{ CsLeft = Rest }
; [C],
{ CsLeft = Cs }
)
; [C],
{ CsLeft = Cs }
),
constraints_collapse(CsLeft).
% solve a (relaxed) LP in standard form
maximize_(Z, S0, S) :-
state_constraints(S0, Cs0),
phrase(constraints_collapse(Cs0), Cs1),
phrase(constraints_normalize(Cs1, Cs, As0), [S0], [S1]),
flatten(As0, As1),
( As1 == [] ->
make_tableau(Z, Cs, Tableau0),
simplex(Tableau0, Tableau),
state_names(S1, Names),
state_integrals(S1, Is),
S = solved(Tableau, Names, Is)
; state_names(S1, Names),
state_integrals(S1, Is),
two_phase_simplex(Z, Cs, As1, Names, Is, S)
).
flatten(Lss, Ls) :-
phrase(seqq(Lss), Ls).
make_tableau(Z, Cs, Tableau) :-
ZC = c(_, Z, _),
phrase(constraints_variables([ZC|Cs]), Variables0),
sort(Variables0, Variables),
constraints_rows(Cs, Variables, Rows),
linsum_row(Variables, Z, Objective1),
all_times(Objective1, -1, Obj),
length(Variables, LVs),
length(Ones, LVs),
all_one(Ones),
Tableau = tableau(row(z, Obj, 0), Variables, Ones, Rows).
all_one(Ones) :- maplist(=(1), Ones).
proper_form(Variables, Rows, _Coeff*A, Obj0, Obj) :-
( find_row(A, Rows, PivotRow) ->
list_first(Variables, A, Col),
row_eliminate(Obj0, PivotRow, Col, Obj)
; Obj = Obj0
).
two_phase_simplex(Z, Cs, As, Names, Is, S) :-
% phase 1: minimize sum of articifial variables
make_tableau(As, Cs, Tableau0),
Tableau0 = tableau(Obj0, Variables, Inds, Rows),
foldl(proper_form(Variables, Rows), As, Obj0, Obj),
simplex(tableau(Obj, Variables, Inds, Rows), Tableau1),
maplist(var_zero(solved(Tableau1, _, _)), As),
% phase 2: remove artificial variables and solve actual LP.
tableau_rows(Tableau1, Rows2),
eliminate_artificial(As, As, Variables, Rows2, Rows3),
list_nths(As, Variables, Nths0),
nths_to_zero(Nths0, Inds, Inds1),
linsum_row(Variables, Z, Objective),
all_times(Objective, -1, Objective1),
foldl(proper_form(Variables, Rows3), Z, row(z, Objective1, 0), ObjRow),
simplex(tableau(ObjRow, Variables, Inds1, Rows3), Tableau),
S = solved(Tableau, Names, Is).
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If artificial variables are still in the basis, replace them with
non-artificial variables if possible. If that is not possible, the
constraint is ignored because it is redundant.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
eliminate_artificial([], _, _, Rows, Rows).
eliminate_artificial([_Coeff*A|Rest], As, Variables, Rows0, Rows) :-
( select(row(A, Left, 0), Rows0, Others) ->
( nth0(Col, Left, Coeff),
Coeff =\= 0,
nth0(Col, Variables, Var),
\+ memberchk(_*Var, As) ->
row_divide(row(A, Left, 0), Coeff, Row),
gauss_elimination(Rows0, Row, Col, Rows1),
swap_basic(Rows1, A, Var, Rows2)
; Rows2 = Others
)
; Rows2 = Rows0
),
eliminate_artificial(Rest, As, Variables, Rows2, Rows).
nths_to_zero([], Inds, Inds).
nths_to_zero([Nth|Nths], Inds0, Inds) :-
nth_to_zero(Inds0, 0, Nth, Inds1),
nths_to_zero(Nths, Inds1, Inds).
nth_to_zero([], _, _, []).
nth_to_zero([I|Is], Curr, Nth, [Z|Zs]) :-
( Curr =:= Nth -> [Z|Zs] = [0|Is]
; Z = I,
Next is Curr + 1,
nth_to_zero(Is, Next, Nth, Zs)
).
list_nths([], _, []).
list_nths([_Coeff*A|As], Variables, [Nth|Nths]) :-
list_first(Variables, A, Nth),
list_nths(As, Variables, Nths).
linsum_negate(Coeff0*Var, Coeff*Var) :- Coeff is -Coeff0.
linsum_row([], _, []).
linsum_row([V|Vs], Ls, [C|Cs]) :-
( member(Coeff*V, Ls) -> C = Coeff
; C = 0
),
linsum_row(Vs, Ls, Cs).
constraints_rows([], _, []).
constraints_rows([C|Cs], Vars, [R|Rs]) :-
C = c(Var, Left0, Right),
linsum_row(Vars, Left0, Left),
R = row(Var, Left, Right),
constraints_rows(Cs, Vars, Rs).
constraints_normalize([], [], []) --> [].
constraints_normalize([C0|Cs0], [C|Cs], [A|As]) -->
{ constraint_op(C0, Op),
constraint_left(C0, Left),
constraint_right(C0, Right),
constraint_name(C0, Name),
Con =.. [Op, Left, Right] },
constraint_normalize(Con, Name, C, A),
constraints_normalize(Cs0, Cs, As).
constraint_normalize(As0 =< B0, Name, c(Slack, [1*Slack|As0], B0), []) -->
state_next_var(Slack),
state_add_name(Name, Slack).
constraint_normalize(As0 = B0, Name, c(AID, [1*AID|As0], B0), [-1*AID]) -->
state_next_var(AID),
state_add_name(Name, AID).
constraint_normalize(As0 >= B0, Name, c(AID, [-1*Slack,1*AID|As0], B0), [-1*AID]) -->
state_next_var(Slack),
state_next_var(AID),
state_add_name(Name, AID).
coeff_one([], []).
coeff_one([L|Ls], [Coeff*Var|Rest]) :-
( L = A*B ->
number_to_rational(A, Coeff),
Var = B
; Coeff = 1, Var = L
),
coeff_one(Ls, Rest).
tableau_optimal(Tableau) :-
tableau_objective(Tableau, Objective),
tableau_indicators(Tableau, Indicators),
Objective = row(_, Left, _),
all_nonnegative(Left, Indicators).
all_nonnegative([], []).
all_nonnegative([Coeff|As], [I|Is]) :-
( I =:= 0 -> true
; Coeff >= 0
),
all_nonnegative(As, Is).
pivot_column(Tableau, PCol) :-
tableau_objective(Tableau, row(_, Left, _)),
tableau_indicators(Tableau, Indicators),
first_negative(Left, Indicators, 0, Index0, Val, RestL, RestI),
Index1 is Index0 + 1,
pivot_column(RestL, RestI, Val, Index1, Index0, PCol).
first_negative([L|Ls], [I|Is], Index0, N, Val, RestL, RestI) :-
Index1 is Index0 + 1,
( I =:= 0 -> first_negative(Ls, Is, Index1, N, Val, RestL, RestI)
; ( L < 0 -> N = Index0, Val = L, RestL = Ls, RestI = Is
; first_negative(Ls, Is, Index1, N, Val, RestL, RestI)
)
).
pivot_column([], _, _, _, N, N).
pivot_column([L|Ls], [I|Is], Coeff0, Index0, N0, N) :-
( I =:= 0 -> Coeff1 = Coeff0, N1 = N0
; ( L < Coeff0 -> Coeff1 = L, N1 = Index0
; Coeff1 = Coeff0, N1 = N0
)
),
Index1 is Index0 + 1,
pivot_column(Ls, Is, Coeff1, Index1, N1, N).
pivot_row(Tableau, PCol, PRow) :-
tableau_rows(Tableau, Rows),
pivot_row(Rows, PCol, false, _, 0, 0, PRow).
pivot_row([], _, Bounded, _, _, Row, Row) :- Bounded.
pivot_row([Row|Rows], PCol, Bounded0, Min0, Index0, PRow0, PRow) :-
Row = row(_Var, Left, B),
nth0(PCol, Left, Ae),
( Ae > 0 ->
Bounded1 = true,
Bound is B rdiv Ae,
( Bounded0 ->
( Bound < Min0 -> Min1 = Bound, PRow1 = Index0
; Min1 = Min0, PRow1 = PRow0
)
; Min1 = Bound, PRow1 = Index0
)
; Bounded1 = Bounded0, Min1 = Min0, PRow1 = PRow0
),
Index1 is Index0 + 1,
pivot_row(Rows, PCol, Bounded1, Min1, Index1, PRow1, PRow).
row_divide(row(Var, Left0, Right0), Div, row(Var, Left, Right)) :-
all_divide(Left0, Div, Left),
Right is Right0 rdiv Div.
all_divide([], _, []).
all_divide([R|Rs], Div, [DR|DRs]) :-
DR is R rdiv Div,
all_divide(Rs, Div, DRs).
gauss_elimination([], _, _, []).
gauss_elimination([Row0|Rows0], PivotRow, Col, [Row|Rows]) :-
PivotRow = row(PVar, _, _),
Row0 = row(Var, _, _),
( PVar == Var -> Row = PivotRow
; row_eliminate(Row0, PivotRow, Col, Row)
),
gauss_elimination(Rows0, PivotRow, Col, Rows).
row_eliminate(row(Var, Ls0, R0), row(_, PLs, PR), Col, row(Var, Ls, R)) :-
nth0(Col, Ls0, Coeff),
( Coeff =:= 0 -> Ls = Ls0, R = R0
; MCoeff is -Coeff,
all_times_plus([PR|PLs], MCoeff, [R0|Ls0], [R|Ls])
).
all_times_plus([], _, _, []).
all_times_plus([A|As], T, [B|Bs], [AT|ATs]) :-
AT is A * T + B,
all_times_plus(As, T, Bs, ATs).
all_times([], _, []).
all_times([A|As], T, [AT|ATs]) :-
AT is A * T,
all_times(As, T, ATs).
simplex(Tableau0, Tableau) :-
( tableau_optimal(Tableau0) -> Tableau0 = Tableau
; pivot_column(Tableau0, PCol),
pivot_row(Tableau0, PCol, PRow),
Tableau0 = tableau(Obj0,Variables,Inds,Matrix0),
nth0(PRow, Matrix0, Row0),
Row0 = row(Leaving, Left0, _Right0),
nth0(PCol, Left0, PivotElement),
row_divide(Row0, PivotElement, Row1),
gauss_elimination([Obj0|Matrix0], Row1, PCol, [Obj|Matrix1]),
nth0(PCol, Variables, Entering),
swap_basic(Matrix1, Leaving, Entering, Matrix),
simplex(tableau(Obj,Variables,Inds,Matrix), Tableau)
).
swap_basic([Row0|Rows0], Old, New, Matrix) :-
Row0 = row(Var, Left, Right),
( Var == Old -> Matrix = [row(New, Left, Right)|Rows0]
; Matrix = [Row0|Rest],
swap_basic(Rows0, Old, New, Rest)
).
constraints_variables([]) --> [].
constraints_variables([c(_,Left,_)|Cs]) -->
variables(Left),
constraints_variables(Cs).
variables([]) --> [].
variables([_Coeff*Var|Rest]) --> [Var], variables(Rest).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
A dual algorithm ("algorithm alpha-beta" in Papadimitriou and
Steiglitz) is used for transportation and assignment problems. The
arising max-flow problem is solved with Edmonds-Karp, itself a dual
algorithm.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
An attributed variable is introduced for each node. Attributes:
node: Original name of the node.
edges: arc_to(To,F,Capacity) (F has an attribute "flow") or
arc_from(From,F,Capacity)
parent: used in breadth-first search
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
:- attribute
node/1,
edges/1,
flow/1,
parent/1.
arcs([], Assoc, Assoc).
arcs([arc(From0,To0,C)|As], Assoc0, Assoc) :-
( get_assoc(From0, Assoc0, From) -> Assoc1 = Assoc0
; put_assoc(From0, Assoc0, From, Assoc1),
put_atts(From, node(From0))
),
( get_atts(From, edges(Es)) -> true
; Es = []
),
put_atts(F, flow(0)),
put_atts(From, edges([arc_to(To,F,C)|Es])),
( get_assoc(To0, Assoc1, To) -> Assoc2 = Assoc1
; put_assoc(To0, Assoc1, To, Assoc2),
put_atts(To, node(To0))
),
( get_atts(To, edges(Es1)) -> true
; Es1 = []
),
put_atts(To, edges([arc_from(From,F,C)|Es1])),
arcs(As, Assoc2, Assoc).
edmonds_karp(Arcs0, Arcs) :-
empty_assoc(E),
arcs(Arcs0, E, Assoc),
get_assoc(s, Assoc, S),
get_assoc(t, Assoc, T),
maximum_flow(S, T),
% fetch attvars before deleting visited edges
term_attributed_variables(S, AttVars),
phrase(flow_to_arcs(S), Ls),
arcs_assoc(Ls, Arcs),
maplist(del_attrs, AttVars).
del_attrs(V) :-
put_atts(V, [-node(_),-edges(_),-flow(_),-parent(_)]).
flow_to_arcs(V) -->
( { get_atts(V, edges(Es)) } ->
{ put_atts(V, -edges(_)),
get_atts(V, node(Name)) },
flow_to_arcs_(Es, Name)
; []
).
flow_to_arcs_([], _) --> [].
flow_to_arcs_([E|Es], Name) -->
edge_to_arc(E, Name),
flow_to_arcs_(Es, Name).
edge_to_arc(arc_from(_,_,_), _) --> [].
edge_to_arc(arc_to(To,F,C), Name) -->
{ get_atts(To, node(NTo)),
get_atts(F, flow(Flow)) },
[arc(Name,NTo,Flow,C)],
flow_to_arcs(To).
arcs_assoc(Arcs, Hash) :-
empty_assoc(E),
arcs_assoc(Arcs, E, Hash).
arcs_assoc([], Hs, Hs).
arcs_assoc([arc(From,To,F,C)|Rest], Hs0, Hs) :-
( get_assoc(From, Hs0, As) -> Hs1 = Hs0
; put_assoc(From, Hs0, [], Hs1),
empty_assoc(As)
),
put_assoc(To, As, arc(From,To,F,C), As1),
put_assoc(From, Hs1, As1, Hs2),
arcs_assoc(Rest, Hs2, Hs).
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Strategy: Breadth-first search until we find a free right vertex in