Example #1
0
    public void Run()
    {
        using (Context ctx = new Context()) {
            ctx.UpdateParamValue("DL_ENGINE", "1");
            ctx.UpdateParamValue("DL_PDR_USE_FARKAS", "true");
//          ctx.UpdateParamValue("VERBOSE","2");
            var       s  = ctx.MkFixedpoint();
            BoolSort  B  = ctx.BoolSort;
            IntSort   I  = ctx.IntSort;
            FuncDecl  mc = ctx.MkFuncDecl("mc", new Sort[] { I, I }, B);
            ArithExpr x  = (ArithExpr)ctx.MkBound(0, I);
            ArithExpr y  = (ArithExpr)ctx.MkBound(1, I);
            ArithExpr z  = (ArithExpr)ctx.MkBound(2, I);
            s.RegisterRelation(mc);
            BoolExpr gt = ctx.MkGt(x, ctx.MkInt(100));
            s.AddRule(ctx.MkImplies(gt, (BoolExpr)mc[x, ctx.MkSub(x, ctx.MkInt(10))]));
            s.AddRule(ctx.MkImplies(ctx.MkAnd(ctx.MkNot(gt),
                                              (BoolExpr)mc[ctx.MkAdd(x, ctx.MkInt(11)), y],
                                              (BoolExpr)mc[y, z]),
                                    (BoolExpr)mc[x, z]));
            Console.WriteLine(s.Query(ctx.MkAnd((BoolExpr)mc[x, y], ctx.MkGt(y, ctx.MkInt(100)))));
            Console.WriteLine(s.GetAnswer());

            Console.WriteLine(s.Query(ctx.MkAnd((BoolExpr)mc[x, y], ctx.MkLt(y, ctx.MkInt(91)))));
            Console.WriteLine(s.GetAnswer());
        }
    }
Example #2
0
    public void Run()
    {
        Dictionary <string, string> cfg = new Dictionary <string, string>()
        {
            { "AUTO_CONFIG", "true" }
        };

        using (Context ctx = new Context(cfg))
        {
            IntExpr x = ctx.MkIntConst("x");
            IntExpr y = ctx.MkIntConst("y");

            Console.WriteLine(ctx.MkAdd(x, y) == ctx.MkAdd(x, y));
            Console.WriteLine(ctx.MkAdd(x, y) == ctx.MkAdd(y, x));

            ArithExpr n = ctx.MkAdd(x, y);

            Console.WriteLine(n == ctx.MkAdd(x, y));

            IntExpr x2 = ctx.MkIntConst("x");

            Console.WriteLine(x == x2);

            Console.WriteLine(ctx.MkIntConst("x") == ctx.MkRealConst("x"));
        }
    }
        public static BoolExpr GetSpec(ERelationalOperators opr, ArithExpr arg_1, ArithExpr arg_2, Context ctx)
        {
            switch (opr)
            {
            case (ERelationalOperators.Eq):
                return(ctx.MkEq(arg_1, arg_2));

            case (ERelationalOperators.Gt):
                return(ctx.MkGt(arg_1, arg_2));

            case (ERelationalOperators.L):
                return(ctx.MkLt(arg_1, arg_2));

            case (ERelationalOperators.GtEq):
                var first  = ctx.MkEq(arg_1, arg_2);
                var second = ctx.MkGt(arg_1, arg_2);
                return(ctx.MkOr(first, second));

            case (ERelationalOperators.LEq):
                var firsts  = ctx.MkEq(arg_1, arg_2);
                var seconds = ctx.MkLt(arg_1, arg_2);
                return(ctx.MkOr(firsts, seconds));
            }
            return(null);
        }
Example #4
0
        public BoolExpr IsNearerThan(Z3Point3D that, double distanceThreshold)
        {
            ArithExpr distance = this.CalcApproximateDistance(that);
            BoolExpr  result   = Z3.Context.MkLt(distance, Z3Math.Real(distanceThreshold));

            return(result);
        }
Example #5
0
    public void Run()
    {
        Dictionary<string, string> cfg = new Dictionary<string, string>() {
            { "AUTO_CONFIG", "true" } };

        using (Context ctx = new Context(cfg))
        {
            IntExpr[] X = new IntExpr[5];
            for (uint i = 0; i < 5; i++)
                X[i] = ctx.MkIntConst(string.Format("x_{0}", i));

            RealExpr[] Y = new RealExpr[5];
            for (uint i = 0; i < 5; i++)
                Y[i] = ctx.MkRealConst(string.Format("y_{0}", i));

            BoolExpr[] P = new BoolExpr[5];
            for (uint i = 0; i < 5; i++)
                P[i] = ctx.MkBoolConst(string.Format("p_{0}", i));

            foreach (Expr x in X)
                Console.WriteLine(x);
            foreach (Expr x in Y)
                Console.WriteLine(x);
            foreach (Expr x in P)
                Console.WriteLine(x);

            foreach (ArithExpr y in Y)
                Console.WriteLine(ctx.MkPower(y, ctx.MkReal(2)));

            ArithExpr[] Yp = new ArithExpr[Y.Length];
            for (uint i = 0; i < Y.Length; i++)
                Yp[i] = ctx.MkPower(Y[i], ctx.MkReal(2));
            Console.WriteLine(ctx.MkAdd(Yp));
        }
    }
