public void Clone_PolynomialEqualsCloneOfPolynomial_TrueReturned()
        {
            Polynomial polynom = new Polynomial(1, 2, 3);
            Polynomial cloneOfPolinom = (Polynomial)polynom.Clone();

            polynom.Equals(cloneOfPolinom);
        }
Example #2
0
        //        double a = 0D;
        //        double b = 1D;
        private void Map_TextChanged(object sender, TextChangedEventArgs e)
        {
            Window1 w = Utilities.getWindow(this);
            if (w == null) return; //initialization run only
            TextBox tb = (TextBox)sender;
            string str = tb.Text;
            try
            {
                p = new Polynomial(str, 'v');
                w.RemoveError(tb);
            }
            catch
            {
                w.LogError(tb);
            }
            /*            Match m = Regex.Match(str, @"^(?<a>([+-]?(\d+\.?|\d*\.\d+)(?!v)(?=[+\-$]))?)(?<b>[+-]?(\d+\.?|\d*\.\d+)?)v$"); //
            if (!m.Success)
            {
                w.LogError(tb);
                return;
            }

            str = m.Groups["a"].Value;
            a = str == "" ? 0D : Convert.ToDouble(str);
            str = m.Groups["b"].Value;
            b = (str == "" || str == "+") ? 1D : (str == "-") ? -1D : Convert.ToDouble(str);

            w.RemoveError(tb); */
        }
  public void Clone_PolynomialReferenceEqualsCloneOfPolynomial_FalseReturned()
  {
      Polynomial polynom = new Polynomial(1, 2, 3);
      Polynomial cloneOfPolynom = (Polynomial)polynom.Clone();
 
      Assert.AreEqual(false, ReferenceEquals(polynom, cloneOfPolynom));
  }
        public void Equality_OfTwoPolynomials()
        {
            Polynomial first = new Polynomial(5, 7);
            Polynomial second = new Polynomial(5, 7);

            Assert.IsTrue(first.Equals(second));
        }
        public void NonEquality_OfTwoPolynomials()
        {
            Polynomial first = new Polynomial(5, 7);
            Polynomial second = new Polynomial(3, 7, 8);

            Assert.IsFalse(first.Equals(second));
        }
        public void Equality_OfPolynomialAndNULL()
        {
            Polynomial first = new Polynomial(5, 7);
            Polynomial second = null;

            Assert.IsTrue(first.Equals(second));
        }
         public void Reduce_OfPolynomialAndNumber()
         {
             Polynomial first = new Polynomial(5, 7);
             Polynomial result = 5 - first;

             Assert.AreEqual(7, result.ResultOfPolynomial(1));
         }
         public void Multiply_OfPolynomialAndNumber()
         {
             Polynomial first = new Polynomial(5, 7);
             Polynomial result = 3 * first;

             Assert.AreEqual(36, result.ResultOfPolynomial(1));
         }
 public void Subtract_TwoPolynomials_ReturnsPolynomialWithCorrectValue()
 {
     Polynomial p = new Polynomial(new double[] { 0, 5.6, 5, 0.5, 0, 0, 0 });
     Polynomial pp = new Polynomial(new double[] { 0, 5.6, 5, 0.5, 0, 0, 8, 9.11, 5 });
     p = Polynomial.Subtract(p, pp);
     Assert.AreEqual(-22.11, p.GetValue(1));
 }
        public void Equals_123Equals124_FalseReturned()
        {
            Polynomial a = new Polynomial(1, 2, 3);
            Polynomial b = new Polynomial(1, 2, 4);

            Assert.AreEqual(false, a.Equals(b));
        }
        public void Equals_123Equals123_TrueReturned()
        {
            Polynomial a = new Polynomial(1, 2, 3);
            Polynomial b = new Polynomial(1, 2, 3);

            Assert.AreEqual(true, a.Equals(b));
        }
        public void OperatoPlus_123Plus456_579Returned()
        {
            Polynomial a = new Polynomial(1, 2, 3);
            Polynomial b = new Polynomial(4, 5, 6);
            Polynomial sum = a + b;

            Assert.AreEqual(true, sum.Equals(new Polynomial(5, 7, 9)));
        }
        public void Addition_OfTwoPolynomial()
        {
            Polynomial first = new Polynomial(5, 7);
            Polynomial second = new Polynomial(-5, -7);

            Polynomial result = first + second;
            Assert.AreEqual(0, result.ResultOfPolynomial(1));
        }
         public void Reduce_OfTwoPolynomial()
         {
             Polynomial first = new Polynomial(5, 7);
             Polynomial second = new Polynomial(5, 7);

             Polynomial result = first - second;
             Assert.AreEqual(0, result.ResultOfPolynomial(1));
         }
 public void Subtract_TwoPolynomials_ReturnsNewPolynomial()
 {
     Polynomial p = new Polynomial(new double[] { 0, 5.6, 5, 0.5, 0, 0, 0 });
     Polynomial pp = new Polynomial(new double[] { 0, 5.6, 5, 0.5, 0, 0, 8, 9.11, 5 });
     Polynomial result = Polynomial.Subtract(p, pp);
     Assert.AreNotSame(p, result);
     Assert.AreNotSame(pp, result);
 }
Example #16
0
 public static Polynomial operator *(Polynomial polyA, Polynomial polyB)
 {
     Polynomial result = new Polynomial();
     for (int i = 0; i < polyA.elements.Count; i++)
         for (int j = 0; j < polyB.elements.Count; j++)
             result.AddElement(polyA.elements.Keys[i] + polyB.elements.Keys[j], polyA.elements.Values[i]*polyB.elements.Values[j]);
     return result;
 }
 public void Ctor_GivenMultipleCoefficients_ReturnsPolynomialWithSameCoefficients()
 {
     double[] coeffs = { 1, 2, 3, 4 };
     var poly = new Polynomial(1, 2, 3, 4);
     for (int i = 0; i < poly.Degree; i++)
     {
         Assert.AreEqual(coeffs[i], poly[i]);
     }
 }
