Inheritance: Z3Object
Exemple #1
0
        /// <summary>
        /// Checks whether the assertions in the context are consistent or not.
        /// </summary>
        public static Status Check(Context ctx, List<BoolExpr> core, ref Model model, ref Expr proof, params Expr[] assumptions)
        {
            Z3_lbool r;
            model = null;
            proof = null;
            if (assumptions == null || assumptions.Length == 0)
                r = (Z3_lbool)Native.Z3_check(ctx.nCtx);
            else {
                IntPtr mdl = IntPtr.Zero, prf = IntPtr.Zero;
                uint core_size = 0;
                IntPtr[] native_core = new IntPtr[assumptions.Length];
                r = (Z3_lbool)Native.Z3_check_assumptions(ctx.nCtx, 
                                   (uint)assumptions.Length, AST.ArrayToNative(assumptions),
                                   ref mdl, ref prf, ref core_size, native_core);

                for (uint i = 0; i < core_size; i++)
                    core.Add((BoolExpr)Expr.Create(ctx, native_core[i]));
                if (mdl != IntPtr.Zero) {
                    model = new Model(ctx, mdl);
                }
                if (prf != IntPtr.Zero) {
                    proof = Expr.Create(ctx, prf);
                }

            }
            switch (r)
            {
                case Z3_lbool.Z3_L_TRUE: return Status.SATISFIABLE;
                case Z3_lbool.Z3_L_FALSE: return Status.UNSATISFIABLE;
                default: return Status.UNKNOWN;
            }
        }
        /// <summary>
        /// Convert a model for the subgoal <paramref name="i"/> into a model for the original 
        /// goal <c>g</c>, that the ApplyResult was obtained from. 
        /// </summary>
        /// <returns>A model for <c>g</c></returns>
        public Model ConvertModel(uint i, Model m)
        {
            Contract.Requires(m != null);
            Contract.Ensures(Contract.Result<Model>() != null);

            return new Model(Context, Native.Z3_apply_result_convert_model(Context.nCtx, NativeObject, i, m.NativeObject));
        }
Exemple #3
0
        public IDictionary <string, List <object> > Solve()
        {
            Dictionary <string, List <object> > variableValues = new Dictionary <string, List <object> >(StringComparer.CurrentCultureIgnoreCase);

            new Model.ViewModelLocator().MainModel.AddDisplayText("Z3 Solve");
            Solver s = this.z3Context.MkSolver();

            foreach (BoolExpr sa in this.solverAssertions)
            {
                s.Assert(sa);
            }

            Console.WriteLine(s.Check());
            new Model.ViewModelLocator().MainModel.AddDisplayText(s.Check().ToString());

            Microsoft.Z3.Model m = s.Model;
            foreach (FuncDecl d in m.Decls)
            {
                string varName  = d.Name.ToString();
                Expr   valExpr  = m.ConstInterp(d);
                string varValue = valExpr.ToString();
                if (valExpr is FPExpr)
                {
                    FPExpr fp  = (FPExpr)valExpr;
                    FPNum  fn  = (FPNum)fp;
                    double val = Convert.ToDouble(fn.Significand);
                    val = val * System.Math.Pow(2, fn.ExponentInt64);

                    if (fn.Sign)
                    {
                        val = val * -1;
                    }

                    varValue = val.ToString();

                    if (valExpr.ToString() == "+zero")
                    {
                        varValue = "0.01";
                    }
                    if (valExpr.ToString() == "-zero")
                    {
                        varValue = "-0.01";
                    }
                }


                string message = varName + " -> " + varValue;
                new Model.ViewModelLocator().MainModel.AddDisplayText(message);

                if (!variableValues.ContainsKey(varName))
                {
                    variableValues.Add(varName, new List <object>());
                }

                variableValues[varName].Add(varValue);
            }
            return(variableValues);
        }
        /// <summary> 
        /// Computes an interpolant.
        /// </summary>    
        /// <remarks>For more information on interpolation please refer
        /// too the function Z3_compute_interpolant in the C/C++ API, which is 
        /// well documented.</remarks>
        public Z3_lbool ComputeInterpolant(Expr pat, Params p, out BoolExpr[] interp, out Model model)
        {
            Contract.Requires(pat != null);
            Contract.Requires(p != null);
            Contract.Ensures(Contract.ValueAtReturn(out interp) != null);
            Contract.Ensures(Contract.ValueAtReturn(out model) != null);

            CheckContextMatch(pat);
            CheckContextMatch(p);

            IntPtr i = IntPtr.Zero, m = IntPtr.Zero;
            int r = Native.Z3_compute_interpolant(nCtx, pat.NativeObject, p.NativeObject, ref i, ref m);
            interp = new ASTVector(this, i).ToBoolExprArray();
            model = new Model(this, m);
            return (Z3_lbool)r;
        }