Example #6
0
        private BoolExpr handleRealRectangularObstacle(RectangularObstacle obstacle, Context ctx, IntExpr[] sourcesX,
                                                       IntExpr[] sourcesY, IntExpr[] destinationsX, IntExpr[] destinationsY)
        {
            RealExpr obstacleLeftX  = ctx.MkReal(obstacle.realLocation.x.ToString(new CultureInfo("en-US")));
            RealExpr obstacleRightX = ctx.MkReal((obstacle.realLocation.x + obstacle.width).ToString(new CultureInfo("en-US")));
            RealExpr obstacleLeftY  = ctx.MkReal(obstacle.realLocation.y.ToString(new CultureInfo("en-US")));
            RealExpr obstacleRightY = ctx.MkReal((obstacle.realLocation.y + obstacle.length).ToString(new CultureInfo("en-US")));
            RealExpr passDistance   = ctx.MkReal(obstaclePassDistance);

            BoolExpr[] avoidingObstaclesX        = new BoolExpr[pathSegments];
            BoolExpr[] avoidingObstaclesY        = new BoolExpr[pathSegments];
            BoolExpr[] avoidingObstaclesCombined = new BoolExpr[pathSegments];
            for (int i = 0; i < pathSegments; i++)
            {
                ArithExpr xl_minus_xs = ctx.MkSub(obstacleLeftX, sourcesX[i]);
                ArithExpr xl_minus_xd = ctx.MkSub(obstacleLeftX, destinationsX[i]);
                ArithExpr xs_minus_xh = ctx.MkSub(sourcesX[i], obstacleRightX);
                ArithExpr xd_minus_xh = ctx.MkSub(destinationsX[i], obstacleRightX);
                avoidingObstaclesX[i] = ctx.MkOr(ctx.MkAnd(ctx.MkGe(xl_minus_xs, passDistance), ctx.MkGe(xl_minus_xd, passDistance)),
                                                 ctx.MkAnd(ctx.MkGe(xs_minus_xh, passDistance), ctx.MkGe(xd_minus_xh, passDistance)));

                ArithExpr yl_minus_ys = ctx.MkSub(obstacleLeftY, sourcesY[i]);
                ArithExpr yl_minus_yd = ctx.MkSub(obstacleLeftY, destinationsY[i]);
                ArithExpr ys_minus_yh = ctx.MkSub(sourcesY[i], obstacleRightY);
                ArithExpr yd_minus_yh = ctx.MkSub(destinationsY[i], obstacleRightY);
                avoidingObstaclesY[i] = ctx.MkOr(ctx.MkAnd(ctx.MkGe(yl_minus_ys, passDistance), ctx.MkGe(yl_minus_yd, passDistance)),
                                                 ctx.MkAnd(ctx.MkGe(ys_minus_yh, passDistance), ctx.MkGe(yd_minus_yh, passDistance)));
                avoidingObstaclesCombined[i] = ctx.MkOr(avoidingObstaclesX[i], avoidingObstaclesY[i]);
            }

            return(ctx.MkAnd(avoidingObstaclesCombined));
        }
Example #7
0
        //internal static SimpleBodyRestriction TouchRestriction(JointType jointType, JointSide handSide)
        //{
        //    double maxY = TrigonometryHelper.GetSine(5);

        //    return new TouchBodyRestriction(jointType, handSide);
        //}

        internal static BoolExpr EvaluateNorms(Z3Body body1, Z3Body body2)
        {
            double normsThreshold = 0.1;

            BoolExpr result     = Z3Math.True;
            var      jointTypes = EnumUtil.GetValues <JointType>();

            foreach (var jointType in jointTypes)
            {
                // Calc the distance between the two norms
                ArithExpr distance =
                    Z3Math.Abs(
                        Z3Math.Sub(
                            body1.Norms[jointType],
                            body2.Norms[jointType]));

                // Create the boolean expression to evaluate the distance
                result =
                    Z3.Context.MkAnd(
                        result,
                        Z3.Context.MkLt(
                            distance,
                            Z3Math.Real(normsThreshold)));
            }

            return(result);
        }
Example #8
0
        /// <summary>
        /// Adds a MSF variable with the coresponding assertion to the Z3 variables.
        /// </summary>
        /// <param name="vid">The MSF id of the variable</param>
        internal void AddVariable(int vid)
        {
            // Is the variable an integer
            bool isInteger = _model.GetIntegrality(vid);

            // Construct the sort we will be using
            Sort sort = isInteger ? (Sort)_context.IntSort : (Sort)_context.RealSort;

            // Get the variable key
            object key = _model.GetKeyFromIndex(vid);

            // Try to construct the name
            string name;

            if (key != null)
            {
                name = String.Format("x_{0}_{1}", key, vid);
            }
            else
            {
                name = String.Format("x_{0}", vid);
            }
            ArithExpr variable = (ArithExpr)_context.MkConst(name, sort);

            // Create the variable and add it to the map
            Debug.Assert(!_variables.ContainsKey(vid), "Variable names should be unique.");
            _variables.Add(vid, variable);

            AssertArith(vid, variable);
        }