Example #18
0
    public void TestConstructor()
    {
        Polynomial poly2 = new Polynomial(1, 2, 3, 0);

                Assert.AreEqual(2, poly2.Degree);
                Assert.AreEqual(1, poly2[0]);
                Assert.AreEqual(2, poly2[1]);
                Assert.AreEqual(3, poly2[2]);
    }
        public void Multiply_CLSMethodName()
        {
            Polynomial pol = new Polynomial(3, 6, 4);
            int number = 4;
            Polynomial expected = new Polynomial(12, 24, 16);

            Polynomial actual = Polynomial.Multiply(pol, number);

            Assert.AreEqual(actual, expected);
        }
        public void Subtract()
        {
            Polynomial pol = new Polynomial(3, 6, 4);
            Polynomial pol2 = new Polynomial(-5, 2, 1);
            Polynomial expected = new Polynomial(8, 4, 3);

            Polynomial actual = pol - pol2;

            Assert.AreEqual(actual, expected);
        }
        public void Subtract_CLSMethodName()
        {
            Polynomial pol = new Polynomial(3, 6, 4);
            Polynomial pol2 = new Polynomial(-5, 2, 1);
            Polynomial expected = new Polynomial(8, 4, 3);

            Polynomial actual = Polynomial.Subtract(pol, pol2);

            Assert.AreEqual(actual, expected);
        }
        public void Add()
        {
            Polynomial pol = new Polynomial(3, 6, 4);
            Polynomial pol2 = new Polynomial(-5, 2, 1);
            Polynomial expected = new Polynomial(-2, 8, 5);

            Polynomial actual = pol + pol2;

            Assert.AreEqual(actual, expected);
        }
        public void Add_CLSMethodName()
        {
            Polynomial pol = new Polynomial(3, 6, 4);
            Polynomial pol2 = new Polynomial(-5, 2, 1);
            Polynomial expected = new Polynomial(-2, 8, 5);

            Polynomial actual = Polynomial.Add(pol, pol2);

            Assert.AreEqual(actual, expected);
        }
        public void Multiply_RightPositionNumber()
        {
            Polynomial pol = new Polynomial(3, 6, 4);
            int number = 4;
            Polynomial expected = new Polynomial(12, 24, 16);

            Polynomial actual = pol * number;

            Assert.AreEqual(actual, expected);
        }
    // Subtraction
    public static Polynomial operator -(Polynomial left, Polynomial right)
    {
        Polynomial result = new Polynomial(Math.Max(left.Degree, right.Degree));

        // Subtract the coefficients
        for (int i = 0; i < result.Degree; i++)
            result[i] = (i < left.Degree ? left[i] : 0) - (i < right.Degree ? right[i] : 0);

        return result;
    }
    // Multiplication
    public static Polynomial operator *(Polynomial left, Polynomial right)
    {
        Polynomial result = new Polynomial(left.Degree + right.Degree);

        for (int indLeft = 0; indLeft < left.Degree; indLeft++)
            for (int indRight = 0; indRight < right.Degree; indRight++)
                result[indLeft + indRight] += left[indLeft] * right[indRight];

        return result;
    }
Example #27
0
    static void Main(string[] args)
    {
        Polynomial a = new Polynomial();
            Polynomial b = new Polynomial();

            a.ReadPolynomial();
            b.ReadPolynomial();

            Polynomial result = a + b;
            Console.WriteLine(result.ToString());
    }
        public void Addition()
        {
            Polynomial result;
            Polynomial a=new Polynomial(new double[]{3,2,1});
            Polynomial b = new Polynomial(new double[] { 5, 6, 7 });
            Polynomial expectedResult = new Polynomial(new double[] { 8, 8, 8 });

            result = a + b;
            
            Assert.IsTrue(result.Equals(expectedResult));
        }
