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
|
//
// Polynomial.cs
//
// Authors:
// Alexander Chebaturkin (chebaturkin@gmail.com)
//
// Copyright (C) 2012 Alexander Chebaturkin
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using Mono.CodeContracts.Static.DataStructures;
namespace Mono.CodeContracts.Static.Analysis.Numerical {
struct Polynomial<TVar, TExpr>
where TVar : IEquatable<TVar> {
readonly Monomial<TVar>[] left;
readonly ExpressionOperator? relation;
readonly Monomial<TVar>[] right;
IImmutableSet<TVar> cached_variables;
public Polynomial (Monomial<TVar> monome)
{
relation = null;
left = new[] {monome};
right = null;
cached_variables = null;
}
public Polynomial (Monomial<TVar>[] monomes)
{
relation = null;
left = monomes;
right = null;
cached_variables = null;
}
public Polynomial (ExpressionOperator op, Monomial<TVar>[] left, Monomial<TVar>[] right)
{
relation = op;
this.left = left;
this.right = right;
cached_variables = null;
}
public Polynomial (ExpressionOperator op, Monomial<TVar>[] left, Monomial<TVar> right)
{
relation = op;
this.left = left;
this.right = new[] {right};
cached_variables = null;
}
public Polynomial (ExpressionOperator op, Polynomial<TVar, TExpr> left, Polynomial<TVar, TExpr> right)
{
relation = op;
this.left = left.left;
this.right = right.left;
cached_variables = null;
}
public Polynomial (Polynomial<TVar, TExpr> that)
{
relation = that.relation;
left = DuplicateFrom (that.left);
right = that.right != null ? DuplicateFrom (that.right) : null;
cached_variables = null;
}
public ExpressionOperator? Relation { get { return relation; } }
public IImmutableSet<TVar> Variables
{
get
{
if (cached_variables == null) {
cached_variables = ImmutableSet<TVar>.Empty ();
foreach (var monome in left)
cached_variables = cached_variables.AddRange (monome.Variables);
if (relation.HasValue)
foreach (var monome in right)
cached_variables = cached_variables.AddRange (monome.Variables);
}
return cached_variables;
}
}
public Monomial<TVar>[] Left { get { return left; } }
public Monomial<TVar>[] Right { get { return right; } }
public Polynomial<TVar, TExpr> LeftAsPolynomial
{
get
{
Polynomial<TVar, TExpr> polynome;
TryToPolynomial (left, out polynome);
return polynome;
}
}
/// <summary>
/// Returns true if poly is in form: 'k*x < c'
/// </summary>
public bool IsIntervalForm
{
get
{
var op = Relation;
if (!op.HasValue)
return false;
if (left.Length != 1 || right.Length != 1 || left[0].Degree != 1 || !right[0].IsConstant)
return false;
return op.Value == ExpressionOperator.LessEqualThan;
}
}
public bool IsLinear
{
get
{
if (left.Any (m => !m.IsLinear))
return false;
if (Relation.HasValue && right.Any (m => !m.IsLinear))
return false;
return true;
}
}
static Monomial<TVar>[] DuplicateFrom (Monomial<TVar>[] original)
{
var res = new Monomial<TVar>[original.Length];
Array.Copy (original, res, original.Length);
return res;
}
public static bool TryToPolynomial (Monomial<TVar>[] monomials, out Polynomial<TVar, TExpr> polynome)
{
if (monomials.Length > 1) {
polynome = new Polynomial<TVar, TExpr> (monomials);
return polynome.TryToCanonicalForm (out polynome);
}
return true.With (new Polynomial<TVar, TExpr> (monomials), out polynome);
}
public bool TryToCanonicalForm (out Polynomial<TVar, TExpr> polynome)
{
var poly = this;
if (poly.relation.HasValue) {
switch (poly.relation.Value) {
case ExpressionOperator.GreaterThan:
poly = poly.SwapOperands (ExpressionOperator.LessThan);
break;
case ExpressionOperator.GreaterEqualThan:
poly = poly.SwapOperands (ExpressionOperator.LessEqualThan);
break;
}
poly = poly.MoveConstantsAndMonomes ();
Debug.Assert (poly.relation.HasValue);
Monomial<TVar>[] left;
Monomial<TVar>[] right;
if (TrySimplifyMonomes (poly.left, out left) && TrySimplifyMonomes (poly.right, out right))
return true.With (new Polynomial<TVar, TExpr> (poly.relation.Value, left, right), out polynome);
}
else {
Monomial<TVar>[] monome;
if (TrySimplifyMonomes (left, out monome))
return true.With (new Polynomial<TVar, TExpr> (monome), out polynome);
}
return false.Without (out polynome);
}
static bool TrySimplifyMonomes (Monomial<TVar>[] monomes, out Monomial<TVar>[] result)
{
if (monomes.Length <= 1)
return true.With (monomes, out result);
var dict = new Dictionary<ListEqual<TVar>, Monomial<TVar>> ();
foreach (var monomial in monomes) {
var key = new ListEqual<TVar> (monomial.Degree, monomial.Variables);
Monomial<TVar> monome;
if (dict.TryGetValue (key, out monome)) {
Rational coeff;
if (!Rational.TryAdd (monome.Coeff, monomial.Coeff, out coeff))
return false.With (monomes, out result);
var sum = monome.With (coeff);
dict[key] = sum;
}
else
dict.Add (key, monomial);
}
var left = new List<Monomial<TVar>> (dict.Count);
var right = new List<Monomial<TVar>> (dict.Count);
Monomial<TVar>? resMonome = null;
foreach (var pair in dict) {
var monome = pair.Value;
if (!monome.Coeff.IsZero) {
if (monome.IsConstant)
resMonome = monome;
else if (monome.Coeff > 0L)
left.Add (monome);
else
right.Add (monome);
}
}
var list = new List<Monomial<TVar>> (dict.Count);
list.AddRange (left);
list.AddRange (right);
if (resMonome.HasValue)
list.Add (resMonome.Value);
if (list.Count == 0)
list.Add (Monomial<TVar>.From (Rational.Zero));
return true.With (list.ToArray (), out result);
}
Polynomial<TVar, TExpr> MoveConstantsAndMonomes ()
{
if (!relation.HasValue)
return this;
var left = new List<Monomial<TVar>> ();
var right = new List<Monomial<TVar>> ();
foreach (var monomial in this.left)
if (!monomial.IsConstant)
left.Add (monomial);
else
right.Add (-monomial);
foreach (var monomial in this.right)
if (!monomial.IsConstant)
left.Add (-monomial);
else
right.Add (monomial);
if (left.Count == 0)
left.Add (Monomial<TVar>.From (0L));
if (right.Count == 0)
right.Add (Monomial<TVar>.From (0));
return new Polynomial<TVar, TExpr> (relation.Value, left.ToArray (), right.ToArray ());
}
Polynomial<TVar, TExpr> SwapOperands (ExpressionOperator newOp)
{
return new Polynomial<TVar, TExpr> (newOp, right, left);
}
public override string ToString ()
{
if (!relation.HasValue)
return ListToString (left);
return string.Format ("{0} {1} {2}", ListToString (left), relation, ListToString (right));
}
static string ListToString (Monomial<TVar>[] list)
{
if (list == null)
return string.Empty;
if (list.Length == 0)
return "()";
var sb = new StringBuilder ();
var stringsOrdered = list.Select (x => x.ToString ()).OrderBy (x => x);
var first = true;
sb.Append ("(");
foreach (var str in stringsOrdered) {
if (first)
first = false;
else
sb.Append (", ");
sb.Append (str);
}
sb.Append (")");
return sb.ToString ();
}
public static bool TryReduceCoefficients (Monomial<TVar>[] simplifiedLeft, Monomial<TVar>[] simplifiedRight)
{
if (simplifiedRight[0].Coeff.IsMinValue)
return false;
var abs = Rational.Abs (simplifiedRight[0].Coeff);
if (abs.IsZero)
return true;
if (simplifiedLeft.Any (monome => !(monome.Coeff / abs).IsInteger))
return true;
simplifiedRight[0] = simplifiedRight[0].With ((c) => c / abs);
for (var i = 0; i < simplifiedLeft.Length; i++)
simplifiedLeft[i] = simplifiedLeft[i].With (c => c / abs);
return true;
}
public static bool TryBuildFrom (TExpr expr, IExpressionDecoder<TVar, TExpr> decoder, out Polynomial<TVar, TExpr> result)
{
return new PolynomialBuilder (decoder).Build (expr, out result);
}
static bool TryMinus (Polynomial<TVar, TExpr> p, out Polynomial<TVar, TExpr> result)
{
if (p.Relation.HasValue)
return false.Without (out result);
var monomes = new Monomial<TVar>[p.left.Length];
var cnt = 0;
foreach (var m in p.left) {
var k = -m.Coeff;
if (k.IsInfinity)
return false.Without (out result);
var mm = m.With (k);
monomes[cnt++] = mm;
}
return true.With (new Polynomial<TVar, TExpr> (monomes), out result);
}
bool IsIntConstant (out long constant)
{
if (Relation.HasValue || left.Length != 1)
return false.Without (out constant);
return left[0].IsIntConstant (out constant);
}
static Polynomial<TVar, TExpr> Concatenate (Polynomial<TVar, TExpr> left, Polynomial<TVar, TExpr> right)
{
if (left.Relation.HasValue || right.Relation.HasValue)
throw new InvalidOperationException ();
var monomes = new Monomial<TVar>[left.left.Length + right.left.Length];
Array.Copy (left.left, monomes, left.left.Length);
Array.Copy (right.left, 0, monomes, left.left.Length, right.left.Length);
return new Polynomial<TVar, TExpr> (left.left);
}
public static bool TryToPolynomial (ExpressionOperator op, Polynomial<TVar, TExpr> left, Polynomial<TVar, TExpr> right, out Polynomial<TVar, TExpr> result)
{
if (op.IsBinary () && !left.Relation.HasValue) {
try {
var poly = new Polynomial<TVar, TExpr> (op, left, right);
if (poly.TryToCanonicalForm (out result))
return true;
}
catch (Exception) {
}
}
return false.Without (out result);
}
#region Nested type: ConstantGatherer
class ConstantGatherer : GenericTypeExpressionVisitor<TVar, TExpr, Dummy, Pair<Rational, bool>> {
static readonly Pair<Rational, bool> Failure = new Pair<Rational, bool> (Rational.PlusInfinity, false);
public ConstantGatherer (IExpressionDecoder<TVar, TExpr> decoder)
: base (decoder)
{
}
protected override Pair<Rational, bool> Default (TExpr expr, Dummy input)
{
if (Decoder.IsNull (expr))
return Success (Rational.Zero);
return Failure;
}
protected override Pair<Rational, bool> VisitBool (TExpr expr, Dummy input)
{
return Failure;
}
protected override Pair<Rational, bool> VisitInt32 (TExpr expr, Dummy input)
{
int value;
if (Decoder.TryValueOf (expr, ExpressionType.Int32, out value))
return Success (Rational.For (value));
return Failure;
}
static Pair<Rational, bool> Success (Rational value)
{
return new Pair<Rational, bool> (value, true);
}
}
#endregion
#region Nested type: ListEqual
class ListEqual<T> {
readonly Lazy<int> cached_hash_code;
readonly T[] elements;
public ListEqual (int len, IEnumerable<T> seq)
{
elements = seq.Take (len).ToArray ();
cached_hash_code = new Lazy<int> (() => elements.Sum (elem => elem.GetHashCode ()), LazyThreadSafetyMode.None);
}
public override int GetHashCode ()
{
return cached_hash_code.Value;
}
public override bool Equals (object obj)
{
var leq = obj as ListEqual<T>;
if (leq == null || elements.Length != leq.elements.Length)
return false;
if (elements.Length == 1)
return elements[0].Equals (leq.elements[0]);
return elements.Intersect (leq.elements).Count () == elements.Count ();
}
}
#endregion
#region Nested type: PolynomialBuilder
class PolynomialBuilder : GenericExpressionVisitor<Dummy, bool, TVar, TExpr> {
Polynomial<TVar, TExpr> poly;
public PolynomialBuilder (IExpressionDecoder<TVar, TExpr> decoder)
: base (decoder)
{
}
public bool Build (TExpr expr, out Polynomial<TVar, TExpr> result)
{
if (base.Visit (expr, Dummy.Value))
return true.With (poly, out result);
return false.Without (out result);
}
protected override bool Default (Dummy data)
{
return false;
}
public override bool VisitSizeOf (TExpr expr, Dummy data)
{
int sizeOf;
if (!Decoder.TrySizeOf (expr, out sizeOf))
return false;
return true.With (new Polynomial<TVar, TExpr> (Monomial<TVar>.From (Rational.For (sizeOf))), out poly);
}
public override bool VisitConstant (TExpr expr, Dummy data)
{
var pair = new ConstantGatherer (Decoder).Visit (expr, Dummy.Value);
if (!pair.Value || pair.Key.IsInfinity)
return false;
poly = new Polynomial<TVar, TExpr> (Monomial<TVar>.From (pair.Key));
return true;
}
public override bool VisitAddition (TExpr left, TExpr right, TExpr original, Dummy data)
{
Polynomial<TVar, TExpr> polyLeft, polyRight;
if (!Build (left, out polyLeft) || !Build (right, out polyRight))
return false;
long kLeft, kRight;
object addition;
if (polyLeft.IsIntConstant (out kLeft) && polyRight.IsIntConstant (out kRight) &&
EvaluateArithmeticWithOverflow.TryBinary (Decoder.TypeOf (original), ExpressionOperator.Add, kLeft, kRight, out addition)) {
var longValue = addition.ConvertToLong ();
if (longValue.HasValue)
return true.With (new Polynomial<TVar, TExpr> (Monomial<TVar>.From (Rational.For (longValue.Value))), out poly);
}
return true.With (Concatenate (polyLeft, polyRight), out poly);
}
public override bool VisitSubtraction (TExpr left, TExpr right, TExpr original, Dummy data)
{
Polynomial<TVar, TExpr> polyLeft, polyRight;
if (!Build (left, out polyLeft) || !Build (right, out polyRight))
return false;
long kLeft, kRight;
object subtraction;
if (polyLeft.IsIntConstant (out kLeft) && polyRight.IsIntConstant (out kRight) &&
EvaluateArithmeticWithOverflow.TryBinary (Decoder.TypeOf (original), ExpressionOperator.Sub, kLeft, kRight, out subtraction)) {
var longValue = subtraction.ConvertToLong ();
if (longValue.HasValue)
return true.With (new Polynomial<TVar, TExpr> (Monomial<TVar>.From (Rational.For (longValue.Value))), out poly);
}
return TryToPolynomialHelperForSubtraction (polyLeft, polyRight, out poly);
}
public override bool VisitMultiply (TExpr left, TExpr right, TExpr original, Dummy data)
{
Polynomial<TVar, TExpr> l, r;
var lBuilt = Build (left, out l);
var rBuilt = Build (right, out r);
if (lBuilt && rBuilt) {
long kLeft, kRight;
object mult;
if (l.IsIntConstant (out kLeft) && r.IsIntConstant (out kRight) &&
EvaluateArithmeticWithOverflow.TryBinary (
Decoder.TypeOf (original), ExpressionOperator.Mult, kLeft, kRight, out mult)) {
var longValue = mult.ConvertToLong ();
if (longValue.HasValue) {
var monomial = Monomial<TVar>.From (Rational.For (longValue.Value));
return true.With (new Polynomial<TVar, TExpr> (monomial), out poly);
}
}
return TryToPolynomialHelperForMultiplication (l, r, out poly);
}
return false;
}
static bool TryToPolynomialHelperForMultiplication (Polynomial<TVar, TExpr> left, Polynomial<TVar, TExpr> right, out Polynomial<TVar, TExpr> result)
{
var list = new List<Monomial<TVar>> (left.left.Length + right.left.Length);
foreach (var m in left.left)
foreach (var n in right.left) {
Rational mul;
if (!Rational.TryMultiply (m.Coeff, n.Coeff, out mul))
return false.Without (out result);
list.Add (Monomial<TVar>.From (mul, m.Variables.Concat (n.Variables)));
}
return true.With (new Polynomial<TVar, TExpr> (list.ToArray ()), out result);
}
static bool TryToPolynomialHelperForSubtraction (Polynomial<TVar, TExpr> left, Polynomial<TVar, TExpr> right, out Polynomial<TVar, TExpr> result)
{
Polynomial<TVar, TExpr> minusRight;
if (TryMinus (right, out minusRight))
return true.With (Concatenate (left, right), out result);
return false.Without (out result);
}
public override bool VisitVariable (TVar var, TExpr expr, Dummy data)
{
var monome = Monomial<TVar>.From (Rational.One, Sequence<TVar>.Singleton (Decoder.UnderlyingVariable (expr)));
return true.With (new Polynomial<TVar, TExpr> (monome), out poly);
}
public override bool VisitNotEqual (TExpr left, TExpr right, TExpr original, Dummy data)
{
return DefaultRelation (left, right, original);
}
public override bool VisitLessThan (TExpr left, TExpr right, TExpr original, Dummy data)
{
return DefaultRelation (left, right, original);
}
public override bool VisitLessEqualThan (TExpr left, TExpr right, TExpr original, Dummy data)
{
return DefaultRelation (left, right, original);
}
public override bool VisitGreaterThan (TExpr left, TExpr right, TExpr original, Dummy data)
{
return DefaultRelation (left, right, original);
}
public override bool VisitGreaterEqualThan (TExpr left, TExpr right, TExpr original, Dummy data)
{
return DefaultRelation (left, right, original);
}
public override bool VisitDivision (TExpr left, TExpr right, TExpr original, Dummy data)
{
Polynomial<TVar, TExpr> l, r;
if (!Build (left, out l) || !Build (right, out r))
return false;
return HelperForDivision (l, r, out poly);
}
bool HelperForDivision (Polynomial<TVar, TExpr> left, Polynomial<TVar, TExpr> right, out Polynomial<TVar, TExpr> result)
{
if (right.left.Length == 1) {
var div = right.left[0];
if (div.IsConstant && !div.Coeff.IsZero) {
var monomes = new Monomial<TVar>[left.left.Length];
var cnt = 0;
foreach (var m in left.left) {
Rational k;
try {
k = m.Coeff / div.Coeff;
}
catch (ArithmeticException) {
return false.Without (out result);
}
monomes[cnt++] = m.With (k);
}
return true.With (new Polynomial<TVar, TExpr> (monomes), out result);
}
}
return false.Without (out result);
}
bool DefaultRelation (TExpr left, TExpr right, TExpr original)
{
Polynomial<TVar, TExpr> l, r;
if (!Build (left, out l) || !Build (right, out r) || l.Relation.HasValue || r.Relation.HasValue)
return false;
return true.With (new Polynomial<TVar, TExpr> (Decoder.OperatorFor (original), l.left, r.left), out poly);
}
}
#endregion
}
}
|