Example #9
0
        /// <summary>
        /// Get corresponding Z3 formula of a MSF row.
        /// </summary>
        /// <param name="rid">The MSF row id</param>
        private ArithExpr MkGoalRow(int rid)
        {
            // Start with the 0 term
            List <ArithExpr> row = new List <ArithExpr>();

            // Now, add all the entries of this row
            foreach (LinearEntry entry in GetRowEntries(rid))
            {
                // Get the variable and constant in the row
                ArithExpr e = _solver.GetVariable(entry.Index);
                if (!entry.Value.IsOne)
                {
                    e = _solver.Context.MkMul(_solver.GetNumeral(entry.Value, e.Sort), e);
                }
                row.Add(e);
            }
            switch (row.Count)
            {
            case 0: return(_solver.GetNumeral(new Rational()));

            case 1: return(row[0]);

            default: return(_solver.Context.MkAdd(row.ToArray()));
            }
        }
Example #10
0
        /// <summary>
        /// Adds a MSF row to the Z3 assertions.
        /// </summary>
        /// <param name="rid">The MSF row id</param>
        private void AddRow(int rid)
        {
            // Start with the 0 term
            ArithExpr row = MkGoalRow(rid);

            _solver.AssertArith(rid, row);
        }
Example #11
0
        public Z3Point3D GetInverted()
        {
            ArithExpr invertedX = Z3Math.Neg(this.X);
            ArithExpr invertedY = Z3Math.Neg(this.Y);
            ArithExpr invertedZ = Z3Math.Neg(this.Z);

            return(new Z3Point3D(invertedX, invertedY, invertedZ));
        }
Example #12
0
        public override void ToSMTConstraints(Context z3Context, Solver z3Solver, int maxNumVars, VariableCache variableGenerator)
        {
            this.constraintVariable = variableGenerator.GetVarChoiceVariable(orgId);
            ArithExpr myVariable = z3Context.MkIntConst(this.constraintVariable);

            z3Solver.Assert(z3Context.MkLe(z3Context.MkInt(0), myVariable));
            z3Solver.Assert(z3Context.MkLe(myVariable, z3Context.MkInt(maxNumVars - 1)));
        }
Example #13
0
        private static BoolExpr CreateAssignmentFormula(Context z3Context, Model lastModel, string choiceVariable)
        {
            ArithExpr z3Variable        = z3Context.MkIntConst(choiceVariable);
            ArithExpr assignment        = (ArithExpr)lastModel.ConstInterp(z3Variable);
            BoolExpr  currentAssignment = z3Context.MkEq(z3Variable, assignment);

            return(currentAssignment);
        }