Exemple #5
0
        public void Solve1()
        {
            using (Context ctx = new Context()){
                Expr a = ctx.MkIntConst("a");

                IntExpr twelve = ctx.MkInt(12);

                Solver s = ctx.MkSolver();

                s.Assert(ctx.MkEq(a, twelve));
                Console.WriteLine(s.Check());

                Microsoft.Z3.Model m = s.Model;
                foreach (FuncDecl d in m.Decls)
                {
                    Console.WriteLine(d.Name + " -> " + m.ConstInterp(d));
                }

                Console.ReadLine();
            }
        }
 public override PDLSet InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     return new PDLAllPos();
 }
 public char InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     int concChoice = ((IntNum)model.ConstInterp(context.MkIntConst(this.constraintVariable))).Int;
     return alphabet[concChoice];
 }
 //Constructor
 public Z3Solution(Microsoft.Z3.Model model, Dictionary<string, Z3Variable> variables)
 {
     _model = model;
     _variables = variables;
 }
 public override PDLSet InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     int concChoice = this.GetConcChoice(context, model);
     PDLPos conc = this.original.InterpretModel(alphabet, context, model);
     switch (concChoice)
     {
         case 0: return new PDLSetCmpPos(conc, PDLComparisonOperator.Eq);
         case 1: return new PDLSetCmpPos(conc, PDLComparisonOperator.Ge);
         case 2: return new PDLSetCmpPos(conc, PDLComparisonOperator.Geq);
         case 3: return new PDLSetCmpPos(conc, PDLComparisonOperator.Le);
         case 4: return new PDLSetCmpPos(conc, PDLComparisonOperator.Leq);
     }
     return null;
 }
 public override PDLPred InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     PDLSet set1Conc = this.set1.InterpretModel(alphabet, context, model);
     PDLSet set2Conc = this.set2.InterpretModel(alphabet, context, model);
     return new PDLSubset(set1Conc, set2Conc);
 }
 public override PDLPos InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     return new PDLPosVar(this.variable);
 }
 public abstract PDLPred InterpretModel(IList<char> alphabet, Context context, Model model);
 protected int GetConcChoice(Context context, Model model)
 {
     int concChoice = ((IntNum)model.ConstInterp(context.MkIntConst(this.constraintVariable))).Int;
     return concChoice;
 }
 public override PDLPred InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     PDLPos posConc = this.originalPosition.InterpretModel(alphabet, context, model);
     PDLSet setConc = this.originalSet.InterpretModel(alphabet, context, model);
     return new PDLBelongs(posConc, setConc);
 }
 public int InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     int concChoice = ((IntNum)model.ConstInterp(context.MkIntConst(this.constraintVariable))).Int;
     Debug.Assert(concChoice != 0 || this.includeZero == true);
     return concChoice;
 }
 public string InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     int concChoice = ((IntNum)model.ConstInterp(context.MkIntConst(this.constraintVariable))).Int;
     int alphabetSize = alphabet.Count;
     string returnValue = "";
     for (int currentIndex = 0; currentIndex < this.originalValue.Length; ++currentIndex)
     {
         int currentChoice = concChoice % alphabetSize;
         returnValue += alphabet[currentChoice];
         concChoice -= currentChoice;
         concChoice = concChoice / alphabetSize;
     }
     return returnValue;
 }
        public override PDLPred InterpretModel(IList<char> alphabet, Context context, Model model)
        {
            int concChoice = this.GetConcChoice(context, model);
            PDLPred lhsConc = this.lhs.InterpretModel(alphabet, context, model);
            PDLPred rhsConc = this.rhs.InterpretModel(alphabet, context, model);

            if (original.Equals(PDLLogicalOperator.And) || original.Equals(PDLLogicalOperator.Or))
            {
                if (concChoice == 0)
                {
                    return new PDLAnd(lhsConc, rhsConc);
                }
                else
                {
                    return new PDLOr(lhsConc, rhsConc);
                }
            }
            else
            {
                if (concChoice == 0)
                {
                    return new PDLIf(lhsConc, rhsConc);
                }
                else 
                {
                    return new PDLIff(lhsConc, rhsConc);
                }
            }
        }
 public override PDLSet InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     PDLPred predConc = this.pred.InterpretModel(alphabet, context, model);
     return new PDLPredSet(this.FOVar, predConc);
 }
 public override PDLPred InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     int concChoice = this.GetConcChoice(context, model);
     PDLSet concSet = this.originalSet.InterpretModel(alphabet, context, model);
     int m = this.originalM.InterpretModel(alphabet, context, model);
     int n = this.originalN.InterpretModel(alphabet, context, model);
     switch (concChoice)
     {
         case 0: return new PDLSetModuleComparison(concSet, m, n, PDLComparisonOperator.Eq);
         case 1: return new PDLSetModuleComparison(concSet, m, n, PDLComparisonOperator.Ge);
         case 2: return new PDLSetModuleComparison(concSet, m, n, PDLComparisonOperator.Geq);
         case 3: return new PDLSetModuleComparison(concSet, m, n, PDLComparisonOperator.Le);
         case 4: return new PDLSetModuleComparison(concSet, m, n, PDLComparisonOperator.Leq);
     }
     return null;
 }
 private static BoolExpr CreateCharacteristicFormula(IEnumerable<string> choiceVariables, Context z3Context, Model lastModel)
 {
     BoolExpr characteristicFormula = null;
     foreach (string choiceVariable in choiceVariables)
     {
         BoolExpr currentAssignment = CreateAssignmentFormula(z3Context, lastModel, choiceVariable);
         if (characteristicFormula == null)
         {
             characteristicFormula = currentAssignment;
         }
         else
         {
             characteristicFormula = z3Context.MkAnd(characteristicFormula, currentAssignment);
         }
     }
     return characteristicFormula;
 }
 public override PDLPred InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     int concChoice = this.GetConcChoice(context, model);
     string stringConc = this.original.InterpretModel(alphabet, context, model);
     if (concChoice == 0) { return new PDLStartsWith(stringConc); }
     else { return new PDLEndsWith(stringConc); }
 }
 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;
 }
 public override PDLPred InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     return new PDLEmptyString();
 }
 public override PDLPred InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     int concChoice = this.GetConcChoice(context, model);
     PDLPred originalConc = this.originalFormula.InterpretModel(alphabet, context, model);
     switch (concChoice)
     {
         case 0: return new PDLForallSO(this.variableName, originalConc);
         case 1: return new PDLExistsSO(this.variableName, originalConc);
     }
     return null;
 }
 public override PDLPred InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     string stringConc = this.original.InterpretModel(alphabet, context, model);
     return new PDLContains(stringConc);
 }
 public override PDLPred InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     int concChoice = this.GetConcChoice(context, model);
     PDLPred originalConc = this.original.InterpretModel(alphabet, context, model);
     switch (concChoice)
     {
         case 0: return originalConc;
         case 1: return new PDLNot(originalConc);
     }
     return null;
 }
 public override PDLPos InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     int concChoice = this.GetConcChoice(context, model);
     if (concChoice == 0) { return new PDLFirst(); }
     else { return new PDLLast(); }
 }
 public override PDLPred InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     int concChoice = this.GetConcChoice(context, model);
     switch (concChoice)
     {
         case 0: return new PDLTrue();
         case 1: return new PDLFalse();
     }
     return null;
 }
        public static Z3Body CreateBodyWitness(
			Z3Body z3ConstCheckedBody,
			Model model,
			List<JointType> evaluatedJoints,
			Z3Body defaultBody)
        {
            var witness = new Z3Body();
            var jointTypes = EnumUtil.GetValues<JointType>();
            foreach (var jointType in jointTypes)
            {
                if (evaluatedJoints.Contains(jointType))
                {
                    var joint = new Z3Point3D(
                        model.Evaluate(z3ConstCheckedBody.Joints[jointType].X, true) as ArithExpr,
                        model.Evaluate(z3ConstCheckedBody.Joints[jointType].Y, true) as ArithExpr,
                        model.Evaluate(z3ConstCheckedBody.Joints[jointType].Z, true) as ArithExpr);
                    witness.Joints.Add(jointType, joint);

                    var norm = model.Evaluate(z3ConstCheckedBody.Norms[jointType]) as ArithExpr;

                    // Check if norm is still an app (meaning it can be anything), then set it to be the default norm
                    if (norm.ASTKind == Z3_ast_kind.Z3_APP_AST)
                        witness.Norms.Add(jointType, defaultBody.Norms[jointType]);
                    else
                        witness.Norms.Add(jointType, norm);
                }
                else
                {
                    witness.Joints.Add(jointType, defaultBody.Joints[jointType]);
                    witness.Norms.Add(jointType, defaultBody.Norms[jointType]);
                }
            }

            return witness;
        }
 public override PDLPred InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     int concChoice = this.GetConcChoice(context, model);
     PDLPos lhsConc = this.lhs.InterpretModel(alphabet, context, model);
     PDLPos rhsConc = this.rhs.InterpretModel(alphabet, context, model);
     switch (concChoice)
     {
         case 0: return new PDLBinaryPosFormula(lhsConc, rhsConc, PDLPosComparisonOperator.Eq);
         case 1: return new PDLBinaryPosFormula(lhsConc, rhsConc, PDLPosComparisonOperator.Ge);
         case 2: return new PDLBinaryPosFormula(lhsConc, rhsConc, PDLPosComparisonOperator.Geq);
         case 3: return new PDLBinaryPosFormula(lhsConc, rhsConc, PDLPosComparisonOperator.Le);
         case 4: return new PDLBinaryPosFormula(lhsConc, rhsConc, PDLPosComparisonOperator.Leq);
     }
     return null;
 }
        internal void Solve(Z3BaseParams parameters, IEnumerable <IGoal> modelGoals,
                            Action <int> addRow, Func <int, ArithExpr> mkGoalRow, Action <Z3Result> setResult)
        {
            _variables.Clear();
            _goals.Clear();

            try
            {
                // Mark that we are in solving phase
                _isSolving = true;

                // Construct Z3
                ConstructSolver(parameters);

                // Add all the variables
                foreach (int vid in _model.VariableIndices)
                {
                    AddVariable(vid);
                }

                // Add all the rows
                foreach (int rid in _model.RowIndices)
                {
                    addRow(rid);
                }

                // Add enabled goals to optimization problem
                foreach (IGoal g in modelGoals)
                {
                    if (!g.Enabled)
                    {
                        continue;
                    }

                    ArithExpr gr = mkGoalRow(g.Index);
                    if (g.Minimize)
                    {
                        _goals.Add(g, _optSolver.MkMinimize(gr));
                    }
                    else
                    {
                        _goals.Add(g, _optSolver.MkMaximize(gr));
                    }
                }

                if (_goals.Any() && parameters.SMT2LogFile != null)
                {
                    Debug.WriteLine("Dumping SMT2 benchmark to log file...");
                    File.WriteAllText(parameters.SMT2LogFile, _optSolver.ToString());
                }

                bool aborted = parameters.QueryAbort();

                if (!aborted)
                {
                    // Start the abort thread
                    AbortWorker abortWorker = new AbortWorker(_context, parameters.QueryAbort);
                    Thread      abortThread = new Thread(abortWorker.Start);
                    abortThread.Start();

                    // Now solve the problem
                    Status status = _optSolver.Check();

                    // Stop the abort thread
                    abortWorker.Stop();
                    abortThread.Join();

                    switch (status)
                    {
                    case Status.SATISFIABLE:
                        Microsoft.Z3.Model model = _optSolver.Model;
                        Debug.Assert(model != null, "Should be able to get Z3 model.");
                        // Remember the solution values
                        foreach (KeyValuePair <int, Expr> pair in _variables)
                        {
                            var value = Utils.ToRational(model.Eval(pair.Value, true));
                            _model.SetValue(pair.Key, value);
                        }
                        // Remember all objective values
                        foreach (var pair in _goals)
                        {
                            var optimalValue = Utils.ToRational(pair.Value.Upper);
                            _model.SetValue(pair.Key.Index, optimalValue);
                        }
                        model.Dispose();
                        setResult(_goals.Any() ? Z3Result.Optimal : Z3Result.Feasible);
                        break;

                    case Status.UNSATISFIABLE:
                        setResult(Z3Result.Infeasible);
                        break;

                    case Status.UNKNOWN:
                        if (abortWorker.Aborted)
                        {
                            Microsoft.Z3.Model subOptimalModel = _optSolver.Model;
                            if (subOptimalModel != null && subOptimalModel.NumConsts != 0)
                            {
                                // Remember the solution values
                                foreach (KeyValuePair <int, Expr> pair in _variables)
                                {
                                    var value = Utils.ToRational(subOptimalModel.Eval(pair.Value, true));
                                    _model.SetValue(pair.Key, value);
                                }
                                // Remember all objective values
                                foreach (var pair in _goals)
                                {
                                    var optimalValue = Utils.ToRational(pair.Value.Upper);
                                    _model.SetValue(pair.Key.Index, optimalValue);
                                }
                                subOptimalModel.Dispose();

                                setResult(Z3Result.LocalOptimal);
                            }
                            else
                            {
                                setResult(Z3Result.Infeasible);
                            }
                        }
                        else
                        {
                            setResult(Z3Result.Interrupted);
                        }
                        break;

                    default:
                        Debug.Assert(false, "Unrecognized Z3 Status");
                        break;
                    }
                }
            }
            finally
            {
                _isSolving = false;
            }

            // Now kill Z3
            DestructSolver(true);
        }
 public override PDLPred InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     PDLPos posConc = this.originalPos.InterpretModel(alphabet, context, model);
     char charConc = this.originalChar.InterpretModel(alphabet, context, model);
     return new PDLAtPos(charConc, posConc);
 }
 public override PDLPred InterpretModel(IList<char> alphabet, Context context, Model model)
 {
     char charConc = this.originalChar.InterpretModel(alphabet, context, model);
     PDLSet posConc = this.originalSet.InterpretModel(alphabet, context, model);
     return new PDLAtSet(charConc, posConc);
 }
Exemple #34
0
 internal Model(Context context, Microsoft.Z3.Model z3model)
 {
     this.context = context;
     this.model   = z3model;
 }