Assert() public method

Assert a constraint (or multiple) into the solver.
public Assert ( ) : void
return void
        private void AddRelation_Constraint(RelationTypes relationType, string parentFeatureIdentifier, string childFeatureIdentifier)
        {
            // Variables
            string   parentFeatureSID      = GenerateFeatureSID(parentFeatureIdentifier);
            string   childFeatureSID       = GenerateFeatureSID(childFeatureIdentifier);
            Constant parentFeatureConstant = _constants[parentFeatureSID];
            Constant childFeatureConstant  = _constants[childFeatureSID];

            // Create the constraint in the Z3 context
            BoolExpr expr = null;

            switch (relationType)
            {
            case RelationTypes.Mandatory:
            {
                expr = MakeEquivalence(parentFeatureConstant.Expr as BoolExpr, childFeatureConstant.Expr as BoolExpr);
                break;
            }

            case RelationTypes.Optional:
            {
                expr = _context.MkImplies((BoolExpr)childFeatureConstant.Expr, (BoolExpr)parentFeatureConstant.Expr);
                break;
            }
            }

            // Assert the constraint in the Z3 solver
            _solver.Assert(expr);

            // Keep track of the constraint
            _constraints.Add(new Constraint(expr));
        }
Example #2
0
        /// <summary>
        /// Try to find a configuration with low weight.
        /// </summary>
        /// <param name="sortedRanking">A list of binary options and their weight ordered by their weight.</param>
        /// <param name="cache">A sat solver cache instance that already contains the constraints of
        /// size and disallowed features.</param>
        /// <param name="vm">The variability model of the given system.</param>
        /// <returns>A configuration that has a small weight.</returns>
        public static List <BinaryOption> getSmallWeightConfig(List <KeyValuePair <List <BinaryOption>, int> > sortedRanking,
                                                               Z3Cache cache, VariabilityModel vm)
        {
            KeyValuePair <List <BinaryOption>, int>[] ranking = sortedRanking.ToArray();
            Microsoft.Z3.Solver solver    = cache.GetSolver();
            Context             z3Context = cache.GetContext();

            for (int i = 0; i < ranking.Length; i++)
            {
                List <BinaryOption> candidates = ranking[i].Key;
                solver.Push();
                solver.Assert(forceFeatures(candidates, z3Context, cache.GetOptionToTermMapping()));

                if (solver.Check() == Status.SATISFIABLE)
                {
                    Model model = solver.Model;
                    solver.Pop();
                    return(Z3VariantGenerator.RetrieveConfiguration(cache.GetVariables(), model,
                                                                    cache.GetTermToOptionMapping()));
                }
                solver.Pop();
            }

            return(null);
        }
Example #3
0
        private bool Solve_Brtrue(CflowStack stack)
        {
            var val1 = stack.Pop();

            if (val1 is BitVecExpr)
            {
                FinalExpr = ctx.MkEq(val1 as BitVecExpr, ctx.MkBV(0, 32));

                if ((val1 as BitVecExpr).Simplify().IsNumeral)
                {
                    Microsoft.Z3.Solver s = ctx.MkSolver();
                    s.Assert(FinalExpr);
                    if (s.Check() == Status.UNSATISFIABLE)
                    {
                        this.PopPushedArgs(1);

                        block.ReplaceBccWithBranch(true);

                        return(true);
                    }
                    else
                    {
                        this.PopPushedArgs(1);

                        block.ReplaceBccWithBranch(false);

                        return(true);
                    }
                }
            }

            return(false);
        }
Example #4
0
        protected override void AddControllerOverflow(Microsoft.Z3.Context ctx, Microsoft.Z3.Solver solver, string varName)
        {
            FixedPointNumber var  = discreteVariablesByName[varName];
            FixedPointNumber expr = assigns[varName];

            solver.Assert(expr.overflow);
        }
Example #5
0
        /// <summary>
        /// Add controller code for output/memory variable 'var'
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="solver"></param>
        /// <param name="variable"></param>
        protected override void AddController(Microsoft.Z3.Context ctx, Microsoft.Z3.Solver solver, string varName)
        {
            FixedPointNumber     var    = discreteVariablesByName[varName];
            FixedPointNumber     expr   = assigns[varName];
            BoolExprWithOverflow assert = ctx.MkFPEq(var, expr);

            solver.Assert(assert.bv);
        }