Example #29
0
 // Rideheight?
 public Chassis(float weight, float fuelTankSize, float dragBody, Polynomial dragFrontWing, Polynomial dragRearWing, Polynomial dragRadiator, Polynomial dragBrakeDucts, float rideheightFront)
 {
     Weight = weight;
     FuelTankSize = fuelTankSize;
     DragBody = dragBody;
     DragFrontWing = dragFrontWing;
     DragRearWing = dragRearWing;
     DragRadiator = dragRadiator;
     DragBrakeDucts = dragBrakeDucts;
     RideheightFront = rideheightFront;
 }
    static void Main()
    {
        // Write a method that adds two polynomials. Represent them as arrays of their coefficients.
        // Example: x^2 + 5 = 1x^2 + 0x + 5 -> { 5, 0, 1 }

        // We will use a special class to easily work with polynomials
        Polynomial polyA = new Polynomial(5, 0, 1); // x^2 + 5
        Polynomial polyB = new Polynomial(-7, 4, 5, -1); // -x^3 + 5x^2 + 4x - 7
        Polynomial sumAB = polyA + polyB;

        Console.WriteLine("({0}) + ({1}) = {2}", polyA, polyB, sumAB);
    }
        static public List <Pair <Variable, IType> > InferConstraints_Leq <Variable, Expression, IType>(
            bool isSignedComparison,
            Expression left, Expression right,
            IExpressionDecoder <Variable, Expression> decoder,
            ISetOfNumbersAbstraction <Variable, Expression, Rational, IType> iquery,
            out bool isBottom)
            where IType : IntervalBase <IType, Rational>
        {
            Contract.Requires(iquery != null);
            Contract.Ensures(Contract.Result <List <Pair <Variable, IType> > >() != null);

            isBottom = false; // false, unless someine proves the contrary

            var result = new List <Pair <Variable, IType> >();

            if (IsFloat(left, decoder) || IsFloat(right, decoder))
            {
                return(result);
            }

            var kLeft  = iquery.Eval(left);
            var kRight = iquery.Eval(right);

            // We have to take into account the polymorphism of constants
            if (!isSignedComparison)
            {
                kLeft  = kLeft.ToUnsigned();
                kRight = kRight.ToUnsigned();
            }

            //AssumeKLessEqualThanRight(kLeft, this.Decoder.UnderlyingVariable(right))

            IType refinedIntv;
            var   rightVar = decoder.UnderlyingVariable(right);

            if (IntervalInference.TryRefine_KLessEqualThanRight(isSignedComparison, kLeft, rightVar, iquery, out refinedIntv))
            {
                // If it is an unsigned comparison, and it is a constant, then we should avoid generating the constraint
                // Example: left <={un} right, with right == -1 then we do not want to generate the constraint right == 2^{32}-1 which is wrong!

                // unsigned ==> right is not a constant
                if (isSignedComparison || !kRight.IsSingleton)
                {
                    result.Add(rightVar, refinedIntv);
                }
            }

            //AssumeLeftLessEqualThanK(this.Decoder.UnderlyingVariable(left), kRight);
            var leftVar = decoder.UnderlyingVariable(left);

            if (IntervalInference.TryRefine_LeftLessEqualThanK(isSignedComparison, leftVar, kRight, iquery, out refinedIntv))
            {
                // unsigned ==> left is not a constant
                if (isSignedComparison || !kLeft.IsSingleton)
                {
                    result.Add(leftVar, refinedIntv);
                }
            }

            if (isSignedComparison)
            {
                Polynomial <Variable, Expression> guardInCanonicalForm;

                if (Polynomial <Variable, Expression> .TryToPolynomialForm(ExpressionOperator.LessEqualThan, left, right, decoder, out guardInCanonicalForm) &&
                    guardInCanonicalForm.IsLinear)
                {
                    // We consider only the case when there is at MOST one variable on the left, i.e. a * x \leq b, or TWO, i.e. a*x +b*y <= c
                    if (guardInCanonicalForm.Left.Length == 1)
                    {
                        return(HelperFortestTrueLessEqualThan_AxLeqK(guardInCanonicalForm, iquery, result, out isBottom));
                    }
                    else if (guardInCanonicalForm.Left.Length == 2)
                    {
                        return(HelperFortestTrueLessEqualThan_AxByLtK(guardInCanonicalForm, iquery, result, out isBottom));
                    }
                }
            }

            return(result);
        }
 static public Polynomial Multiply(Polynomial p1, Polynomial p2)
 {
     return(Distributor.Distribute(p1, p2));
 }
        static public List <Pair <Variable, IType> > InferConstraints_LT <Variable, Expression, IType>(
            bool isSignedComparison,
            Expression left, Expression right,
            IExpressionDecoder <Variable, Expression> decoder,
            ISetOfNumbersAbstraction <Variable, Expression, Rational, IType> iquery,
            out bool isBottom)
            where IType : IntervalBase <IType, Rational>
        {
            Contract.Ensures(Contract.Result <List <Pair <Variable, IType> > >() != null);

            isBottom = false; // False untils someone proves the contrary

            var result = new List <Pair <Variable, IType> >();

            var kLeft  = iquery.Eval(left);
            var kRight = iquery.Eval(right);

            if (!isSignedComparison && !IsFloat(left, decoder) && !IsFloat(right, decoder))
            {
                kLeft  = kLeft.ToUnsigned();
                kRight = kRight.ToUnsigned();
            }

            IType refinedIntv;
            var   rightVar = decoder.UnderlyingVariable(right);

            var succ = IsFloat(left, decoder) || IsFloat(right, decoder) ? Rational.For(0) : Rational.For(1);

            if (TryRefine_KLessThanRight(isSignedComparison, kLeft, rightVar, succ, iquery, out refinedIntv))
            {
                // If it is an unsigned comparison, and it is a constant, then we should avoid generating the constraint
                // Example: left <{un} right, with right == -1 then we do not want to generate the constraint right == 2^{32}-1 which is wrong!

                // unsigned ==> right is not a constant
                if (isSignedComparison || !kRight.IsSingleton)
                {
                    result.Add(rightVar, refinedIntv);
                }
            }

            if (IsFloat(left, decoder) || IsFloat(right, decoder))
            {
                return(result);
            }

            var leftVar = decoder.UnderlyingVariable(left);

            if (TryRefine_LeftLessThanK(isSignedComparison, leftVar, kRight, iquery, out refinedIntv))
            {
                // As above
                // unsigned ==> right is not a constant
                if (isSignedComparison || !kLeft.IsSingleton)
                {
                    result.Add(leftVar, refinedIntv);
                }
            }

            if (isSignedComparison)
            {
                // Try to infer some more fact
                Polynomial <Variable, Expression> guardInCanonicalForm;
                if (Polynomial <Variable, Expression> .TryToPolynomialForm(ExpressionOperator.LessThan, left, right, decoder, out guardInCanonicalForm) &&
                    guardInCanonicalForm.IsLinear)
                {
                    // First, we consider only the case when there is at MOST one variable on the left, i.e. a * x < b
                    {
                        if (guardInCanonicalForm.Left.Length == 1)
                        {
                            result = HelperFortestTrueLessThan_AxLtK(guardInCanonicalForm, iquery, result, out isBottom);
                        }
                        // Then, we consider the case when it is in the form a*x + b*y < k
                        else if (guardInCanonicalForm.Left.Length == 2)
                        {
                            return(HelperFortestTrueLessThan_AxByLtK(guardInCanonicalForm, iquery, result, out isBottom));
                        }
                    }
                }
                else
                {
                    #region Try to infer something else...
                    switch (decoder.OperatorFor(left))
                    {
                    case ExpressionOperator.And: // case "(leftLeft && leftRight) < right
                        var leftRight = decoder.RightExpressionFor(left);

                        Int32 valueLeft;
                        if (decoder.IsConstantInt(leftRight, out valueLeft))
                        {
                            if (IsPowerOfTwoMinusOne(valueLeft))
                            { // add the constraint " 0 <= right < valueLeft "
                                var oldVal  = iquery.Eval(right);
                                var evalVal = iquery.Eval(left);
                                var newVal  = iquery.For(Rational.For(0), Rational.For(valueLeft - 1)); //  [0, valueLeft-1], "-1" as we know it is an integer

                                result.Add(rightVar, oldVal.Meet(newVal).Meet(evalVal));
                            }
                        }
                        break;

                    default:
                        // do nothing...
                        break;
                    }

                    #endregion
                }
            }
            return(result);
        }
Example #34
0
        /// <summary>
        /// Inverting <paramref name="gcd"/> polynomial in ring GF[x]/x^<paramref name="modularPolynomialDegree"/>-1
        /// </summary>
        private static Polynomial InvertGcdInPolynomialsRing(Polynomial gcd, int modularPolynomialDegree)
        {
            var result = new Polynomial(gcd.Field, gcd.Field.InverseForMultiplication(gcd[gcd.Degree]));

            return(gcd.Degree == 0 ? result : result.RightShift((modularPolynomialDegree - gcd.Degree) % modularPolynomialDegree));
        }
        public void Polynomial_InitializeTest(double[] coeffs)
        {
            Polynomial newPolynomial = new Polynomial(coeffs);

            Assert.IsNotNull(newPolynomial);
        }
Example #36
0
    private static void elim(Vector expr, Vector vars, int n)
    {
        if (n >= expr.Length())
        {
            return;
        }
        double     maxc = 0.0;
        int        iv = 0, ie = 0;
        Variable   vp = null;
        Algebraic  f  = Symbolic.ONE;
        Polynomial pm = null;

        for (int i = 0; i < vars.Length(); i++)
        {
            var v = ((Polynomial)vars[i])._v;
            for (int k = n; k < expr.Length(); k++)
            {
                var pa = expr[k];
                if (pa is Polynomial)
                {
                    var    p  = (Polynomial)pa;
                    var    c  = p.coefficient(v, 1);
                    double nm = c.Norm();
                    if (nm > maxc)
                    {
                        maxc = nm;
                        vp   = v;
                        ie   = k;
                        iv   = i;
                        f    = c;
                        pm   = p;
                    }
                }
            }
        }
        if (maxc == 0.0)
        {
            return;
        }

        expr.set(ie, expr[n]);
        expr.set(n, pm);

        for (int i = n + 1; i < expr.Length(); i++)
        {
            var p = expr[i];

            if (p is Polynomial)
            {
                var fc = ((Polynomial)p).coefficient(vp, 1);

                if (!fc.Equals(Symbolic.ZERO))
                {
                    p = p - pm * fc / f;
                }
            }

            expr.set(i, p);
        }

        elim(expr, vars, n + 1);
    }
