{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Operators concatenation\n\nThis example shows how to use 'stacking' operators such as\n:py:class:`pylops.VStack`, :py:class:`pylops.HStack`,\n:py:class:`pylops.Block`, :py:class:`pylops.BlockDiag`,\nand :py:class:`pylops.Kronecker`.\n\nThese operators allow for different combinations of multiple linear operators\nin a single operator. Such functionalities are used within PyLops as the basis\nfor the creation of complex operators as well as in the definition of various\ntypes of optimization problems with regularization or preconditioning.\n\nSome of this operators naturally lend to embarassingly parallel computations.\nWithin PyLops we leverage the multiprocessing module to run multiple processes\nat the same time evaluating a subset of the operators involved in one of the\nstacking operations.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport pylops\n\nplt.close(\"all\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let's start by defining two second derivatives :py:class:`pylops.SecondDerivative`\nthat we will be using in this example.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "D2hop = pylops.SecondDerivative(dims=(11, 21), axis=1, dtype=\"float32\")\nD2vop = pylops.SecondDerivative(dims=(11, 21), axis=0, dtype=\"float32\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Chaining of operators represents the simplest concatenation that\ncan be performed between two or more linear operators.\nThis can be easily achieved using the ``*`` symbol\n\n   .. math::\n      \\mathbf{D_{cat}}=  \\mathbf{D_v} \\mathbf{D_h}\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "Nv, Nh = 11, 21\nX = np.zeros((Nv, Nh))\nX[int(Nv / 2), int(Nh / 2)] = 1\n\nD2op = D2vop * D2hop\nY = D2op * X\n\nfig, axs = plt.subplots(1, 2, figsize=(10, 3))\nfig.suptitle(\"Chain\", fontsize=14, fontweight=\"bold\", y=0.95)\nim = axs[0].imshow(X, interpolation=\"nearest\")\naxs[0].axis(\"tight\")\naxs[0].set_title(r\"$x$\")\nplt.colorbar(im, ax=axs[0])\nim = axs[1].imshow(Y, interpolation=\"nearest\")\naxs[1].axis(\"tight\")\naxs[1].set_title(r\"$y=(D_x+D_y) x$\")\nplt.colorbar(im, ax=axs[1])\nplt.tight_layout()\nplt.subplots_adjust(top=0.8)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We now want to *vertically stack* three operators\n\n   .. math::\n      \\mathbf{D_{Vstack}} =\n       \\begin{bmatrix}\n         \\mathbf{D_v}    \\\\\n         \\mathbf{D_h}\n       \\end{bmatrix}, \\qquad\n      \\mathbf{y} =\n       \\begin{bmatrix}\n         \\mathbf{D_v}\\mathbf{x}    \\\\\n         \\mathbf{D_h}\\mathbf{x}\n       \\end{bmatrix}\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "Nv, Nh = 11, 21\nX = np.zeros((Nv, Nh))\nX[int(Nv / 2), int(Nh / 2)] = 1\nDstack = pylops.VStack([D2vop, D2hop])\n\nY = np.reshape(Dstack * X.ravel(), (Nv * 2, Nh))\n\nfig, axs = plt.subplots(1, 2, figsize=(10, 3))\nfig.suptitle(\"Vertical stacking\", fontsize=14, fontweight=\"bold\", y=0.95)\nim = axs[0].imshow(X, interpolation=\"nearest\")\naxs[0].axis(\"tight\")\naxs[0].set_title(r\"$x$\")\nplt.colorbar(im, ax=axs[0])\nim = axs[1].imshow(Y, interpolation=\"nearest\")\naxs[1].axis(\"tight\")\naxs[1].set_title(r\"$y$\")\nplt.colorbar(im, ax=axs[1])\nplt.tight_layout()\nplt.subplots_adjust(top=0.8)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Similarly we can now *horizontally stack* three operators\n\n   .. math::\n      \\mathbf{D_{Hstack}} =\n       \\begin{bmatrix}\n          \\mathbf{D_v}  & 0.5*\\mathbf{D_v} & -1*\\mathbf{D_h}\n       \\end{bmatrix}, \\qquad\n      \\mathbf{y} =\n       \\mathbf{D_v}\\mathbf{x}_1 + 0.5*\\mathbf{D_v}\\mathbf{x}_2 -\n       \\mathbf{D_h}\\mathbf{x}_3\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "Nv, Nh = 11, 21\nX = np.zeros((Nv * 3, Nh))\nX[int(Nv / 2), int(Nh / 2)] = 1\nX[int(Nv / 2) + Nv, int(Nh / 2)] = 1\nX[int(Nv / 2) + 2 * Nv, int(Nh / 2)] = 1\n\nHstackop = pylops.HStack([D2vop, 0.5 * D2vop, -1 * D2hop])\nY = np.reshape(Hstackop * X.ravel(), (Nv, Nh))\n\nfig, axs = plt.subplots(1, 2, figsize=(10, 3))\nfig.suptitle(\"Horizontal stacking\", fontsize=14, fontweight=\"bold\", y=0.95)\nim = axs[0].imshow(X, interpolation=\"nearest\")\naxs[0].axis(\"tight\")\naxs[0].set_title(r\"$x$\")\nplt.colorbar(im, ax=axs[0])\nim = axs[1].imshow(Y, interpolation=\"nearest\")\naxs[1].axis(\"tight\")\naxs[1].set_title(r\"$y$\")\nplt.colorbar(im, ax=axs[1])\nplt.tight_layout()\nplt.subplots_adjust(top=0.8)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can even stack them both *horizontally* and *vertically* such that we\ncreate a *block* operator\n\n   .. math::\n      \\mathbf{D_{Block}} =\n       \\begin{bmatrix}\n          \\mathbf{D_v} & 0.5*\\mathbf{D_v} & -1*\\mathbf{D_h} \\\\\n          \\mathbf{D_h} & 2*\\mathbf{D_h}   & \\mathbf{D_v} \\\\\n       \\end{bmatrix}, \\qquad\n      \\mathbf{y} =\n       \\begin{bmatrix}\n          \\mathbf{D_v} \\mathbf{x_1} + 0.5*\\mathbf{D_v} \\mathbf{x_2} -\n          \\mathbf{D_h} \\mathbf{x_3} \\\\\n          \\mathbf{D_h} \\mathbf{x_1} + 2*\\mathbf{D_h} \\mathbf{x_2} +\n          \\mathbf{D_v} \\mathbf{x_3}\n       \\end{bmatrix}\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "Bop = pylops.Block([[D2vop, 0.5 * D2vop, -1 * D2hop], [D2hop, 2 * D2hop, D2vop]])\nY = np.reshape(Bop * X.ravel(), (2 * Nv, Nh))\n\nfig, axs = plt.subplots(1, 2, figsize=(10, 3))\nfig.suptitle(\"Block\", fontsize=14, fontweight=\"bold\", y=0.95)\nim = axs[0].imshow(X, interpolation=\"nearest\")\naxs[0].axis(\"tight\")\naxs[0].set_title(r\"$x$\")\nplt.colorbar(im, ax=axs[0])\nim = axs[1].imshow(Y, interpolation=\"nearest\")\naxs[1].axis(\"tight\")\naxs[1].set_title(r\"$y$\")\nplt.colorbar(im, ax=axs[1])\nplt.tight_layout()\nplt.subplots_adjust(top=0.8)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Finally we can use the *block-diagonal operator* to apply three operators\nto three different subset of the model and data\n\n   .. math::\n      \\mathbf{D_{BDiag}} =\n       \\begin{bmatrix}\n          \\mathbf{D_v}  & \\mathbf{0}       &  \\mathbf{0}  \\\\\n          \\mathbf{0}    & 0.5*\\mathbf{D_v} &  \\mathbf{0}  \\\\\n          \\mathbf{0}    & \\mathbf{0}       &  -\\mathbf{D_h}\n       \\end{bmatrix}, \\qquad\n      \\mathbf{y} =\n       \\begin{bmatrix}\n          \\mathbf{D_v}     \\mathbf{x_1}  \\\\\n          0.5*\\mathbf{D_v} \\mathbf{x_2}  \\\\\n          -\\mathbf{D_h}  \\mathbf{x_3}\n       \\end{bmatrix}\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "BD = pylops.BlockDiag([D2vop, 0.5 * D2vop, -1 * D2hop])\nY = np.reshape(BD * X.ravel(), (3 * Nv, Nh))\n\nfig, axs = plt.subplots(1, 2, figsize=(10, 3))\nfig.suptitle(\"Block-diagonal\", fontsize=14, fontweight=\"bold\", y=0.95)\nim = axs[0].imshow(X, interpolation=\"nearest\")\naxs[0].axis(\"tight\")\naxs[0].set_title(r\"$x$\")\nplt.colorbar(im, ax=axs[0])\nim = axs[1].imshow(Y, interpolation=\"nearest\")\naxs[1].axis(\"tight\")\naxs[1].set_title(r\"$y$\")\nplt.colorbar(im, ax=axs[1])\nplt.tight_layout()\nplt.subplots_adjust(top=0.8)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "If we consider now the case of having a large number of operators inside a\nblockdiagonal structure, it may be convenient to span multiple processes\nhandling subset of operators at the same time. This can be easily achieved\nby simply defining the number of processes we want to use via ``nproc``.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "X = np.zeros((Nv * 10, Nh))\nfor iv in range(10):\n    X[int(Nv / 2) + iv * Nv, int(Nh / 2)] = 1\n\nBD = pylops.BlockDiag([D2vop] * 10, nproc=2)\nprint(\"BD Operator multiprocessing pool\", BD.pool)\nY = np.reshape(BD * X.ravel(), (10 * Nv, Nh))\nBD.pool.close()\n\nfig, axs = plt.subplots(1, 2, figsize=(10, 3))\nfig.suptitle(\"Block-diagonal\", fontsize=14, fontweight=\"bold\", y=0.95)\nim = axs[0].imshow(X, interpolation=\"nearest\")\naxs[0].axis(\"tight\")\naxs[0].set_title(r\"$x$\")\nplt.colorbar(im, ax=axs[0])\nim = axs[1].imshow(Y, interpolation=\"nearest\")\naxs[1].axis(\"tight\")\naxs[1].set_title(r\"$y$\")\nplt.colorbar(im, ax=axs[1])\nplt.tight_layout()\nplt.subplots_adjust(top=0.8)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Finally we use the *Kronecker operator* and replicate this example on\n[wiki](https://en.wikipedia.org/wiki/Kronecker_product).\n\n   .. math::\n      \\begin{bmatrix}\n          1  & 2  \\\\\n          3  & 4 \\\\\n      \\end{bmatrix} \\otimes\n      \\begin{bmatrix}\n          0  & 5  \\\\\n          6  & 7 \\\\\n      \\end{bmatrix} =\n      \\begin{bmatrix}\n           0 &  5 &  0 & 10 \\\\\n           6 &  7 & 12 & 14 \\\\\n           0 & 15 &  0 & 20 \\\\\n          18 & 21 & 24 & 28 \\\\\n      \\end{bmatrix}\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "A = np.array([[1, 2], [3, 4]])\nB = np.array([[0, 5], [6, 7]])\nAB = np.kron(A, B)\n\nn1, m1 = A.shape\nn2, m2 = B.shape\n\nAop = pylops.MatrixMult(A)\nBop = pylops.MatrixMult(B)\n\nABop = pylops.Kronecker(Aop, Bop)\nx = np.ones(m1 * m2)\n\ny = AB.dot(x)\nyop = ABop * x\nxinv = ABop / yop\n\nprint(f\"AB = \\n {AB}\")\n\nprint(f\"x = {x}\")\nprint(f\"y = {y}\")\nprint(f\"yop = {yop}\")\nprint(f\"xinv = {xinv}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can also use :py:class:`pylops.Kronecker` to do something more\ninteresting. Any operator can in fact be applied on a single direction of a\nmulti-dimensional input array if combined with an :py:class:`pylops.Identity`\noperator via Kronecker product. We apply here the\n:py:class:`pylops.FirstDerivative` to the second dimension of the model.\n\nNote that for those operators whose implementation allows their application\nto a single axis via the ``axis`` parameter, using the Kronecker product\nwould lead to slower performance. Nevertheless, the Kronecker product allows\nany other operator to be applied to a single dimension.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "Nv, Nh = 11, 21\n\nIop = pylops.Identity(Nv, dtype=\"float32\")\nD2hop = pylops.FirstDerivative(Nh, dtype=\"float32\")\n\nX = np.zeros((Nv, Nh))\nX[Nv // 2, Nh // 2] = 1\nD2hop = pylops.Kronecker(Iop, D2hop)\n\nY = D2hop * X.ravel()\nY = Y.reshape(Nv, Nh)\n\nfig, axs = plt.subplots(1, 2, figsize=(10, 3))\nfig.suptitle(\"Kronecker\", fontsize=14, fontweight=\"bold\", y=0.95)\nim = axs[0].imshow(X, interpolation=\"nearest\")\naxs[0].axis(\"tight\")\naxs[0].set_title(r\"$x$\")\nplt.colorbar(im, ax=axs[0])\nim = axs[1].imshow(Y, interpolation=\"nearest\")\naxs[1].axis(\"tight\")\naxs[1].set_title(r\"$y$\")\nplt.colorbar(im, ax=axs[1])\nplt.tight_layout()\nplt.subplots_adjust(top=0.8)"
      ]
    }
  ],
  "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.9.15"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}