~jozilla/uiml.net/uiml.net-tp

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
/*
  Cassowary.net: an incremental constraint solver for .NET
  (http://lumumba.uhasselt.be/jo/projects/cassowary.net/)
  
  Copyright (C) 2005  Jo Vermeulen (jo.vermeulen@uhasselt.be)
  
  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public License
  as published by the Free Software Foundation; either version 2.1
  of  the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

using System;
using System.Collections;

namespace Cassowary
{
  public class ClLinearExpression : Cl, ICloneable
  {
    public ClLinearExpression(ClAbstractVariable clv, double value, double constant)
    {
      if (Cl.GC)
      {
        #if !COMPACT
          Console.Error.WriteLine("new ClLinearExpression");
        #else
          Console.WriteLine("new ClLinearExpression");
        #endif
      }

      _constant = new ClDouble(constant);
      _terms = new Hashtable(1);
      
      if (clv != null)
        _terms.Add(clv, new ClDouble(value));
    }

    public ClLinearExpression(double num) : this(null, 0, num)
    {}

    public ClLinearExpression() : this(0)
    {}

    public ClLinearExpression(ClAbstractVariable clv, double value) : this(clv, value, 0.0)
    {}

    public ClLinearExpression(ClAbstractVariable clv) : this(clv, 1, 0)
    {}

    /// <summary>
    /// For use by the clone method.
    /// </summary>
    protected ClLinearExpression(ClDouble constant, Hashtable terms)
    {
      if (Cl.GC)
      {
        #if !COMPACT
          Console.Error.WriteLine("clone ClLinearExpression");
        #else
          Console.WriteLine("clone ClLinearExpression");
        #endif
      }
      
      _constant = (ClDouble) constant.Clone();
      _terms = new Hashtable();

      // need to unalias the ClDouble-s that we clone (do a deep clone)
      foreach (ClAbstractVariable clv in terms.Keys)
      {
        _terms.Add(clv, ((ClDouble) terms[clv]).Clone());
      }
    }

    public ClLinearExpression MultiplyMe(double x)
    {
      _constant.Value = _constant.Value * x;
      
      foreach (ClAbstractVariable clv in _terms.Keys)
      {
        ClDouble cld = (ClDouble) _terms[clv];
        cld.Value = cld.Value * x;
      }
 
      return this;
    }

    public virtual object Clone()
    {
      return new ClLinearExpression(_constant, _terms);
    }

    public /*sealed*/ ClLinearExpression Times(double x)
    {
      return ((ClLinearExpression) Clone()).MultiplyMe(x);
    }

    public /*sealed*/ ClLinearExpression Times(ClLinearExpression expr) 
      /*throws ExCLNonlinearExpression*/
    {
      if (IsConstant)
      {
        return expr.Times(_constant.Value);
      }
      else if (!expr.IsConstant)
      {
        throw new ExClNonlinearExpression();
      } 
      
      return Times(expr._constant.Value);
    }

    public /*sealed*/ ClLinearExpression Plus(ClLinearExpression expr)
    {
      return ((ClLinearExpression) Clone()).AddExpression(expr, 1.0);
    }

    public /*sealed*/ ClLinearExpression Plus(ClVariable var) 
      /*throws ExCLNonlinearExpression*/
    { 
      return ((ClLinearExpression) Clone()).AddVariable(var, 1.0);
    }

    public /*sealed*/ ClLinearExpression Minus(ClLinearExpression expr)
    {
      return ((ClLinearExpression) Clone()).AddExpression(expr, -1.0);
    }

    public /*sealed*/ ClLinearExpression Minus(ClVariable var) 
      /*throws ExCLNonlinearExpression*/
    { 
      return ((ClLinearExpression) Clone()).AddVariable(var, -1.0);
    }

    public /*sealed*/ ClLinearExpression Divide(double x) 
      /*throws ExCLNonlinearExpression*/
    {
      if (Cl.Approx(x, 0.0))
      { 
        throw new ExClNonlinearExpression();
      }
            
      return Times(1.0 / x);
    }

    public /*sealed*/ ClLinearExpression Divide(ClLinearExpression expr) 
      /*throws ExCLNonlinearExpression*/
    {
      if (!expr.IsConstant)
      {
        throw new ExClNonlinearExpression();
      }

      return Divide(expr._constant.Value);
    }

    public /*sealed*/ ClLinearExpression DivFrom(ClLinearExpression expr) 
      /*throws ExCLNonlinearExpression*/
    {
      if (!IsConstant || Cl.Approx(_constant.Value, 0.0))
      {
        throw new ExClNonlinearExpression();
      }
      
      return expr.Divide(_constant.Value);
    }

    public /*sealed*/ ClLinearExpression SubtractFrom(ClLinearExpression expr)
    { 
      return expr.Minus(this);
    }

    /// <summary>
    /// Add n*expr to this expression from another expression expr.
    /// Notify the solver if a variable is added or deleted from this
    /// expression.
    /// </summary>
    public /*sealed*/ ClLinearExpression AddExpression(ClLinearExpression expr, double n,
      ClAbstractVariable subject, ClTableau solver)
    {
      IncrementConstant(n * expr.Constant);
      
      foreach (ClAbstractVariable clv in expr.Terms.Keys)
      {
        double coeff = ((ClDouble) expr.Terms[clv]).Value;
        AddVariable(clv, coeff * n, subject, solver);
      }

      return this;
    }

    /// <summary>
    /// Add n*expr to this expression from another expression expr.
    /// </summary>
    public /*sealed*/ ClLinearExpression AddExpression(ClLinearExpression expr, double n)
    {
      IncrementConstant(n * expr.Constant);
      
      foreach (ClAbstractVariable clv in expr.Terms.Keys)
      {
        double coeff = ((ClDouble) expr.Terms[clv]).Value;
        AddVariable(clv, coeff * n);
      }

      return this;
    }

    public /*sealed*/ ClLinearExpression AddExpression(ClLinearExpression expr)
    {
      return AddExpression(expr, 1.0);
    }

    /// <summary>
    /// Add a term c*v to this expression.  If the expression already
    /// contains a term involving v, add c to the existing coefficient.
    /// If the new coefficient is approximately 0, delete v.
    /// </summary>
    public /*sealed*/ ClLinearExpression AddVariable(ClAbstractVariable v, double c)
    { 
      // body largely duplicated below
      if (Trace) 
        FnEnterPrint(string.Format("AddVariable: {0}, {1}", v, c));

      ClDouble coeff = (ClDouble) _terms[v];
      
      if (coeff != null) 
      {
        double new_coefficient = coeff.Value + c;
        
        if (Cl.Approx(new_coefficient, 0.0)) 
        {
          _terms.Remove(v);
        }
        else 
        {
          coeff.Value = new_coefficient;
        }
      } 
      else 
      {
        if (!Cl.Approx(c, 0.0)) 
        {
          _terms.Add(v, new ClDouble(c));
        }
      }
      
      return this;
    }

    public /*sealed*/ ClLinearExpression AddVariable(ClAbstractVariable v)
    { 
      return AddVariable(v, 1.0); 
    }


    public /*sealed*/ ClLinearExpression SetVariable(ClAbstractVariable v, double c)
    { 
      // Assert(c != 0.0);
      ClDouble coeff = (ClDouble) _terms[v];
      
      if (coeff != null) 
        coeff.Value = c;
      else
        _terms.Add(v, new ClDouble(c)); 
      
      return this;
    }

    /// <summary>
    /// Add a term c*v to this expression.  If the expression already
    /// contains a term involving v, add c to the existing coefficient.
    /// If the new coefficient is approximately 0, delete v.  Notify the
    /// solver if v appears or disappears from this expression.
    /// </summary>
    public /*sealed*/ ClLinearExpression AddVariable(ClAbstractVariable v, double c,
      ClAbstractVariable subject, ClTableau solver)
    { 
      // body largely duplicated above
      if (Trace) 
        FnEnterPrint(string.Format("AddVariable: {0}, {1}, {2}, ...", v, c, subject));

      ClDouble coeff = (ClDouble) _terms[v];
      
      if (coeff != null) 
      {
        double new_coefficient = coeff.Value + c;
        
        if (Cl.Approx(new_coefficient, 0.0)) 
        {
          solver.NoteRemovedVariable(v, subject);
          _terms.Remove(v);
        } 
        else 
        { 
          coeff.Value = new_coefficient;
        }
      } 
      else 
      {
        if (!Cl.Approx(c, 0.0)) 
        {
          _terms.Add(v, new ClDouble(c));
          solver.NoteAddedVariable(v, subject);
        }
      }

      return this;
    }

    /// <summary>
    /// Return a pivotable variable in this expression.  (It is an error
    /// if this expression is constant -- signal ExCLInternalError in
    /// that case).  Return null if no pivotable variables
    /// </summary>
    public /*sealed*/ ClAbstractVariable AnyPivotableVariable() 
      /*throws ExCLInternalError*/
    {
      if (IsConstant)
      {
        throw new ExClInternalError("anyPivotableVariable called on a constant");
      }

      foreach (ClAbstractVariable clv in _terms.Keys)
      {
        if (clv.IsPivotable)
          return clv;
      } 

      // No pivotable variables, so just return null, and let the caller
      // error if needed
      return null;
    }

    /// <summary>
    /// Replace var with a symbolic expression expr that is equal to it.
    /// If a variable has been added to this expression that wasn't there
    /// before, or if a variable has been dropped from this expression
    /// because it now has a coefficient of 0, inform the solver.
    /// PRECONDITIONS:
    ///   var occurs with a non-zero coefficient in this expression.
    /// </summary>
    public /*sealed*/ void SubstituteOut(ClAbstractVariable var, ClLinearExpression expr, 
      ClAbstractVariable subject, ClTableau solver)
    {
      if (Trace) 
        FnEnterPrint(string.Format("CLE:SubstituteOut: {0}, {1}, {2}, ...", var, expr, subject));
      if (Trace) 
        TracePrint("this = " + this);

      double multiplier = ((ClDouble) _terms[var]).Value;
       _terms.Remove(var);
      IncrementConstant(multiplier * expr.Constant);
        
      foreach (ClAbstractVariable clv in expr.Terms.Keys)
      {
        double coeff = ((ClDouble) expr.Terms[clv]).Value;
        ClDouble d_old_coeff = (ClDouble) _terms[clv];
        
        if (d_old_coeff != null) 
        {
          double old_coeff = d_old_coeff.Value;
          double newCoeff = old_coeff + multiplier * coeff;
          
          if (Cl.Approx(newCoeff, 0.0)) 
          {
            solver.NoteRemovedVariable(clv, subject);
            _terms.Remove(clv);
          } 
          else 
          {
            d_old_coeff.Value = newCoeff;
          }
        } 
        else 
        {
          // did not have that variable already
          _terms.Add(clv, new ClDouble(multiplier * coeff));
          solver.NoteAddedVariable(clv, subject);
        }
      }

      if (Trace) 
        TracePrint("Now this is " + this);
    }

    /// <summary>
    /// This linear expression currently represents the equation
    /// oldSubject=self.  Destructively modify it so that it represents
    /// the equation newSubject=self.
    ///
    /// Precondition: newSubject currently has a nonzero coefficient in
    /// this expression.
    ///
    /// NOTES
    ///   Suppose this expression is c + a*newSubject + a1*v1 + ... + an*vn.
    ///
    ///   Then the current equation is 
    ///       oldSubject = c + a*newSubject + a1*v1 + ... + an*vn.
    ///   The new equation will be
    ///        newSubject = -c/a + oldSubject/a - (a1/a)*v1 - ... - (an/a)*vn.
    ///   Note that the term involving newSubject has been dropped.
    /// </summary>
    public /*sealed*/ void ChangeSubject(ClAbstractVariable old_subject, ClAbstractVariable new_subject)
    {
      ClDouble cld = (ClDouble) _terms[old_subject];
      
      if (cld != null)
        cld.Value  = NewSubject(new_subject);
      else
        _terms.Add(old_subject, new ClDouble(NewSubject(new_subject)));
    }
  
    /// <summary>
    /// This linear expression currently represents the equation self=0.  Destructively modify it so 
    /// that subject=self represents an equivalent equation.  
    ///
    /// Precondition: subject must be one of the variables in this expression.
    /// NOTES
    ///   Suppose this expression is
    ///     c + a*subject + a1*v1 + ... + an*vn
    ///   representing 
    ///     c + a*subject + a1*v1 + ... + an*vn = 0
    /// The modified expression will be
    ///    subject = -c/a - (a1/a)*v1 - ... - (an/a)*vn
    ///   representing
    ///    subject = -c/a - (a1/a)*v1 - ... - (an/a)*vn
    ///
    /// Note that the term involving subject has been dropped.
    /// Returns the reciprocal, so changeSubject can use it, too
    /// </summary>
    public /*sealed*/ double NewSubject(ClAbstractVariable subject)
    {
      if (Trace) 
        FnEnterPrint(string.Format("newSubject: {0}", subject));
      
      ClDouble coeff = (ClDouble) _terms[subject];
      _terms.Remove(subject);
      
      double reciprocal = 1.0 / coeff.Value;
      MultiplyMe(-reciprocal);
      
      return reciprocal;
    }

    /// <summary>
    /// Return the coefficient corresponding to variable var, i.e.,
    /// the 'ci' corresponding to the 'vi' that var is:
    ///      v1*c1 + v2*c2 + .. + vn*cn + c
    /// </summary>
    public /*sealed*/ double CoefficientFor(ClAbstractVariable var)
    { 
      ClDouble coeff = (ClDouble) _terms[var];
      
      if (coeff != null)
        return coeff.Value;
      else
        return 0.0;
    }

    public double Constant
    {
      get {
        return _constant.Value; 
      }
      set {
        _constant.Value = value;
      }
    }

    public Hashtable Terms
    {
      get {
        return _terms; 
      }
    }

    public /*sealed*/ void IncrementConstant(double c)
    { 
      _constant.Value = _constant.Value + c;
    }

    public bool IsConstant
    {
      get {
        return _terms.Count == 0;
      }
    }

    public override string ToString()
    {
      String s = "";
      
      IDictionaryEnumerator e = _terms.GetEnumerator();

      if (!Cl.Approx(_constant.Value, 0.0) || _terms.Count == 0) 
      {
        s += _constant.ToString();
      }
      else
      {
        if (_terms.Count == 0)
        {
          return s;
        }
        e.MoveNext(); // go to first element
        ClAbstractVariable clv = (ClAbstractVariable) e.Key;
        ClDouble coeff = (ClDouble) _terms[clv];
        s += string.Format("{0}*{1}", coeff.ToString(), clv.ToString());
      }
      while (e.MoveNext())
      {
        ClAbstractVariable clv = (ClAbstractVariable) e.Key;
        ClDouble coeff = (ClDouble) _terms[clv];
        s += string.Format(" + {0}*{1}", coeff.ToString(), clv.ToString());
      }
      
      return s;
    }

    public /*sealed*/ new static ClLinearExpression Plus(ClLinearExpression e1, ClLinearExpression e2)
    { 
      return e1.Plus(e2); 
    }

    public /*sealed*/ new static ClLinearExpression Minus(ClLinearExpression e1, ClLinearExpression e2)
    { 
      return e1.Minus(e2); 
    }

    public /*sealed*/ new static ClLinearExpression Times(ClLinearExpression e1, ClLinearExpression e2) 
      /* throws ExCLNonlinearExpression */
    { 
      return e1.Times(e2);
    }

    public /*sealed*/ new static ClLinearExpression Divide(ClLinearExpression e1, ClLinearExpression e2) 
      /* throws ExCLNonlinearExpression */
    { 
      return e1.Divide(e2);
    }

    public /*sealed*/ static bool FEquals(ClLinearExpression e1, ClLinearExpression e2)
    { 
      return e1 == e2;
    }

    private ClDouble _constant;
    private Hashtable _terms; // from ClVariable to ClDouble
  }
}