<commit_before>{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Writing high(ish) performance code with Clifford and Numba via Numpy\n",
    "This document describes how to take algorithms developed in the clifford package with notation that is close to the maths and convert it into numerically efficient and fast running code. To do this we will expose the underlying representation of multivector as a numpy array of canonical basis vector coeficients and operate directly on these arrays in a manner that is conducive to JIT compilation with numba."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## First import the Clifford library as well as numpy and numba"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import clifford as cf\n",
    "import numpy as np\n",
    "import numba"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Choose a specific space\n",
    "For this document we will use 3d euclidean space embedded in the conformal framework giving a Cl(4,1) algebra.\n",
    "We will also rename some of the variables to match the notation that used by Lasenby et al. in \"A Covariant Approach to Geometry using Geometric Algebra\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from clifford import g3c\n",
    "# Get the layout in our local namespace etc etc\n",
    "layout = g3c.layout\n",
    "locals().update(g3c.blades)\n",
    "\n",
    "ep, en, up, down, homo, E0, ninf, no = (g3c.stuff[\"ep\"], g3c.stuff[\"en\"], \n",
    "                                        g3c.stuff[\"up\"], g3c.stuff[\"down\"], g3c.stuff[\"homo\"], \n",
    "                                        g3c.stuff[\"E0\"], g3c.stuff[\"einf\"], -g3c.stuff[\"eo\"])\n",
    "# Define a few useful terms\n",
    "E = ninf^(no)\n",
    "I5 = e12345\n",
    "I3 = e123"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Performance of mathematically iodmatic Clifford algorithms\n",
    "By default the Clifford library sacrifices performance for syntactic convenience.\n",
    "\n",
    "Consider a function that applies a rotor to a multivector:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def apply_rotor(R,mv):\n",
    "    return R*mv*~R"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will define a rotor that takes one line to another:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "line_one = (up(0)^up(e1)^ninf).normal()\n",
    "line_two = (up(0)^up(e2)^ninf).normal()\n",
    "R = 1 + line_two*line_one"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Check that this works"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1.0^e245)\n",
      "(1.0^e245)\n"
     ]
    }
   ],
   "source": [
    "print(line_two)\n",
    "print(apply_rotor(R,line_one).normal())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We would like to improve the speed of our algorithm, first we will profile it and see where it spends its time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(1000000):\n",
    "#    apply_rotor(R,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An example profile output from running this notebook on the author's laptop is as follows:\n",
    "```\n",
    "   ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000   66.290   66.290 {built-in method builtins.exec}\n",
    "        1    0.757    0.757   66.290   66.290 <string>:2(<module>)\n",
    "  1000000    3.818    0.000   65.534    0.000 <ipython-input-13-70a01003bf51>:1(apply_rotor)\n",
    "  2000000    9.269    0.000   55.641    0.000 __init__.py:751(__mul__)\n",
    "  2000000    3.167    0.000   29.900    0.000 __init__.py:717(_checkOther)\n",
    "  2000000    1.371    0.000   19.906    0.000 __init__.py:420(__ne__)\n",
    "  2000000    6.000    0.000   18.535    0.000 numeric.py:2565(array_equal)\n",
    "  2000000   10.505    0.000   10.505    0.000 __init__.py:260(mv_mult)\n",
    "```\n",
    "We can see that the function spends almost all of its time in `__mul__` and within `__mul__` it spends most of its time in `_checkOther`. In fact it only spends a small fraction of its time in `mv_mult` which does the numerical multivector multiplication. To write more performant code we need to strip away the high level abstractions and deal with the underlying representations of the blade component data."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Canonical blade coeficient representation in Clifford\n",
    "In Clifford a multivector is internally represented as a numpy array of the coefficients of the canonical basis vectors, they are arranged in order of grade. So for our 4,1 algebra the first element is the scalar part, the next 5 are the vector coeficients, the next 10 are the bivectors, the next 10 the triectors, the next 5 the quadvectors and the final value is the pseudoscalar coefficient."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.        ,  5.        , -1.        ,  0.        ,  0.        ,\n",
       "        0.        ,  1.        ,  0.        ,  0.        ,  0.        ,\n",
       "        0.        ,  0.        ,  0.        ,  0.        ,  0.        ,\n",
       "        0.        ,  0.        ,  0.        ,  0.        ,  0.        ,\n",
       "        1.        ,  0.        ,  0.        ,  0.        ,  0.        ,\n",
       "        0.        ,  3.14159265,  0.        ,  0.        ,  0.        ,\n",
       "        0.        ,  0.        ])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(5.0*e1 - e2 + e12 + e135 + np.pi*e1234).value"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exploiting blade representation to write a fast function\n",
    "We can rewrite our rotor application function using the functions that the layout exposes for operations on the numpy arrays themselves."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def apply_rotor_faster(R,mv):\n",
    "    return cf.MultiVector( layout, layout.gmt_func(R.value,layout.gmt_func(mv.value,layout.adjoint_func(R.value))) )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(1000000):\n",
    "#    apply_rotor_faster(R,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This gives a much faster function\n",
    "```\n",
    "   ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000   19.567   19.567 {built-in method builtins.exec}\n",
    "        1    0.631    0.631   19.567   19.567 <string>:2(<module>)\n",
    "  1000000    7.373    0.000   18.936    0.000 <ipython-input-35-6a5344d83bdb>:1(apply_rotor_faster)\n",
    "  2000000    9.125    0.000    9.125    0.000 __init__.py:260(mv_mult)\n",
    "  1000000    1.021    0.000    1.619    0.000 __init__.py:677(__init__)\n",
    "  1000000    0.819    0.000    0.819    0.000 __init__.py:244(adjoint_func)\n",
    "```\n",
    "We have successfully skipped past the higher level checks on the multivectors while maintaining extactly the same function signature.\n",
    "It is important to check that we still have the correct answer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1.0^e245)\n",
      "(1.0^e245)\n"
     ]
    }
   ],
   "source": [
    "print(line_two)\n",
    "print(apply_rotor_faster(R,line_one).normal())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The performance improvements gained by rewriting our function are significant but it comes at the cost of readibility.\n",
    "\n",
    "By loading the layouts gmt_func and adjoint_func into the global namespace before the function is defined and \n",
    "separating the value operations from the multivector wrapper we can make our code more concise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "gmt_func = layout.gmt_func\n",
    "adjoint_func = layout.adjoint_func\n",
    "\n",
    "def apply_rotor_val(R_val,mv_val):\n",
    "    return gmt_func(R_val,gmt_func(mv_val,adjoint_func(R_val)))\n",
    "\n",
    "def apply_rotor_wrapped(R,mv):\n",
    "    return cf.MultiVector(layout,apply_rotor_val(R.value,mv.value))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(1000000):\n",
    "#    apply_rotor_wrapped(R,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The time cost is essentially the same, there is probably some minor overhead from the function call itself\n",
    "```\n",
    "  ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000   19.621   19.621 {built-in method builtins.exec}\n",
    "        1    0.557    0.557   19.621   19.621 <string>:2(<module>)\n",
    "  1000000    1.421    0.000   19.064    0.000 <ipython-input-38-a1e0b5c53cdc>:7(apply_rotor_wrapped)\n",
    "  1000000    6.079    0.000   16.033    0.000 <ipython-input-38-a1e0b5c53cdc>:4(apply_rotor_val)\n",
    "  2000000    9.154    0.000    9.154    0.000 __init__.py:260(mv_mult)\n",
    "  1000000    1.017    0.000    1.610    0.000 __init__.py:677(__init__)\n",
    "  1000000    0.800    0.000    0.800    0.000 __init__.py:244(adjoint_func)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1.0^e245)\n",
      "(1.0^e245)\n"
     ]
    }
   ],
   "source": [
    "print(line_two)\n",
    "print(apply_rotor_wrapped(R,line_one).normal())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The additional advantage of splitting the function like this is that the numba JIT compiler can reason about the memory layout of numpy arrays in no python mode as long as no pure python objects are operated upon within the function. This means we can JIT our function that operates on the value directly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "@numba.njit\n",
    "def apply_rotor_val_numba(R_val,mv_val):\n",
    "    return gmt_func(R_val,gmt_func(mv_val,adjoint_func(R_val)))\n",
    "\n",
    "def apply_rotor_wrapped_numba(R,mv):\n",
    "    return cf.MultiVector(layout,apply_rotor_val_numba(R.value,mv.value))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(1000000):\n",
    "#    apply_rotor_wrapped_numba(R,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This gives a small improvement in performance but more importantly it allows us to write larger functions that also use the jitted `apply_rotor_val_numba` and are themselves jitted.\n",
    "```\n",
    " ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000   16.033   16.033 {built-in method builtins.exec}\n",
    "        1    0.605    0.605   16.033   16.033 <string>:2(<module>)\n",
    "  1000000    2.585    0.000   15.428    0.000 <ipython-input-42-1142126d93ca>:5(apply_rotor_wrapped_numba)\n",
    "  1000000    8.606    0.000    8.606    0.000 <ipython-input-42-1142126d93ca>:1(apply_rotor_val_numba)\n",
    "        1    0.000    0.000    2.716    2.716 dispatcher.py:294(_compile_for_args)\n",
    "      7/1    0.000    0.000    2.716    2.716 dispatcher.py:554(compile)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Composing larger functions\n",
    "By chaining together functions that operate on the value arrays of multivectors it is easy to construct fast and readable code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1.0^e14) - (1.0^e15) - (1.0^e45)\n",
      "(1.0^e14) - (1.0^e15) - (1.0^e45)\n",
      "(1.0^e14) - (1.0^e15) - (1.0^e45)\n"
     ]
    }
   ],
   "source": [
    "I5_val = I5.value\n",
    "omt_func = layout.omt_func\n",
    "\n",
    "def dual_mv(mv):\n",
    "    return -I5*mv\n",
    "\n",
    "def meet_unwrapped(mv_a,mv_b):\n",
    "    return -dual_mv(dual_mv(mv_a)^dual_mv(mv_b))\n",
    "\n",
    "@numba.njit\n",
    "def dual_val(mv_val):\n",
    "    return -gmt_func(I5_val,mv_val)\n",
    "\n",
    "@numba.njit\n",
    "def meet_val(mv_a_val,mv_b_val):\n",
    "    return -dual_val( omt_func( dual_val(mv_a_val) , dual_val(mv_b_val)) )\n",
    "\n",
    "def meet_wrapped(mv_a,mv_b):\n",
    "    return cf.MultiVector(layout, meet_val(mv_a.value, mv_b.value))\n",
    "\n",
    "sphere = (up(0)^up(e1)^up(e2)^up(e3)).normal()\n",
    "print(sphere.meet(line_one).normal().normal())\n",
    "print(meet_unwrapped(sphere,line_one).normal())\n",
    "print(meet_wrapped(line_one,sphere).normal())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(100000):\n",
    "#    meet_unwrapped(sphere,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000   13.216   13.216 {built-in method builtins.exec}\n",
    "        1    0.085    0.085   13.216   13.216 <string>:2(<module>)\n",
    "   100000    0.418    0.000   13.131    0.000 <ipython-input-98-f91457c8741a>:7(meet_unwrapped)\n",
    "   300000    0.681    0.000    9.893    0.000 <ipython-input-98-f91457c8741a>:4(dual_mv)\n",
    "   300000    1.383    0.000    8.127    0.000 __init__.py:751(__mul__)\n",
    "   400000    0.626    0.000    5.762    0.000 __init__.py:717(_checkOther)\n",
    "   400000    0.270    0.000    3.815    0.000 __init__.py:420(__ne__)\n",
    "   400000    1.106    0.000    3.544    0.000 numeric.py:2565(array_equal)\n",
    "   100000    0.460    0.000    2.439    0.000 __init__.py:783(__xor__)\n",
    "   800000    0.662    0.000    2.053    0.000 __init__.py:740(_newMV)\n",
    "   400000    1.815    0.000    1.815    0.000 __init__.py:260(mv_mult)\n",
    "   ```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(100000):\n",
    "#    meet_wrapped(sphere,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " ```\n",
    " ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000    1.951    1.951 {built-in method builtins.exec}\n",
    "        1    0.063    0.063    1.951    1.951 <string>:2(<module>)\n",
    "   100000    0.274    0.000    1.888    0.000 <ipython-input-98-f91457c8741a>:18(meet_wrapped)\n",
    "   100000    1.448    0.000    1.448    0.000 <ipython-input-98-f91457c8741a>:14(meet_val)\n",
    "   100000    0.096    0.000    0.166    0.000 __init__.py:677(__init__)\n",
    "   ```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Algorithms exploiting known sparseness of  MultiVector value array "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The standard multiplication generator function for two general multivectors is as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_mult_function(mult_table,n_dims):\n",
    "    ''' \n",
    "    Returns a function that implements the mult_table on two input multivectors\n",
    "    '''\n",
    "    non_zero_indices = mult_table.nonzero()\n",
    "    k_list = non_zero_indices[0]\n",
    "    l_list = non_zero_indices[1]\n",
    "    m_list = non_zero_indices[2]\n",
    "    mult_table_vals = np.array([mult_table[k,l,m] for k,l,m in np.transpose(non_zero_indices)],dtype=int)\n",
    "\n",
    "    @numba.njit\n",
    "    def mv_mult(value,other_value):\n",
    "        output = np.zeros(n_dims)\n",
    "        for ind,k in enumerate(k_list):\n",
    "            l = l_list[ind]\n",
    "            m = m_list[ind]\n",
    "            output[l] += value[k]*mult_table_vals[ind]*other_value[m]\n",
    "        return output\n",
    "    return mv_mult"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are however instances in which we might be able to use the known sparseness of the input data value representation to speed up the operations. For example, in Cl(4,1) rotors only contain even grade blades and we can therefore remove all the operations accessing odd grade objects."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_grade_from_index(index_in):\n",
    "    if index_in == 0:\n",
    "        return 0\n",
    "    elif index_in < 6:\n",
    "        return 1\n",
    "    elif index_in < 16:\n",
    "        return 2\n",
    "    elif index_in < 26:\n",
    "        return 3\n",
    "    elif index_in < 31:\n",
    "        return 4\n",
    "    elif index_in == 31:\n",
    "        return 5\n",
    "    else:\n",
    "        raise ValueError('Index is out of multivector bounds')\n",
    "\n",
    "def get_sparse_mult_function(mult_table,n_dims,grades_a,grades_b):\n",
    "    ''' \n",
    "    Returns a function that implements the mult_table on two input multivectors\n",
    "    '''\n",
    "    non_zero_indices = mult_table.nonzero()\n",
    "    k_list = non_zero_indices[0]\n",
    "    l_list = non_zero_indices[1]\n",
    "    m_list = non_zero_indices[2]\n",
    "    mult_table_vals = np.array([mult_table[k,l,m] for k,l,m in np.transpose(non_zero_indices)],dtype=int)\n",
    "    \n",
    "    # Now filter out the sparseness\n",
    "    filter_mask = np.zeros(len(k_list), dtype=bool)\n",
    "    for i in range(len(filter_mask)):\n",
    "        if get_grade_from_index(k_list[i]) in grades_a:\n",
    "            if get_grade_from_index(m_list[i]) in grades_b:\n",
    "                filter_mask[i] = 1\n",
    "    \n",
    "    k_list = k_list[filter_mask]\n",
    "    l_list = l_list[filter_mask]\n",
    "    m_list = m_list[filter_mask]\n",
    "    mult_table_vals = mult_table_vals[filter_mask]\n",
    "\n",
    "    @numba.njit\n",
    "    def mv_mult(value,other_value):\n",
    "        output = np.zeros(n_dims)\n",
    "        for ind,k in enumerate(k_list):\n",
    "            l = l_list[ind]\n",
    "            m = m_list[ind]\n",
    "            output[l] += value[k]*mult_table_vals[ind]*other_value[m]\n",
    "        return output\n",
    "    return mv_mult"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "left_rotor_mult = get_sparse_mult_function(layout.gmt,layout.gaDims,[0,2,4],[0,1,2,3,4,5])\n",
    "right_rotor_mult = get_sparse_mult_function(layout.gmt,layout.gaDims,[0,1,2,3,4,5],[0,2,4])\n",
    "\n",
    "@numba.njit\n",
    "def sparse_apply_rotor_val(R_val,mv_val):\n",
    "    return left_rotor_mult(R_val,right_rotor_mult(mv_val,adjoint_func(R_val)))\n",
    "\n",
    "def sparse_apply_rotor(R,mv):\n",
    "    return cf.MultiVector(layout,sparse_apply_rotor_val(R.value,mv.value))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(1000000):\n",
    "#    sparse_apply_rotor(R,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    " ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000    9.490    9.490 {built-in method builtins.exec}\n",
    "        1    0.624    0.624    9.489    9.489 <string>:2(<module>)\n",
    "  1000000    2.684    0.000    8.865    0.000 <ipython-input-146-f75aae3ce595>:8(sparse_apply_rotor)\n",
    "  1000000    4.651    0.000    4.651    0.000 <ipython-input-146-f75aae3ce595>:4(sparse_apply_rotor_val)\n",
    "  1000000    0.934    0.000    1.530    0.000 __init__.py:677(__init__)\n",
    "  1000000    0.596    0.000    0.596    0.000 {built-in method numpy.core.multiarray.array}\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1.0^e245)\n",
      "(1.0^e245)\n"
     ]
    }
   ],
   "source": [
    "print(line_two)\n",
    "print(sparse_apply_rotor(R,line_one).normal())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can do the same with the meet operation that we defined earlier if we know what grade objects we are meeting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1.0^e14) - (1.0^e15) - (1.0^e45)\n",
      "(1.0^e14) - (1.0^e15) - (1.0^e45)\n"
     ]
    }
   ],
   "source": [
    "left_pseudo_mult = get_sparse_mult_function(layout.gmt,layout.gaDims,[5],[0,1,2,3,4,5])\n",
    "sparse_omt_2_1 = get_sparse_mult_function(layout.omt,layout.gaDims,[2],[1])\n",
    "\n",
    "@numba.njit\n",
    "def dual_sparse_val(mv_val):\n",
    "    return -left_pseudo_mult(I5_val,mv_val)\n",
    "\n",
    "@numba.njit\n",
    "def meet_sparse_3_4_val(mv_a_val,mv_b_val):\n",
    "    return -dual_sparse_val( sparse_omt_2_1( dual_sparse_val(mv_a_val) , dual_sparse_val(mv_b_val)) )\n",
    "\n",
    "def meet_sparse_3_4(mv_a,mv_b):\n",
    "    return cf.MultiVector(layout, meet_sparse_3_4_val(mv_a.value, mv_b.value))\n",
    "\n",
    "print(sphere.meet(line_one).normal().normal())\n",
    "print(meet_sparse_3_4(line_one,sphere).normal())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(100000):\n",
    "#    meet_sparse_3_4(line_one,sphere)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "   ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000    0.725    0.725 {built-in method builtins.exec}\n",
    "        1    0.058    0.058    0.725    0.725 <string>:2(<module>)\n",
    "   100000    0.252    0.000    0.667    0.000 <ipython-input-156-f346d0563682>:12(meet_sparse_3_4)\n",
    "   100000    0.267    0.000    0.267    0.000 <ipython-input-156-f346d0563682>:8(meet_sparse_3_4_val)\n",
    "   100000    0.088    0.000    0.148    0.000 __init__.py:677(__init__)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Future work\n",
    "Investigate efficient operations on containers of multivectors.\n",
    "Possibly investigate http://numba.pydata.org/numba-doc/0.13/CUDAJit.html for larger algebras/other areas in which GPU memory latency will not be such a large factor, ie, lots of bulk parallel numerical operations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],<commit_msg>Modified tutorial notebook to make future work a sub heading<commit_after>{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Writing high(ish) performance code with Clifford and Numba via Numpy\n",
    "This document describes how to take algorithms developed in the clifford package with notation that is close to the maths and convert it into numerically efficient and fast running code. To do this we will expose the underlying representation of multivector as a numpy array of canonical basis vector coeficients and operate directly on these arrays in a manner that is conducive to JIT compilation with numba."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## First import the Clifford library as well as numpy and numba"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import clifford as cf\n",
    "import numpy as np\n",
    "import numba"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Choose a specific space\n",
    "For this document we will use 3d euclidean space embedded in the conformal framework giving a Cl(4,1) algebra.\n",
    "We will also rename some of the variables to match the notation that used by Lasenby et al. in \"A Covariant Approach to Geometry using Geometric Algebra\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from clifford import g3c\n",
    "# Get the layout in our local namespace etc etc\n",
    "layout = g3c.layout\n",
    "locals().update(g3c.blades)\n",
    "\n",
    "ep, en, up, down, homo, E0, ninf, no = (g3c.stuff[\"ep\"], g3c.stuff[\"en\"], \n",
    "                                        g3c.stuff[\"up\"], g3c.stuff[\"down\"], g3c.stuff[\"homo\"], \n",
    "                                        g3c.stuff[\"E0\"], g3c.stuff[\"einf\"], -g3c.stuff[\"eo\"])\n",
    "# Define a few useful terms\n",
    "E = ninf^(no)\n",
    "I5 = e12345\n",
    "I3 = e123"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Performance of mathematically iodmatic Clifford algorithms\n",
    "By default the Clifford library sacrifices performance for syntactic convenience.\n",
    "\n",
    "Consider a function that applies a rotor to a multivector:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def apply_rotor(R,mv):\n",
    "    return R*mv*~R"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will define a rotor that takes one line to another:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "line_one = (up(0)^up(e1)^ninf).normal()\n",
    "line_two = (up(0)^up(e2)^ninf).normal()\n",
    "R = 1 + line_two*line_one"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Check that this works"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1.0^e245)\n",
      "(1.0^e245)\n"
     ]
    }
   ],
   "source": [
    "print(line_two)\n",
    "print(apply_rotor(R,line_one).normal())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We would like to improve the speed of our algorithm, first we will profile it and see where it spends its time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(1000000):\n",
    "#    apply_rotor(R,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An example profile output from running this notebook on the author's laptop is as follows:\n",
    "```\n",
    "   ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000   66.290   66.290 {built-in method builtins.exec}\n",
    "        1    0.757    0.757   66.290   66.290 <string>:2(<module>)\n",
    "  1000000    3.818    0.000   65.534    0.000 <ipython-input-13-70a01003bf51>:1(apply_rotor)\n",
    "  2000000    9.269    0.000   55.641    0.000 __init__.py:751(__mul__)\n",
    "  2000000    3.167    0.000   29.900    0.000 __init__.py:717(_checkOther)\n",
    "  2000000    1.371    0.000   19.906    0.000 __init__.py:420(__ne__)\n",
    "  2000000    6.000    0.000   18.535    0.000 numeric.py:2565(array_equal)\n",
    "  2000000   10.505    0.000   10.505    0.000 __init__.py:260(mv_mult)\n",
    "```\n",
    "We can see that the function spends almost all of its time in `__mul__` and within `__mul__` it spends most of its time in `_checkOther`. In fact it only spends a small fraction of its time in `mv_mult` which does the numerical multivector multiplication. To write more performant code we need to strip away the high level abstractions and deal with the underlying representations of the blade component data."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Canonical blade coeficient representation in Clifford\n",
    "In Clifford a multivector is internally represented as a numpy array of the coefficients of the canonical basis vectors, they are arranged in order of grade. So for our 4,1 algebra the first element is the scalar part, the next 5 are the vector coeficients, the next 10 are the bivectors, the next 10 the triectors, the next 5 the quadvectors and the final value is the pseudoscalar coefficient."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.        ,  5.        , -1.        ,  0.        ,  0.        ,\n",
       "        0.        ,  1.        ,  0.        ,  0.        ,  0.        ,\n",
       "        0.        ,  0.        ,  0.        ,  0.        ,  0.        ,\n",
       "        0.        ,  0.        ,  0.        ,  0.        ,  0.        ,\n",
       "        1.        ,  0.        ,  0.        ,  0.        ,  0.        ,\n",
       "        0.        ,  3.14159265,  0.        ,  0.        ,  0.        ,\n",
       "        0.        ,  0.        ])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(5.0*e1 - e2 + e12 + e135 + np.pi*e1234).value"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exploiting blade representation to write a fast function\n",
    "We can rewrite our rotor application function using the functions that the layout exposes for operations on the numpy arrays themselves."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def apply_rotor_faster(R,mv):\n",
    "    return cf.MultiVector( layout, layout.gmt_func(R.value,layout.gmt_func(mv.value,layout.adjoint_func(R.value))) )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(1000000):\n",
    "#    apply_rotor_faster(R,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This gives a much faster function\n",
    "```\n",
    "   ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000   19.567   19.567 {built-in method builtins.exec}\n",
    "        1    0.631    0.631   19.567   19.567 <string>:2(<module>)\n",
    "  1000000    7.373    0.000   18.936    0.000 <ipython-input-35-6a5344d83bdb>:1(apply_rotor_faster)\n",
    "  2000000    9.125    0.000    9.125    0.000 __init__.py:260(mv_mult)\n",
    "  1000000    1.021    0.000    1.619    0.000 __init__.py:677(__init__)\n",
    "  1000000    0.819    0.000    0.819    0.000 __init__.py:244(adjoint_func)\n",
    "```\n",
    "We have successfully skipped past the higher level checks on the multivectors while maintaining extactly the same function signature.\n",
    "It is important to check that we still have the correct answer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1.0^e245)\n",
      "(1.0^e245)\n"
     ]
    }
   ],
   "source": [
    "print(line_two)\n",
    "print(apply_rotor_faster(R,line_one).normal())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The performance improvements gained by rewriting our function are significant but it comes at the cost of readibility.\n",
    "\n",
    "By loading the layouts gmt_func and adjoint_func into the global namespace before the function is defined and \n",
    "separating the value operations from the multivector wrapper we can make our code more concise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "gmt_func = layout.gmt_func\n",
    "adjoint_func = layout.adjoint_func\n",
    "\n",
    "def apply_rotor_val(R_val,mv_val):\n",
    "    return gmt_func(R_val,gmt_func(mv_val,adjoint_func(R_val)))\n",
    "\n",
    "def apply_rotor_wrapped(R,mv):\n",
    "    return cf.MultiVector(layout,apply_rotor_val(R.value,mv.value))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(1000000):\n",
    "#    apply_rotor_wrapped(R,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The time cost is essentially the same, there is probably some minor overhead from the function call itself\n",
    "```\n",
    "  ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000   19.621   19.621 {built-in method builtins.exec}\n",
    "        1    0.557    0.557   19.621   19.621 <string>:2(<module>)\n",
    "  1000000    1.421    0.000   19.064    0.000 <ipython-input-38-a1e0b5c53cdc>:7(apply_rotor_wrapped)\n",
    "  1000000    6.079    0.000   16.033    0.000 <ipython-input-38-a1e0b5c53cdc>:4(apply_rotor_val)\n",
    "  2000000    9.154    0.000    9.154    0.000 __init__.py:260(mv_mult)\n",
    "  1000000    1.017    0.000    1.610    0.000 __init__.py:677(__init__)\n",
    "  1000000    0.800    0.000    0.800    0.000 __init__.py:244(adjoint_func)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1.0^e245)\n",
      "(1.0^e245)\n"
     ]
    }
   ],
   "source": [
    "print(line_two)\n",
    "print(apply_rotor_wrapped(R,line_one).normal())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The additional advantage of splitting the function like this is that the numba JIT compiler can reason about the memory layout of numpy arrays in no python mode as long as no pure python objects are operated upon within the function. This means we can JIT our function that operates on the value directly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "@numba.njit\n",
    "def apply_rotor_val_numba(R_val,mv_val):\n",
    "    return gmt_func(R_val,gmt_func(mv_val,adjoint_func(R_val)))\n",
    "\n",
    "def apply_rotor_wrapped_numba(R,mv):\n",
    "    return cf.MultiVector(layout,apply_rotor_val_numba(R.value,mv.value))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(1000000):\n",
    "#    apply_rotor_wrapped_numba(R,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This gives a small improvement in performance but more importantly it allows us to write larger functions that also use the jitted `apply_rotor_val_numba` and are themselves jitted.\n",
    "```\n",
    " ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000   16.033   16.033 {built-in method builtins.exec}\n",
    "        1    0.605    0.605   16.033   16.033 <string>:2(<module>)\n",
    "  1000000    2.585    0.000   15.428    0.000 <ipython-input-42-1142126d93ca>:5(apply_rotor_wrapped_numba)\n",
    "  1000000    8.606    0.000    8.606    0.000 <ipython-input-42-1142126d93ca>:1(apply_rotor_val_numba)\n",
    "        1    0.000    0.000    2.716    2.716 dispatcher.py:294(_compile_for_args)\n",
    "      7/1    0.000    0.000    2.716    2.716 dispatcher.py:554(compile)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Composing larger functions\n",
    "By chaining together functions that operate on the value arrays of multivectors it is easy to construct fast and readable code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1.0^e14) - (1.0^e15) - (1.0^e45)\n",
      "(1.0^e14) - (1.0^e15) - (1.0^e45)\n",
      "(1.0^e14) - (1.0^e15) - (1.0^e45)\n"
     ]
    }
   ],
   "source": [
    "I5_val = I5.value\n",
    "omt_func = layout.omt_func\n",
    "\n",
    "def dual_mv(mv):\n",
    "    return -I5*mv\n",
    "\n",
    "def meet_unwrapped(mv_a,mv_b):\n",
    "    return -dual_mv(dual_mv(mv_a)^dual_mv(mv_b))\n",
    "\n",
    "@numba.njit\n",
    "def dual_val(mv_val):\n",
    "    return -gmt_func(I5_val,mv_val)\n",
    "\n",
    "@numba.njit\n",
    "def meet_val(mv_a_val,mv_b_val):\n",
    "    return -dual_val( omt_func( dual_val(mv_a_val) , dual_val(mv_b_val)) )\n",
    "\n",
    "def meet_wrapped(mv_a,mv_b):\n",
    "    return cf.MultiVector(layout, meet_val(mv_a.value, mv_b.value))\n",
    "\n",
    "sphere = (up(0)^up(e1)^up(e2)^up(e3)).normal()\n",
    "print(sphere.meet(line_one).normal().normal())\n",
    "print(meet_unwrapped(sphere,line_one).normal())\n",
    "print(meet_wrapped(line_one,sphere).normal())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(100000):\n",
    "#    meet_unwrapped(sphere,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000   13.216   13.216 {built-in method builtins.exec}\n",
    "        1    0.085    0.085   13.216   13.216 <string>:2(<module>)\n",
    "   100000    0.418    0.000   13.131    0.000 <ipython-input-98-f91457c8741a>:7(meet_unwrapped)\n",
    "   300000    0.681    0.000    9.893    0.000 <ipython-input-98-f91457c8741a>:4(dual_mv)\n",
    "   300000    1.383    0.000    8.127    0.000 __init__.py:751(__mul__)\n",
    "   400000    0.626    0.000    5.762    0.000 __init__.py:717(_checkOther)\n",
    "   400000    0.270    0.000    3.815    0.000 __init__.py:420(__ne__)\n",
    "   400000    1.106    0.000    3.544    0.000 numeric.py:2565(array_equal)\n",
    "   100000    0.460    0.000    2.439    0.000 __init__.py:783(__xor__)\n",
    "   800000    0.662    0.000    2.053    0.000 __init__.py:740(_newMV)\n",
    "   400000    1.815    0.000    1.815    0.000 __init__.py:260(mv_mult)\n",
    "   ```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(100000):\n",
    "#    meet_wrapped(sphere,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " ```\n",
    " ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000    1.951    1.951 {built-in method builtins.exec}\n",
    "        1    0.063    0.063    1.951    1.951 <string>:2(<module>)\n",
    "   100000    0.274    0.000    1.888    0.000 <ipython-input-98-f91457c8741a>:18(meet_wrapped)\n",
    "   100000    1.448    0.000    1.448    0.000 <ipython-input-98-f91457c8741a>:14(meet_val)\n",
    "   100000    0.096    0.000    0.166    0.000 __init__.py:677(__init__)\n",
    "   ```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Algorithms exploiting known sparseness of  MultiVector value array "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The standard multiplication generator function for two general multivectors is as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_mult_function(mult_table,n_dims):\n",
    "    ''' \n",
    "    Returns a function that implements the mult_table on two input multivectors\n",
    "    '''\n",
    "    non_zero_indices = mult_table.nonzero()\n",
    "    k_list = non_zero_indices[0]\n",
    "    l_list = non_zero_indices[1]\n",
    "    m_list = non_zero_indices[2]\n",
    "    mult_table_vals = np.array([mult_table[k,l,m] for k,l,m in np.transpose(non_zero_indices)],dtype=int)\n",
    "\n",
    "    @numba.njit\n",
    "    def mv_mult(value,other_value):\n",
    "        output = np.zeros(n_dims)\n",
    "        for ind,k in enumerate(k_list):\n",
    "            l = l_list[ind]\n",
    "            m = m_list[ind]\n",
    "            output[l] += value[k]*mult_table_vals[ind]*other_value[m]\n",
    "        return output\n",
    "    return mv_mult"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are however instances in which we might be able to use the known sparseness of the input data value representation to speed up the operations. For example, in Cl(4,1) rotors only contain even grade blades and we can therefore remove all the operations accessing odd grade objects."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_grade_from_index(index_in):\n",
    "    if index_in == 0:\n",
    "        return 0\n",
    "    elif index_in < 6:\n",
    "        return 1\n",
    "    elif index_in < 16:\n",
    "        return 2\n",
    "    elif index_in < 26:\n",
    "        return 3\n",
    "    elif index_in < 31:\n",
    "        return 4\n",
    "    elif index_in == 31:\n",
    "        return 5\n",
    "    else:\n",
    "        raise ValueError('Index is out of multivector bounds')\n",
    "\n",
    "def get_sparse_mult_function(mult_table,n_dims,grades_a,grades_b):\n",
    "    ''' \n",
    "    Returns a function that implements the mult_table on two input multivectors\n",
    "    '''\n",
    "    non_zero_indices = mult_table.nonzero()\n",
    "    k_list = non_zero_indices[0]\n",
    "    l_list = non_zero_indices[1]\n",
    "    m_list = non_zero_indices[2]\n",
    "    mult_table_vals = np.array([mult_table[k,l,m] for k,l,m in np.transpose(non_zero_indices)],dtype=int)\n",
    "    \n",
    "    # Now filter out the sparseness\n",
    "    filter_mask = np.zeros(len(k_list), dtype=bool)\n",
    "    for i in range(len(filter_mask)):\n",
    "        if get_grade_from_index(k_list[i]) in grades_a:\n",
    "            if get_grade_from_index(m_list[i]) in grades_b:\n",
    "                filter_mask[i] = 1\n",
    "    \n",
    "    k_list = k_list[filter_mask]\n",
    "    l_list = l_list[filter_mask]\n",
    "    m_list = m_list[filter_mask]\n",
    "    mult_table_vals = mult_table_vals[filter_mask]\n",
    "\n",
    "    @numba.njit\n",
    "    def mv_mult(value,other_value):\n",
    "        output = np.zeros(n_dims)\n",
    "        for ind,k in enumerate(k_list):\n",
    "            l = l_list[ind]\n",
    "            m = m_list[ind]\n",
    "            output[l] += value[k]*mult_table_vals[ind]*other_value[m]\n",
    "        return output\n",
    "    return mv_mult"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "left_rotor_mult = get_sparse_mult_function(layout.gmt,layout.gaDims,[0,2,4],[0,1,2,3,4,5])\n",
    "right_rotor_mult = get_sparse_mult_function(layout.gmt,layout.gaDims,[0,1,2,3,4,5],[0,2,4])\n",
    "\n",
    "@numba.njit\n",
    "def sparse_apply_rotor_val(R_val,mv_val):\n",
    "    return left_rotor_mult(R_val,right_rotor_mult(mv_val,adjoint_func(R_val)))\n",
    "\n",
    "def sparse_apply_rotor(R,mv):\n",
    "    return cf.MultiVector(layout,sparse_apply_rotor_val(R.value,mv.value))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(1000000):\n",
    "#    sparse_apply_rotor(R,line_one)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    " ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000    9.490    9.490 {built-in method builtins.exec}\n",
    "        1    0.624    0.624    9.489    9.489 <string>:2(<module>)\n",
    "  1000000    2.684    0.000    8.865    0.000 <ipython-input-146-f75aae3ce595>:8(sparse_apply_rotor)\n",
    "  1000000    4.651    0.000    4.651    0.000 <ipython-input-146-f75aae3ce595>:4(sparse_apply_rotor_val)\n",
    "  1000000    0.934    0.000    1.530    0.000 __init__.py:677(__init__)\n",
    "  1000000    0.596    0.000    0.596    0.000 {built-in method numpy.core.multiarray.array}\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1.0^e245)\n",
      "(1.0^e245)\n"
     ]
    }
   ],
   "source": [
    "print(line_two)\n",
    "print(sparse_apply_rotor(R,line_one).normal())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can do the same with the meet operation that we defined earlier if we know what grade objects we are meeting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1.0^e14) - (1.0^e15) - (1.0^e45)\n",
      "(1.0^e14) - (1.0^e15) - (1.0^e45)\n"
     ]
    }
   ],
   "source": [
    "left_pseudo_mult = get_sparse_mult_function(layout.gmt,layout.gaDims,[5],[0,1,2,3,4,5])\n",
    "sparse_omt_2_1 = get_sparse_mult_function(layout.omt,layout.gaDims,[2],[1])\n",
    "\n",
    "@numba.njit\n",
    "def dual_sparse_val(mv_val):\n",
    "    return -left_pseudo_mult(I5_val,mv_val)\n",
    "\n",
    "@numba.njit\n",
    "def meet_sparse_3_4_val(mv_a_val,mv_b_val):\n",
    "    return -dual_sparse_val( sparse_omt_2_1( dual_sparse_val(mv_a_val) , dual_sparse_val(mv_b_val)) )\n",
    "\n",
    "def meet_sparse_3_4(mv_a,mv_b):\n",
    "    return cf.MultiVector(layout, meet_sparse_3_4_val(mv_a.value, mv_b.value))\n",
    "\n",
    "print(sphere.meet(line_one).normal().normal())\n",
    "print(meet_sparse_3_4(line_one,sphere).normal())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "#%%prun -s cumtime\n",
    "#for i in range(100000):\n",
    "#    meet_sparse_3_4(line_one,sphere)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "   ncalls  tottime  percall  cumtime  percall filename:lineno(function)\n",
    "        1    0.000    0.000    0.725    0.725 {built-in method builtins.exec}\n",
    "        1    0.058    0.058    0.725    0.725 <string>:2(<module>)\n",
    "   100000    0.252    0.000    0.667    0.000 <ipython-input-156-f346d0563682>:12(meet_sparse_3_4)\n",
    "   100000    0.267    0.000    0.267    0.000 <ipython-input-156-f346d0563682>:8(meet_sparse_3_4_val)\n",
    "   100000    0.088    0.000    0.148    0.000 __init__.py:677(__init__)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Future work on performance\n",
    "Investigate efficient operations on containers of large numbers of multivectors.\n",
    "\n",
    "Possibly investigate http://numba.pydata.org/numba-doc/0.13/CUDAJit.html for larger algebras/other areas in which GPU memory latency will not be such a large factor, ie, lots of bulk parallel numerical operations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
{'fraction_non_alphanumeric': 0.17193867258422432, 'fraction_numerical': 0.07105103893483962, 'mean_word_length': 2.336990912150791, 'pattern_counts': {'":': 458, '<': 71, '<?xml version=': 0, '>': 63, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5613818', 'n_tokens_mistral': 21097, 'n_tokens_neox': 18987, 'n_words': 3899}