Example #14
0
        private static Dictionary <JointType, ArithExpr> CreateSyntheticNorms()
        {
            var result = new Dictionary <JointType, ArithExpr>();

            ArithExpr spineBase     = Z3Math.Real(0.0);
            ArithExpr spineMid      = Z3Math.Real(0.3);
            ArithExpr spineShoulder = Z3Math.Real(0.3);
            ArithExpr neck          = Z3Math.Real(0.15);
            ArithExpr head          = Z3Math.Real(0.15);
            ArithExpr shoulderLeft  = Z3Math.Real(0.25);
            ArithExpr elbowLeft     = Z3Math.Real(0.25);
            ArithExpr wristLeft     = Z3Math.Real(0.25);
            ArithExpr handLeft      = Z3Math.Real(0.05);
            ArithExpr handTipLeft   = Z3Math.Real(0.05);
            ArithExpr thumbLeft     = Z3Math.Real(0.05);
            ArithExpr hipLeft       = Z3Math.Real(0.25);
            ArithExpr kneeLeft      = Z3Math.Real(0.35);
            ArithExpr ankleLeft     = Z3Math.Real(0.35);
            ArithExpr footLeft      = Z3Math.Real(0.1);
            ArithExpr shoulderRight = Z3Math.Real(0.25);
            ArithExpr elbowRight    = Z3Math.Real(0.25);
            ArithExpr wristRight    = Z3Math.Real(0.25);
            ArithExpr handRight     = Z3Math.Real(0.05);
            ArithExpr handTipRight  = Z3Math.Real(0.05);
            ArithExpr thumbRight    = Z3Math.Real(0.05);
            ArithExpr hipRight      = Z3Math.Real(0.25);
            ArithExpr kneeRight     = Z3Math.Real(0.35);
            ArithExpr ankleRight    = Z3Math.Real(0.35);
            ArithExpr footRight     = Z3Math.Real(0.1);

            result.Add(JointType.SpineBase, spineBase);
            result.Add(JointType.SpineMid, spineMid);
            result.Add(JointType.SpineShoulder, spineShoulder);
            result.Add(JointType.Neck, neck);
            result.Add(JointType.Head, head);
            result.Add(JointType.ShoulderLeft, shoulderLeft);
            result.Add(JointType.ElbowLeft, elbowLeft);
            result.Add(JointType.WristLeft, wristLeft);
            result.Add(JointType.HandLeft, handLeft);
            result.Add(JointType.HandTipLeft, handTipLeft);
            result.Add(JointType.ThumbLeft, thumbLeft);
            result.Add(JointType.HipLeft, hipLeft);
            result.Add(JointType.KneeLeft, kneeLeft);
            result.Add(JointType.AnkleLeft, ankleLeft);
            result.Add(JointType.FootLeft, footLeft);
            result.Add(JointType.ShoulderRight, shoulderRight);
            result.Add(JointType.ElbowRight, elbowRight);
            result.Add(JointType.WristRight, wristRight);
            result.Add(JointType.HandRight, handRight);
            result.Add(JointType.HandTipRight, handTipRight);
            result.Add(JointType.ThumbRight, thumbRight);
            result.Add(JointType.HipRight, hipRight);
            result.Add(JointType.KneeRight, kneeRight);
            result.Add(JointType.AnkleRight, ankleRight);
            result.Add(JointType.FootRight, footRight);

            return(result);
        }
        /// <summary>
        /// The method aims at finding a configuration which is similar to the given configuration, but does not contain the optionToBeRemoved. If further options need to be removed from the given configuration, they are outputed in removedElements.
        /// </summary>
        /// <param name="optionToBeRemoved">The binary configuration option that must not be part of the new configuration.</param>
        /// <param name="originalConfig">The configuration for which we want to find a similar one.</param>
        /// <param name="removedElements">If further options need to be removed from the given configuration to build a valid configuration, they are outputed in this list.</param>
        /// <param name="vm">The variability model containing all options and their constraints.</param>
        /// <returns>A configuration that is valid, similar to the original configuration and does not contain the optionToBeRemoved.</returns>
        public List <BinaryOption> GenerateConfigWithoutOption(BinaryOption optionToBeRemoved, List <BinaryOption> originalConfig, out List <BinaryOption> removedElements, VariabilityModel vm)
        {
            removedElements = new List <BinaryOption>();
            var originalConfigWithoutRemoved = originalConfig.Where(x => !x.Equals(optionToBeRemoved));

            List <BoolExpr> variables;
            Dictionary <BoolExpr, BinaryOption> termToOption;
            Dictionary <BinaryOption, BoolExpr> optionToTerm;
            Tuple <Context, BoolExpr>           z3Tuple = Z3Solver.GetInitializedBooleanSolverSystem(out variables, out optionToTerm, out termToOption, vm, this.henard);
            Context         z3Context     = z3Tuple.Item1;
            BoolExpr        z3Constraints = z3Tuple.Item2;
            List <BoolExpr> constraints   = new List <BoolExpr>();

            constraints.Add(z3Constraints);

            constraints.Add(z3Context.MkNot(optionToTerm[optionToBeRemoved]));

            ArithExpr[] minGoals = new ArithExpr[variables.Count];


            for (int r = 0; r < variables.Count; r++)
            {
                BinaryOption currOption      = termToOption[variables[r]];
                ArithExpr    numericVariable = z3Context.MkIntConst(currOption.Name);

                int weight = -1000;

                if (!originalConfigWithoutRemoved.Contains(currOption))
                {
                    weight = 1000;
                }
                else if (currOption.Equals(optionToBeRemoved))
                {
                    weight = 100000;
                }

                constraints.Add(z3Context.MkEq(numericVariable, z3Context.MkITE(variables[r], z3Context.MkInt(weight), z3Context.MkInt(0))));
                minGoals[r] = numericVariable;
            }

            Optimize optimizer = z3Context.MkOptimize();

            optimizer.Assert(constraints.ToArray());
            optimizer.MkMinimize(z3Context.MkAdd(minGoals));

            if (optimizer.Check() != Status.SATISFIABLE)
            {
                return(null);
            }
            else
            {
                Model model = optimizer.Model;
                List <BinaryOption> similarConfig = RetrieveConfiguration(variables, model, termToOption);
                removedElements = originalConfigWithoutRemoved.Except(similarConfig).ToList();
                return(similarConfig);
            }
        }
Example #16
0
        // Arithmetic helpers
        public static ArithExpr Abs(ArithExpr expr)
        {
            Expr result = Z3.Context.MkITE(
                Z3.Context.MkGe(expr, Z3Math.Zero),
                expr,
                Z3Math.Neg(expr));

            return(result as ArithExpr);
        }
Example #17
0
        public static ArithExpr Max(ArithExpr expr1, ArithExpr expr2)
        {
            Expr result = Z3.Context.MkITE(
                Z3.Context.MkGe(expr1, expr2),
                expr1,
                expr2);

            return(result as ArithExpr);
        }
Example #18
0
        public static double GetRealValue(ArithExpr expr, Context localContext)
        {
            RatNum      xRatNum     = expr.Simplify() as RatNum;
            IntNum      d           = xRatNum.Denominator;
            IntNum      n           = xRatNum.Numerator;
            BigRational bigRational = new BigRational(n.BigInteger, d.BigInteger);

            return((double)bigRational);
        }
Example #19
0
        public override void ToSMTConstraints(Context z3Context, Solver z3Solver, int maxNumVars, VariableCache variableGenerator)
        {
            this.constraintVariable = variableGenerator.GetFreshVariableName();
            ArithExpr myVariable = z3Context.MkIntConst(this.constraintVariable);

            z3Solver.Assert(z3Context.MkLe(z3Context.MkInt(0), myVariable));
            z3Solver.Assert(z3Context.MkLe(myVariable, z3Context.MkInt(1)));
            this.condition.ToSMTConstraints(z3Context, z3Solver, maxNumVars, variableGenerator);
        }