Example #37
0
 /// <summary>
 /// Search zeroes of a polynomial function by executing a bisection algorithm
 /// using Sturm's theorem
 /// </summary>
 /// <param name="poly">the function, whose zeroes are searched</param>
 /// <param name="num">the number of the wanted zero; counting starts from<code>lower</code></param>
 /// <param name="lower">lower bound of the interval, in which the zero is searched</param>
 /// <param name="upper">upper bound of the interval, in which the zero is searched</param>
 /// <param name="iterations">maximum number of iterations (the more iterations, the more
 /// precise the result); the algorithm stops before that maximum
 /// number, when it reaches sufficient precision (machine
 /// precision)</param>
 /// <returns>The zero</returns>
 public static double solve(Polynomial poly, int num, double lower,
                            double upper, int iterations)
 {
     return(bisection(calculateSturm(poly), num, lower, upper,
                      FLOATING_POINT_PRECISION, iterations));
 }
Example #38
0
 public AlgebraicFactorbaseBuilder(Polynomial polynomial, IRootFinder rootFinder, long primeBound)
 {
     _primeBound = primeBound;
     _rootFinder = rootFinder;
     _polynomial = polynomial;
 }
Example #39
0
        public void GridsearchConstructorTest()
        {
            Accord.Math.Random.Generator.Seed = 0;

            // Example binary data
            double[][] inputs =
            {
                new double[] { -1, -1 },
                new double[] { -1,  1 },
                new double[] {  1, -1 },
                new double[] {  1,  1 }
            };

            int[] xor = // xor labels
            {
                -1, 1, 1, -1
            };

            // Declare the parameters and ranges to be searched
            GridSearchRange[] ranges =
            {
                new GridSearchRange("complexity", new double[] { 0.00000001, 5.20, 0.30, 0.50 }),
                new GridSearchRange("degree",     new double[] {          1,   10,    2,3, 4, 5 }),
                new GridSearchRange("constant",   new double[] {          0,    1, 2 })
            };


            // Instantiate a new Grid Search algorithm for Kernel Support Vector Machines
            var gridsearch = new GridSearch <KernelSupportVectorMachine>(ranges);

#if DEBUG
            gridsearch.ParallelOptions.MaxDegreeOfParallelism = 1;
#endif

            // Set the fitting function for the algorithm
            gridsearch.Fitting = delegate(GridSearchParameterCollection parameters, out double error)
            {
                // The parameters to be tried will be passed as a function parameter.
                int    degree     = (int)parameters["degree"].Value;
                double constant   = parameters["constant"].Value;
                double complexity = parameters["complexity"].Value;

                // Use the parameters to build the SVM model
                Polynomial kernel = new Polynomial(degree, constant);
                KernelSupportVectorMachine ksvm = new KernelSupportVectorMachine(kernel, 2);

                // Create a new learning algorithm for SVMs
                SequentialMinimalOptimization smo = new SequentialMinimalOptimization(ksvm, inputs, xor);
                smo.Complexity = complexity;

                // Measure the model performance to return as an out parameter
                error = smo.Run();

                return(ksvm); // Return the current model
            };


            // Declare some out variables to pass to the grid search algorithm
            GridSearchParameterCollection bestParameters; double minError;

            // Compute the grid search to find the best Support Vector Machine
            KernelSupportVectorMachine bestModel = gridsearch.Compute(out bestParameters, out minError);


            // A linear kernel can't solve the xor problem.
            Assert.AreEqual(1, bestParameters["degree"].Value);
            Assert.AreEqual(1, bestParameters["constant"].Value);
            Assert.AreEqual(1e-8, bestParameters["complexity"].Value);

            // The minimum error should be zero because the problem is well-known.
            Assert.AreEqual(minError, 0.0);


            Assert.IsNotNull(bestModel);
            Assert.IsNotNull(bestParameters);
            Assert.AreEqual(bestParameters.Count, 3);
        }
Example #40
0
        public void Test_FromString_ExponentSyntaxException(string input, string expectedError)
        {
            Exception ex = Assert.Throws <ExponentSyntaxException>(() => Polynomial.FromString(input));

            Assert.Equal(expectedError, ex.Message);
        }
        /// <summary>
        /// Infer exp \in [0, +oo], and if exp is a compound expression also some other constraints
        /// </summary>
        static public List <Pair <Variable, IType> > InferConstraints_GeqZero <Variable, Expression, IType>(
            Expression exp, IExpressionDecoder <Variable, Expression> decoder,
            ISetOfNumbersAbstraction <Variable, Expression, Rational, IType> iquery)
            where IType : IntervalBase <IType, Rational>
        {
            Contract.Requires(decoder != null);
            Contract.Requires(iquery != null);

            Contract.Ensures(Contract.Result <List <Pair <Variable, IType> > >() != null);

            var result = new List <Pair <Variable, IType> >();

            var expVar = decoder.UnderlyingVariable(exp);

            result.Add(expVar, iquery.Eval(exp).Meet(iquery.Interval_Positive));

            if (!decoder.IsVariable(exp))
            {
                Polynomial <Variable, Expression> zero; // = 0

                if (!Polynomial <Variable, Expression> .TryToPolynomialForm(new Monomial <Variable>[] { new Monomial <Variable>(0) }, out zero))
                {
                    throw new AbstractInterpretationException("It can never be the case that the conversion of a list of monomials into a polynomial fails");
                }

                Polynomial <Variable, Expression> expAsPolynomial, newPolynomial;

                if (Polynomial <Variable, Expression> .TryToPolynomialForm(exp, decoder, out expAsPolynomial) &&
                    Polynomial <Variable, Expression> .TryToPolynomialForm(ExpressionOperator.LessEqualThan, zero, expAsPolynomial, out newPolynomial)) // 0 <= exp
                {
                    if (newPolynomial.IsIntervalForm)
                    { // if it is in the form of k1 * x <= k2
                        var k1 = newPolynomial.Left[0].K;
                        var x  = newPolynomial.Left[0].VariableAt(0);

                        var k2 = newPolynomial.Right[0].K;

                        Rational bound;
                        if (Rational.TryDiv(k2, k1, out bound)) //var bound = k2 / k1;
                        {
                            if (k1 > 0)
                            {
                                var intv = iquery.Eval(x).Meet(iquery.IntervalLeftOpen(bound));
                                result.Add(x, intv);
                            }
                            else if (k1 < 0)
                            {
                                var intv = iquery.Eval(x).Meet(iquery.IntervalRightOpen(bound));
                                result.Add(x, intv);
                            }
                            else
                            {
                                throw new AbstractInterpretationException("Impossible case");
                            }
                        }
                    }
                }
            }

            return(result);
        }
