{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Matrix Multiplication\n\nThis example shows how to use the :py:class:`pylops_gpu.MatrixMult` operator\nto perform *Matrix inversion* of the following linear system.\n\n\\begin{align}\\mathbf{y}=  \\mathbf{A} \\mathbf{x}\\end{align}\n\nFor square $\\mathbf{A}$, we will use the\n:py:func:`pylops_gpu.optimization.leastsquares.cg` solver.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as pltgs\nimport pylops_gpu\n\nfrom pylops_gpu.utils.backend import device\nfrom pylops_gpu.optimization.cg import cg\n\ntorch.manual_seed(0)\ndev = device()\nprint('PyLops-gpu working on %s...' % dev)\nplt.close('all')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's define the size ``N`` of thesquare matrix $\\mathbf{A}$ and\nfill the matrix with random numbers\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "N = 20\nA = torch.randn((N, N), dtype=torch.float32).to(dev)\nA = torch.matmul(A.t(), A) # need semi-definite positive matrix for cg\nAop = pylops_gpu.MatrixMult(A, dtype=torch.float32)\n\nx = torch.ones(N, dtype=torch.float32).to(dev)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can now apply the forward operator to create the data vector $\\mathbf{y}$\nand use ``/`` to solve the system by means of an explicit solver.\nIf you prefer to customize the solver (e.g., choosing the number of\niterations) use the method ``div`` instead.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "y = Aop * x\nxest = Aop / y\nxest = Aop.div(y, niter=2*N)\n\nprint('x', x)\nprint('xest', xest)"
      ]
    }
  ],
  "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.6.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}