Example #20
0
        //public Z3Point3D GetApproximateNormalized()
        //{
        //	Z3Point3D result = this.GetManhattanNormalized();

        //	result.X = CalcApproximateCoordFromManhattanToEuclidianSystem(result.X, result.Y, result.Z);
        //	result.Y = CalcApproximateCoordFromManhattanToEuclidianSystem(result.Y, result.X, result.Z);
        //	result.Z = CalcApproximateCoordFromManhattanToEuclidianSystem(result.Z, result.Y, result.X);

        //	return result;
        //}

        public ArithExpr Norm()
        {
            ArithExpr result =
                Z3Math.Max(
                    Z3Math.Abs(CalcApproximateCoordFromManhattanToEuclidianSystem(this.X, this.Y, this.Z)),
                    Z3Math.Abs(CalcApproximateCoordFromManhattanToEuclidianSystem(this.Y, this.X, this.Z)),
                    Z3Math.Abs(CalcApproximateCoordFromManhattanToEuclidianSystem(this.Z, this.Y, this.X)));

            return(result);
        }
Example #21
0
    public void Run()
    {
        Dictionary<string, string> cfg = new Dictionary<string, string>() {
            { "AUTO_CONFIG", "true" } };

        using (Context ctx = new Context(cfg))
        {
            ArithExpr[] a = new ArithExpr[5];
            for (uint x = 0; x < 5; x++)
                a[x] = ctx.MkInt(x+1);

            foreach (Expr e in a)
                Console.WriteLine(e);

            ArithExpr[] X = new ArithExpr[5];
            for (uint i = 0; i < 5; i++)
                X[i] = ctx.MkIntConst(string.Format("x{0}", i));

            ArithExpr[] Y = new ArithExpr[5];
            for (uint i = 0; i < 5; i++)
                Y[i] = ctx.MkIntConst(string.Format("y{0}", i));

            foreach (Expr e in X)
                Console.WriteLine(e);

            ArithExpr[] X_plus_Y = new ArithExpr[5];
            for (uint i = 0; i < 5; i++)
                X_plus_Y[i] = ctx.MkAdd(X[i], Y[i]);

            foreach (Expr e in X_plus_Y)
                Console.WriteLine(e);

            BoolExpr[] X_gt_Y = new BoolExpr[5];
            for (uint i = 0; i < 5; i++)
                X_gt_Y[i] = ctx.MkGt(X[i], Y[i]);

            foreach (Expr e in X_gt_Y)
                Console.WriteLine(e);

            Console.WriteLine(ctx.MkAnd(X_gt_Y));

            Expr[][] matrix = new Expr[3][];
            for (uint i = 0; i < 3; i++) {
                matrix[i] = new Expr[3];
                for (uint j = 0; j < 3; j++)
                    matrix[i][j] = ctx.MkIntConst(string.Format("x_{0}_{1}", i + 1, j + 1));
            }

            foreach(Expr[] row in matrix) {
                foreach(Expr e in row)
                    Console.Write(" " + e);
                Console.WriteLine();
            }
        }
    }
Example #22
0
            public static void Run()
            {
                Z3Point3D constPoint = Z3Point3D.MkZ3Const("const"); // ("const X", "const Y", "const Z")

                Z3Point3D normalized = new Z3Point3D();

                ArithExpr higherCoord =
                    Z3Math.Max(
                        Z3Math.Max(
                            Z3Math.Abs(constPoint.X),
                            Z3Math.Abs(constPoint.Y)),
                        Z3Math.Abs(constPoint.Z));

                normalized.X = Z3.Context.MkDiv(constPoint.X, constPoint.Y);
                normalized.Y = Z3Math.One;//Z3.Context.MkDiv(constPoint.Y, higherCoord);
                normalized.Z = Z3.Context.MkDiv(constPoint.Z, constPoint.Y);

                normalized.X = CalcApproximateCoordFromManhattanToEuclidianSystem(normalized.X, normalized.Y, normalized.Z);
                normalized.Y = CalcApproximateCoordFromManhattanToEuclidianSystem(normalized.Y, normalized.X, normalized.Z);
                normalized.Z = CalcApproximateCoordFromManhattanToEuclidianSystem(normalized.Z, normalized.Y, normalized.X);

                Z3Point3D up      = Z3Point3D.DirectionPoint(Direction.Up); // (0, 1, 0)
                Z3Point3D distVec = normalized - up;

                ArithExpr distance =
                    Max(
                        Abs(CalcApproximateCoordFromManhattanToEuclidianSystem(distVec.X, distVec.Y, distVec.Z)),
                        Abs(CalcApproximateCoordFromManhattanToEuclidianSystem(distVec.Y, distVec.X, distVec.Z)),
                        Abs(CalcApproximateCoordFromManhattanToEuclidianSystem(distVec.Z, distVec.Y, distVec.X)));

                BoolExpr expr = Z3.Context.MkLt(distance, Z3.Context.MkReal(1, 2));


                Solver solver = Z3.Context.MkSolver();

                solver.Assert(expr);
                Status     status = solver.Check();
                Statistics stats  = solver.Statistics;

                switch (status)
                {
                case Status.UNKNOWN:
                    Console.WriteLine("Solver check for witness returned Status.UNKNOWN because: " + solver.ReasonUnknown);
                    throw new ArgumentException("Test Failed Expception");

                case Status.UNSATISFIABLE:
                    Console.WriteLine("There is no valid witness for " + expr);
                    throw new ArgumentException("Test Failed Expception");

                case Status.SATISFIABLE:
                    Console.WriteLine("OK, model: " + solver.Model);
                    break;
                }
            }