Example #6
0
        public bool SolveBranchAssisted(Context ctx, BoolExpr expr)
        {
            Instruction instr = block.LastInstr.Instruction;

            if (instr.OpCode.Code == Code.Brfalse || instr.OpCode.Code == Code.Brfalse_S)
            {
                Microsoft.Z3.Solver s = ctx.MkSolver();
                s.Assert(expr);
                if (s.Check() == Status.SATISFIABLE)
                {
                    this.PopPushedArgs(1);

                    block.ReplaceBccWithBranch(true);

                    return(true);
                }
                else
                {
                    this.PopPushedArgs(1);

                    block.ReplaceBccWithBranch(false);

                    return(true);
                }
            }
            else if (instr.OpCode.Code == Code.Brtrue || instr.OpCode.Code == Code.Brtrue_S)
            {
                Microsoft.Z3.Solver s = ctx.MkSolver();
                s.Assert(expr);
                if (s.Check() == Status.UNSATISFIABLE)
                {
                    this.PopPushedArgs(1);

                    block.ReplaceBccWithBranch(true);

                    return(true);
                }
                else
                {
                    this.PopPushedArgs(1);

                    block.ReplaceBccWithBranch(false);

                    return(true);
                }
            }
            else
            {
                Microsoft.Z3.Solver s1 = ctx.MkSolver();
                Microsoft.Z3.Solver s2 = ctx.MkSolver();

                s1.Add(expr);
                s2.Add(ctx.MkNot(expr));

                return(this.CheckBranch(s1, s2));
            }
        }
        /// <summary>
        /// Generates all valid combinations of all configuration options in the given model.
        /// </summary>
        /// <param name="vm">the variability model containing the binary options and their constraints</param>
        /// <param name="optionsToConsider">the options that should be considered. All other options are ignored</param>
        /// <returns>Returns a list of <see cref="Configuration"/></returns>
        public List <Configuration> GenerateAllVariants(VariabilityModel vm, List <ConfigurationOption> optionsToConsider)
        {
            List <Configuration> allConfigurations = new List <Configuration>();
            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;

            Microsoft.Z3.Solver solver = z3Context.MkSolver();

            // TODO: The following line works for z3Solver version >= 4.6.0
            //solver.Set (RANDOM_SEED, z3RandomSeed);
            Params solverParameter = z3Context.MkParams();

            solverParameter.Add(RANDOM_SEED, z3RandomSeed);
            solver.Parameters = solverParameter;

            solver.Assert(z3Constraints);

            while (solver.Check() == Status.SATISFIABLE)
            {
                Model model = solver.Model;

                List <BinaryOption> binOpts = RetrieveConfiguration(variables, model, termToOption, optionsToConsider);

                Configuration c = new Configuration(binOpts);
                // Check if the non-boolean constraints are satisfied
                if (vm.configurationIsValid(c) && !VariantGenerator.IsInConfigurationFile(c, allConfigurations) && VariantGenerator.FulfillsMixedConstraints(c, vm))
                {
                    allConfigurations.Add(c);
                }
                solver.Push();
                solver.Assert(Z3Solver.NegateExpr(z3Context, Z3Solver.ConvertConfiguration(z3Context, binOpts, optionToTerm, vm)));
            }

            solver.Push();
            solver.Pop(Convert.ToUInt32(allConfigurations.Count() + 1));
            return(allConfigurations);
        }
Example #8
0
        public bool checkConfigurationSAT(List <BinaryOption> config, VariabilityModel vm, bool partialConfiguration)
        {
            List <BoolExpr> variables;
            Dictionary <BoolExpr, BinaryOption> termToOption;
            Dictionary <BinaryOption, BoolExpr> optionToTerm;
            Tuple <Context, BoolExpr>           z3Tuple = Z3Solver.GetInitializedBooleanSolverSystem(out variables, out optionToTerm, out termToOption, vm, false);
            Context  z3Context     = z3Tuple.Item1;
            BoolExpr z3Constraints = z3Tuple.Item2;

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

            Microsoft.Z3.Solver solver = z3Context.MkSolver();
            solver.Assert(z3Constraints);
            solver.Assert(Z3Solver.ConvertConfiguration(z3Context, config, optionToTerm, vm, partialConfiguration));

            if (solver.Check() == Status.SATISFIABLE)
            {
                return(true);
            }
            return(false);
        }
