{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Z3 API in Python\n",
    "\n",
    "Z3 is a high performance theorem prover developed at Microsoft Research. Z3 is used in many applications such as: software/hardware verification and testing, constraint solving, analysis of hybrid systems, security, biology (in silicon analysis), and geometrical problems.\n",
    "\n",
    "This tutorial demonstrates the main capabilities of Z3Py: the Z3 API in Python. No Python background is needed to read this tutorial. However, it is useful to learn Python (a fun language!) at some point, and there are many excellent free resources for doing so (Python Tutorial).\n",
    "\n",
    "The Z3 distribution also contains the C, C++, .Net, Java and OCaml APIs. The source code of Z3Py is available in the Z3 distribution on https://github.com/z3prover/z3.git where you are invited to download, use and update the code, add pull requests and file issues on usability, bugs and features.\n",
    "\n",
    "\n",
    "## First things first\n",
    "Import Z3\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from z3 import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Getting Started\n",
    "\n",
    "Let us start with the following simple example:\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Int('x')\n",
    "y = Int('y')\n",
    "solve(x > 2, y < 10, x + 2*y == 7)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The function Int('x') creates an integer variable in Z3 named x. \n",
    "The solve function solves a system of constraints.\n",
    "The example above uses two variables x and y, and three constraints. \n",
    "Z3Py like Python uses = for assignment. \n",
    "The operators <, <=, >, >=, == and != for comparison. \n",
    "In the example above, the expression x + 2*y == 7 is a Z3 constraint.\n",
    "Z3 can solve and crunch formulas.\n",
    "\n",
    "The next examples show how to use the Z3 formula/expression simplifier.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Int('x')\n",
    "y = Int('y')\n",
    "print(simplify(x + y + 2*x + 3))\n",
    "print(simplify(x < y + x + 2))\n",
    "print(simplify(And(x + 1 >= 3, x**2 + x**2 + y**2 + 2 >= 5)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default, Z3Py (for the web) displays formulas and expressions using mathematical notation. As usual, ∧ is the logical and, ∨ is the logical or, and so on. The command set_option(html_mode=False) makes all formulas and expressions to be displayed in Z3Py notation. This is also the default mode for the offline version of Z3Py that comes with the Z3 distribution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Int('x')\n",
    "y = Int('y')\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": [
    "### html mode: use copy paste into a markdown-cell\n",
    "After execution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "set_option(html_mode=True)\n",
    "print(x**2 + y**2 >= 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### copied from the printed result:\n",
    "x<sup>2</sup> + y<sup>2</sup> &ge; 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Z3 provides functions for traversing expressions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Int('x')\n",
    "y = Int('y')\n",
    "n = x + y >= 3\n",
    "print(\"num args: \", n.num_args())\n",
    "print(\"children: \", n.children())\n",
    "print(\"1st child:\", n.arg(0))\n",
    "print(\"2nd child:\", n.arg(1))\n",
    "print(\"operator: \", n.decl())\n",
    "print(\"op name:  \", n.decl().name())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Z3 provides all basic mathematical operations. \n",
    "Z3Py uses the same operator precedence of the Python language. \n",
    "Like Python, ** is the power operator. \n",
    "Z3 can solve nonlinear polynomial constraints."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Real('x')\n",
    "y = Real('y')\n",
    "solve(x**2 + 0.12 * y**2 > 3, x**3 + y < 5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The procedure Real('x') creates the real variable x. Z3Py can represent arbitrarily large integers, rational numbers (like in the example above), and irrational algebraic numbers. An irrational algebraic number is a root of a polynomial with integer coefficients. Internally, Z3 represents all these numbers precisely. The irrational numbers are displayed in decimal notation for making it easy to read the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Real('x')\n",
    "y = Real('y')\n",
    "solve(x**2 + y**2 == 3, x**3 == 2)\n",
    "\n",
    "set_option(precision=30)\n",
    "print(\"Solving, and displaying result with 30 decimal places\")\n",
    "solve(x**2 + y**2 == 3, x**3 == 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# The procedure <font color='green'>set_option</font> is used to configure the Z3 environment. \n",
    "It is used to set global configuration options such as how the result is displayed. The option set_option(precision=30) sets the number of decimal places used when displaying results. \n",
    "\n",
    "The <font color='red' size=18>?</font> mark in 1.259921049894873164767210607278? indicates the output is truncated.\n",
    "\n",
    "The following example demonstrates a common mistake. The expression 3/2 is a Python integer and not a Z3 rational number. The example also shows different ways to create rational numbers in Z3Py. The procedure Q(num, den) creates a Z3 rational where num is the numerator and den is the denominator.\n",
    "The RealVal(1) creates a Z3 real number representing \n",
    "the number 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(1/3)\n",
    "print(RealVal(1)/3)\n",
    "\n",
    "x = Real('x')\n",
    "print(x + 1/3)\n",
    "print(x + \"1/3\")\n",
    "print(x + 0.25)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "Rational numbers can also be displayed in decimal\n",
    "notation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Real('x')\n",
    "solve(3*x == 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "set_option(rational_to_decimal=True)\n",
    "solve(3*x == 1)\n",
    "\n",
    "set_option(precision=20)\n",
    "solve(3*x == 1)\n",
    "set_option(rational_to_decimal=False)\n",
    "solve(6*x == 37)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A system of constraints may not have a solution.\n",
    "In this case, we say the system is unsatisfiable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Real('x')\n",
    "solve(x > 4, x < 0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "Like in Python, comments begin with the hash character # and are terminated by the end of line. Z3Py does not support comments that span more than one line.\n",
    "Boolean Logic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "set_option(html_mode=False)\n",
    "# This is a comment\n",
    "x = Real('x') # comment: creating x\n",
    "print(x**2 + 2*x + 2) # comment: printing polynomial)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Boolean Logic\n",
    "\n",
    "Z3 supports Boolean operators: And, Or, Not, Implies (implication), If (if-then-else). \n",
    "Bi-implications are represented using equality ==. \n",
    "The following example shows how to solve\n",
    "a simple set of Boolean constraints.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "p = Bool('p')\n",
    "q = Bool('q')\n",
    "r = Bool('r')\n",
    "solve(Implies(p, q), r == Not(q), Or(Not(p), r))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Python Boolean constants True and False\n",
    "can be used to build Z3 Boolean expressions.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "p = Bool('p')\n",
    "q = Bool('q')\n",
    "print(And(p, q, True))\n",
    "print(simplify(And(p, q, True)))\n",
    "print(simplify(And(p, False)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following example uses a combination of polynomial and Boolean constraints."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "p = Bool('p')\n",
    "x = Real('x')\n",
    "solve(Or(x < 5, x > 10), Or(p, x**2 == 2), Not(p))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Solvers\n",
    "\n",
    "\n",
    "Z3 provides different solvers. The command solve, used in the previous examples, is implemented using the Z3 solver API. The implementation can be found in the file z3.py in the Z3 distribution. The following example demonstrates the basic Solver API.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Int('x')\n",
    "y = Int('y')\n",
    "\n",
    "s = Solver()\n",
    "print(s)\n",
    "\n",
    "s.add(x > 10, y == x + 2)\n",
    "print(s)\n",
    "print(\"Solving constraints in the solver s ...\")\n",
    "print(s.check())\n",
    "\n",
    "print(\"Create a new scope...\")\n",
    "s.push()\n",
    "s.add(y < 11)\n",
    "print(s)\n",
    "print(\"Solving updated set of constraints...\")\n",
    "print(s.check())\n",
    "\n",
    "print(\"Restoring state...\")\n",
    "s.pop()\n",
    "print(s)\n",
    "print(\"Solving restored set of constraints...\")\n",
    "print(s.check())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Info ...\n",
    "The command Solver() creates a general purpose solver. Constraints can be added using the method add. We say the constraints have been asserted in the solver. The method check() solves the asserted constraints. The result is sat (satisfiable) if a solution was found. The result is unsat (unsatisfiable) if no solution exists. We may also say the system of asserted constraints is infeasible. Finally, a solver may fail to solve a system of constraints and unknown is returned.\n",
    "\n",
    "In some applications, we want to explore several similar problems that share several constraints. We can use the commands push and pop for doing that. Each solver maintains a stack of assertions. The command push creates a new scope by saving the current stack size. The command pop removes any assertion performed between it and the matching push. The check method always operates on the content of solver assertion stack.\n",
    "\n",
    "The following example shows an example that Z3 cannot solve. The solver returns unknown in this case. Recall that Z3 can solve nonlinear polynomial constraints, but 2**x is not a polynomial.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Real('x')\n",
    "s = Solver()\n",
    "s.add(2**x == 3)\n",
    "print(s.check())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following example shows how to traverse the constraints asserted into a solver, and how to collect performance statistics for the check method.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Real('x')\n",
    "y = Real('y')\n",
    "s = Solver()\n",
    "s.add(x > 1, y > 1, Or(x + y > 3, x - y < 2))\n",
    "print(\"asserted constraints...\")\n",
    "for c in s.assertions():\n",
    "    print(c)\n",
    "\n",
    "print(s.check())\n",
    "print(\"statistics for the last check method...\")\n",
    "print(s.statistics())\n",
    "# Traversing statistics\n",
    "for k, v in s.statistics():\n",
    "    print(\"%s : %s\" % (k, v))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The command check returns sat when Z3 finds a solution for the set of asserted constraints. We say Z3 satisfied the set of constraints. We say the solution is a model for the set of asserted constraints. A model is an interpretation that makes each asserted constraint true. \n",
    "\n",
    "### The following example shows the basic methods for inspecting models.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x, y, z = Reals('x y z')\n",
    "s = Solver()\n",
    "s.add(x > 1, y > 1, x + y > 3, z - x < 10)\n",
    "print(s.check())\n",
    "\n",
    "m = s.model()\n",
    "print(\"x = %s\" % m[x])\n",
    "\n",
    "print(\"traversing model...\")\n",
    "for d in m.decls():\n",
    "    print(\"%s = %s\" % (d.name(), m[d]))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the example above, the function Reals('x y z') creates the variables. x, y and z. It is shorthand for:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Real('x')\n",
    "y = Real('y')\n",
    "z = Real('z')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The expression m[x] returns the interpretation of x in the model m. The expression \"%s = %s\" % (d.name(), m[d]) returns a string where the first %s is replaced with the name of d (i.e., d.name()), and the second %s with a textual representation of the interpretation of d (i.e., m[d]). Z3Py automatically converts Z3 objects into a textual representation when needed.\n",
    "\n",
    "# Arithmetic\n",
    "\n",
    "Z3 supports real and integer variables. They can be mixed in a single problem. Like most programming languages, Z3Py will automatically add coercions converting integer expressions to real ones when needed. The following example demonstrates different ways to declare integer and real variables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Real('x')\n",
    "y = Int('y')\n",
    "a, b, c = Reals('a b c')\n",
    "s, r = Ints('s r')\n",
    "print(x + y + 1 + (a + s))\n",
    "print(ToReal(y) + c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The function ToReal casts an integer expression into a real expression.\n",
    "\n",
    "\n",
    "Z3Py supports all basic arithmetic operations.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a, b, c = Ints('a b c')\n",
    "d, e = Reals('d e')\n",
    "solve(a > b + 2,\n",
    "      a == 2*c + 10,\n",
    "      c + b <= 1000,\n",
    "      d >= e)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The command simplify applies simple transformations on Z3 expressions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x, y = Reals('x y')\n",
    "# Put expression in sum-of-monomials form\n",
    "t = simplify((x + y)**3, som=True)\n",
    "print(t)\n",
    "# Use power operator\n",
    "t = simplify(t, mul_to_power=True)\n",
    "print(t)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The command help_simplify() prints all available options. Z3Py allows users to write option in two styles. The Z3 internal option names start with : and words are separated by -. These options can be used in Z3Py. Z3Py also supports Python-like names, where : is suppressed and - is replaced with _. The following example demonstrates how to use both styles."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x, y = Reals('x y')\n",
    "# Using Z3 native option names\n",
    "print(simplify(x == y + 2, ':arith-lhs', True))\n",
    "# Using Z3Py option names\n",
    "print(simplify(x == y + 2, arith_lhs=True))\n",
    "\n",
    "print(\"\\nAll available options:\")\n",
    "help_simplify()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# large numbers\n",
    "Z3Py supports arbitrarily large numbers. The following example demonstrates how to perform basic arithmetic using larger integer, rational and irrational numbers. Z3Py only supports algebraic irrational numbers. Algebraic irrational numbers are sufficient for presenting the solutions of systems of polynomial constraints. Z3Py will always display irrational numbers in decimal notation since it is more convenient to read. The internal representation can be extracted using the method sexpr(). It displays Z3 internal representation for mathematical formulas and expressions in s-expression (Lisp-like) notation.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x, y = Reals('x y')\n",
    "solve(x + 10000000000000000000000 == y, y > 20000000000000000)\n",
    "\n",
    "print(Sqrt(2) + Sqrt(3))\n",
    "print(simplify(Sqrt(2) + Sqrt(3)))\n",
    "print(simplify(Sqrt(2) + Sqrt(3)).sexpr())\n",
    "# The sexpr() method is available for any Z3 expression\n",
    "print((x + Sqrt(y) * 2).sexpr())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Machine Arithmetic\n",
    "\n",
    "\n",
    "Modern CPUs and main-stream programming languages use arithmetic over fixed-size bit-vectors. Machine arithmetic is available in Z3Py as Bit-Vectors. They implement the precise semantics of unsigned and of signed two-complements arithmetic.\n",
    "\n",
    "The following example demonstrates how to create bit-vector variables and constants. The function BitVec('x', 16) creates a bit-vector variable in Z3 named x with 16 bits. For convenience, integer constants can be used to create bit-vector expressions in Z3Py. The function BitVecVal(10, 32) creates a bit-vector of size 32 containing the value 10.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = BitVec('x', 16)\n",
    "y = BitVec('y', 16)\n",
    "print(x + 2)\n",
    "# Internal representation\n",
    "print((x + 2).sexpr())\n",
    "\n",
    "# -1 is equal to 65535 for 16-bit integers \n",
    "print(simplify(x + y - 1))\n",
    "\n",
    "# Creating bit-vector constants\n",
    "a = BitVecVal(-1, 16)\n",
    "b = BitVecVal(65535, 16)\n",
    "print(simplify(a == b))\n",
    "\n",
    "a = BitVecVal(-1, 32)\n",
    "b = BitVecVal(65535, 32)\n",
    "# -1 is not equal to 65535 for 32-bit integers \n",
    "print(simplify(a == b))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# In contrast to programming languages, such as\n",
    "C, C++, C#, Java, there is no distinction between signed and unsigned bit-vectors as numbers. Instead, Z3 provides special signed versions of arithmetical operations where it makes a difference whether the bit-vector is treated as signed or unsigned. In Z3Py, the operators <, <=, >, >=, /, % and >> correspond to the signed versions. The corresponding unsigned operators are ULT, ULE, UGT, UGE, UDiv, URem and LShR.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create to bit-vectors of size 32\n",
    "x, y = BitVecs('x y', 32)\n",
    "\n",
    "solve(x + y == 2, x > 0, y > 0)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Bit-wise operators\n",
    "# & bit-wise and\n",
    "# | bit-wise or\n",
    "# ~ bit-wise not\n",
    "solve(x & y == ~y)\n",
    "\n",
    "solve(x < 0)\n",
    "\n",
    "# using unsigned version of < \n",
    "solve(ULT(x, 0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The operator >> is the arithmetic shift right, and << is the shift left. \n",
    "\n",
    "The logical shift right is the operator LShR.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    " # Create to bit-vectors of size 32\n",
    "x, y = BitVecs('x y', 32)\n",
    "\n",
    "solve(x >> 2 == 3)\n",
    "\n",
    "solve(x << 2 == 3)\n",
    "\n",
    "solve(x << 2 == 24)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Functions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "Unlike programming languages, where functions have side-effects, can throw exceptions, or never return, functions in Z3 have no side-effects and are total. That is, they are defined on all input values. This includes functions, such as division. Z3 is based on first-order logic.\n",
    "\n",
    "Given a constraints such as x + y > 3, we have been saying that x and y are variables. In many textbooks, x and y are called uninterpreted constants. That is, they allow any interpretation that is consistent with the constraint x + y > 3.\n",
    "\n",
    "More precisely, 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 functions belonging to the signature of theories, such as arithmetic where the function + has a fixed standard interpretation (it adds two numbers). 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 the uninterpreted integer constants (aka variables) x, y. Finally let f be an uninterpreted function that takes one argument of type (aka sort) integer and results in an integer value. 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.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Int('x')\n",
    "y = Int('y')\n",
    "f = Function('f', IntSort(), IntSort())\n",
    "solve(f(f(x)) == x, f(x) == y, x != y)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The solution (interpretation) for f should be read as f(0) is 1, f(1) is 0, \n",
    "\n",
    "and f(a) is 1 for all a different from 0 and 1.\n",
    "\n",
    "In Z3, we can also evaluate expressions in the model for a system of constraints. The following example shows how to use the evaluate method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = Int('x')\n",
    "y = Int('y')\n",
    "f = Function('f', IntSort(), IntSort())\n",
    "s = Solver()\n",
    "s.add(f(f(x)) == x, f(x) == y, x != y)\n",
    "print(s.check())\n",
    "m = s.model()\n",
    "print(\"f(f(x)) =\", m.evaluate(f(f(x))))\n",
    "print(\"f(x)    =\", m.evaluate(f(x)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    " \n",
    "#In Z3, we can also evaluate expressions in the model for a system of constraints. The following example shows how to use the evaluate method.\n",
    "\n",
    "x = Int('x')\n",
    "y = Int('y')\n",
    "f = Function('f', IntSort(), IntSort())\n",
    "s = Solver()\n",
    "s.add(f(f(x)) == x, f(x) == y, x != y)\n",
    "print(s.check())\n",
    "m = s.model()\n",
    "print(\"f(f(x)) =\", m.evaluate(f(f(x))))\n",
    "print(\"f(x)    =\", m.evaluate(f(x)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "# Satisfiability and Validity\n",
    "\n",
    "A formula/constraint F is valid if F always evaluates to true for any assignment of appropriate values to its uninterpreted symbols. A formula/constraint F is satisfiable if there is some assignment of appropriate values to its uninterpreted symbols under which F evaluates to true. Validity is about finding a proof of a statement; satisfiability is about finding a solution to a set of constraints. Consider a formula F containing a and b. We can ask whether F is valid, that is whether it is always true for any combination of values for a and b. If F is always true, then Not(F) is always false, and then Not(F) will not have any satisfying assignment (i.e., solution); that is, Not(F) is unsatisfiable. That is, F is valid precisely when Not(F) is not satisfiable (is unsatisfiable). Alternately, F is satisfiable if and only if Not(F) is not valid (is invalid). The following example proves the deMorgan's law.\n",
    "\n",
    "The following example redefines the Z3Py function prove that receives a formula as a parameter. This function creates a solver, adds/asserts the negation of the formula, and check if the negation is unsatisfiable. The implementation of this function is a simpler version of the Z3Py command prove.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "p, q = Bools('p q')\n",
    "demorgan = And(p, q) == Not(Or(Not(p), Not(q)))\n",
    "print(demorgan)\n",
    "\n",
    "def prove(f):\n",
    "    s = Solver()\n",
    "    s.add(Not(f))\n",
    "    if s.check() == unsat:\n",
    "        print(\"proved\")\n",
    "    else:\n",
    "        print(\"failed to prove\")\n",
    "\n",
    "print(\"Proving demorgan...\")\n",
    "prove(demorgan)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# List comprehension\n",
    "\n",
    "Python supports list comprehensions. List comprehensions provide a concise way to create lists. They can be used to create Z3 expressions and problems in Z3Py. The following example demonstrates how to use Python list comprehensions in Z3Py.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# Create list [1, ..., 5] \n",
    "print([ x + 1 for x in range(5) ])\n",
    "\n",
    "# Create two lists containing 5 integer variables\n",
    "X = [ Int('x%s' % i) for i in range(5) ]\n",
    "Y = [ Int('y%s' % i) for i in range(5) ]\n",
    "print(X)\n",
    "\n",
    "# Create a list containing X[i]+Y[i]\n",
    "X_plus_Y = [ X[i] + Y[i] for i in range(5) ]\n",
    "print(X_plus_Y)\n",
    "\n",
    "# Create a list containing X[i] > Y[i]\n",
    "X_gt_Y = [ X[i] > Y[i] for i in range(5) ]\n",
    "print(X_gt_Y)\n",
    "\n",
    "print(And(X_gt_Y))\n",
    "\n",
    "# Create a 3x3 \"matrix\" (list of lists) of integer variables\n",
    "X = [ [ Int(\"x_%s_%s\" % (i+1, j+1)) for j in range(3) ]\n",
    "      for i in range(3) ]\n",
    "pp(X)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "In the example above, the expression \"x%s\" % i returns a string where %s is replaced with the value of i.\n",
    "\n",
    "The command pp is similar to print, but it uses Z3Py formatter for lists and tuples instead of Python's formatter.\n",
    "\n",
    "Z3Py also provides functions for creating vectors of Boolean, Integer and Real variables. These functions are implemented using list comprehensions.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = IntVector('x', 5)\n",
    "Y = RealVector('y', 5)\n",
    "P = BoolVector('p', 5)\n",
    "print(X)\n",
    "print(Y)\n",
    "print(P)\n",
    "print([ y**2 for y in Y ])\n",
    "print(Sum([ y**2 for y in Y ]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Kinematic equations\n",
    "\n",
    "In high school, students learn the kinematic equations. These equations describe the mathematical relationship between displacement (d), time (t), acceleration (a), initial velocity (v_i) and final velocity (v_f). In Z3Py notation, we can write these equations as:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a, t ,v_i, v_f = Reals('a t v__i v__f') #missing in HTML?\n",
    "d == v_i * t + (a*t**2)/2,\n",
    "v_f == v_i + a*t\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "v_f"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Problem 1\n",
    "\n",
    "Ima Hurryin is approaching a stoplight moving with a velocity of 30.0 m/s. The light turns yellow, and Ima applies the brakes and skids to a stop. If Ima's acceleration is -8.00 m/s2, then determine the displacement of the car during the skidding process."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "d, a, t, v_i, v_f = Reals('d a t v__i v__f')\n",
    "\n",
    "equations = [\n",
    "   d == v_i * t + (a*t**2)/2,\n",
    "   v_f == v_i + a*t,\n",
    "]\n",
    "print(\"Kinematic equations:\")\n",
    "print(equations)\n",
    "\n",
    "# Given v_i, v_f and a, find d\n",
    "problem = [\n",
    "    v_i == 30,\n",
    "    v_f == 0,\n",
    "    a   == -8\n",
    "]\n",
    "print(\"Problem:\")\n",
    "print(problem)\n",
    "\n",
    "print(\"Solution:\")\n",
    "solve(equations + problem)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Problem 2\n",
    "\n",
    "Ben Rushin is waiting at a stoplight. When it finally turns green, Ben accelerated from rest at a rate of a 6.00 m/s2 for a time of 4.10 seconds. Determine the displacement of Ben's car during this time period.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "d, a, t, v_i, v_f = Reals('d a t v__i v__f')\n",
    "\n",
    "equations = [\n",
    "   d == v_i * t + (a*t**2)/2,\n",
    "   v_f == v_i + a*t,\n",
    "]\n",
    "\n",
    "# Given v_i, t and a, find d\n",
    "problem = [\n",
    "    v_i == 0,\n",
    "    t   == 4.10,\n",
    "    a   == 6\n",
    "]\n",
    "\n",
    "solve(equations + problem)\n",
    "\n",
    "# Display rationals in decimal notation\n",
    "set_option(rational_to_decimal=True)\n",
    "\n",
    "solve(equations + problem)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Bit Tricks\n",
    "\n",
    "Some low level hacks are very popular with C programmers. We use some of these hacks in the Z3 implementation.\n",
    "\n",
    "Power of two\n",
    "\n",
    "This hack is frequently used in C programs (Z3 included) to test whether a machine integer is a power of two. We can use Z3 to prove it really works. The claim is that x != 0 && !(x & (x - 1)) is true if and only if x is a power of two.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x      = BitVec('x', 32)\n",
    "powers = [ 2**i for i in range(32) ]\n",
    "fast   = And(x != 0, x & (x - 1) == 0)\n",
    "slow   = Or([ x == p for p in powers ])\n",
    "print(fast)\n",
    "prove(fast == slow)\n",
    "\n",
    "print(\"trying to prove buggy version...\")\n",
    "fast   = x & (x - 1) == 0\n",
    "prove(fast == slow)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Opposite signs\n",
    "\n",
    "The following simple hack can be used to test whether two machine integers have opposite signs.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "x      = BitVec('x', 32)\n",
    "y      = BitVec('y', 32)\n",
    "\n",
    "# Claim: (x ^ y) < 0 iff x and y have opposite signs\n",
    "trick  = (x ^ y) < 0\n",
    "\n",
    "# Naive way to check if x and y have opposite signs\n",
    "opposite = Or(And(x < 0, y >= 0),\n",
    "              And(x >= 0, y < 0))\n",
    "\n",
    "prove(trick == opposite)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Puzzles\n",
    "\n",
    "## Dog, Cat and Mouse\n",
    "\n",
    "Consider the following puzzle. Spend exactly 100 dollars and buy exactly 100 animals. Dogs cost 15 dollars, cats cost 1 dollar, and mice cost 25 cents each. You have to buy at least one of each. How many of each should you buy?\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create 3 integer variables\n",
    "dog, cat, mouse = Ints('dog cat mouse')\n",
    "solve(dog >= 1,   # at least one dog\n",
    "      cat >= 1,   # at least one cat\n",
    "      mouse >= 1, # at least one mouse\n",
    "      # we want to buy 100 animals\n",
    "      dog + cat + mouse == 100,\n",
    "      # We have 100 dollars (10000 cents):\n",
    "      #   dogs cost 15 dollars (1500 cents), \n",
    "      #   cats cost 1 dollar (100 cents), and \n",
    "      #   mice cost 25 cents \n",
    "      1500 * dog + 100 * cat + 25 * mouse == 10000)"
   ]
  },
  {
   "attachments": {
    "sudoku.png": {
     "image/png": "[encoded data, 16460 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sodoku\n",
    "\n",
    "<p><a target=\"_blank\" href=\"http://www.dailysudoku.com/sudoku/\">Sudoku</a>is a very popular puzzle. The goal is to insert the numbers in the boxes to satisfy only one condition: each row, column and 3x3 box must contain the digits 1 through 9 exactly once.\n",
    "    \n",
    "![sudoku.png](attachment:sudoku.png)\n",
    "    \n",
    "The following example encodes the sudoku problem in Z3. Different sudoku instances can be solved by modifying the matrix instance. This example makes heavy use of list comprehensions available in the Python programming language.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    " # 9x9 matrix of integer variables\n",
    "X = [ [ Int(\"x_%s_%s\" % (i+1, j+1)) for j in range(9) ]\n",
    "      for i in range(9) ]\n",
    "\n",
    "# each cell contains a value in {1, ..., 9}\n",
    "cells_c  = [ And(1 <= X[i][j], X[i][j] <= 9)\n",
    "             for i in range(9) for j in range(9) ]\n",
    "\n",
    "# each row contains a digit at most once\n",
    "rows_c   = [ Distinct(X[i]) for i in range(9) ]\n",
    "\n",
    "# each column contains a digit at most once\n",
    "cols_c   = [ Distinct([ X[i][j] for i in range(9) ])\n",
    "             for j in range(9) ]\n",
    "\n",
    "# each 3x3 square contains a digit at most once\n",
    "sq_c     = [ Distinct([ X[3*i0 + i][3*j0 + j]\n",
    "                        for i in range(3) for j in range(3) ])\n",
    "             for i0 in range(3) for j0 in range(3) ]\n",
    "\n",
    "sudoku_c = cells_c + rows_c + cols_c + sq_c\n",
    "\n",
    "# sudoku instance, we use '0' for empty cells\n",
    "instance = ((0,0,0,0,9,4,0,3,0),\n",
    "            (0,0,0,5,1,0,0,0,7),\n",
    "            (0,8,9,0,0,0,0,4,0),\n",
    "            (0,0,0,0,0,0,2,0,8),\n",
    "            (0,6,0,2,0,1,0,5,0),\n",
    "            (1,0,2,0,0,0,0,0,0),\n",
    "            (0,7,0,0,0,0,5,2,0),\n",
    "            (9,0,0,0,6,5,0,0,0),\n",
    "            (0,4,0,9,7,0,0,0,0))\n",
    "\n",
    "instance_c = [ If(instance[i][j] == 0,\n",
    "                  True,\n",
    "                  X[i][j] == instance[i][j])\n",
    "               for i in range(9) for j in range(9) ]\n",
    "\n",
    "s = Solver()\n",
    "s.add(sudoku_c + instance_c)\n",
    "if s.check() == sat:\n",
    "    m = s.model()\n",
    "    r = [ [ m.evaluate(X[i][j]) for j in range(9) ]\n",
    "          for i in range(9) ]\n",
    "    print_matrix(r)\n",
    "else:\n",
    "    print(\"failed to solve\")\n",
    "    \n",
    "\n",
    "# Let us remove 9 from the first row and see if there is more than one solution\n",
    "\n",
    "instance = ((0,0,0,0,0,4,0,3,0),\n",
    "            (0,0,0,5,1,0,0,0,7),\n",
    "            (0,8,9,0,0,0,0,4,0),\n",
    "            (0,0,0,0,0,0,2,0,8),\n",
    "            (0,6,0,2,0,1,0,5,0),\n",
    "            (1,0,2,0,0,0,0,0,0),\n",
    "            (0,7,0,0,0,0,5,2,0),\n",
    "            (9,0,0,0,6,5,0,0,0),\n",
    "            (0,4,0,9,7,0,0,0,0))\n",
    "\n",
    "instance_c = [ If(instance[i][j] == 0,\n",
    "                  True,\n",
    "                  X[i][j] == instance[i][j])\n",
    "               for i in range(9) for j in range(9) ]    \n",
    "    \n",
    "def n_solutions(n):\n",
    "    s = Solver()\n",
    "    s.add(sudoku_c + instance_c)\n",
    "    i = 0\n",
    "    while s.check() == sat and i < n:\n",
    "        m = s.model()\n",
    "        print([[ m.evaluate(X[i][j]) for j in range(9)] for i in range(9)])\n",
    "        fml = And([X[i][j] == m.evaluate(X[i][j]) for i in range(9) for j in range(9)])\n",
    "        s.add(Not(fml))\n",
    "        i += 1\n",
    "        \n",
    "n_solutions(10)"
   ]
  },
  {
   "attachments": {
    "queens.png": {
     "image/png": "[encoded data, 9812 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Eight queens\n",
    "\n",
    "\n",
    "The eight queens puzzle is the problem of placing eight chess queens on an 8x8 chessboard so that no two queens attack each other. Thus, a solution requires that no two queens share the same row, column, or diagonal.\n",
    "\n",
    "![queens.png](attachment:queens.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# We know each queen must be in a different row.\n",
    "# So, we represent each queen by a single integer: the column position\n",
    "Queens = [ Int('Q_%i' % (i + 1)) for i in range(8) ]\n",
    "\n",
    "# Each queen is in a column {1, ... 8 }\n",
    "val_c = [ And(1 <= Queens[i], Queens[i] <= 8) for i in range(8) ]\n",
    "\n",
    "# At most one queen per column\n",
    "col_c = [ Distinct(Queens) ]\n",
    "\n",
    "# Diagonal constraint\n",
    "diag_c = [ If(i == j,\n",
    "              True,\n",
    "              And(Queens[i] - Queens[j] != i - j, Queens[i] - Queens[j] != j - i))\n",
    "           for i in range(8) for j in range(i) ]\n",
    "\n",
    "solve(val_c + col_c + diag_c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Application: Install Problem\n",
    "\n",
    "The install problem consists of determining whether a new set of packages can be installed in a system. This application is based on the article OPIUM: Optimal Package Install/Uninstall Manager. Many packages depend on other packages to provide some functionality. Each distribution contains a meta-data file that explicates the requirements of each package of the distribution. The meta-data contains details like the name, version, etc. More importantly, it contains depends and conflicts clauses that stipulate which other packages should be on the system. The depends clauses stipulate which other packages must be present. The conflicts clauses stipulate which other packages must not be present.\n",
    "\n",
    "The install problem can be easily solved using Z3. The idea is to define a Boolean variable for each package. This variable is true if the package must be in the system. If package a depends on packages b, c and z, we write:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a, b, c, d, e, f, g, z = Bools('a b c d e f g z')\n",
    "\n",
    "#DependsOn(a, [b, c, z])\n",
    "#DependsOn is a simple Python function that creates Z3 constraints that capture the depends clause semantics.\n",
    "\n",
    "def DependsOn(pack, deps):\n",
    "   return And([ Implies(pack, dep) for dep in deps ])\n",
    "\n",
    "#Thus, DependsOn(a, [b, c, z]) generates the constraint\n",
    "# And(Implies(a, b), Implies(a, c), Implies(a, z))\n",
    "\n",
    "print(DependsOn(a, [b, c, z]))\n",
    "\n",
    "#That is, if users install package a, they must also install packages b, c and z.\n",
    "\n",
    "#If package d conflicts with package e, we write Conflict(d, e). Conflict is also a simple Python function.\n",
    "\n",
    "def Conflict(p1, p2):\n",
    "    return Or(Not(p1), Not(p2))\n",
    "\n",
    "# Conflict(d, e) generates the constraint Or(Not(d), Not(e)). \n",
    "# With these two functions, we can easily encode the example \n",
    "# in the Opium article (Section 2) in Z3Py as:\n",
    "\n",
    "def DependsOn(pack, deps):\n",
    "    return And([ Implies(pack, dep) for dep in deps ])\n",
    "\n",
    "def Conflict(p1, p2):\n",
    "    return Or(Not(p1), Not(p2))\n",
    "\n",
    "\n",
    "solve(DependsOn(a, [b, c, z]),\n",
    "      DependsOn(b, [d]),\n",
    "      DependsOn(c, [Or(d, e), Or(f, g)]),\n",
    "      Conflict(d, e),\n",
    "      a, z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def DependsOn(pack, deps):\n",
    "    return And([ Implies(pack, dep) for dep in deps ])\n",
    "\n",
    "def Conflict(p1, p2):\n",
    "    return Or(Not(p1), Not(p2))\n",
    "\n",
    "a, b, c, d, e, f, g, z = Bools('a b c d e f g z')\n",
    "\n",
    "solve(DependsOn(a, [b, c, z]),\n",
    "      DependsOn(b, [d]),\n",
    "      DependsOn(c, [Or(d, e), Or(f, g)]),\n",
    "      Conflict(d, e),\n",
    "      a, z)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "def install_check(*problem):\n",
    "    s = Solver()\n",
    "    s.add(*problem)\n",
    "    if s.check() == sat:\n",
    "        m = s.model()\n",
    "        r = []\n",
    "        for x in m:\n",
    "            if is_true(m[x]):\n",
    "                # x is a Z3 declaration\n",
    "                # x() returns the Z3 expression\n",
    "                # x.name() returns a string\n",
    "                r.append(x())\n",
    "        print(r)\n",
    "    else:\n",
    "        print(\"invalid installation profile\")\n",
    "\n",
    "print(\"Check 1\")\n",
    "install_check(DependsOn(a, [b, c, z]),\n",
    "              DependsOn(b, [d]),\n",
    "              DependsOn(c, [Or(d, e), Or(f, g)]),\n",
    "              Conflict(d, e),\n",
    "              Conflict(d, g),\n",
    "              a, z)\n",
    "\n",
    "print(\"Check 2\")\n",
    "install_check(DependsOn(a, [b, c, z]),\n",
    "              #DependsOn(b, d),\n",
    "              DependsOn(b, [d]),\n",
    "              DependsOn(c, [Or(d, e), Or(f, g)]),\n",
    "              Conflict(d, e),\n",
    "              Conflict(d, g),\n",
    "              a, z, g)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Special thanks to Peter Gragert for porting the original web-based guide to the jupyter notebook format."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