Example #23
0
    public void Run()
    {
        Dictionary <string, string> cfg = new Dictionary <string, string>()
        {
            { "AUTO_CONFIG", "true" }
        };

        using (Context ctx = new Context(cfg))
        {
            IntExpr[] X = new IntExpr[5];
            for (uint i = 0; i < 5; i++)
            {
                X[i] = ctx.MkIntConst(string.Format("x_{0}", i));
            }

            RealExpr[] Y = new RealExpr[5];
            for (uint i = 0; i < 5; i++)
            {
                Y[i] = ctx.MkRealConst(string.Format("y_{0}", i));
            }

            BoolExpr[] P = new BoolExpr[5];
            for (uint i = 0; i < 5; i++)
            {
                P[i] = ctx.MkBoolConst(string.Format("p_{0}", i));
            }

            foreach (Expr x in X)
            {
                Console.WriteLine(x);
            }
            foreach (Expr x in Y)
            {
                Console.WriteLine(x);
            }
            foreach (Expr x in P)
            {
                Console.WriteLine(x);
            }

            foreach (ArithExpr y in Y)
            {
                Console.WriteLine(ctx.MkPower(y, ctx.MkReal(2)));
            }

            ArithExpr[] Yp = new ArithExpr[Y.Length];
            for (uint i = 0; i < Y.Length; i++)
            {
                Yp[i] = ctx.MkPower(Y[i], ctx.MkReal(2));
            }
            Console.WriteLine(ctx.MkAdd(Yp));
        }
    }
Example #24
0
        public override void ToSMTConstraints(Context z3Context, Solver z3Solver, int maxNumVars, VariableCache variableGenerator)
        {
            this.constraintVariable = variableGenerator.GetConstChoiceVariable(orgValue);
            ArithExpr myVariable = z3Context.MkIntConst(this.constraintVariable);
            //range for variation of constants
            //TODO: allow 0?
            int lowerBound = Math.Max((int)(this.orgValue / 2), 0);
            int upperBound = Math.Max((int)(this.orgValue * 2), 0);

            z3Solver.Assert(z3Context.MkLe(z3Context.MkInt(lowerBound), myVariable));
            z3Solver.Assert(z3Context.MkLe(myVariable, z3Context.MkInt(upperBound)));
        }
Example #25
0
        public override void ToSMTConstraints(Context z3Context, Solver z3Solver, int maxNumVars, VariableCache variableGenerator)
        {
            /* constraint variable in { 0, 1 }
             * 0 -> increment
             * 1 -> decrement
             */
            this.constraintVariable = variableGenerator.GetFreshVariableName();
            ArithExpr myVariable = z3Context.MkIntConst(this.constraintVariable);

            z3Solver.Assert(z3Context.MkLe(z3Context.MkInt(0), myVariable));
            z3Solver.Assert(z3Context.MkLe(myVariable, z3Context.MkInt(1)));
            this.arg.ToSMTConstraints(z3Context, z3Solver, maxNumVars, variableGenerator);
        }
Example #26
0
        /// <summary>
        /// Based on a given (partial) configuration and a variability, we aim at finding all optimally maximal or minimal (in terms of selected binary options) configurations.
        /// </summary>
        /// <param name="config">The (partial) configuration which needs to be expanded to be valid.</param>
        /// <param name="vm">Variability model containing all options and their constraints.</param>
        /// <param name="minimize">If true, we search for the smallest (in terms of selected options) valid configuration. If false, we search for the largest one.</param>
        /// <param name="unwantedOptions">Binary options that we do not want to become part of the configuration. Might be part if there is no other valid configuration without them</param>
        /// <returns>A list of configurations that satisfies the VM and the goal (or null if there is none).</returns>
        public List <List <BinaryOption> > MaximizeConfig(List <BinaryOption> config, VariabilityModel vm, bool minimize, List <BinaryOption> unwantedOptions)
        {
            List <BoolExpr> variables;
            Dictionary <BoolExpr, BinaryOption> termToOption;
            Dictionary <BinaryOption, BoolExpr> optionToTerm;
            Tuple <Context, BoolExpr>           z3Tuple = Z3Solver.GetInitializedBooleanSolverSystem(out variables, out optionToTerm, out termToOption, vm, this.henard);
            Context  z3Context     = z3Tuple.Item1;
            BoolExpr z3Constraints = z3Tuple.Item2;

            List <BoolExpr> constraints = new List <BoolExpr>();

            constraints.Add(z3Constraints);
            List <BoolExpr> requireConfigs = new List <BoolExpr>();

            if (config != null)
            {
                foreach (BinaryOption option in config)
                {
                    requireConfigs.Add(optionToTerm[option]);
                }
                constraints.Add(z3Context.MkAnd(requireConfigs.ToArray()));
            }

            ArithExpr[] optimizationGoals = new ArithExpr[variables.Count];

            for (int r = 0; r < variables.Count; r++)
            {
                BinaryOption currOption      = termToOption[variables[r]];
                ArithExpr    numericVariable = z3Context.MkIntConst(currOption.Name);

                constraints.Add(z3Context.MkEq(numericVariable, z3Context.MkITE(variables[r], z3Context.MkInt(1), z3Context.MkInt(0))));

                optimizationGoals[r] = numericVariable;
            }

            Optimize optimizer = z3Context.MkOptimize();

            optimizer.Assert(constraints.ToArray());
            optimizer.MkMaximize(z3Context.MkAdd(optimizationGoals));

            if (optimizer.Check() != Status.SATISFIABLE)
            {
                return(null);
            }
            List <BinaryOption> solution = RetrieveConfiguration(variables, optimizer.Model, termToOption);

            return(new List <List <BinaryOption> >
            {
                solution
            });
        }