Example #9
0
        /// <summary>
        /// Generates all valid combinations of all configuration options in the given model.
        /// </summary>
        /// <param name="vm">the variability model containing the binary options and their constraints</param>
        /// <param name="optionsToConsider">the options that should be considered. All other options are ignored</param>
        /// <returns>Returns a list of <see cref="Configuration"/></returns>
        public List <Configuration> GenerateAllVariants(VariabilityModel vm, List <ConfigurationOption> optionsToConsider)
        {
            List <Configuration> allConfigurations = new List <Configuration>();
            List <Expr>          variables;
            Dictionary <Expr, ConfigurationOption> termToOption;
            Dictionary <ConfigurationOption, Expr> optionToTerm;
            Tuple <Context, BoolExpr> z3Tuple = Z3Solver.GetInitializedSolverSystem(out variables, out optionToTerm, out termToOption, vm);
            Context  z3Context     = z3Tuple.Item1;
            BoolExpr z3Constraints = z3Tuple.Item2;

            Microsoft.Z3.Solver solver = z3Context.MkSolver();

            solver.Set(RANDOM_SEED, z3RandomSeed);

            solver.Assert(z3Constraints);

            while (solver.Check() == Status.SATISFIABLE)
            {
                Model model = solver.Model;

                Tuple <List <BinaryOption>, Dictionary <NumericOption, double> > confOpts = RetrieveConfiguration(variables, model, termToOption, optionsToConsider);

                Configuration c = new Configuration(confOpts.Item1, confOpts.Item2);
                // Check if the non-boolean constraints are satisfied
                bool configIsValid             = vm.configurationIsValid(c);
                bool isInConfigurationFile     = !VariantGenerator.IsInConfigurationFile(c, allConfigurations);
                bool fulfillsMixedConstraintrs = VariantGenerator.FulfillsMixedConstraints(c, vm);
                if (configIsValid && isInConfigurationFile && fulfillsMixedConstraintrs)
                {
                    allConfigurations.Add(c);
                }
                solver.Push();
                solver.Assert(Z3Solver.NegateExpr(z3Context, Z3Solver.ConvertConfiguration(z3Context, confOpts.Item1, optionToTerm, vm, numericValues: confOpts.Item2)));
            }

            solver.Push();
            solver.Pop(Convert.ToUInt32(allConfigurations.Count() + 1));
            return(allConfigurations);
        }
        public bool checkConfigurationSAT(Configuration c, VariabilityModel vm, bool partialConfiguration = false)
        {
            List <Expr> variables;
            Dictionary <Expr, ConfigurationOption> termToOption;
            Dictionary <ConfigurationOption, Expr> optionToTerm;
            Tuple <Context, BoolExpr> z3Tuple = Z3Solver.GetInitializedSolverSystem(out variables, out optionToTerm, out termToOption, vm);
            Context  z3Context     = z3Tuple.Item1;
            BoolExpr z3Constraints = z3Tuple.Item2;

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

            Microsoft.Z3.Solver solver = z3Context.MkSolver();
            solver.Assert(z3Constraints);

            solver.Assert(Z3Solver.ConvertConfiguration(z3Context, c.getBinaryOptions(BinaryOption.BinaryValue.Selected), optionToTerm, vm, partialConfiguration, c.NumericOptions));

            if (solver.Check() == Status.SATISFIABLE)
            {
                return(true);
            }
            return(false);
        }
        // Constructor
        public SolverContext(Modelling.BLOs.Model model)
        {
            // Create an empty z3 context
            Dictionary <string, string> configSettings = new Dictionary <string, string>();

            configSettings["MODEL"]        = "true";
            configSettings["MACRO_FINDER"] = "true";
            _context           = new Context(configSettings);
            _context.PrintMode = Z3_ast_print_mode.Z3_PRINT_SMTLIB2_COMPLIANT;


            // Setup the z3 context and solver
            _solver = _context.MkSolver();

            // Setup custom conversion method BoolToInt (boolean -> integer)
            FuncDecl boolToInt  = _context.MkFuncDecl("BoolToInt", _context.MkBoolSort(), _context.MkIntSort());
            Expr     i          = _context.MkConst("i", _context.MkBoolSort());
            Expr     fDef       = _context.MkITE(_context.MkEq(i, _context.MkTrue()), _context.MkInt(1), _context.MkInt(0)); // x == true => 1, x == false => 0
            Expr     fStatement = _context.MkForall(new Expr[] { i }, _context.MkEq(_context.MkApp(boolToInt, i), fDef));

            _solver.Assert(fStatement as BoolExpr);
            _functions.Add("BoolToInt", new Function(boolToInt));

            // Create the static part (constants and constraints)
            model.Features.ForEach(feature =>
            {
                string featureSID = GenerateFeatureSID(feature.Identifier);
                AddFeature_Constant(feature.Identifier);
                feature.Attributes.ForEach(attribute => AddAttribute_Constant(attribute.Identifier, feature.Identifier, attribute.AttributeDataType));
            });
            model.Relations.ForEach(relation =>
            {
                AddRelation_Constraint(relation.RelationType, relation.ParentFeature.Identifier, relation.ChildFeature.Identifier);
            });
            model.GroupRelations.ForEach(groupRelation =>
            {
                string[] childFeatureIDs = groupRelation.ChildFeatures.Select(feature => feature.Identifier).ToArray();
                AddGroupRelation_Constraint(groupRelation.GroupRelationType, groupRelation.ParentFeature.Identifier, childFeatureIDs,
                                            groupRelation.UpperBound ?? default(int), groupRelation.LowerBound ?? default(int));
            });
            model.CompositionRules.ForEach(compRule =>
            {
                AddCompositionRule_Constraint(compRule.CompositionRuleType, compRule.FirstFeature.Identifier, compRule.SecondFeature.Identifier);
            });

            // Create initial point
            _solver.Push();
        }