Example #42
0
 public void Test_FromPolynomial_Null()
 {
     Assert.Null(Polynomial.FromPolynomial(null));
 }
Example #43
0
 /// <summary>Gets informations of the current object as a specific <see cref="InfoOutput" /> instance.
 /// </summary>
 /// <param name="infoOutput">The <see cref="InfoOutput" /> object which is to be filled with informations concering the current instance.</param>
 /// <param name="categoryName">The name of the category, i.e. all informations will be added to these category.</param>
 public void FillInfoOutput(InfoOutput infoOutput, string categoryName = InfoOutput.GeneralCategoryName)
 {
     Polynomial.FillInfoOutput(this, infoOutput.AcquirePackage(categoryName));
 }
Example #44
0
        internal override void Operate(Interval operand1, ref IntervalSet output)
        {
            Polynomial result = (operand1.Polynomial ^ 2);

            output.AddInterval(new Interval(output, operand1.LowerBound, operand1.UpperBound, result));
        }
        public void Equals_Null_False()
        {
            Polynomial a = Polynomial1;

            Assert.False(a.Equals(null));
        }
Example #46
0
        public void ShouldPerformDecodeReceivedCodevord(int n, int k, Tuple <FieldElement, FieldElement>[] decodedCodeword, int errorsCount, Polynomial expectedInformationPolynomial)
        {
            // When
            var actualInformationPolynomial = _decoder.Decode(n, k, decodedCodeword, errorsCount);

            // Then
            Assert.Equal(expectedInformationPolynomial, actualInformationPolynomial);
        }
Example #47
0
        /// <summary>
        /// Method for computing wavelet code's codeword for information polynomial <paramref name="informationPolynomial"/>
        /// </summary>
        /// <param name="n">Codeword length</param>
        /// <param name="generatingPolynomial">Generating polynomial of the wavelet code</param>
        /// <param name="informationPolynomial">Information polynomial</param>
        /// <param name="modularPolynomial">Modular polynomial for wavelet code encoding scheme</param>
        /// <returns>Computed codeword</returns>
        public Tuple <FieldElement, FieldElement>[] Encode(int n, Polynomial generatingPolynomial, Polynomial informationPolynomial,
                                                           Polynomial modularPolynomial = null)
        {
            var field = generatingPolynomial.Field;
            var m     = modularPolynomial;

            if (m == null)
            {
                m    = new Polynomial(field, 1).RightShift(n);
                m[0] = field.InverseForAddition(1);
            }
            var codeWordPolynomial = (informationPolynomial.RaiseVariableDegree(2) * generatingPolynomial) % m;

            var i        = 0;
            var codeword = new Tuple <FieldElement, FieldElement> [n];

            for (; i <= codeWordPolynomial.Degree; i++)
            {
                codeword[i] = Tuple.Create(field.CreateElement(field.GetGeneratingElementPower(i)), field.CreateElement(codeWordPolynomial[i]));
            }
            for (; i < n; i++)
            {
                codeword[i] = Tuple.Create(field.CreateElement(field.GetGeneratingElementPower(i)), field.Zero());
            }

            return(codeword);
        }
Example #48
0
 private static object[] PrepareTestsDataWithoutErrors(int n, int k, IEncoder encoder, Polynomial informationPolynomial, int errorsCount)
 {
     return(new object[]
     {
         n, k,
         encoder.Encode(n, informationPolynomial), errorsCount,
         informationPolynomial
     });
 }