Example #27
0
    public void Run()
    {
        Dictionary <string, string> cfg = new Dictionary <string, string>()
        {
            { "AUTO_CONFIG", "true" }
        };

        using (Context ctx = new Context(cfg))
        {
            ArithExpr[] Q = new ArithExpr[8];
            for (uint i = 0; i < 8; i++)
            {
                Q[i] = ctx.MkIntConst(string.Format("Q_{0}", i + 1));
            }

            BoolExpr[] val_c = new BoolExpr[8];
            for (uint i = 0; i < 8; i++)
            {
                val_c[i] = ctx.MkAnd(ctx.MkLe(ctx.MkInt(1), Q[i]),
                                     ctx.MkLe(Q[i], ctx.MkInt(8)));
            }

            BoolExpr col_c = ctx.MkDistinct(Q);

            BoolExpr[][] diag_c = new BoolExpr[8][];
            for (uint i = 0; i < 8; i++)
            {
                diag_c[i] = new BoolExpr[i];
                for (uint j = 0; j < i; j++)
                {
                    diag_c[i][j] = (BoolExpr)ctx.MkITE(ctx.MkEq(ctx.MkInt(i), ctx.MkInt(j)),
                                                       ctx.MkTrue(),
                                                       ctx.MkAnd(ctx.MkNot(ctx.MkEq(ctx.MkSub(Q[i], Q[j]),
                                                                                    ctx.MkSub(ctx.MkInt(i), ctx.MkInt(j)))),
                                                                 ctx.MkNot(ctx.MkEq(ctx.MkSub(Q[i], Q[j]),
                                                                                    ctx.MkSub(ctx.MkInt(j), ctx.MkInt(i))))));
                }
            }

            Solver s = ctx.MkSolver();
            s.Assert(val_c);
            s.Assert(col_c);
            foreach (var c in diag_c)
            {
                s.Assert(c);
            }

            Console.WriteLine(s.Check());
            Console.WriteLine(s.Model);
        }
    }
Example #28
0
        public override void ToSMTConstraints(Context z3Context, Solver z3Solver, int maxNumVars, VariableCache variableGenerator)
        {
            /* constraint variable in { 0, 1 }
             * 0 -> and
             * 1 -> or
             */
            this.constraintVariable = variableGenerator.GetFreshVariableName();
            ArithExpr myVariable = z3Context.MkIntConst(this.constraintVariable);

            z3Solver.Assert(z3Context.MkLe(z3Context.MkInt(0), myVariable));
            z3Solver.Assert(z3Context.MkLe(myVariable, z3Context.MkInt(Enum.GetNames(typeof(WCCompound.Logic)).Length - 1)));
            this.cond1.ToSMTConstraints(z3Context, z3Solver, maxNumVars, variableGenerator);
            this.cond2.ToSMTConstraints(z3Context, z3Solver, maxNumVars, variableGenerator);
        }
Example #29
0
        public override void ToSMTConstraints(Context z3Context, Solver z3Solver, int maxNumVars, VariableCache variableGenerator)
        {
            /* constraint variable in { 0, ..., 5 }
             * -> eq, l, leq, neq, g, geq
             */

            this.constraintVariable = variableGenerator.GetFreshVariableName();
            ArithExpr myVariable = z3Context.MkIntConst(this.constraintVariable);

            z3Solver.Assert(z3Context.MkLe(z3Context.MkInt(0), myVariable));
            z3Solver.Assert(z3Context.MkLe(myVariable, z3Context.MkInt(Enum.GetNames(typeof(WCComparison.CompareType)).Length - 1)));
            this.arg1.ToSMTConstraints(z3Context, z3Solver, maxNumVars, variableGenerator);
            //Currently, arg2 may be concretized to a 0 constant, possibly resulting in an '== 0' or '!= 0' condition, which is a simple condition.
            this.arg2.ToSMTConstraints(z3Context, z3Solver, maxNumVars, variableGenerator);
        }
Example #30
0
        public override void ToSMTConstraints(Context z3Context, Solver z3Solver, int maxNumVars, VariableCache variableGenerator)
        {
            /* constraint variable in { 0, 1 }
             * 0 -> plus
             * 1 -> minus
             */
            this.constraintVariable = variableGenerator.GetFreshVariableName();
            ArithExpr myVariable = z3Context.MkIntConst(this.constraintVariable);

            z3Solver.Assert(z3Context.MkLe(z3Context.MkInt(0), myVariable));
            z3Solver.Assert(z3Context.MkLe(myVariable, z3Context.MkInt(Enum.GetNames(typeof(WEArith.ArithOp)).Length - 1)));
            this.lhs.ToSMTConstraints(z3Context, z3Solver, maxNumVars, variableGenerator);
            this.arg1.ToSMTConstraints(z3Context, z3Solver, maxNumVars, variableGenerator);
            this.arg2.ToSMTConstraints(z3Context, z3Solver, maxNumVars, variableGenerator);
        }
Example #31
0
    Expr ParseMulExpr()
    {
        Expr left = ParsePrimExpr();

        if (!Is("*") && !Is("/"))
        {
            return(left);
        }
        ArithExpr expr = new ArithExpr();

        expr.Op    = (string)tokens[ix++].Value;
        expr.Left  = left;
        expr.Right = ParsePrimExpr();
        return(expr);
    }