Example #12
0
        /// <summary>
        /// Demonstrate how to use <code>Push</code>and <code>Pop</code>to
        /// control the size of models.
        /// </summary>
        /// <remarks>Note: this test is specialized to 32-bit bitvectors.</remarks>
        public static void CheckSmall(Context ctx, Solver solver, BitVecExpr[] to_minimize)
        {
            Sort bv32 = ctx.MkBitVecSort(32);

            int num_Exprs = to_minimize.Length;
            UInt32[] upper = new UInt32[num_Exprs];
            UInt32[] lower = new UInt32[num_Exprs];
            BitVecExpr[] values = new BitVecExpr[num_Exprs];
            for (int i = 0; i < upper.Length; ++i)
            {
                upper[i] = UInt32.MaxValue;
                lower[i] = 0;
            }
            bool some_work = true;
            int last_index = -1;
            UInt32 last_upper = 0;
            while (some_work)
            {
                solver.Push();

                bool check_is_sat = true;
                while (check_is_sat && some_work)
                {
                    // Assert all feasible bounds.
                    for (int i = 0; i < num_Exprs; ++i)
                    {
                        solver.Assert(ctx.MkBVULE(to_minimize[i], ctx.MkBV(upper[i], 32)));
                    }

                    check_is_sat = Status.SATISFIABLE == solver.Check();
                    if (!check_is_sat)
                    {
                        if (last_index != -1)
                        {
                            lower[last_index] = last_upper + 1;
                        }
                        break;
                    }
                    Console.WriteLine("{0}", solver.Model);

                    // narrow the bounds based on the current model.
                    for (int i = 0; i < num_Exprs; ++i)
                    {
                        Expr v = solver.Model.Evaluate(to_minimize[i]);
                        UInt64 ui = ((BitVecNum)v).UInt64;
                        if (ui < upper[i])
                        {
                            upper[i] = (UInt32)ui;
                        }
                        Console.WriteLine("{0} {1} {2}", i, lower[i], upper[i]);
                    }

                    // find a new bound to add
                    some_work = false;
                    last_index = 0;
                    for (int i = 0; i < num_Exprs; ++i)
                    {
                        if (lower[i] < upper[i])
                        {
                            last_upper = (upper[i] + lower[i]) / 2;
                            last_index = i;
                            solver.Assert(ctx.MkBVULE(to_minimize[i], ctx.MkBV(last_upper, 32)));
                            some_work = true;
                            break;
                        }
                    }
                }
                solver.Pop();
            }
        }
        /// <summary>
        /// This method searches for a corresponding methods in the dynamically loaded assemblies and calls it if found. It prefers due to performance reasons the Microsoft Solver Foundation implementation.
        /// </summary>
        /// <param name="config">The (partial) configuration which needs to be expaned 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>The valid configuration (or null if there is none) that satisfies the VM and the goal.</returns>
        public List <BinaryOption> MinimizeConfig(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);

            //Feature Selection
            foreach (BinaryOption binOpt in config)
            {
                BoolExpr term = optionToTerm[binOpt];
                constraints.Add(term);
            }

            Model model = null;

            if (minimize == true)
            {
                //Defining Goals
                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);

                    int weight = 1;
                    if (unWantedOptions != null && (unWantedOptions.Contains(termToOption[variables[r]]) && !config.Contains(termToOption[variables[r]])))
                    {
                        weight = 1000;
                    }

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

                    optimizationGoals[r] = numericVariable;
                }
                // For minimization, we need the class 'Optimize'
                Optimize optimizer = z3Context.MkOptimize();
                optimizer.Assert(constraints.ToArray());
                optimizer.MkMinimize(z3Context.MkAdd(optimizationGoals));

                if (optimizer.Check() != Status.SATISFIABLE)
                {
                    return(new List <BinaryOption>());
                }
                else
                {
                    model = optimizer.Model;
                }
            }
            else
            {
                // Return the first configuration returned by the solver
                Microsoft.Z3.Solver solver = z3Context.MkSolver();

                // TODO: The following line works for z3Solver version >= 4.6.0
                //solver.Set (RANDOM_SEED, z3RandomSeed);
                Params solverParameter = z3Context.MkParams();
                solverParameter.Add(RANDOM_SEED, z3RandomSeed);
                solver.Parameters = solverParameter;

                solver.Assert(constraints.ToArray());

                if (solver.Check() != Status.SATISFIABLE)
                {
                    return(new List <BinaryOption>());
                }
                else
                {
                    model = solver.Model;
                }
            }


            List <BinaryOption> result = RetrieveConfiguration(variables, model, termToOption);

            return(result);
        }
        /// <summary>
        /// Generates up to n solutions of the given variability model.
        /// Note that this method could also generate less than n solutions if the variability model does not contain sufficient solutions.
        /// Moreover, in the case that <code>n &lt; 0</code>, all solutions are generated.
        /// </summary>
        /// <param name="vm">The <see cref="VariabilityModel"/> to obtain solutions for.</param>
        /// <param name="n">The number of solutions to obtain.</param>
        /// <returns>A list of configurations, in which a configuration is a list of SELECTED binary options.</returns>
        public List <List <BinaryOption> > GenerateUpToNFast(VariabilityModel vm, int n)
        {
            // Use the random seed to produce new random seeds
            Random random = new Random(Convert.ToInt32(z3RandomSeed));

            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, random.Next());
            Context         z3Context              = z3Tuple.Item1;
            BoolExpr        z3Constraints          = z3Tuple.Item2;
            List <BoolExpr> excludedConfigurations = new List <BoolExpr>();
            List <BoolExpr> constraints            = Z3Solver.lastConstraints;

            List <List <BinaryOption> > configurations = new List <List <BinaryOption> >();

            Microsoft.Z3.Solver s = z3Context.MkSolver();

            // TODO: The following line works for z3Solver version >= 4.6.0
            //solver.Set (RANDOM_SEED, z3RandomSeed);
            Params solverParameter = z3Context.MkParams();

            if (henard)
            {
                solverParameter.Add(RANDOM_SEED, NextUInt(random));
            }
            else
            {
                solverParameter.Add(RANDOM_SEED, z3RandomSeed);
            }
            s.Parameters = solverParameter;

            s.Assert(z3Constraints);
            s.Push();

            Model model = null;

            while (s.Check() == Status.SATISFIABLE && (configurations.Count < n || n < 0))
            {
                model = s.Model;

                List <BinaryOption> config = RetrieveConfiguration(variables, model, termToOption);

                configurations.Add(config);

                if (henard)
                {
                    BoolExpr newConstraint = Z3Solver.NegateExpr(z3Context, Z3Solver.ConvertConfiguration(z3Context, config, optionToTerm, vm));

                    excludedConfigurations.Add(newConstraint);

                    Dictionary <BoolExpr, BinaryOption> oldTermToOption = termToOption;

                    // Now, initialize a new one for the next configuration
                    z3Tuple       = Z3Solver.GetInitializedBooleanSolverSystem(out variables, out optionToTerm, out termToOption, vm, this.henard, random.Next());
                    z3Context     = z3Tuple.Item1;
                    z3Constraints = z3Tuple.Item2;

                    s = z3Context.MkSolver();

                    //s.Set (RANDOM_SEED, NextUInt (random));
                    solverParameter = z3Context.MkParams();

                    solverParameter.Add(RANDOM_SEED, NextUInt(random));
                    s.Parameters = solverParameter;

                    constraints = Z3Solver.lastConstraints;

                    excludedConfigurations = Z3Solver.ConvertConstraintsToNewContext(oldTermToOption, optionToTerm, excludedConfigurations, z3Context);

                    constraints.AddRange(excludedConfigurations);

                    s.Assert(z3Context.MkAnd(Z3Solver.Shuffle(constraints, new Random(random.Next()))));

                    s.Push();
                }
                else
                {
                    s.Add(Z3Solver.NegateExpr(z3Context, Z3Solver.ConvertConfiguration(z3Context, config, optionToTerm, vm)));
                }
            }

            return(configurations);
        }
    /*!
       \brief Extract unsatisfiable core example
    */
    public void unsat_core_and_proof_example()
    {
        if (this.z3 != null)
        {
            this.z3.Dispose();
        }
        Dictionary<string, string> cfg = new Dictionary<string, string>() {
            { "PROOF_MODE", "2" } };
        this.z3 = new Context(cfg);
        this.solver = z3.MkSolver();

        BoolExpr pa = mk_bool_var("PredA");
        BoolExpr pb = mk_bool_var("PredB");
        BoolExpr pc = mk_bool_var("PredC");
        BoolExpr pd = mk_bool_var("PredD");
        BoolExpr p1 = mk_bool_var("P1");
        BoolExpr p2 = mk_bool_var("P2");
        BoolExpr p3 = mk_bool_var("P3");
        BoolExpr p4 = mk_bool_var("P4");
        BoolExpr[] assumptions = new BoolExpr[] { z3.MkNot(p1), z3.MkNot(p2), z3.MkNot(p3), z3.MkNot(p4) };
        BoolExpr f1 = z3.MkAnd(new BoolExpr[] { pa, pb, pc });
        BoolExpr f2 = z3.MkAnd(new BoolExpr[] { pa, z3.MkNot(pb), pc });
        BoolExpr f3 = z3.MkOr(z3.MkNot(pa), z3.MkNot(pc));
        BoolExpr f4 = pd;

        solver.Assert(z3.MkOr(f1, p1));
        solver.Assert(z3.MkOr(f2, p2));
        solver.Assert(z3.MkOr(f3, p3));
        solver.Assert(z3.MkOr(f4, p4));
        Status result = solver.Check(assumptions);

        if (result == Status.UNSATISFIABLE)
        {
            Console.WriteLine("unsat");
            Console.WriteLine("proof: {0}", solver.Proof);
            foreach (Expr c in solver.UnsatCore)
            {
                Console.WriteLine("{0}", c);
            }
        }
    }
 public override void ToSMTConstraints(Context z3Context, Solver z3Solver, int alphabetSize, VariableCache variableGenerator)
 {
     // Take a constraint variable just for good measure
     this.constraintVariable = variableGenerator.GetFreshVariableName();
     ArithExpr myVariable = z3Context.MkIntConst(this.constraintVariable);
     z3Solver.Assert(z3Context.MkEq(myVariable, z3Context.MkInt(0)));
 }
 public void ToSMTConstraints(Context z3Context, Solver z3Solver, int alphabetSize, VariableCache variableGenerator)
 {
     this.constraintVariable = variableGenerator.GetStringChoiceVariable(this.originalValue);
     ArithExpr myVariable = z3Context.MkIntConst(this.constraintVariable);
     z3Solver.Assert(z3Context.MkLe(z3Context.MkInt(0), myVariable));
     /* We have |s| * |\Sigma| options for concretizing this string
      * Thus, since we are 0-based: originalValue.Length * alphabet - 1 */
     z3Solver.Assert(z3Context.MkLe(myVariable, z3Context.MkInt(this.originalValue.Length * alphabetSize - 1)));
 }
 public override void ToSMTConstraints(Context z3Context, Solver z3Solver, int alphabetSize, VariableCache variableGenerator)
 {
     this.constraintVariable = variableGenerator.GetFreshVariableName();
     ArithExpr myVariable = z3Context.MkIntConst(this.constraintVariable);
     z3Solver.Assert(z3Context.MkEq(myVariable, z3Context.MkInt(0)));
     this.originalPosition.ToSMTConstraints(z3Context, z3Solver, alphabetSize, variableGenerator);
     this.originalSet.ToSMTConstraints(z3Context, z3Solver, alphabetSize, variableGenerator);
 }
 private void GenerateInequalityConstraints(ICollection<string> vars, Context z3Context, Solver z3Solver)
 {
     List<string> varList = new List<string>(vars);
     for (int i = 0; i < varList.Count; ++i)
     {
         for (int j = i + 1; j < varList.Count; ++j)
         {
             // Assert vars[i] != vars[j]
             z3Solver.Assert(
                 z3Context.MkNot(
                     z3Context.MkEq(
                         z3Context.MkIntConst(varList[i]), 
                         z3Context.MkIntConst(varList[j])
                     )
                 )
             );
         }
     }
 }
 private static void ExcludeLastModel(IEnumerable<string> choiceVariables, Context z3Context, Solver z3Solver)
 {
     Model lastModel = z3Solver.Model;
     BoolExpr characteristicFormula = CreateCharacteristicFormula(choiceVariables, z3Context, lastModel);
     z3Solver.Assert(z3Context.MkNot(characteristicFormula));
 }
 public void ToSMTConstraints(Context z3Context, Solver z3Solver, int alphabetSize, VariableCache variableGenerator)
 {
     this.constraintVariable = variableGenerator.GetCharChoiceVariable(this.originalValue);
     ArithExpr myVariable = z3Context.MkIntConst(this.constraintVariable);
     z3Solver.Assert(z3Context.MkLe(z3Context.MkInt(0), myVariable));
     z3Solver.Assert(z3Context.MkLe(myVariable, z3Context.MkInt(alphabetSize - 1)));
 }
        public void ToSMTConstraints(Context z3Context, Solver z3Solver, int alphabetSize, VariableCache variableGenerator)
        {
            this.constraintVariable = variableGenerator.GetIntegerChoiceVariable(this.originalValue);
            ArithExpr myVariable = z3Context.MkIntConst(this.constraintVariable);
            // For now, just concretize in the range [floor(origVal / 2), ceil(origVal * 1.5)]
            z3Solver.Assert(z3Context.MkLe(z3Context.MkInt((int)(this.originalValue * 0.5)), myVariable));
            z3Solver.Assert(z3Context.MkLe(myVariable, z3Context.MkInt((int)(this.originalValue * 1.5))));

            if (this.includeZero == false)
            {
                z3Solver.Assert(z3Context.MkNot(z3Context.MkEq(z3Context.MkInt(0), myVariable)));
            }
        }
 public override void ToSMTConstraints(Context z3Context, Solver z3Solver, int alphabetSize, 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)));
 }
    /*! \brief Prove that <tt>f(x, y) = f(w, v) implies y = v</tt> when
        \c f is injective in the second argument.

        \sa assert_inj_axiom.
    */
    public void quantifier_example1_abs()
    {
        Console.WriteLine("quantifier_example1_abs");

        Dictionary<string, string> cfg = new Dictionary<string, string>() { { "MBQI", "false" }, { "PROOF_MODE", "2" } };

        /* If quantified formulas are asserted in a logical context, then
           the model produced by Z3 should be viewed as a potential model.

        */
        if (this.z3 != null)
        {
            this.z3.Dispose();
        }
        this.z3 = new Context(cfg);
        this.solver = z3.MkSolver();

        /* declare function f */
        Sort int_type = mk_int_type();
        FuncDecl f = z3.MkFuncDecl("f", new Sort[] { int_type, int_type }, int_type);

        /* assert that f is injective in the second argument. */
        assert_inj_axiom_abs(f, 1);

        /* create x, y, v, w, fxy, fwv */
        Expr x = mk_int_var("x");
        Expr y = mk_int_var("y");
        Expr v = mk_int_var("v");
        Expr w = mk_int_var("w");
        Expr fxy = mk_binary_app(f, x, y);
        Expr fwv = mk_binary_app(f, w, v);

        /* assert f(x, y) = f(w, v) */
        BoolExpr p1 = z3.MkEq(fxy, fwv);
        solver.Assert(p1);

        /* prove f(x, y) = f(w, v) implies y = v */
        BoolExpr p2 = z3.MkEq(y, v);
        Console.WriteLine("prove: f(x, y) = f(w, v) implies y = v");
        prove(p2);

        /* disprove f(x, y) = f(w, v) implies x = w */
        BoolExpr p3 = z3.MkEq(x, w);
        Console.WriteLine("disprove: f(x, y) = f(w, v) implies x = w");
        prove(p3);
    }