Example #49
0
 private static object[] PrepareTestsWithErrors(int n, int k, IEncoder encoder, Polynomial informationPolynomial, int randomErrorsCount)
 {
     return(new object[]
     {
         n, k,
         AddRandomNoise(encoder.Encode(n, informationPolynomial), randomErrorsCount), randomErrorsCount,
         informationPolynomial
     });
 }
        /// <summary>
        /// Because of expression reconstruction, ptr is refined to exp[base]
        /// We generate the two proof obligations:
        /// offset >= 0 (lower bound)
        /// offset + sizeof(type) \leq WB(base)
        /// </summary>
        /// <returns>false if no proof obligation could be inferred</returns>
        public static bool TryInferSafeBufferAccessConstraints <Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions>
        (
            this IMethodDriver <Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mdriver, APC pc, Type type,
            Variable ptr,
            out BoxedExpression lowerBound, out BoxedExpression upperBound
        )
            where Type : IEquatable <Type>
            where Expression : IEquatable <Expression>
            where Variable : IEquatable <Variable>
            where LogOptions : IFrameworkLogOptions
        {
            var ptrType = mdriver.Context.ValueContext.GetType(pc, ptr);

            // If we do not have a type, or it is a managed pointer, we are done
            if (!ptrType.IsNormal || mdriver.MetaDataDecoder.IsManagedPointer(ptrType.Value))
            {
                return(FailedToInferObligation(out lowerBound, out upperBound));
            }

            // F: need to consider when sizeof is there?

            Polynomial <BoxedVariable <Variable>, BoxedExpression> pol;

            if (Polynomial <BoxedVariable <Variable>, BoxedExpression> .TryToPolynomialForm(BoxedExpression.For(mdriver.Context.ExpressionContext.Refine(pc, ptr), mdriver.ExpressionDecoder), mdriver.BoxedDecoder(), out pol))
            {
                Contract.Assume(!object.ReferenceEquals(pol, null));

                BoxedExpression basePtr, wbPtr, offset;

                if (!mdriver.TrySplitBaseWBAndOffset(pc, pol, out basePtr, out wbPtr, out offset))
                {
                    return(FailedToInferObligation(out lowerBound, out upperBound));
                }

                // 0 <= offset
                lowerBound = BoxedExpression.Binary(BinaryOperator.Cle, BoxedExpression.Const(0, mdriver.MetaDataDecoder.System_Int32, mdriver.MetaDataDecoder), offset);

                // offset + sizeof(T) <= WB
                var size = mdriver.MetaDataDecoder.TypeSize(type);

                if (size >= 0)
                {
                    //var neededbytes = BoxedExpression.Binary(BinaryOperator.Add, offset, BoxedExpression.SizeOf(type, size));
                    var neededbytes = BoxedExpression.Binary(BinaryOperator.Add,
                                                             offset, BoxedExpression.Const(size, mdriver.MetaDataDecoder.System_Int32, mdriver.MetaDataDecoder));

                    upperBound = BoxedExpression.Binary(BinaryOperator.Cle, neededbytes, wbPtr);
                }
                else // We cannot get the size statically, and we create an expression with the size expressed symbolically
                {
                    var neededbytes = BoxedExpression.Binary(BinaryOperator.Add, offset, BoxedExpression.SizeOf(type, size));

                    upperBound = BoxedExpression.Binary(BinaryOperator.Cle, neededbytes, wbPtr);
                }

                return(true);
            }
            else
            {
                // TODO: Consider the non-polynomial case
                // F: for instance "*(p + a/b)" we do not infer any proof obligation.
                return(FailedToInferObligation(out lowerBound, out upperBound));
            }
        }
        //private readonly string mssKey = "82069A88-26BD-4902-9CA6-7AE324193FE3:X";
        //private readonly string nssKey = "0EECCFF2-8CAE-4D65-935F-15E1AF31709B:X" ;

        public bool GetShapeFunctions(Element targetElement, out Polynomial[] nss, out Polynomial[] mss)
        {
            nss = null;
            mss = null;

            var mssKey = "7AE324193FE3:X" + this.Direction;
            var nssKey = "15E1AF31709B:X" + this.Direction;


            var sb = new StringBuilder();

            var bar = targetElement as BarElement;

            var n = bar.NodeCount;


            List <Condition> cnds = null;

            {
                var xis = new Func <int, double>(i =>
                {
                    var delta = 2.0 / (n - 1);

                    return(-1 + delta * i);
                });

                bar.TryGetCache(mssKey, out mss);
                bar.TryGetCache(nssKey, out nss);

                if (nss != null && mss != null)
                {
                    //return true;

                    cnds = GetShapeFunctionConditions(bar);

                    var flag = true;

                    foreach (var cnd in cnds)
                    {
                        var pn = (cnd.Type == Condition.FunctionType.N) ? nss[cnd.NodeNumber] : mss[cnd.NodeNumber];

                        var epsilon = (pn.EvaluateDerivative(cnd.Xi, cnd.DifferentialDegree) - cnd.RightSide);

                        if (epsilon < 0)
                        {
                            epsilon *= -1;
                        }

                        if (epsilon > 1e-10)
                        {
                            flag = false;
                            break;
                        }
                    }

                    if (flag)
                    {
                        CondsListPool.Free(cnds);
                        return(true);
                    }
                    else
                    {
                        mss = nss = null;
                    }
                }

                if (cnds == null)
                {
                    cnds = GetShapeFunctionConditions(bar);
                }
            }


            var grpd = cnds.GroupBy(i => Tuple.Create(i.NodeNumber, i.Type)).ToArray();

            CondsListPool.Free(cnds);

            mss = new Polynomial[n];
            nss = new Polynomial[n];

            foreach (var grp in grpd)
            {
                var nodeNum   = grp.Key.Item1;
                var tp        = grp.Key.Item2;
                var condCount = grp.Count();

                var mtx =
                    bar.MatrixPool.Allocate(condCount, condCount);
                //new Matrix(condCount, condCount);

                var rightSide =
                    bar.MatrixPool.Allocate(condCount, 1);
                //new Matrix(condCount, 1);

                var arr = grp.ToArray();

                for (var i = 0; i < arr.Length; i++)
                {
                    var itm = arr[i];

                    mtx.SetRow(i, Diff(itm.Xi, condCount - 1, itm.DifferentialDegree));

                    rightSide.SetRow(i, itm.RightSide);
                }

                Polynomial pl;

                if (arr.Length != 0)
                {
                    //var cfs = mtx.Inverse2() * rightSide;
                    var cfs = mtx.Solve(rightSide.CoreArray);//.Inverse2() * rightSide;

                    pl = new Polynomial(cfs);
                }
                else
                {
                    pl = new Polynomial();
                }

                //bar.ReturnMatrixToPool(rightSide, mtx);

                if (tp == Condition.FunctionType.M)
                {
                    mss[nodeNum] = pl;
                }

                if (tp == Condition.FunctionType.N)
                {
                    nss[nodeNum] = pl;
                }

                mtx.ReturnToPool();
                rightSide.ReturnToPool();
            }

            for (var i = 0; i < n; i++)
            {
                if (nss[i] == null)
                {
                    nss[i] = new Polynomial();
                }

                if (mss[i] == null)
                {
                    mss[i] = new Polynomial();
                }
            }

            {
                bar.SetCache(nssKey, nss);
                bar.SetCache(mssKey, mss);
            }


            return(true);
        }
        private static bool TrySplitBaseWBAndOffset <Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions>
        (
            this IMethodDriver <Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mdriver,
            APC pc, Polynomial <BoxedVariable <Variable>, BoxedExpression> pol, out BoxedExpression basePtr, out BoxedExpression wbPtr, out BoxedExpression offset
        )
            where LogOptions : IFrameworkLogOptions
            where Type : IEquatable <Type>
            where Variable : IEquatable <Variable>
            where Expression : IEquatable <Expression>
        {
            var foundAPointer = false;
            var offsets       = new List <Monomial <BoxedVariable <Variable> > >(pol.Left.Length);
            var basePtrVar    = default(Variable);

            // 1. Fetch the pointer
            foreach (var m in pol.Left)
            {
                BoxedVariable <Variable> tryVar;
                Variable v;
                if (m.IsVariable(out tryVar) && tryVar.TryUnpackVariable(out v))
                {
                    var type = mdriver.Context.ValueContext.GetType(mdriver.Context.MethodContext.CFG.Post(pc), v);

                    if (type.IsNormal && (mdriver.MetaDataDecoder.IsUnmanagedPointer(type.Value) || mdriver.MetaDataDecoder.IsReferenceType(type.Value)))
                    {
                        basePtrVar = v;

                        Contract.Assume(foundAPointer == false);
                        foundAPointer = true;

                        continue;
                    }
                }
                offsets.Add(m);
            }

            if (!foundAPointer)
            {
                basePtr = offset = wbPtr = default(BoxedExpression);

                return(false);
            }

            // 2. Get the WB

            Variable varForWB;

            if (!mdriver.Context.ValueContext.TryGetWritableBytes(mdriver.Context.MethodContext.CFG.Post(pc), basePtrVar, out varForWB))
            {
                basePtr = offset = wbPtr = default(BoxedExpression);

                return(false);
            }

            // 3. Construct the offset
            Polynomial <BoxedVariable <Variable>, BoxedExpression> tmpPol;

            if (!Polynomial <BoxedVariable <Variable>, BoxedExpression> .TryToPolynomialForm(offsets.ToArray(), out tmpPol))
            {
                throw new AbstractInterpretationException("Impossible case?");
            }

            basePtr = BoxedExpression.Var(basePtrVar);
            wbPtr   = BoxedExpression.Var(varForWB);
            offset  = tmpPol.ToPureExpression(mdriver.BoxedEncoder());

            return(true);
        }
