{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e5401ac2",
   "metadata": {},
   "source": [
    "# Part 1. The circle is a group: a proof by computation\n",
    "\n",
    "The unit circle\n",
    "\n",
    "$$\n",
    "S^1=\\{(a,b) : a^2+b^2=1\\}\n",
    "$$\n",
    "\n",
    "has the operation\n",
    "\n",
    "$$\n",
    "m\\bigl((a,b),(c,d)\\bigr)=(ac-bd,\\ ad+bc).\n",
    "$$\n",
    "\n",
    "Where does this formula come from? It is the multiplication of complex numbers $(a+bi)(c+di)=(ac-bd)+(ad+bc)i$,\n",
    "and in geometry it is the composition of rotations: the point $(a,b)=(\\cos\\alpha,\\sin\\alpha)$ is the rotation by\n",
    "the angle $\\alpha$. In this part, however, we use neither complex numbers nor angles. We verify the group axioms\n",
    "**by computing with polynomials only**, so that every step ends in a computation a computer can repeat. Some of the\n",
    "proofs are polynomial identities, and some need the equation of the circle; then the computer finds a\n",
    "**certificate**, which is checked by expanding brackets alone. We start from the computations done in class: the\n",
    "group law, the point $(3/5,4/5)$, and an attempt to check closure in SymPy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c85a0da",
   "metadata": {},
   "outputs": [],
   "source": [
    "from fractions import Fraction\n",
    "\n",
    "import sympy as sp\n",
    "\n",
    "a, b, c, d, e, f = sp.symbols(\"a b c d e f\")\n",
    "\n",
    "\n",
    "def m(P, Q):\n",
    "    \"\"\"Prawo grupowe okręgu: (a, b)·(c, d) = (ac - bd, ad + bc).\"\"\"\n",
    "    a, b = P\n",
    "    c, d = Q\n",
    "    return (a * c - b * d, a * d + b * c)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "caf3426a",
   "metadata": {},
   "source": [
    "## The group law on rational numbers\n",
    "\n",
    "The point $P=(3/5,4/5)$ lies on the circle because $9+16=25$. The operation $m$ applied to fractions gives fractions\n",
    "again, so we can compute the powers of $P$ exactly with the `Fraction` type and, for comparison, with `float` numbers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3c5b666d",
   "metadata": {},
   "outputs": [],
   "source": [
    "P = (Fraction(3, 5), Fraction(4, 5))\n",
    "print(\"P·P =\", m(P, P))\n",
    "\n",
    "Q_dokl, Q_float = P, (3 / 5, 4 / 5)\n",
    "for _ in range(999):                     # P do potęgi 1000\n",
    "    Q_dokl = m(Q_dokl, P)\n",
    "    Q_float = m(Q_float, (3 / 5, 4 / 5))\n",
    "\n",
    "print(\"float:    a² + b² - 1 =\", Q_float[0]**2 + Q_float[1]**2 - 1)\n",
    "print(\"Fraction: a² + b² - 1 =\", Q_dokl[0]**2 + Q_dokl[1]**2 - 1)\n",
    "print(\"mianownik P^1000 = 5^1000:\", Q_dokl[0].denominator == 5**1000)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db0bceda",
   "metadata": {},
   "source": [
    "After a thousand multiplications the point computed in `float` has left the circle (the rounding errors from\n",
    "Lecture 1 accumulate), while the point computed exactly still lies on it. But we have checked “still lies on it”\n",
    "only for one point and one power. We want a proof for **all** points.\n",
    "\n",
    "## First attempt: the `==` sign in SymPy\n",
    "\n",
    "Take two points with symbolic coordinates and ask whether their product lies on the circle."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6adce1bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "def na_okregu(P):\n",
    "    x, y = P\n",
    "    return x**2 + y**2 == 1\n",
    "\n",
    "\n",
    "print(na_okregu(m((a, b), (c, d))))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77bcb8d6",
   "metadata": {},
   "source": [
    "The answer `False` is not a mathematical theorem. In SymPy, `==` compares **expression trees**\n",
    "(see Lecture 1, {doc}`§1.3 <../wyklady/w01_3_jak_dziala_cas>`): it asks whether both expressions are built\n",
    "the same way, not whether they are equal as polynomials. Besides, $(ac-bd)^2+(ad+bc)^2$ is not equal to\n",
    "$1$ for arbitrary $a,b,c,d$ at all. What holds is only the implication: *if* $a^2+b^2=1$ and $c^2+d^2=1$,\n",
    "*then* the product lies on the circle. Let us see what is really true."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6db9614c",
   "metadata": {},
   "outputs": [],
   "source": [
    "x, y = m((a, b), (c, d))\n",
    "print(sp.factor(x**2 + y**2))\n",
    "print(sp.expand(x**2 + y**2 - (a**2 + b**2) * (c**2 + d**2)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b13a15b6",
   "metadata": {},
   "source": [
    "We got the **Brahmagupta–Fibonacci identity** (already known to Diophantus; Brahmagupta generalized it\n",
    "in the 7th century, and Fibonacci described it in the *Liber quadratorum* in 1225):\n",
    "\n",
    "$$\n",
    "(ac-bd)^2+(ad+bc)^2=(a^2+b^2)(c^2+d^2).\n",
    "$$\n",
    "\n",
    "The second line is its proof: after expanding the brackets, the difference of the two sides is the zero polynomial.\n",
    "Expansion gives the canonical form of a polynomial (a sum of monomials with ordered coefficients),\n",
    "so “after expanding we got 0” is a proof, not just a test. For polynomials, zero testing is decidable;\n",
    "for expressions with $\\sin$, $|\\cdot|$ and the constant $\\pi$ it is not — that is the subject of the deep dive\n",
    "{doc}`../richardson/richardson`.\n",
    "\n",
    "Closure follows from the identity: the norm of a product is the product of the norms, and $1\\cdot1=1$.\n",
    "\n",
    "## Closure with a certificate\n",
    "\n",
    "The identity worked because the expression was short. Take a longer word, such as\n",
    "$P\\cdot(P\\cdot((P\\cdot Q)\\cdot Q))\\cdot Q$, and prove directly that it lies on the circle when $P$ and $Q$\n",
    "lie on it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9809cd19",
   "metadata": {},
   "outputs": [],
   "source": [
    "P, Q = (a, b), (c, d)\n",
    "x, y = m(m(P, m(P, m(m(P, Q), Q))), Q)\n",
    "w = x**2 + y**2 - 1\n",
    "print(\"liczba jednomianów:\", len(sp.Poly(w, a, b, c, d).terms()))\n",
    "print(sp.factor(w + 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bd73a45",
   "metadata": {},
   "source": [
    "The claim “$w=0$ on the circle” means exactly that $w$ can be written as\n",
    "\n",
    "$$\n",
    "w = h_1\\cdot(a^2+b^2-1) + h_2\\cdot(c^2+d^2-1)\n",
    "$$\n",
    "\n",
    "for some polynomials $h_1,h_2$. Such a representation is a **certificate**: whoever receives it checks it by\n",
    "expanding brackets, without any knowledge of how it was found. Finding it is harder:\n",
    "we divide $w$ with remainder by the circle equations (division by several polynomials and Gröbner bases are\n",
    "the topic of Lecture 6, §6.3). Here `sp.reduced` suffices,\n",
    "because the leading monomials $a^2$ and $c^2$ are coprime, so the two circle equations already form\n",
    "a Gröbner basis."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "df7afe3f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def certyfikat(w, relacje, zmienne):\n",
    "    \"\"\"Zwraca [h_1, ..., h_k] z w = sum h_i * relacje[i] albo None.\"\"\"\n",
    "    ilorazy, reszta = sp.reduced(sp.expand(w), relacje, *zmienne)\n",
    "    return ilorazy if reszta == 0 else None\n",
    "\n",
    "\n",
    "def sprawdz(w, relacje, cert):\n",
    "    \"\"\"Kontroler certyfikatu: tylko rozwinięcie nawiasów.\"\"\"\n",
    "    return sp.expand(w - sum(h * g for h, g in zip(cert, relacje))) == 0\n",
    "\n",
    "\n",
    "OKREGI = [a**2 + b**2 - 1, c**2 + d**2 - 1]\n",
    "cert = certyfikat(w, OKREGI, (a, b, c, d))\n",
    "for i, h in enumerate(cert, 1):\n",
    "    print(f\"h_{i} =\", sp.factor(h))\n",
    "print(\"certyfikat poprawny:\", sprawdz(w, OKREGI, cert))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa511f45",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert sprawdz(w, OKREGI, cert)\n",
    "assert all(wsp.is_integer\n",
    "           for h in cert for wsp in sp.Poly(h, a, b, c, d).coeffs())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32feba81",
   "metadata": {},
   "source": [
    "The division of labor is the same as for the MiniCAS certificates in Lecture 3 (§3.4): a big algorithm searches,\n",
    "a small checker verifies. We trust the checker `sprawdz` because it is simple; we do not need to trust the algorithm `sp.reduced`.\n",
    "\n",
    "The polynomials $h_1,h_2$ have integer coefficients, so the certificate is an equality in the ring\n",
    "$\\mathbb{Z}[a,b,c,d]$ and holds after substituting elements of any commutative ring.\n",
    "The Brahmagupta–Fibonacci identity and the other checks in this part also have integer coefficients.\n",
    "That is why the circle is a group also over $\\mathbb{Q}$, over a finite field $\\mathbb{F}_p$ (Part 4)\n",
    "and over every other field. This is what an **algebraic group** looks like: a set defined by\n",
    "polynomial equations, with an operation given by polynomials. We will return to this notion in Part 5.\n",
    "\n",
    "## The remaining axioms\n",
    "\n",
    "The identity element is $(1,0)$, and the inverse of $(a,b)$ is $(a,-b)$. Associativity and commutativity are\n",
    "polynomial identities (they hold for all pairs of numbers, not only on the circle), while\n",
    "the inverse needs the equation of the circle. We check everything at once."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4d0dedaa",
   "metadata": {},
   "outputs": [],
   "source": [
    "def tozsamosc(L, R):\n",
    "    return all(sp.expand(l - r) == 0 for l, r in zip(L, R))\n",
    "\n",
    "\n",
    "P, Q, R = (a, b), (c, d), (e, f)\n",
    "E = (sp.Integer(1), sp.Integer(0))\n",
    "odwrotny = (a, -b)\n",
    "iloczyn = m(P, odwrotny)\n",
    "\n",
    "wyniki = {\n",
    "    \"neutralny: P·E = E·P = P\":\n",
    "        tozsamosc(m(P, E), P) and tozsamosc(m(E, P), P),\n",
    "    \"łączność: (P·Q)·R = P·(Q·R)\":\n",
    "        tozsamosc(m(m(P, Q), R), m(P, m(Q, R))),\n",
    "    \"przemienność: P·Q = Q·P\": tozsamosc(m(P, Q), m(Q, P)),\n",
    "    \"odwrotny leży na okręgu\":\n",
    "        sp.expand(a**2 + (-b)**2 - (a**2 + b**2)) == 0,\n",
    "}\n",
    "cert_odw = certyfikat(iloczyn[0] - 1, OKREGI[:1], (a, b))\n",
    "wyniki[\"odwrotny: P·(a, -b) = E na okręgu\"] = (\n",
    "    cert_odw is not None and sprawdz(iloczyn[0] - 1, OKREGI[:1], cert_odw)\n",
    "    and sp.expand(iloczyn[1]) == 0)\n",
    "\n",
    "for nazwa, ok in wyniki.items():\n",
    "    print(f\"{nazwa:36} {ok}\")\n",
    "print(\"P·(a, -b) =\", iloczyn, \"  certyfikat:\", cert_odw)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3319deb",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "assert all(wyniki.values())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2d90ecf",
   "metadata": {},
   "source": [
    "These five lines together with closure are the whole proof that $(S^1,m)$ is a commutative group:\n",
    "closure, associativity and commutativity are equalities of polynomials, the inverse needs a certificate\n",
    "from the equation of the circle, and the identity element is a substitution. The computer approximates nothing here\n",
    "and checks nothing on examples.\n",
    "\n",
    "```{admonition} Why this is a proof, not a test\n",
    ":class: note\n",
    "Every line ends with a check that a certain polynomial with rational coefficients is\n",
    "zero, and that is settled by expanding brackets. So we trust only that SymPy multiplies\n",
    "and adds polynomials correctly. A formal proof in Lean would check even that: the `ring` tactic proves\n",
    "identities in commutative rings, and `linear_combination` accepts exactly our certificate\n",
    "$h_1,h_2$.\n",
    "```\n",
    "\n",
    "## Rational points and a parametrization\n",
    "\n",
    "The line through the point $(-1,0)$ with slope $t$ meets the circle at a second point\n",
    "\n",
    "$$\n",
    "\\Bigl(\\frac{1-t^2}{1+t^2},\\ \\frac{2t}{1+t^2}\\Bigr),\n",
    "$$\n",
    "\n",
    "and a rational $t$ gives a rational point. Conversely, every rational point other than $(-1,0)$ determines\n",
    "a rational slope $t=\\frac{b}{1+a}$. This is how all Pythagorean triples arise: $t=1/2$ gives\n",
    "$(3/5,4/5)$, and $t=2/3$ gives $(5/13,12/13)$. What does the group law look like in the parameter $t$?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ae6269b",
   "metadata": {},
   "outputs": [],
   "source": [
    "s, t = sp.symbols(\"s t\")\n",
    "\n",
    "\n",
    "def punkt(t):\n",
    "    return ((1 - t**2) / (1 + t**2), 2 * t / (1 + t**2))\n",
    "\n",
    "\n",
    "X = m(punkt(s), punkt(t))\n",
    "Y = punkt((s + t) / (1 - s * t))\n",
    "print([sp.simplify(X[i] - Y[i]) for i in range(2)])\n",
    "print(punkt(sp.Rational(1, 2)), punkt(sp.Rational(2, 3)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "320eab8a",
   "metadata": {},
   "source": [
    "In the parameter, multiplication of points is the operation $s\\oplus t=\\dfrac{s+t}{1-st}$, that is, the addition\n",
    "formula for the tangent: $t=\\operatorname{tg}(\\alpha/2)$ for the point $(\\cos\\alpha,\\sin\\alpha)$.\n",
    "\n",
    "## The point $(3/5,4/5)$ has infinite order\n",
    "\n",
    "Does some power of $P=(3/5,4/5)$ return to $(1,0)$? Let us compute a few denominators."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72301311",
   "metadata": {},
   "outputs": [],
   "source": [
    "P = (Fraction(3, 5), Fraction(4, 5))\n",
    "Q, mianowniki = P, []\n",
    "for n in range(1, 41):\n",
    "    mianowniki.append(Q[0].denominator == 5**n)\n",
    "    Q = m(Q, P)\n",
    "print(\"mianownik P^n równy 5^n dla n = 1..40:\", all(mianowniki))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40e3dbd8",
   "metadata": {},
   "source": [
    "Forty examples are not yet a proof. Write $P^n=(A_n/5^n,\\ B_n/5^n)$, where $A_n,B_n$\n",
    "are integers; then $A_1=3$, $B_1=4$ and $A_{n+1}=3A_n-4B_n$, $B_{n+1}=4A_n+3B_n$. We will prove\n",
    "by induction that $A_n\\equiv3$ and $B_n\\equiv4 \\pmod 5$. The induction step is a symbolic computation:\n",
    "we substitute $A=3+5k$, $B=4+5l$ and check that all coefficients of $A'-3$ and $B'-4$ are\n",
    "divisible by $5$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4f7290d7",
   "metadata": {},
   "outputs": [],
   "source": [
    "k, l = sp.symbols(\"k l\")\n",
    "A, B = 3 + 5 * k, 4 + 5 * l\n",
    "A1, B1 = sp.expand(3 * A - 4 * B), sp.expand(4 * A + 3 * B)\n",
    "\n",
    "\n",
    "def podzielny_przez_5(w):\n",
    "    return all(wsp % 5 == 0 for wsp in sp.Poly(w, k, l).coeffs())\n",
    "\n",
    "\n",
    "print(\"A' =\", A1, \"   B' =\", B1)\n",
    "print(\"A' ≡ 3 i B' ≡ 4 (mod 5):\",\n",
    "      podzielny_przez_5(A1 - 3) and podzielny_przez_5(B1 - 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbbc4901",
   "metadata": {},
   "source": [
    "Since $A_n\\equiv3\\pmod5$, the fraction $A_n/5^n$ is in lowest terms, so for $n\\ge1$ it is not equal to $1$.\n",
    "Hence $P^n\\ne(1,0)$ for every $n\\ge1$: the point $(3/5,4/5)$ has infinite order, that is, the angle\n",
    "$\\alpha$ with $\\cos\\alpha=3/5$ is not a rational fraction of the full angle. In Part 3 we will see that among the\n",
    "rational points of the circle only four have finite order.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Write down the certificate $h_1,h_2$ for the claim “$P^2\\cdot Q^3$ lies on the circle” and check it with the\n",
    "   function `sprawdz`.\n",
    "2. Prove in the same way as for $(3/5,4/5)$ that the point $(5/13,12/13)$ has infinite\n",
    "   order. Which modulus replaces $5$ here?\n",
    "3. The matrices $\\begin{pmatrix}a&-b\\\\ b&a\\end{pmatrix}$ with $a^2+b^2=1$ also form a group. Check\n",
    "   symbolically that the product of such matrices corresponds to the operation $m$, and that the determinant is $a^2+b^2$.\n",
    "4. Check, in the parameter $t$, the associativity of the operation $s\\oplus t=\\frac{s+t}{1-st}$. Which point of the circle\n",
    "   corresponds to “$t=\\infty$”, and why is it missing?\n",
    "\n",
    "## Literature and further reading\n",
    "\n",
    "* D. Cox, J. Little, D. O'Shea, *Ideals, Varieties, and Algorithms*, 4th ed., Springer, 2015\n",
    "  ([DOI](https://doi.org/10.1007/978-3-319-16721-3)) — ideal membership, division by several\n",
    "  polynomials and Gröbner bases, that is, what stands behind the function `certyfikat`.\n",
    "* [Brahmagupta–Fibonacci identity](https://en.wikipedia.org/wiki/Brahmagupta%E2%80%93Fibonacci_identity)\n",
    "  — history and generalizations (Euler’s four-square and Degen’s eight-square identities).\n",
    "* The deep dive {doc}`../richardson/richardson` — why for polynomials “after expanding we got 0”\n",
    "  settles the matter, while for expressions with elementary functions it does not.\n",
    "* In Lean with the Mathlib library, the `ring` tactic proves the identities of this part, and\n",
    "  `linear_combination` accepts the certificate $h_1,h_2$ directly."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