Example #32
0
        public static void ProveExample2(Context ctx)
        {
            Console.WriteLine("ProveExample2");

            /* declare function g */
            Sort I = ctx.IntSort;

            FuncDecl g = ctx.MkFuncDecl("g", I, I);

            /* create x, y, and z */
            IntExpr x = ctx.MkIntConst("x");
            IntExpr y = ctx.MkIntConst("y");
            IntExpr z = ctx.MkIntConst("z");

            /* create gx, gy, gz */
            Expr gx = ctx.MkApp(g, x);
            Expr gy = ctx.MkApp(g, y);
            Expr gz = ctx.MkApp(g, z);

            /* create zero */
            IntExpr zero = ctx.MkInt(0);

            /* assert not(g(g(x) - g(y)) = g(z)) */
            ArithExpr gx_gy  = ctx.MkSub((IntExpr)gx, (IntExpr)gy);
            Expr      ggx_gy = ctx.MkApp(g, gx_gy);
            BoolExpr  eq     = ctx.MkEq(ggx_gy, gz);
            BoolExpr  c1     = ctx.MkNot(eq);

            /* assert x + z <= y */
            ArithExpr x_plus_z = ctx.MkAdd(x, z);
            BoolExpr  c2       = ctx.MkLe(x_plus_z, y);

            /* assert y <= x */
            BoolExpr c3 = ctx.MkLe(y, x);

            /* prove z < 0 */
            BoolExpr f = ctx.MkLt(z, zero);

            Console.WriteLine("prove: not(g(g(x) - g(y)) = g(z)), x + z <= y <= x implies z < 0");
            Prove(ctx, f, c1, c2, c3);

            /* disprove z < -1 */
            IntExpr minus_one = ctx.MkInt(-1);

            f = ctx.MkLt(z, minus_one);
            Console.WriteLine("disprove: not(g(g(x) - g(y)) = g(z)), x + z <= y <= x implies z < -1");
            Disprove(ctx, f, c1, c2, c3);
        }
Example #33
0
    public void Run()
    {
        Dictionary<string, string> cfg = new Dictionary<string, string>() {
            { "AUTO_CONFIG", "true" } };

        using (Context ctx = new Context(cfg))
        {
            ArithExpr[] Q = new ArithExpr[8];
            for (uint i = 0; i < 8; i++)
                Q[i] = ctx.MkIntConst(string.Format("Q_{0}", i + 1));

            BoolExpr[] val_c = new BoolExpr[8];
            for (uint i = 0; i < 8; i++)
                val_c[i] = ctx.MkAnd(ctx.MkLe(ctx.MkInt(1), Q[i]),
                                     ctx.MkLe(Q[i], ctx.MkInt(8)));

            BoolExpr col_c = ctx.MkDistinct(Q);

            BoolExpr[][] diag_c = new BoolExpr[8][];
            for (uint i = 0; i < 8; i++)
            {
                diag_c[i] = new BoolExpr[i];
                for (uint j = 0; j < i; j++)
                    diag_c[i][j] = (BoolExpr)ctx.MkITE(ctx.MkEq(ctx.MkInt(i), ctx.MkInt(j)),
                                             ctx.MkTrue(),
                                             ctx.MkAnd(ctx.MkNot(ctx.MkEq(ctx.MkSub(Q[i], Q[j]),
                                                                          ctx.MkSub(ctx.MkInt(i), ctx.MkInt(j)))),
                                                       ctx.MkNot(ctx.MkEq(ctx.MkSub(Q[i], Q[j]),
                                                                          ctx.MkSub(ctx.MkInt(j), ctx.MkInt(i))))));
            }

            Solver s = ctx.MkSolver();
            s.Assert(val_c);
            s.Assert(col_c);
            foreach (var c in diag_c)
                s.Assert(c);

            Console.WriteLine(s.Check());
            Console.WriteLine(s.Model);
        }
    }
Example #34
0
    private Expr ParseExpr()
    {
        if (_index == _tokens.Count) throw new Exception("expected expression, got EOF");

        var nexttoken = _tokens[_index + 1];
        var isLoop = nexttoken is string && (string)nexttoken == "up" ||
                     nexttoken is string && (string)nexttoken == "down";

        //check if this is a arithmetic-expr or simple expr
        if ((nexttoken is string && (string)nexttoken == "to")|| isLoop ||  // loop
            (nexttoken is Scanner.ArithToken && (Scanner.ArithToken)nexttoken == Scanner.ArithToken.Semi))
        {
            if (isLoop)
                SetLoopType(nexttoken);

            return ParseSimpleExpr();
        }

        var binexpr = new ArithExpr();
        binexpr.Op = GetArithOperator(nexttoken);
        binexpr.Left = ParseSimpleExpr();
        _index++;
        binexpr.Right = ParseExpr();
        return binexpr;
    }
Example #35
0
 Expr ParseMulExpr()
 {
     Expr left = ParsePrimExpr();
     if (!Is("*") && !Is("/")) return left;
     ArithExpr expr = new ArithExpr();
     expr.Op = (string)tokens[ix++].Value;
     expr.Left = left;
     expr.Right = ParsePrimExpr();
     return expr;
 }