Example #53
0
        private static void MultiplyFineFinalPolynomial(List <Polynomial> tPolynomial, List <Polynomial> fPolynomial, List <Polynomial> fgidPolynomial, double _fineResolution, double _mwResolution, double _fineMinProb)
        {
            int i = tPolynomial.Count;
            int j = fPolynomial.Count;

            if (i == 0 || j == 0)
            {
                return;
            }

            double deltaMass      = (_fineResolution / _mwResolution);
            double minProbability = _fineMinProb;

            double minMass = tPolynomial[0].Power + fPolynomial[0].Power;
            double maxMass = tPolynomial[i - 1].Power + fPolynomial[j - 1].Power;

            int maxIndex = (int)(Math.Abs(maxMass - minMass) / deltaMass + 0.5);

            if (maxIndex >= fgidPolynomial.Count)
            {
                j = maxIndex - fgidPolynomial.Count;
                for (i = 0; i <= j; i++)
                {
                    fgidPolynomial.Add(new Polynomial {
                        Probablity = double.NaN, Power = double.NaN
                    });
                }
            }

            for (int t = 0; t < tPolynomial.Count; t++)
            {
                for (int f = 0; f < fPolynomial.Count; f++)
                {
                    double prob = tPolynomial[t].Probablity * fPolynomial[f].Probablity;
                    if (prob <= minProbability)
                    {
                        continue;
                    }

                    double power  = tPolynomial[t].Power + fPolynomial[f].Power;
                    var    indext = (int)(Math.Abs(power - minMass) / deltaMass + 0.5);

                    Polynomial tempPolynomial = fgidPolynomial[indext];

                    var poww  = tempPolynomial.Power;
                    var probb = tempPolynomial.Probablity;
                    if (double.IsNaN(poww) || double.IsNaN(prob))
                    {
                        fgidPolynomial[indext] = new Polynomial {
                            Power = power * prob, Probablity = prob
                        }
                    }
                    ;
                    else
                    {
                        fgidPolynomial[indext] = new Polynomial {
                            Power = poww + power * prob, Probablity = probb + prob
                        }
                    };
                }
            }

            var index = tPolynomial.Count;

            j = 0;
            for (i = 0; i < fgidPolynomial.Count; i++)
            {
                if (!double.IsNaN(fgidPolynomial[i].Probablity))
                {
                    if (j < index)
                    {
                        tPolynomial[j] = new Polynomial {
                            Power = fgidPolynomial[i].Power / fgidPolynomial[i].Probablity, Probablity = fgidPolynomial[i].Probablity
                        };
                        j++;
                    }
                    else
                    {
                        tPolynomial.Add(new Polynomial {
                            Power = fgidPolynomial[i].Power / fgidPolynomial[i].Probablity, Probablity = fgidPolynomial[i].Probablity
                        });
                    }
                }

                fgidPolynomial[i] = new Polynomial {
                    Probablity = double.NaN, Power = double.NaN
                };
            }

            if (j < index)
            {
                tPolynomial.RemoveRange(j, tPolynomial.Count - j);
            }
        }
        /// <summary>
        /// Handles the case when the guard is in the form of "A*x + B*y &lt; k"
        /// </summary>
        /// <param name="guardInCanonicalForm">A polynomial that must have been already put into canonical form</param>
        static private List <Pair <Variable, IType> > HelperFortestTrueLessThan_AxByLtK <Variable, Expression, IType>(
            Polynomial <Variable, Expression> guardInCanonicalForm, ISetOfNumbersAbstraction <Variable, Expression, Rational, IType> iquery,
            List <Pair <Variable, IType> > result,
            out bool isBottom)
            where IType : IntervalBase <IType, Rational>
        {
            Contract.Requires(!object.ReferenceEquals(guardInCanonicalForm, null));
            Contract.Requires(iquery != null);
            Contract.Requires(result != null);
            Contract.Requires(guardInCanonicalForm.Left.Length == 2);
            Contract.Requires(guardInCanonicalForm.Right.Length == 1);

            Contract.Ensures(Contract.Result <List <Pair <Variable, IType> > >() != null);

            isBottom = false; // False, unless another proof

            var monomialForX = guardInCanonicalForm.Left[0];
            var monomialForY = guardInCanonicalForm.Left[1];

            var X = monomialForX.VariableAt(0);
            var Y = monomialForY.VariableAt(0);

            var K = guardInCanonicalForm.Right[0].K;

            var A = monomialForX.K;
            var B = monomialForY.K;

            var intervalForA = iquery.For(A);
            var intervalForB = iquery.For(B);
            var intervalForK = iquery.For(K);

            var intervalForX = iquery.Eval(X);
            var intervalForY = iquery.Eval(Y);

            // 1. Handle the case for x

            // evalForX =(k - b * y) / a
            var evalForX = iquery.Interval_Div((iquery.Interval_Sub(intervalForK, (iquery.Interval_Mul(intervalForB, intervalForY)))), intervalForA);

            if (A > 0)
            { // x < (k - b * y) / a
                var   upperBound = evalForX.UpperBound;
                IType gt;
                if (upperBound.IsInteger)
                {
                    gt = iquery.IntervalLeftOpen(upperBound - 1);
                }
                else
                {
                    gt = iquery.IntervalLeftOpen(upperBound.PreviousInt32);
                }

                var intv = intervalForX.Meet(gt);

                if (intv.IsBottom)
                {
                    isBottom = true;
                    return(result);
                }
                result.Add(X, intv);
            }
            else if (A < 0)
            { // x > (k - b * y) / a
                var lowerBound = evalForX.LowerBound;

                IType lt;

                if (lowerBound.IsInteger)
                {
                    lt = iquery.IntervalRightOpen(lowerBound + 1);
                }
                else
                {
                    lt = iquery.IntervalRightOpen(lowerBound.NextInt32);
                }

                var intv = intervalForX.Meet(lt);

                if (intv.IsBottom)
                {
                    isBottom = true;
                    return(result);
                }
                result.Add(X, intv);
            }
            else
            {
                Contract.Assert(false, "Cannot have a == 0");
            }

            // 2. Handle the case for y

            // evalForY =(k - a * x) / b
            var evalForY = iquery.Interval_Div((iquery.Interval_Sub(intervalForK, (iquery.Interval_Mul(intervalForA, intervalForX)))), intervalForB);

            if (B > 0)
            { // y < (k - a * x) / b
                var   upperBound = evalForY.UpperBound;
                IType gt;

                if (upperBound.IsInteger)
                {
                    gt = iquery.IntervalLeftOpen(upperBound - 1);
                }
                else
                {
                    gt = iquery.IntervalLeftOpen(upperBound.PreviousInt32);
                }

                var intv = intervalForY.Meet(gt);
                if (intv.IsBottom)
                {
                    isBottom = true;
                    return(result);
                }

                result.Add(Y, intv);
            }
            else if (B < 0)
            { // x > (k - a * x) / b
                var   lowerBound = evalForY.LowerBound;
                IType lt;

                if (lowerBound.IsInteger)
                {
                    lt = iquery.IntervalRightOpen(lowerBound + 1);
                }
                else
                {
                    lt = iquery.IntervalRightOpen(lowerBound.NextInt32);
                }

                var intv = intervalForY.Meet(lt);

                if (intv.IsBottom)
                {
                    isBottom = true;
                    return(result);
                }

                result.Add(Y, intv);
            }
            else
            {
                Contract.Assert(false, "Cannot have b == 0");
            }

            return(result);
        }
