{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Transitioning from VTK to PyVista\n\nVTK is primarily developed in C++ and uses chained setter and getter\ncommands to access data. Instead, PyVista wraps the VTK data types into\nnumpy arrays so that users can benefit from its bracket syntax and fancy\nindexing. This section demonstrates the difference between the two\napproaches in a series of examples.\n\nFor example, to hard-code values for a `vtkImageData`{.interpreted-text\nrole=\"vtk\"} data structure using VTK Python\\'s bindings, one would write\nthe following:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from math import cos, sin\n\nimport vtk"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Create values for a 300x300 image dataset\n\nIn our example, we want to have values from the function\n\n``` python\n127.5 + (1.0 + sin(x/25.0)*cos(y/25.0))\n```\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "values = vtk.vtkDoubleArray()\nvalues.SetName(\"values\")\nvalues.SetNumberOfComponents(1)\nvalues.SetNumberOfTuples(300 * 300)\n\nfor x in range(300):\n    for y in range(300):\n        values.SetValue(x * 300 + y, 127.5 + (1.0 + sin(x / 25.0) * cos(y / 25.0)))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Create the image structure\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image_data = vtk.vtkImageData()\nimage_data.SetOrigin(0, 0, 0)\nimage_data.SetSpacing(1, 1, 1)\nimage_data.SetDimensions(300, 300, 1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Assign the values to the image\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image_data.GetPointData().SetScalars(values)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "As you can see, there is quite a bit of boilerplate that goes into the\ncreation of a simple `vtkImageData`{.interpreted-text role=\"vtk\"}\ndataset. PyVista provides much more concise syntax that is more\n\\\"Pythonic\\\". The equivalent code in PyVista is:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\nimport pyvista as pv"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Use the meshgrid function to create 2D \\\"grids\\\" of the x and y values.\nThis section effectively replaces the vtkDoubleArray.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "xi = np.arange(300)\nx, y = np.meshgrid(xi, xi)\nvalues = 127.5 + (1.0 + np.sin(x / 25.0) * np.cos(y / 25.0))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Create the grid. Note how the values must use Fortran ordering.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "grid = pv.ImageData(dimensions=(300, 300, 1))\ngrid.point_data[\"values\"] = values.flatten(order=\"F\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Here, PyVista has done several things for us:\n\n1.  PyVista combines the dimensionality of the data (in the shape of the\n    `numpy.ndarray`{.interpreted-text role=\"class\"}) with the values of\n    the data in one line. VTK uses \\\"tuples\\\" to describe the shape of\n    the data (where it sits in space) and \\\"components\\\" to describe the\n    type of data (1 = scalars/scalar fields, 2 = vectors/vector fields,\n    n = tensors/tensor fields). Here, shape and values are stored\n    concretely in one variable.\n\n2.  `pyvista.ImageData`{.interpreted-text role=\"class\"} wraps\n    `vtkImageData`{.interpreted-text role=\"vtk\"}, just with a different\n    name; they are both containers of evenly spaced points. Your data\n    does not have to be an \\\"image\\\" to use it with\n    `vtkImageData`{.interpreted-text role=\"vtk\"}; rather, like images,\n    values in the dataset are evenly spaced apart like pixels in an\n    image.\n\n    Furthermore, since we know the container is for uniformly spaced\n    data, pyvista sets the origin and spacing by default to `(0, 0, 0)`\n    and `(1, 1, 1)`. This is another great thing about PyVista and\n    Python! Rather than having to know everything about the VTK library\n    up front, you can get started very easily! Once you get more\n    familiar with it and need to do something more complex, you can dive\n    deeper. For example, changing the origin and spacing is as simple\n    as:\n\n    ``` python\n    grid.origin = (10, 20, 10)\n    grid.spacing = (2, 3, 5)\n    ```\n\n3.  The name for the\n    `point_array <pyvista.point_array>`{.interpreted-text role=\"attr\"}\n    is given directly in dictionary-style fashion. Also, since VTK\n    stores data on the heap (linear segments of RAM; a C++ concept), the\n    data must be flattened and put in Fortran ordering (which controls\n    how multidimensional data is laid out in physically 1d memory; numpy\n    uses \\\"C\\\"-style memory layout by default). This is why in our\n    earlier example, the first argument to `SetValue()` was written as\n    `x*300 + y`. Here, numpy takes care of this for us quite nicely and\n    it\\'s made more explicit in the code, following the Python best\n    practice of \\\"Explicit is better than implicit\\\".\n\nFinally, with PyVista, each geometry class contains methods that allow\nyou to immediately plot the mesh without also setting up the plot. For\nexample, in VTK you would have to do:\n\n``` python\nactor = vtk.vtkImageActor()\nactor.GetMapper().SetInputData(image_data)\nren = vtk.vtkRenderer()\nrenWin = vtk.vtkRenderWindow()\nrenWin.AddRenderer(ren)\nrenWin.SetWindowName('ReadSTL')\niren = vtk.vtkRenderWindowInteractor()\niren.SetRenderWindow(renWin)\nren.AddActor(actor)\niren.Initialize()\nrenWin.Render()\niren.Start()\n```\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "However, with PyVista you only need:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "grid.plot(cpos=\"xy\", show_scalar_bar=False, cmap=\"coolwarm\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# PointSet Construction\n\nPyVista heavily relies on NumPy to efficiently allocate and access\nVTK\\'s C arrays. For example, to create an array of points within VTK\none would normally loop through all the points of a list and supply that\nto a `vtkPoints`{.interpreted-text role=\"vtk\"} class. For example:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "vtk_array = vtk.vtkDoubleArray()\nvtk_array.SetNumberOfComponents(3)\nvtk_array.SetNumberOfValues(9)\nvtk_array.SetValue(0, 0)\nvtk_array.SetValue(1, 0)\nvtk_array.SetValue(2, 0)\nvtk_array.SetValue(3, 1)\nvtk_array.SetValue(4, 0)\nvtk_array.SetValue(5, 0)\nvtk_array.SetValue(6, 0.5)\nvtk_array.SetValue(7, 0.667)\nvtk_array.SetValue(8, 0)\nvtk_points = vtk.vtkPoints()\nvtk_points.SetData(vtk_array)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "To do the same within PyVista, you simply need to create a NumPy array:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "np_points = np.array([[0, 0, 0], [1, 0, 0], [0.5, 0.667, 0]])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "::: note\n::: title\nNote\n:::\n\nYou can use `pyvista.vtk_points`{.interpreted-text role=\"func\"} to\nconstruct a `vtkPoints`{.interpreted-text role=\"vtk\"} object, but this\nis unnecessary in almost all situations.\n:::\n\nSince the end goal is to construct a `pyvista.DataSet\n<pyvista.core.dataset.DataSet>`{.interpreted-text role=\"class\"}, you\nwould simply pass the `np_points` array to the\n`pyvista.PolyData`{.interpreted-text role=\"class\"} constructor:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "poly_data = pv.PolyData(np_points)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Whereas in VTK you would have to do:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "vtk_poly_data = vtk.vtkPolyData()\nvtk_poly_data.SetPoints(vtk_points)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The same goes with assigning face or cell connectivity/topology. With\nVTK you would normally have to loop using\n`InsertNextCell`{.interpreted-text role=\"func\"} and\n`InsertCellPoint`{.interpreted-text role=\"func\"}. For example, to create\na single cell (triangle) and then assign it to\n`vtkPolyData`{.interpreted-text role=\"vtk\"}:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "cell_arr = vtk.vtkCellArray()\ncell_arr.InsertNextCell(3)\ncell_arr.InsertCellPoint(0)\ncell_arr.InsertCellPoint(1)\ncell_arr.InsertCellPoint(2)\nvtk_poly_data.SetPolys(cell_arr)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "In PyVista, we can assign this directly in the constructor and then\naccess it (or change it) from the `faces\n<pyvista.PolyData.faces>`{.interpreted-text role=\"attr\"} attribute.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "faces = np.array([3, 0, 1, 2])\npoly_data = pv.PolyData(np_points, faces)\npoly_data.faces"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# PyVista Tradeoffs\n\nWhile most features can, not everything can be simplified in PyVista\nwithout losing functionality or performance.\n\nIn the `collision <pyvista.PolyDataFilters.collision>`{.interpreted-text\nrole=\"class\"} filter, we demonstrate how to calculate the collision\nbetween two meshes. For example:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# create a default sphere and a shifted sphere\nmesh_a = pv.Sphere()\nmesh_b = pv.Sphere(center=(-0.4, 0, 0))\nout, n_coll = mesh_a.collision(mesh_b, generate_scalars=True, contact_mode=2)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "pl = pv.Plotter()\npl.add_mesh(out)\npl.add_mesh(mesh_b, style=\"wireframe\", color=\"k\")\npl.camera_position = \"xy\"\npl.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Under the hood, the collision filter detects mesh collisions using\noriented bounding box (OBB) trees. For a single collision, this filter\nis as performant as the VTK counterpart, but when computing multiple\ncollisions with the same meshes, as in the [Collision\nExample](https://docs.pyvista.org/examples/01-filter/collisions.html)\nexample, it is more efficient to use the\n[vtkCollisionDetectionFilter](https://vtk.org/doc/nightly/html/classvtkCollisionDetectionFilter.html),\nas the OBB tree is computed once for each mesh. In most cases, pure\nPyVista is sufficient for most data science, but there are times when\nyou may want to use VTK classes directly.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "```{=html}\n<center>\n  <a target=\"_blank\" href=\"https://colab.research.google.com/github/pyvista/pyvista-tutorial/blob/gh-pages/notebooks/tutorial/06_vtk/a_1_transition_vtk.ipynb\">\n    <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/ width=\"150px\">\n  </a>\n</center>\n```\n"
      ]
    }
  ],
  "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.12.11"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}