-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClSimplexSolver.java
1197 lines (1060 loc) · 40 KB
/
ClSimplexSolver.java
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
// $Id$
//
// Cassowary Incremental Constraint Solver
// Original Smalltalk Implementation by Alan Borning
// This Java Implementation by Greg J. Badros, <[email protected]>
// http://www.cs.washington.edu/homes/gjb
// (C) 1998, 1999 Greg J. Badros and Alan Borning
// See ../LICENSE for legal details regarding this software
//
// ClSimplexSolver
//
package EDU.Washington.grad.gjb.cassowary;
import java.util.*;
public class ClSimplexSolver extends ClTableau
{
// Ctr initializes the fields, and creates the objective row
public ClSimplexSolver()
{
_stayMinusErrorVars = new Vector();
_stayPlusErrorVars = new Vector();
_errorVars = new Hashtable();
_markerVars = new Hashtable();
_resolve_pair = new Vector(2);
_resolve_pair.addElement(new ClDouble(0));
_resolve_pair.addElement(new ClDouble(0));
_objective = new ClObjectiveVariable("Z");
_editVarMap = new Hashtable();
_slackCounter = 0;
_artificialCounter = 0;
_dummyCounter = 0;
_epsilon = 1e-8;
_fOptimizeAutomatically = true;
_fNeedsSolving = false;
ClLinearExpression e = new ClLinearExpression();
_rows.put(_objective,e);
_stkCedcns = new Stack();
_stkCedcns.push(new Integer(0));
if (fTraceOn) traceprint("objective expr == " + rowExpression(_objective));
}
// Convenience function for creating a linear inequality constraint
public final ClSimplexSolver addLowerBound(ClAbstractVariable v, double lower)
throws ExCLRequiredFailure, ExCLInternalError
{
ClLinearInequality cn =
new ClLinearInequality(v,CL.GEQ,new ClLinearExpression(lower));
return addConstraint(cn);
}
// Convenience function for creating a linear inequality constraint
public final ClSimplexSolver addUpperBound(ClAbstractVariable v, double upper)
throws ExCLRequiredFailure, ExCLInternalError
{
ClLinearInequality cn =
new ClLinearInequality(v,CL.LEQ,new ClLinearExpression(upper));
return addConstraint(cn);
}
// Convenience function for creating a pair of linear inequality constraint
public final ClSimplexSolver addBounds(ClAbstractVariable v,
double lower, double upper)
throws ExCLRequiredFailure, ExCLInternalError
{ addLowerBound(v,lower); addUpperBound(v,upper); return this; }
// Add constraint "cn" to the solver
public final ClSimplexSolver addConstraint(ClConstraint cn)
throws ExCLRequiredFailure, ExCLInternalError
{
if (fTraceOn) fnenterprint("addConstraint: " + cn);
Vector eplus_eminus = new Vector(2);
ClDouble prevEConstant = new ClDouble();
ClLinearExpression expr = newExpression(cn, /* output to: */
eplus_eminus,
prevEConstant);
boolean fAddedOkDirectly = false;
try {
fAddedOkDirectly = tryAddingDirectly(expr);
if (!fAddedOkDirectly) {
// could not add directly
addWithArtificialVariable(expr);
}
} catch (ExCLRequiredFailure err) {
///try {
/// removeConstraint(cn); // FIXGJB
// } catch (ExCLConstraintNotFound errNF) {
// This should not possibly happen
/// System.err.println("ERROR: could not find a constraint just added\n");
///}
throw err;
}
_fNeedsSolving = true;
if (cn.isEditConstraint()) {
int i = _editVarMap.size();
ClEditConstraint cnEdit = (ClEditConstraint) cn;
ClSlackVariable clvEplus = (ClSlackVariable) eplus_eminus.elementAt(0);
ClSlackVariable clvEminus = (ClSlackVariable) eplus_eminus.elementAt(1);
_editVarMap.put(cnEdit.variable(),
new ClEditInfo(cnEdit,clvEplus,clvEminus,
prevEConstant.doubleValue(),
i));
}
if (_fOptimizeAutomatically) {
optimize(_objective);
setExternalVariables();
}
cn.addedTo(this);
return this;
}
// Same as addConstraint, except returns false if the constraint
// resulted in an unsolvable system (instead of throwing an exception)
public final boolean addConstraintNoException(ClConstraint cn)
throws ExCLInternalError
{
if (fTraceOn) fnenterprint("addConstraintNoException: " + cn);
try
{
addConstraint(cn);
return true;
}
catch (ExCLRequiredFailure e)
{
return false;
}
}
// Add an edit constraint for "v" with given strength
public final ClSimplexSolver addEditVar(ClVariable v, ClStrength strength)
throws ExCLInternalError
{
try
{
ClEditConstraint cnEdit = new ClEditConstraint(v, strength);
return addConstraint(cnEdit);
}
catch (ExCLRequiredFailure e)
{
// should not get this
throw new ExCLInternalError("Required failure when adding an edit variable");
}
}
// default to strength = strong
public final ClSimplexSolver addEditVar(ClVariable v)
throws ExCLInternalError
{ return addEditVar(v, ClStrength.strong); }
// Remove the edit constraint previously added for variable v
public final ClSimplexSolver removeEditVar(ClVariable v)
throws ExCLInternalError, ExCLConstraintNotFound
{
ClEditInfo cei = (ClEditInfo) _editVarMap.get(v);
ClConstraint cn = cei.Constraint();
removeConstraint(cn);
return this;
}
// beginEdit() should be called before sending
// resolve() messages, after adding the appropriate edit variables
public final ClSimplexSolver beginEdit()
throws ExCLInternalError
{
assert(_editVarMap.size() > 0,"_editVarMap.size() > 0");
// may later want to do more in here
_infeasibleRows.clear();
resetStayConstants();
_stkCedcns.addElement(new Integer(_editVarMap.size()));
return this;
}
// endEdit should be called after editing has finished
// for now, it just removes all edit variables
public final ClSimplexSolver endEdit()
throws ExCLInternalError
{
assert(_editVarMap.size() > 0,"_editVarMap.size() > 0");
resolve();
_stkCedcns.pop();
int n = ((Integer)_stkCedcns.peek()).intValue();
removeEditVarsTo(n);
// may later want to do more in here
return this;
}
// removeAllEditVars() just eliminates all the edit constraints
// that were added
public final ClSimplexSolver removeAllEditVars()
throws ExCLInternalError
{ return removeEditVarsTo(0); }
// remove the last added edit vars to leave only n edit vars left
public final ClSimplexSolver removeEditVarsTo(int n)
throws ExCLInternalError
{
try
{
for (Enumeration e = _editVarMap.keys(); e.hasMoreElements() ; ) {
ClVariable v = (ClVariable) e.nextElement();
ClEditInfo cei = (ClEditInfo) _editVarMap.get(v);
if (cei.Index() >= n) {
removeEditVar(v);
}
}
assert(_editVarMap.size() == n, "_editVarMap.size() == n");
return this;
}
catch (ExCLConstraintNotFound e)
{
// should not get this
throw new ExCLInternalError("Constraint not found in removeEditVarsTo");
}
}
// Add weak stays to the x and y parts of each point. These have
// increasing weights so that the solver will try to satisfy the x
// and y stays on the same point, rather than the x stay on one and
// the y stay on another.
public final ClSimplexSolver addPointStays(Vector listOfPoints)
throws ExCLRequiredFailure, ExCLInternalError
{
if (fTraceOn) fnenterprint("addPointStays" + listOfPoints);
double weight = 1.0;
final double multiplier = 2.0;
for (int i = 0; i < listOfPoints.size(); i++) {
addPointStay((ClPoint) listOfPoints.elementAt(i),weight);
weight *= multiplier;
}
return this;
}
public final ClSimplexSolver addPointStay(ClVariable vx,
ClVariable vy,
double weight)
throws ExCLRequiredFailure, ExCLInternalError
{
addStay(vx,ClStrength.weak,weight);
addStay(vy,ClStrength.weak,weight);
return this;
}
public final ClSimplexSolver addPointStay(ClVariable vx,
ClVariable vy)
throws ExCLRequiredFailure, ExCLInternalError
{ addPointStay(vx,vy,1.0); return this; }
public final ClSimplexSolver addPointStay(ClPoint clp, double weight)
throws ExCLRequiredFailure, ExCLInternalError
{
addStay(clp.X(),ClStrength.weak,weight);
addStay(clp.Y(),ClStrength.weak,weight);
return this;
}
public final ClSimplexSolver addPointStay(ClPoint clp)
throws ExCLRequiredFailure, ExCLInternalError
{
addPointStay(clp,1.0);
return this;
}
// Add a stay of the given strength (default to weak) of v to the tableau
public final ClSimplexSolver addStay(ClVariable v,
ClStrength strength,
double weight)
throws ExCLRequiredFailure, ExCLInternalError
{
ClStayConstraint cn = new ClStayConstraint(v,strength,weight);
return addConstraint(cn);
}
// default to weight == 1.0
public final ClSimplexSolver addStay(ClVariable v,
ClStrength strength)
throws ExCLRequiredFailure, ExCLInternalError
{
addStay(v,strength,1.0); return this;
}
// default to strength = weak
public final ClSimplexSolver addStay(ClVariable v)
throws ExCLRequiredFailure, ExCLInternalError
{
addStay(v,ClStrength.weak,1.0); return this;
}
public ClSimplexSolver removeConstraint(ClConstraint cn)
throws ExCLConstraintNotFound, ExCLInternalError
{
removeConstraintInternal(cn);
cn.removedFrom(this);
return this;
}
// Remove the constraint cn from the tableau
// Also remove any error variable associated with cn
private final ClSimplexSolver removeConstraintInternal(ClConstraint cn)
throws ExCLConstraintNotFound, ExCLInternalError
{
if (fTraceOn) fnenterprint("removeConstraint: " + cn);
if (fTraceOn) traceprint(this.toString());
_fNeedsSolving = true;
resetStayConstants();
ClLinearExpression zRow = rowExpression(_objective);
Set eVars = (Set) _errorVars.get(cn);
if (fTraceOn) traceprint("eVars == " + eVars);
if (eVars != null) {
for (Enumeration e = eVars.elements(); e.hasMoreElements() ; ) {
ClAbstractVariable clv = (ClAbstractVariable) e.nextElement();
final ClLinearExpression expr = rowExpression(clv);
if (expr == null ) {
zRow.addVariable(clv, -cn.weight() *
cn.strength().symbolicWeight().asDouble(),
_objective, this);
} else { // the error variable was in the basis
zRow.addExpression(expr, -cn.weight() *
cn.strength().symbolicWeight().asDouble(),
_objective, this);
}
}
}
ClAbstractVariable marker = (ClAbstractVariable) _markerVars.remove(cn);
if (marker == null) {
throw new ExCLConstraintNotFound();
}
if (fTraceOn) traceprint("Looking to remove var " + marker);
if (rowExpression(marker) == null ) {
// not in the basis, so need to do some work
Set col = (Set) _columns.get(marker);
if (fTraceOn) traceprint("Must pivot -- columns are " + col);
ClAbstractVariable exitVar = null;
double minRatio = 0.0;
for (Enumeration e = col.elements(); e.hasMoreElements() ; ) {
final ClAbstractVariable v = (ClAbstractVariable) e.nextElement();
if (v.isRestricted() ) {
final ClLinearExpression expr = rowExpression( v);
double coeff = expr.coefficientFor(marker);
if (fTraceOn) traceprint("Marker " + marker + "'s coefficient in " + expr + " is " + coeff);
if (coeff < 0.0) {
double r = -expr.constant() / coeff;
// Bland's anti-cycling rule:
// if multiple variables are about the same,
// always pick the lowest via some total
// ordering -- I use their hash codes
if (exitVar == null || r < minRatio ||
(CL.approx(r,minRatio) && v.hashCode() < exitVar.hashCode())) {
minRatio = r;
exitVar = v;
}
}
}
}
if (exitVar == null ) {
if (fTraceOn) traceprint("exitVar is still null");
for (Enumeration e = col.elements(); e.hasMoreElements() ; ) {
final ClAbstractVariable v = (ClAbstractVariable) e.nextElement();
if (v.isRestricted() ) {
final ClLinearExpression expr = rowExpression(v);
double coeff = expr.coefficientFor(marker);
double r = expr.constant() / coeff;
if (exitVar == null || r < minRatio) {
minRatio = r;
exitVar = v;
}
}
}
}
if (exitVar == null) {
// exitVar is still null
if (col.size() == 0) {
removeColumn(marker);
} else {
// exitVar = (ClAbstractVariable) col.elements().nextElement();
// was the above; instead, let's be sure we do not
// pick the objective --01/07/01 gjb
for (Enumeration e = col.elements(); e.hasMoreElements(); ) {
ClAbstractVariable v = (ClAbstractVariable) e.nextElement();
if (v != _objective) {
exitVar = v;
break;
}
}
}
}
if (exitVar != null) {
pivot(marker, exitVar);
}
}
if (rowExpression(marker) != null ) {
ClLinearExpression expr = removeRow(marker);
expr = null;
}
if (eVars != null) {
for (Enumeration e = eVars.elements(); e.hasMoreElements(); ) {
ClAbstractVariable v = (ClAbstractVariable) e.nextElement();
// FIXGJBNOW != or equals?
if ( v != marker ) {
removeColumn(v);
v = null;
}
}
}
if (cn.isStayConstraint()) {
if (eVars != null) {
for (int i = 0; i < _stayPlusErrorVars.size(); i++) {
eVars.remove(_stayPlusErrorVars.elementAt(i));
eVars.remove(_stayMinusErrorVars.elementAt(i));
}
}
} else if (cn.isEditConstraint()) {
assert(eVars != null,"eVars != null");
ClEditConstraint cnEdit = (ClEditConstraint) cn;
ClVariable clv = cnEdit.variable();
ClEditInfo cei = (ClEditInfo) _editVarMap.get(clv);
ClSlackVariable clvEditMinus = cei.ClvEditMinus();
// ClSlackVariable clvEditPlus = cei.ClvEditPlus();
// the clvEditPlus is a marker variable that is removed elsewhere
removeColumn( clvEditMinus );
_editVarMap.remove(clv);
}
// FIXGJB do the remove at top
if (eVars != null) {
_errorVars.remove(eVars);
}
marker = null;
if (_fOptimizeAutomatically) {
optimize(_objective);
setExternalVariables();
}
return this;
}
// Re-initialize this solver from the original constraints, thus
// getting rid of any accumulated numerical problems. (Actually, we
// haven't definitely observed any such problems yet)
public final void reset()
throws ExCLInternalError
{
if (fTraceOn) fnenterprint("reset");
throw new ExCLInternalError("reset not implemented");
}
// Re-solve the current collection of constraints for new values for
// the constants of the edit variables.
// DEPRECATED: use suggestValue(...) then resolve()
// If you must use this, be sure to not use it if you
// remove an edit variable (or edit constraint) from the middle
// of a list of edits and then try to resolve with this function
// (you'll get the wrong answer, because the indices will be wrong
// in the ClEditInfo objects)
public final void resolve(Vector newEditConstants)
throws ExCLInternalError
{
if (fTraceOn) fnenterprint("resolve" + newEditConstants);
for (Enumeration e = _editVarMap.keys(); e.hasMoreElements() ; ) {
ClVariable v = (ClVariable) e.nextElement();
ClEditInfo cei = (ClEditInfo) _editVarMap.get(v);
int i = cei.Index();
try {
if (i < newEditConstants.size())
suggestValue(v,((ClDouble) newEditConstants.elementAt(i))
.doubleValue());
} catch (ExCLError err) {
throw new ExCLInternalError("Error during resolve");
}
}
resolve();
}
// Convenience function for resolve-s of two variables
public final void resolve(double x, double y)
throws ExCLInternalError
{
((ClDouble) _resolve_pair.elementAt(0)).setValue(x);
((ClDouble) _resolve_pair.elementAt(1)).setValue(y);
resolve(_resolve_pair);
}
// Re-solve the cuurent collection of constraints, given the new
// values for the edit variables that have already been
// suggested (see suggestValue() method)
public final void resolve()
throws ExCLInternalError
{
if (fTraceOn) fnenterprint("resolve()");
dualOptimize();
setExternalVariables();
_infeasibleRows.clear();
resetStayConstants();
}
// Suggest a new value for an edit variable
// the variable needs to be added as an edit variable
// and beginEdit() needs to be called before this is called.
// The tableau will not be solved completely until
// after resolve() has been called
public final ClSimplexSolver suggestValue(ClVariable v, double x)
throws ExCLError
{
if (fTraceOn) fnenterprint("suggestValue(" + v + ", " + x + ")");
ClEditInfo cei = (ClEditInfo) _editVarMap.get(v);
if (cei == null) {
System.err.println("suggestValue for variable " + v + ", but var is not an edit variable\n");
throw new ExCLError();
}
int i = cei.Index();
ClSlackVariable clvEditPlus = cei.ClvEditPlus();
ClSlackVariable clvEditMinus = cei.ClvEditMinus();
double delta = x - cei.PrevEditConstant();
cei.SetPrevEditConstant(x);
deltaEditConstant(delta, clvEditPlus, clvEditMinus);
return this;
}
// Control whether optimization and setting of external variables
// is done automatically or not. By default it is done
// automatically and solve() never needs to be explicitly
// called by client code; if setAutosolve is put to false,
// then solve() needs to be invoked explicitly before using
// variables' values
// (Turning off autosolve while adding lots and lots of
// constraints [ala the addDel test in ClTests] saved
// about 20% in runtime, from 68sec to 54sec for 900 constraints,
// with 126 failed adds)
public final ClSimplexSolver setAutosolve(boolean f)
{ _fOptimizeAutomatically = f; return this; }
// Tell whether we are autosolving
public final boolean FIsAutosolving()
{ return _fOptimizeAutomatically; }
// If autosolving has been turned off, client code needs
// to explicitly call solve() before accessing variables
// values
public final ClSimplexSolver solve()
throws ExCLInternalError
{
if (_fNeedsSolving) {
optimize(_objective);
setExternalVariables();
}
return this;
}
public ClSimplexSolver setEditedValue(ClVariable v, double n)
throws ExCLInternalError
{
if (!FContainsVariable(v)) {
v.change_value(n);
return this;
}
if (!CL.approx(n, v.value())) {
addEditVar(v);
beginEdit();
try {
suggestValue(v,n);
} catch (ExCLError e) {
// just added it above, so we shouldn't get an error
throw new ExCLInternalError("Error in setEditedValue");
}
endEdit();
}
return this;
}
public final boolean FContainsVariable(ClVariable v)
throws ExCLInternalError
{
return columnsHasKey(v) || (rowExpression(v) != null);
}
public ClSimplexSolver addVar(ClVariable v)
throws ExCLInternalError
{
if (!FContainsVariable(v)) {
try {
addStay(v);
} catch (ExCLRequiredFailure e) {
// cannot have a required failure, since we add w/ weak
throw new ExCLInternalError("Error in addVar -- required failure is impossible");
}
if (fTraceOn) { traceprint("added initial stay on " + v); }
}
return this;
}
// Originally from Michael Noth <noth@cs>
public final String getInternalInfo() {
StringBuffer retstr = new StringBuffer(super.getInternalInfo());
retstr.append("\nSolver info:\n");
retstr.append("Stay Error Variables: ");
retstr.append(_stayPlusErrorVars.size() + _stayMinusErrorVars.size());
retstr.append(" (" + _stayPlusErrorVars.size() + " +, ");
retstr.append(_stayMinusErrorVars.size() + " -)\n");
retstr.append("Edit Variables: " + _editVarMap.size());
retstr.append("\n");
return retstr.toString();
}
public final String getDebugInfo() {
StringBuffer bstr = new StringBuffer(toString());
bstr.append(getInternalInfo());
bstr.append("\n");
return bstr.toString();
}
public final String toString()
{
StringBuffer bstr = new StringBuffer(super.toString());
bstr.append("\n_stayPlusErrorVars: ");
bstr.append(_stayPlusErrorVars);
bstr.append("\n_stayMinusErrorVars: ");
bstr.append(_stayMinusErrorVars);
bstr.append("\n");
return bstr.toString();
}
public Hashtable getConstraintMap()
{ return _markerVars; }
//// END PUBLIC INTERFACE
// Add the constraint expr=0 to the inequality tableau using an
// artificial variable. To do this, create an artificial variable
// av and add av=expr to the inequality tableau, then make av be 0.
// (Raise an exception if we can't attain av=0.)
protected final void addWithArtificialVariable(ClLinearExpression expr)
throws ExCLRequiredFailure, ExCLInternalError
{
if (fTraceOn) fnenterprint("addWithArtificialVariable: " + expr);
ClSlackVariable av = new ClSlackVariable(++_artificialCounter,"a");
ClObjectiveVariable az = new ClObjectiveVariable("az");
ClLinearExpression azRow = (ClLinearExpression) expr.clone();
if (fTraceOn) traceprint("before addRows:\n" + this);
addRow( az, azRow);
addRow( av, expr);
if (fTraceOn) traceprint("after addRows:\n" + this);
optimize(az);
ClLinearExpression azTableauRow = rowExpression(az);
if (fTraceOn) traceprint("azTableauRow.constant() == " + azTableauRow.constant());
if (!CL.approx(azTableauRow.constant(),0.0)) {
removeRow(az);
removeColumn(av);
throw new ExCLRequiredFailure();
}
// See if av is a basic variable
final ClLinearExpression e = rowExpression(av);
if (e != null ) {
// find another variable in this row and pivot,
// so that av becomes parametric
if (e.isConstant()) {
// if there isn't another variable in the row
// then the tableau contains the equation av=0 --
// just delete av's row
removeRow(av);
removeRow(az);
return;
}
ClAbstractVariable entryVar = e.anyPivotableVariable();
pivot( entryVar, av);
}
assert(rowExpression(av) == null, "rowExpression(av) == null");
removeColumn(av);
removeRow(az);
}
// We are trying to add the constraint expr=0 to the appropriate
// tableau. Try to add expr directly to the tableax without
// creating an artificial variable. Return true if successful and
// false if not.
protected final boolean tryAddingDirectly(ClLinearExpression expr)
throws ExCLRequiredFailure
{
if (fTraceOn) fnenterprint("tryAddingDirectly: " + expr );
final ClAbstractVariable subject = chooseSubject(expr);
if (subject == null ) {
if (fTraceOn) fnexitprint("returning false");
return false;
}
expr.newSubject( subject);
if (columnsHasKey( subject)) {
substituteOut( subject,expr);
}
addRow( subject,expr);
if (fTraceOn) fnexitprint("returning true");
return true; // successfully added directly
}
// We are trying to add the constraint expr=0 to the tableaux. Try
// to choose a subject (a variable to become basic) from among the
// current variables in expr. If expr contains any unrestricted
// variables, then we must choose an unrestricted variable as the
// subject. Also, if the subject is new to the solver we won't have
// to do any substitutions, so we prefer new variables to ones that
// are currently noted as parametric. If expr contains only
// restricted variables, if there is a restricted variable with a
// negative coefficient that is new to the solver we can make that
// the subject. Otherwise we can't find a subject, so return nil.
// (In this last case we have to add an artificial variable and use
// that variable as the subject -- this is done outside this method
// though.)
//
// Note: in checking for variables that are new to the solver, we
// ignore whether a variable occurs in the objective function, since
// new slack variables are added to the objective function by
// 'newExpression:', which is called before this method.
protected final ClAbstractVariable chooseSubject(ClLinearExpression expr)
throws ExCLRequiredFailure
{
if (fTraceOn) fnenterprint("chooseSubject: " + expr);
ClAbstractVariable subject = null; // the current best subject, if any
boolean foundUnrestricted = false;
boolean foundNewRestricted = false;
final Hashtable terms = expr.terms();
for (Enumeration e = terms.keys(); e.hasMoreElements() ; ) {
final ClAbstractVariable v = (ClAbstractVariable) e.nextElement();
final double c = ((ClDouble) terms.get(v)).doubleValue();
if (foundUnrestricted){
if (!v.isRestricted()) {
if (!columnsHasKey(v))
return v;
}
} else {
// we haven't found an restricted variable yet
if (v.isRestricted()) {
if (!foundNewRestricted && !v.isDummy() && c < 0.0) {
final Set col = (Set) _columns.get(v);
if (col == null ||
( col.size() == 1 && columnsHasKey(_objective) ) ) {
subject = v;
foundNewRestricted = true;
}
}
} else {
subject = v;
foundUnrestricted = true;
}
}
}
if (subject != null)
return subject;
double coeff = 0.0;
for (Enumeration e = terms.keys(); e.hasMoreElements() ;) {
final ClAbstractVariable v = (ClAbstractVariable) e.nextElement();
final double c = ((ClDouble) terms.get(v)).doubleValue();
if (!v.isDummy())
return null; // nope, no luck
if (!columnsHasKey(v)) {
subject = v;
coeff = c;
}
}
if (!CL.approx(expr.constant(),0.0)) {
throw new ExCLRequiredFailure();
}
if (coeff > 0.0) {
expr.multiplyMe(-1);
}
return subject;
}
// Each of the non-required edits will be represented by an equation
// of the form
// v = c + eplus - eminus
// where v is the variable with the edit, c is the previous edit
// value, and eplus and eminus are slack variables that hold the
// error in satisfying the edit constraint. We are about to change
// something, and we want to fix the constants in the equations
// representing the edit constraints. If one of eplus and eminus is
// basic, the other must occur only in the expression for that basic
// error variable. (They can't both be basic.) Fix the constant in
// this expression. Otherwise they are both nonbasic. Find all of
// the expressions in which they occur, and fix the constants in
// those. See the UIST paper for details.
// (This comment was for resetEditConstants(), but that is now
// gone since it was part of the screwey vector-based interface
// to resolveing. --02/16/99 gjb)
protected final void deltaEditConstant(double delta,
ClAbstractVariable plusErrorVar,
ClAbstractVariable minusErrorVar)
{
if (fTraceOn) fnenterprint("deltaEditConstant :" + delta + ", " + plusErrorVar + ", " + minusErrorVar);
ClLinearExpression exprPlus = rowExpression(plusErrorVar);
if (exprPlus != null ) {
exprPlus.incrementConstant(delta);
if (exprPlus.constant() < 0.0) {
_infeasibleRows.insert(plusErrorVar);
}
return;
}
ClLinearExpression exprMinus = rowExpression(minusErrorVar);
if (exprMinus != null) {
exprMinus.incrementConstant(-delta);
if (exprMinus.constant() < 0.0) {
_infeasibleRows.insert(minusErrorVar);
}
return;
}
Set columnVars = (Set) _columns.get(minusErrorVar);
for (Enumeration e = columnVars.elements(); e.hasMoreElements() ; ) {
final ClAbstractVariable basicVar = (ClAbstractVariable) e.nextElement();
ClLinearExpression expr = rowExpression(basicVar);
//assert(expr != null, "expr != null" );
final double c = expr.coefficientFor(minusErrorVar);
expr.incrementConstant(c * delta);
if (basicVar.isRestricted() && expr.constant() < 0.0) {
_infeasibleRows.insert(basicVar);
}
}
}
// We have set new values for the constants in the edit constraints.
// Re-optimize using the dual simplex algorithm.
protected final void dualOptimize()
throws ExCLInternalError
{
if (fTraceOn) fnenterprint("dualOptimize:");
final ClLinearExpression zRow = rowExpression(_objective);
while (!_infeasibleRows.isEmpty()) {
ClAbstractVariable exitVar =
(ClAbstractVariable) _infeasibleRows.elements().nextElement();
_infeasibleRows.remove(exitVar);
ClAbstractVariable entryVar = null;
ClLinearExpression expr = rowExpression(exitVar);
if (expr != null ) {
if (expr.constant() < 0.0) {
double ratio = Double.MAX_VALUE;
double r;
Hashtable terms = expr.terms();
for (Enumeration e = terms.keys(); e.hasMoreElements() ; ) {
ClAbstractVariable v = (ClAbstractVariable) e.nextElement();
double c = ((ClDouble)terms.get(v)).doubleValue();
if (c > 0.0 && v.isPivotable()) {
double zc = zRow.coefficientFor(v);
r = zc/c; // FIXGJB r:= zc/c or zero, as ClSymbolicWeight-s
if (r < ratio ||
(CL.approx(r,ratio) && v.hashCode() < entryVar.hashCode())) {
entryVar = v;
ratio = r;
}
}
}
if (ratio == Double.MAX_VALUE) {
throw new ExCLInternalError("ratio == nil (MAX_VALUE) in dualOptimize");
}
pivot( entryVar, exitVar);
}
}
}
}
// Make a new linear expression representing the constraint cn,
// replacing any basic variables with their defining expressions.
// Normalize if necessary so that the constant is non-negative. If
// the constraint is non-required give its error variables an
// appropriate weight in the objective function.
protected final ClLinearExpression newExpression(ClConstraint cn,
Vector eplus_eminus,
ClDouble prevEConstant)
{
if (fTraceOn) fnenterprint("newExpression: " + cn);
if (fTraceOn) traceprint("cn.isInequality() == " + cn.isInequality());
if (fTraceOn) traceprint("cn.isRequired() == " + cn.isRequired());
final ClLinearExpression cnExpr = cn.expression();
ClLinearExpression expr = new ClLinearExpression(cnExpr.constant());
ClSlackVariable slackVar = new ClSlackVariable();
ClDummyVariable dummyVar = new ClDummyVariable();
ClSlackVariable eminus = new ClSlackVariable();
ClSlackVariable eplus = new ClSlackVariable();
final Hashtable cnTerms = cnExpr.terms();
for (Enumeration en = cnTerms.keys(); en.hasMoreElements(); ) {
final ClAbstractVariable v = (ClAbstractVariable) en.nextElement();
double c = ((ClDouble) cnTerms.get(v)).doubleValue();
final ClLinearExpression e = rowExpression(v);
if (e == null)
expr.addVariable(v,c);
else
expr.addExpression(e,c);
}
if (cn.isInequality()) {
++_slackCounter;
slackVar = new ClSlackVariable (_slackCounter, "s");
expr.setVariable(slackVar,-1);
_markerVars.put(cn,slackVar);
if (!cn.isRequired()) {
++_slackCounter;
eminus = new ClSlackVariable(_slackCounter, "em");
expr.setVariable(eminus,1.0);
ClLinearExpression zRow = rowExpression(_objective);
ClSymbolicWeight sw = cn.strength().symbolicWeight().times(cn.weight());
zRow.setVariable( eminus,sw.asDouble());
insertErrorVar(cn,eminus);
noteAddedVariable(eminus,_objective);
}
}
else {
// cn is an equality
if (cn.isRequired()) {
++_dummyCounter;
dummyVar = new ClDummyVariable(_dummyCounter, "d");
expr.setVariable(dummyVar,1.0);
_markerVars.put(cn,dummyVar);
if (fTraceOn) traceprint("Adding dummyVar == d" + _dummyCounter);
} else {
++_slackCounter;
eplus = new ClSlackVariable (_slackCounter, "ep");
eminus = new ClSlackVariable (_slackCounter, "em");
expr.setVariable( eplus,-1.0);
expr.setVariable( eminus,1.0);
_markerVars.put(cn,eplus);
ClLinearExpression zRow = rowExpression(_objective);
ClSymbolicWeight sw = cn.strength().symbolicWeight().times(cn.weight());
double swCoeff = sw.asDouble();
if (swCoeff == 0) {
if (fTraceOn) traceprint("sw == " + sw);
if (fTraceOn) traceprint("cn == " + cn);
if (fTraceOn) traceprint("adding " + eplus + " and " + eminus + " with swCoeff == " + swCoeff);
}
zRow.setVariable(eplus,swCoeff);
noteAddedVariable(eplus,_objective);
zRow.setVariable(eminus,swCoeff);
noteAddedVariable(eminus,_objective);
insertErrorVar(cn,eminus);
insertErrorVar(cn,eplus);
if (cn.isStayConstraint()) {
_stayPlusErrorVars.addElement(eplus);
_stayMinusErrorVars.addElement(eminus);
}
else if (cn.isEditConstraint()) {
eplus_eminus.addElement(eplus);
eplus_eminus.addElement(eminus);
prevEConstant.setValue(cnExpr.constant());
}
}
}
if (expr.constant() < 0)
expr.multiplyMe(-1);