Example #55
0
 /// <summary>
 /// Search zeroes of a polynomial function by executing a bisection algorithm
 /// using Sturm's theorem
 /// </summary>
 /// <param name="poly">the function, whose zeroes are searched</param>
 /// <param name="num">the number of the wanted zero; counting starts from<code>lower</code></param>
 /// <param name="lower">lower bound of the interval, in which the zero is searched</param>
 /// <param name="upper">upper bound of the interval, in which the zero is searched</param>
 /// <param name="precision">tolerance in comparing function values</param>
 /// <param name="iterations">maximum number of iterations (the more iterations, the more
 /// precise the result); the algorithm stops before that maximum
 /// number, when it reaches sufficient precision (machine
 /// precision)</param>
 /// <returns>The zero</returns>
 public static double solve(Polynomial poly, int num, double lower,
                            double upper, double precision, int iterations)
 {
     return(bisection(calculateSturm(poly), num, lower, upper, precision,
                      iterations));
 }
        /// <summary>
        /// Handles the case when the guard is in the form of "A*x &lt; k"
        /// </summary>
        /// <param name="guardInCanonicalForm">A polynomial that must have been already put into canonical form</param>
        static private List <Pair <Variable, IType> > HelperFortestTrueLessThan_AxLtK <Variable, Expression, IType>(
            Polynomial <Variable, Expression> guardInCanonicalForm, ISetOfNumbersAbstraction <Variable, Expression, Rational, IType> iquery,
            List <Pair <Variable, IType> > result,
            out bool isBottom)
            where IType : IntervalBase <IType, Rational>
        {
            Contract.Requires(!object.ReferenceEquals(guardInCanonicalForm, null));
            Contract.Requires(guardInCanonicalForm.Right.Length == 1);
            Contract.Requires(iquery != null);
            Contract.Requires(result != null);

            Contract.Ensures(Contract.Result <List <Pair <Variable, IType> > >() != null);

            isBottom = false;

            var MonomialForX = guardInCanonicalForm.Left[0];
            var MonomilaForB = guardInCanonicalForm.Right[0];

            Contract.Assert(MonomilaForB.IsConstant);

            // 1. We have a case a < b
            if (MonomialForX.IsConstant)
            {
                var a = MonomialForX.K;
                var b = MonomilaForB.K;

                if (a >= b)
                {
                    isBottom = true;
                }
            }
            else // 2. We have the case a * x < b
            {
                var x = MonomialForX.VariableAt(0);

                Rational k;
                if (!Rational.TryDiv(MonomilaForB.K, MonomialForX.K, out k)) //var k = MonomilaForB.K / MonomialForX.K;
                {
                    return(result);
                }

                var oldValueForX = iquery.Eval(x);

                IType newConstraint;
                if (MonomialForX.K.Sign == 1)
                { // The constraint is x < k, but if k is a rational, we approximate it with x \leq k
                    if (k.IsInteger)
                    {
                        newConstraint = iquery.IntervalLeftOpen(k - 1);
                    }
                    else
                    {
                        newConstraint = iquery.IntervalLeftOpen(k.PreviousInt32);
                    }
                }
                else
                { // The constraint is x > k, but if k is a rational, we approximate it with k \leq x
                    if (k.IsInteger)
                    {
                        newConstraint = iquery.IntervalRightOpen(k + 1);
                    }
                    else
                    {
                        newConstraint = iquery.IntervalRightOpen(k.NextInt32);
                    }
                }

                var newValueForX = oldValueForX.Meet(newConstraint);

                if (newValueForX.IsBottom)
                {
                    isBottom = true;
                }
                else
                {
                    result.Add(x, newValueForX);
                }
            }

            return(result);
        }
Example #57
0
 public void Test_Null()
 {
     Polynomial polynomial = new Polynomial(null);
 }
        static private List <Pair <Variable, IType> > HelperFortestTrueLessEqualThan_AxLeqK <Variable, Expression, IType>(
            Polynomial <Variable, Expression> guardInCanonicalForm, ISetOfNumbersAbstraction <Variable, Expression, Rational, IType> iquery,
            List <Pair <Variable, IType> > result,
            out bool isBottom)
            where IType : IntervalBase <IType, Rational>
        {
            Contract.Requires(!object.ReferenceEquals(guardInCanonicalForm, null));
            Contract.Requires(result != null);
            Contract.Requires(guardInCanonicalForm.Right.Length == 1);

            Contract.Ensures(Contract.Result <List <Pair <Variable, IType> > >() != null);

            var MonomialForX = guardInCanonicalForm.Left[0];
            var MonomilaForB = guardInCanonicalForm.Right[0];

            Contract.Assert(MonomilaForB.IsConstant);

            isBottom = false;

            // 1. We have a case a <= b
            if (MonomialForX.IsConstant)
            {
                var a = MonomialForX.K;
                var b = MonomilaForB.K;

                if (a > b)
                {
                    isBottom = true;
                }
            }
            else // 2. We have the case a * x \leq b
            {
                var x = MonomialForX.VariableAt(0);

                Rational k;
                if (
                    MonomialForX.K.IsInteger &&
                    Rational.TryDiv(MonomilaForB.K, MonomialForX.K, out k))
                {
                    var oldValueForX = iquery.Eval(x);

                    IType newValueForX;

                    if (MonomialForX.K.Sign == 1)
                    { // The constraint is x \leq k
                        newValueForX = oldValueForX.Meet(iquery.IntervalLeftOpen(k));
                    }
                    else
                    { // The constraint is x \geq k
                        newValueForX = oldValueForX.Meet(iquery.IntervalRightOpen(k));
                    }

                    if (newValueForX.IsBottom)
                    {
                        isBottom = true;
                    }
                    else
                    {
                        Contract.Assert(isBottom == false);

                        result.Add(x, newValueForX);
                    }
                }
            }

            return(result);
        }
        public string Polynomial_ToStringTest(double[] firstCoeffs)
        {
            Polynomial firstPolynomial = new Polynomial(firstCoeffs);

            return(firstPolynomial.ToString());
        }
Example #60
0
 public AnalyzingSample(Polynomial informationPolynomial, Tuple <FieldElement, FieldElement>[] codeword)
 {
     InformationPolynomial = informationPolynomial;
     Codeword = codeword;
 }