{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Advanced Topics\n",
    "\n",
    "More information on Z3 is available from https://github.com/z3prover/z3.git\n",
    "\n",
    "\n",
    "## Expressions, Sorts and Declarations\n",
    "In Z3, expressions, sorts and declarations are called ASTs. ASTs are directed acyclic graphs. Every expression has a sort (aka type). The method sort() retrieves the sort of an expression."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install \"z3-solver\"\n",
    "from z3 import *\n",
    "\n",
    "x = Int('x')\n",
    "y = Real('y')\n",
    "print ((x + 1).sort())\n",
    "print ((y + 1).sort())\n",
    "print ((x >= 2).sort())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The function eq(n1, n2) returns True if n1 and n2 are the same AST. This is a structural test."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x, y = Ints('x y')\n",
    "print (eq(x + y, x + y))\n",
    "print (eq(x + y, y + x))\n",
    "n = x + y\n",
    "print (eq(n, x + y))\n",
    "# x2 is eq to x\n",
    "x2 = Int('x') \n",
    "print (eq(x, x2))\n",
    "# the integer variable x is not equal to \n",
    "# the real variable x\n",
    "print (eq(Int('x'), Real('x')))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The method hash() returns a hashcode for an AST node. If eq(n1, n2) returns True, then n1.hash() is equal to n2.hash()."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Int('x')\n",
    "print ((x + 1).hash())\n",
    "print ((1 + x).hash())\n",
    "print (x.sort().hash())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Z3 expressions can be divided in three basic groups: applications, quantifiers and bound/free variables. Applications are all you need if your problems do not contain universal/existential quantifiers. Although we say Int('x') is an integer \"variable\", it is technically an integer constant, and internally is represented as a function application with 0 arguments. Every application is associated with a declaration and contains 0 or more arguments. The method decl() returns the declaration associated with an application. The method num_args() returns the number of arguments of an application, and arg(i) one of the arguments. The function is_expr(n) returns True if n is an expression. Similarly is_app(n) (is_func_decl(n)) returns True if n is an application (declaration)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Int('x')\n",
    "print (\"is expression: \", is_expr(x))\n",
    "n = x + 1\n",
    "print (\"is application:\", is_app(n))\n",
    "print (\"decl:          \", n.decl())\n",
    "print (\"num args:      \", n.num_args())\n",
    "for i in range(n.num_args()):\n",
    "    print (\"arg(\", i, \") ->\", n.arg(i))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Declarations have names, they are retrieved using the method name(). A (function) declaration has an arity, a domain and range sorts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x   = Int('x')\n",
    "x_d = x.decl()\n",
    "print (\"is_expr(x_d):     \", is_expr(x_d))\n",
    "print (\"is_func_decl(x_d):\", is_func_decl(x_d))\n",
    "print (\"x_d.name():       \", x_d.name())\n",
    "print (\"x_d.range():      \", x_d.range())\n",
    "print (\"x_d.arity():      \", x_d.arity())\n",
    "# x_d() creates an application with 0 arguments using x_d.\n",
    "print (\"eq(x_d(), x):     \", eq(x_d(), x))\n",
    "print (\"\\n\")\n",
    "# f is a function from (Int, Real) to Bool\n",
    "f   = Function('f', IntSort(), RealSort(), BoolSort())\n",
    "print (\"f.name():         \", f.name())\n",
    "print (\"f.range():        \", f.range())\n",
    "print (\"f.arity():        \", f.arity())\n",
    "for i in range(f.arity()):\n",
    "    print (\"domain(\", i, \"): \", f.domain(i))\n",
    "# f(x, x) creates an application with 2 arguments using f.\n",
    "print (f(x, x))\n",
    "print (eq(f(x, x).decl(), f))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The built-in declarations are identified using their kind. The kind is retrieved using the method kind(). The complete list of built-in declarations can be found in the file z3consts.py (z3_api.h) in the Z3 distribution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x, y = Ints('x y')\n",
    "print ((x + y).decl().kind() == Z3_OP_ADD)\n",
    "print ((x + y).decl().kind() == Z3_OP_SUB)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following example demonstrates how to substitute sub-expressions in Z3 expressions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x, y = Ints('x y')\n",
    "f    = Function('f', IntSort(), IntSort(), IntSort())\n",
    "g    = Function('g', IntSort(), IntSort())\n",
    "n    = f(f(g(x), g(g(x))), g(g(y)))\n",
    "print (n)\n",
    "# substitute g(g(x)) with y and g(y) with x + 1\n",
    "print (substitute(n, (g(g(x)), y), (g(y), x + 1)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The function Const(name, sort) declares a constant (aka variable) of the given sort. For example, the functions Int(name) and Real(name) are shorthands for Const(name, IntSort()) and Const(name, RealSort())."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Const('x', IntSort())\n",
    "print (eq(x, Int('x')))\n",
    "\n",
    "a, b = Consts('a b', BoolSort())\n",
    "print (And(a, b))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Arrays\n",
    "\n",
    "As part of formulating a programme of a mathematical theory of computation McCarthy proposed a basic theory of arrays as characterized by the select-store axioms. The expression Select(a, i) returns the value stored at position i of the array a; and Store(a, i, v) returns a new array identical to a, but on position i it contains the value v. In Z3Py, we can also write Select(a, i) as a[i]."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use I as an alias for IntSort()\n",
    "I = IntSort()\n",
    "# A is an array from integer to integer\n",
    "A = Array('A', I, I)\n",
    "x = Int('x')\n",
    "print (A[x])\n",
    "print (Select(A, x))\n",
    "print (Store(A, x, 10))\n",
    "print (simplify(Select(Store(A, 2, x+1), 2)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default, Z3 assumes that arrays are extensional over select. In other words, Z3 also enforces that if two arrays agree on all positions, then the arrays are equal.\n",
    "\n",
    "Z3 also contains various extensions for operations on arrays that remain decidable and amenable to efficient saturation procedures (here efficient means, with an NP-complete satisfiability complexity). We describe these extensions in the following using a collection of examples. Additional background on these extensions is available in the paper [Generalized and Efficient Array Decision Procedures](http://research.microsoft.com/en-us/um/people/leonardo/fmcad09.pdf).\n",
    "\n",
    "Arrays in Z3 are used to model unbounded or very large arrays. Arrays should not be used to model small finite collections of values. It is usually much more efficient to create different variables using list comprehensions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# We want an array with 3 elements.\n",
    "# 1. Bad solution\n",
    "X = Array('x', IntSort(), IntSort())\n",
    "# Example using the array\n",
    "print (X[0] + X[1] + X[2] >=0)\n",
    "\n",
    "# 2. More efficient solution\n",
    "X = IntVector('x', 3)\n",
    "print (X[0] + X[1] + X[2] >= 0)\n",
    "print (Sum(X) >= 0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Select and Store\n",
    "Let us first check a basic property of arrays. Suppose A is an array of integers, then the constraints A[x] == x, Store(A, x, y) == A are satisfiable for an array that contains an index x that maps to x, and when x == y. We can solve these constraints."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A = Array('A', IntSort(), IntSort())\n",
    "x, y = Ints('x y')\n",
    "solve(A[x] == x, Store(A, x, y) == A)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The interpretation/solution for array variables is very similar to the one used for functions.\n",
    "\n",
    "The problem becomes unsatisfiable/infeasible if we add the constraint x != y."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A = Array('A', IntSort(), IntSort())\n",
    "x, y = Ints('x y')\n",
    "solve(A[x] == x, Store(A, x, y) == A, x != y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Constant arrays\n",
    "The array that maps all indices to some fixed value can be specified in Z3Py using the K(s, v) construct where s is a sort/type and v is an expression. K(s, v) returns a array that maps any value of s into v. The following example defines a constant array containing only ones."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "AllOne = K(IntSort(), 1)\n",
    "a, i = Ints('a i')\n",
    "solve(a == AllOne[i])\n",
    "# The following constraints do not have a solution\n",
    "solve(a == AllOne[i], a != 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Datatypes\n",
    "Algebraic datatypes, known from programming languages such as ML, offer a convenient way for specifying common data structures. Records and tuples are special cases of algebraic datatypes, and so are scalars (enumeration types). But algebraic datatypes are more general. They can be used to specify finite lists, trees and other recursive structures.\n",
    "\n",
    "The following example demonstrates how to declare a List in Z3Py. It is more verbose than using the SMT 2.0 front-end, but much simpler than using the Z3 C API. It consists of two phases. First, we have to declare the new datatype, its constructors and accessors. The function Datatype('List') declares a \"placeholder\" that will contain the constructors and accessors declarations. The method declare(cname, (aname, sort)+) declares a constructor named cname with the given accessors. Each accessor has an associated sort or a reference to the datatypes being declared. For example, declare('cons', ('car', IntSort()), ('cdr', List)) declares the constructor named cons that builds a new List using an integer and a List. It also declares the accessors car and cdr. The accessor car extracts the integer of a cons cell, and cdr the list of a cons cell. After all constructors were declared, we use the method create() to create the actual datatype in Z3. Z3Py makes the new Z3 declarations and constants available as slots of the new object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Declare a List of integers\n",
    "List = Datatype('List')\n",
    "# Constructor cons: (Int, List) -> List\n",
    "List.declare('cons', ('car', IntSort()), ('cdr', List))\n",
    "# Constructor nil: List\n",
    "List.declare('nil')\n",
    "# Create the datatype\n",
    "List = List.create()\n",
    "print (is_sort(List))\n",
    "cons = List.cons\n",
    "car  = List.car\n",
    "cdr  = List.cdr\n",
    "nil  = List.nil\n",
    "# cons, car and cdr are function declarations, and nil a constant\n",
    "print (is_func_decl(cons))\n",
    "print (is_expr(nil))\n",
    "\n",
    "l1 = cons(10, cons(20, nil))\n",
    "print (l1)\n",
    "print (simplify(cdr(l1)))\n",
    "print (simplify(car(l1)))\n",
    "print (simplify(l1 == nil))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following example demonstrates how to define a Python function that given a sort creates a list of the given sort."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def DeclareList(sort):\n",
    "    List = Datatype('List_of_%s' % sort.name())\n",
    "    List.declare('cons', ('car', sort), ('cdr', List))\n",
    "    List.declare('nil')\n",
    "    return List.create()\n",
    "\n",
    "IntList     = DeclareList(IntSort())\n",
    "RealList    = DeclareList(RealSort())\n",
    "IntListList = DeclareList(IntList)\n",
    "\n",
    "l1 = IntList.cons(10, IntList.nil)\n",
    "print (l1)\n",
    "print (IntListList.cons(l1, IntListList.cons(l1, IntListList.nil)))\n",
    "print (RealList.cons(\"1/3\", RealList.nil))\n",
    "\n",
    "print (l1.sort())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The example above demonstrates that Z3 supports operator overloading. There are several functions named cons, but they are different since they receive and/or return values of different sorts. Note that it is not necessary to use a different sort name for each instance of the sort list. That is, the expression 'List_of_%s' % sort.name() is not necessary, we use it just to provide more meaningful names.\n",
    "\n",
    "As described above enumeration types are a special case of algebraic datatypes. The following example declares an enumeration type consisting of three values: red, green and blue."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Color = Datatype('Color')\n",
    "Color.declare('red')\n",
    "Color.declare('green')\n",
    "Color.declare('blue')\n",
    "Color = Color.create()\n",
    "\n",
    "print (is_expr(Color.green))\n",
    "print (Color.green == Color.blue)\n",
    "print (simplify(Color.green == Color.blue))\n",
    "\n",
    "# Let c be a constant of sort Color\n",
    "c = Const('c', Color)\n",
    "# Then, c must be red, green or blue\n",
    "prove(Or(c == Color.green, \n",
    "         c == Color.blue,\n",
    "         c == Color.red))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Z3Py also provides the following shorthand for declaring enumeration sorts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Color, (red, green, blue) = EnumSort('Color', ('red', 'green', 'blue'))\n",
    "\n",
    "print (green == blue)\n",
    "print (simplify(green == blue))\n",
    "\n",
    "c = Const('c', Color)\n",
    "solve(c != green, c != blue)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Mutually recursive datatypes can also be declared. The only difference is that we use the function CreateDatatypes instead of the method create() to create the mutually recursive datatypes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "TreeList = Datatype('TreeList')\n",
    "Tree     = Datatype('Tree')\n",
    "Tree.declare('leaf', ('val', IntSort()))\n",
    "Tree.declare('node', ('left', TreeList), ('right', TreeList))\n",
    "TreeList.declare('nil')\n",
    "TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))\n",
    "\n",
    "Tree, TreeList = CreateDatatypes(Tree, TreeList)\n",
    "\n",
    "t1  = Tree.leaf(10)\n",
    "tl1 = TreeList.cons(t1, TreeList.nil)\n",
    "t2  = Tree.node(tl1, TreeList.nil)\n",
    "print (t2)\n",
    "print (simplify(Tree.val(t1)))\n",
    "\n",
    "t1, t2, t3 = Consts('t1 t2 t3', TreeList)\n",
    "\n",
    "solve(Distinct(t1, t2, t3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Uninterpreted Sorts\n",
    "Function and constant symbols in pure first-order logic are uninterpreted or free, which means that no a priori interpretation is attached. This is in contrast to arithmetic operators such as + and - that have a fixed standard interpretation. Uninterpreted functions and constants are maximally flexible; they allow any interpretation that is consistent with the constraints over the function or constant.\n",
    "\n",
    "To illustrate uninterpreted functions and constants let us introduce an (uninterpreted) sort A, and the constants x, y ranging over A. Finally let f be an uninterpreted function that takes one argument of sort A and results in a value of sort A. The example illustrates how one can force an interpretation where f applied twice to x results in x again, but f applied once to x is different from x."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A    = DeclareSort('A')\n",
    "x, y = Consts('x y', A)\n",
    "f    = Function('f', A, A)\n",
    "\n",
    "s    = Solver()\n",
    "s.add(f(f(x)) == x, f(x) == y, x != y)\n",
    "\n",
    "print (s.check())\n",
    "m = s.model()\n",
    "print (m)\n",
    "print (\"interpretation assigned to A:\")\n",
    "print (m[A])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The resulting model introduces abstract values for the elements in A, because the sort A is uninterpreted. The interpretation for f in the model toggles between the two values for x and y, which are different. The expression m[A] returns the interpretation (universe) for the uninterpreted sort A in the model m.\n",
    "\n",
    "## Quantifiers\n",
    "Z3 is can solve quantifier-free problems containing arithmetic, bit-vector, Booleans, arrays, functions and datatypes. Z3 also accepts and can work with formulas that use quantifiers. It is no longer a decision procedure for such formulas in general (and for good reasons, as there can be no decision procedure for first-order logic)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = Function('f', IntSort(), IntSort(), IntSort())\n",
    "x, y = Ints('x y')\n",
    "print (ForAll([x, y], f(x, y) == 0))\n",
    "print (Exists(x, f(x, x) >= 0))\n",
    "\n",
    "a, b = Ints('a b')\n",
    "solve(ForAll(x, f(x, x) == 0), f(a, b) == 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Nevertheless, Z3 is often able to handle formulas involving quantifiers. It uses several approaches to handle quantifiers. The most prolific approach is using pattern-based quantifier instantiation. This approach allows instantiating quantified formulas with ground terms that appear in the current search context based on pattern annotations on quantifiers. Z3 also contains a model-based quantifier instantiation component that uses a model construction to find good terms to instantiate quantifiers with; and Z3 also handles many decidable fragments.\n",
    "\n",
    "Note that in the previous example the constants x and y were used to create quantified formulas. This is a \"trick\" for simplifying the construction of quantified formulas in Z3Py. Internally, these constants are replaced by bounded variables. The next example demonstrates that. The method body() retrieves the quantified expression. In the resultant formula the bounded variables are free. The function Var(index, sort) creates a bounded/free variable with the given index and sort."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = Function('f', IntSort(), IntSort(), IntSort())\n",
    "x, y = Ints('x y')\n",
    "f = ForAll([x, y], f(x, y) == 0)\n",
    "print (f.body())\n",
    "v1 = f.body().arg(0).arg(0)\n",
    "print (v1)\n",
    "print (eq(v1, Var(1, IntSort())))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Modeling with Quantifiers\n",
    "Suppose we want to model an object oriented type system with single inheritance. We would need a predicate for sub-typing. Sub-typing should be a partial order, and respect single inheritance. For some built-in type constructors, such as for array_of, sub-typing should be monotone."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Type     = DeclareSort('Type')\n",
    "subtype  = Function('subtype', Type, Type, BoolSort())\n",
    "array_of = Function('array_of', Type, Type)\n",
    "root     = Const('root', Type)\n",
    "\n",
    "x, y, z  = Consts('x y z', Type)\n",
    "\n",
    "axioms = [ ForAll(x, subtype(x, x)),\n",
    "           ForAll([x, y, z], Implies(And(subtype(x, y), subtype(y, z)),\n",
    "                                     subtype(x, z))),\n",
    "           ForAll([x, y], Implies(And(subtype(x, y), subtype(y, x)),\n",
    "                                  x == y)),\n",
    "           ForAll([x, y, z], Implies(And(subtype(x, y), subtype(x, z)),\n",
    "                                     Or(subtype(y, z), subtype(z, y)))),\n",
    "           ForAll([x, y], Implies(subtype(x, y),\n",
    "                                  subtype(array_of(x), array_of(y)))),\n",
    "           \n",
    "           ForAll(x, subtype(root, x))\n",
    "           ]\n",
    "s = Solver()\n",
    "s.add(axioms)\n",
    "print (s)\n",
    "print (s.check())\n",
    "print (\"Interpretation for Type:\")\n",
    "print (s.model()[Type])\n",
    "print (\"Model:\")\n",
    "print (s.model())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Patterns\n",
    "The Stanford Pascal verifier and the subsequent Simplify theorem prover pioneered the use of pattern-based quantifier instantiation. The basic idea behind pattern-based quantifier instantiation is in a sense straight-forward: Annotate a quantified formula using a pattern that contains all the bound variables. So a pattern is an expression (that does not contain binding operations, such as quantifiers) that contains variables bound by a quantifier. Then instantiate the quantifier whenever a term that matches the pattern is created during search. This is a conceptually easy starting point, but there are several subtleties that are important.\n",
    "\n",
    "In the following example, the first two options make sure that Model-based quantifier instantiation engine is disabled. We also annotate the quantified formula with the pattern f(g(x)). Since there is no ground instance of this pattern, the quantifier is not instantiated, and Z3 fails to show that the formula is unsatisfiable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = Function('f', IntSort(), IntSort())\n",
    "g = Function('g', IntSort(), IntSort())\n",
    "a, b, c = Ints('a b c')\n",
    "x = Int('x')\n",
    "\n",
    "s = Solver()\n",
    "s.set(auto_config=False, mbqi=False)\n",
    "\n",
    "s.add( ForAll(x, f(g(x)) == x, patterns = [f(g(x))]),\n",
    "       g(a) == c,\n",
    "       g(b) == c,\n",
    "       a != b )\n",
    "\n",
    "# Display solver state using internal format\n",
    "print (s.sexpr())\n",
    "print (s.check())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When the more permissive pattern g(x) is used. Z3 proves the formula to be unsatisfiable. More restrictive patterns minimize the number of instantiations (and potentially improve performance), but they may also make Z3 \"less complete\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = Function('f', IntSort(), IntSort())\n",
    "g = Function('g', IntSort(), IntSort())\n",
    "a, b, c = Ints('a b c')\n",
    "x = Int('x')\n",
    "\n",
    "s = Solver()\n",
    "s.set(auto_config=False, mbqi=False)\n",
    "\n",
    "s.add( ForAll(x, f(g(x)) == x, patterns = [g(x)]),\n",
    "       g(a) == c,\n",
    "       g(b) == c,\n",
    "       a != b )\n",
    "\n",
    "# Display solver state using internal format\n",
    "print (s.sexpr())\n",
    "print (s.check())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some patterns may also create long instantiation chains. Consider the following assertion.\n",
    "\n",
    "<pre>\n",
    "ForAll([x, y], Implies(subtype(x, y),\n",
    "                       subtype(array_of(x), array_of(y))),\n",
    "       patterns=[subtype(x, y)])\n",
    "</pre>       \n",
    "The axiom gets instantiated whenever there is some ground term of the form subtype(s, t). The instantiation causes a fresh ground term subtype(array_of(s), array_of(t)), which enables a new instantiation. This undesirable situation is called a matching loop. Z3 uses many heuristics to break matching loops.\n",
    "\n",
    "Before elaborating on the subtleties, we should address an important first question. What defines the terms that are created during search? In the context of most SMT solvers, and of the Simplify theorem prover, terms exist as part of the input formula, they are of course also created by instantiating quantifiers, but terms are also implicitly created when equalities are asserted. The last point means that terms are considered up to congruence and pattern matching takes place modulo ground equalities. We call the matching problem E-matching. For example, if we have the following equalities:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = Function('f', IntSort(), IntSort())\n",
    "g = Function('g', IntSort(), IntSort())\n",
    "a, b, c = Ints('a b c')\n",
    "x = Int('x')\n",
    "\n",
    "s = Solver()\n",
    "s.set(auto_config=False, mbqi=False)\n",
    "\n",
    "s.add( ForAll(x, f(g(x)) == x, patterns = [f(g(x))]),\n",
    "       a == g(b),\n",
    "       b == c,\n",
    "       f(a) != c )\n",
    "\n",
    "print (s.check())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The terms f(a) and f(g(b)) are equal modulo the equalities. The pattern f(g(x)) can be matched and x bound to b and the equality f(g(b)) == b is deduced.\n",
    "\n",
    "While E-matching is an NP-complete problem, the main sources of overhead in larger verification problems comes from matching thousands of patterns in the context of an evolving set of terms and equalities. Z3 integrates an efficient E-matching engine using term indexing techniques.\n",
    "\n",
    "### Multi-patterns\n",
    "In some cases, there is no pattern that contains all bound variables and does not contain interpreted symbols. In these cases, we use multi-patterns. In the following example, the quantified formula states that f is injective. This quantified formula is annotated with the multi-pattern MultiPattern(f(x), f(y))."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A = DeclareSort('A')\n",
    "B = DeclareSort('B')\n",
    "f = Function('f', A, B)\n",
    "a1, a2 = Consts('a1 a2', A)\n",
    "b      = Const('b', B)\n",
    "x,  y  = Consts('x y', A)\n",
    "\n",
    "s = Solver()\n",
    "s.add(a1 != a2,\n",
    "      f(a1) == b,\n",
    "      f(a2) == b,\n",
    "      ForAll([x, y], Implies(f(x) == f(y), x == y),\n",
    "             patterns=[MultiPattern(f(x), f(y))])\n",
    "      )\n",
    "print (s.check())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The quantified formula is instantiated for every pair of occurrences of f. A simple trick allows formulating injectivity of f in such a way that only a linear number of instantiations is required. The trick is to realize that f is injective if and only if it has a partial inverse."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "A = DeclareSort('A')\n",
    "B = DeclareSort('B')\n",
    "f = Function('f', A, B)\n",
    "finv = Function('finv', B, A)\n",
    "a1, a2 = Consts('a1 a2', A)\n",
    "b      = Const('b', B)\n",
    "x,  y  = Consts('x y', A)\n",
    "\n",
    "s = Solver()\n",
    "s.add(a1 != a2,\n",
    "      f(a1) == b,\n",
    "      f(a2) == b,\n",
    "      ForAll(x, finv(f(x)) == x)\n",
    "      )\n",
    "print (s.check())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Other attributes\n",
    "In Z3Py, the following additional attributes are supported: qid (quantifier identifier for debugging), weight (hint to the quantifier instantiation module: \"more weight equals less instances\"), no_patterns (expressions that should not be used as patterns, skid (identifier prefix used to create skolem constants/functions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Multiple Solvers\n",
    "In Z3Py and Z3 4.0 multiple solvers can be simultaneously used. It is also very easy to copy assertions/formulas from one solver to another."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x, y = Ints('x y')\n",
    "s1 = Solver()\n",
    "s1.add(x > 10, y > 10)\n",
    "s2 = Solver()\n",
    "# solver s2 is empty\n",
    "print (s2)\n",
    "# copy assertions from s1 to s2\n",
    "s2.add(s1.assertions())\n",
    "print (s2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Unsat Cores and Soft Constraints\n",
    "Z3Py also supports unsat core extraction. The basic idea is to use assumptions, that is, auxiliary propositional variables that we want to track. Assumptions are also available in the Z3 SMT 2.0 frontend, and in other Z3 front-ends. They are used to extract unsatisfiable cores. They may be also used to \"retract\" constraints. Note that, assumptions are not really soft constraints, but they can be used to implement them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "p1, p2, p3 = Bools('p1 p2 p3')\n",
    "x, y = Ints('x y')\n",
    "# We assert Implies(p, C) to track constraint C using p\n",
    "s = Solver()\n",
    "s.add(Implies(p1, x > 10),\n",
    "      Implies(p1, y > x),\n",
    "      Implies(p2, y < 5),\n",
    "      Implies(p3, y > 0))\n",
    "print (s)\n",
    "# Check satisfiability assuming p1, p2, p3 are true\n",
    "print (s.check(p1, p2, p3))\n",
    "print (s.unsat_core())\n",
    "\n",
    "# Try again retracting p2\n",
    "print (s.check(p1, p3))\n",
    "print (s.model())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The example above also shows that a Boolean variable (p1) can be used to track more than one constraint. Note that Z3 does not guarantee that the unsat cores are minimal.\n",
    "\n",
    "## Formatter\n",
    "Z3Py uses a formatter (aka pretty printer) for displaying formulas, expressions, solvers, and other Z3 objects. The formatter supports many configuration options. The command set_option(html_mode=False) makes all formulas and expressions to be displayed in Z3Py notation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Int('x')\n",
    "y = Int('y')\n",
    "set_option(html_mode=True)\n",
    "print (x**2 + y**2 >= 1)\n",
    "set_option(html_mode=False)\n",
    "print (x**2 + y**2 >= 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default, Z3Py will truncate the output if the object being displayed is too big. Z3Py uses … to denote the output is truncated. The following configuration options can be set to control the behavior of Z3Py's formatter:\n",
    "\n",
    "* max_depth Maximal expression depth. Deep expressions are replaced with ….\n",
    "* max_args Maximal number of arguments to display per node.\n",
    "* rational_to_decimal Display rationals as decimals if True.\n",
    "* precision Maximal number of decimal places for numbers being displayed in decimal notation.\n",
    "* max_lines Maximal number of lines to be displayed.\n",
    "* max_width Maximal line width (this is a suggestion to Z3Py).\n",
    "* max_indent Maximal indentation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = IntVector('x', 20)\n",
    "y = IntVector('y', 20)\n",
    "f = And(Sum(x) >= 0, Sum(y) >= 0)\n",
    "\n",
    "set_option(max_args=5)\n",
    "print (\"\\ntest 1:\", f)\n",
    "\n",
    "set_option(max_args=100, max_lines=10)\n",
    "print (\"\\ntest 2:\", f)\n",
    "\n",
    "set_option(max_width=300)\n",
    "print (\"\\ntest 3:\", f)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
