
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "auto_examples/plot_optical_flow.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_auto_examples_plot_optical_flow.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_auto_examples_plot_optical_flow.py:


Optical flow
============

This tutorial offers a short overview of the optical flow routines available in
pysteps and it will cover how to compute and plot the motion field from a
sequence of radar images.

.. GENERATED FROM PYTHON SOURCE LINES 9-21

.. code-block:: Python


    from datetime import datetime
    from pprint import pprint

    import matplotlib.pyplot as plt
    import numpy as np

    from pysteps import io, motion, rcparams
    from pysteps.utils import conversion, transformation
    from pysteps.visualization import plot_precip_field, quiver
    from pysteps.xarray_helpers import geodata_from_dataset








.. GENERATED FROM PYTHON SOURCE LINES 22-28

Read the radar input images
---------------------------

First, we will import the sequence of radar composites.
You need the pysteps-data archive downloaded and the pystepsrc file
configured with the data_source paths pointing to data folders.

.. GENERATED FROM PYTHON SOURCE LINES 28-33

.. code-block:: Python


    # Selected case
    date = datetime.strptime("201505151630", "%Y%m%d%H%M")
    data_source = rcparams.data_sources["mch"]








.. GENERATED FROM PYTHON SOURCE LINES 34-36

Load the data from the archive
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. GENERATED FROM PYTHON SOURCE LINES 36-54

.. code-block:: Python


    root_path = data_source["root_path"]
    path_fmt = data_source["path_fmt"]
    fn_pattern = data_source["fn_pattern"]
    fn_ext = data_source["fn_ext"]
    importer_name = data_source["importer"]
    importer_kwargs = data_source["importer_kwargs"]
    timestep = data_source["timestep"]

    # Find the input files from the archive
    fns = io.archive.find_by_date(
        date, root_path, path_fmt, fn_pattern, fn_ext, timestep=5, num_prev_files=9
    )

    # Read the radar composites
    importer = io.get_method(importer_name, "importer")
    precip_dataset = io.read_timeseries(fns, importer, **importer_kwargs)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    /home/docs/checkouts/pysteps/checkouts/631/pysteps/xarray_helpers.py:94: UserWarning: No CF grid mapping available for projection 'somerc'; the dataset is created without a grid_mapping attribute
      warnings.warn(
    /home/docs/checkouts/pysteps/checkouts/631/pysteps/xarray_helpers.py:94: UserWarning: No CF grid mapping available for projection 'somerc'; the dataset is created without a grid_mapping attribute
      warnings.warn(
    /home/docs/checkouts/pysteps/checkouts/631/pysteps/xarray_helpers.py:94: UserWarning: No CF grid mapping available for projection 'somerc'; the dataset is created without a grid_mapping attribute
      warnings.warn(
    /home/docs/checkouts/pysteps/checkouts/631/pysteps/xarray_helpers.py:94: UserWarning: No CF grid mapping available for projection 'somerc'; the dataset is created without a grid_mapping attribute
      warnings.warn(
    /home/docs/checkouts/pysteps/checkouts/631/pysteps/xarray_helpers.py:94: UserWarning: No CF grid mapping available for projection 'somerc'; the dataset is created without a grid_mapping attribute
      warnings.warn(
    /home/docs/checkouts/pysteps/checkouts/631/pysteps/xarray_helpers.py:94: UserWarning: No CF grid mapping available for projection 'somerc'; the dataset is created without a grid_mapping attribute
      warnings.warn(
    /home/docs/checkouts/pysteps/checkouts/631/pysteps/xarray_helpers.py:94: UserWarning: No CF grid mapping available for projection 'somerc'; the dataset is created without a grid_mapping attribute
      warnings.warn(
    /home/docs/checkouts/pysteps/checkouts/631/pysteps/xarray_helpers.py:94: UserWarning: No CF grid mapping available for projection 'somerc'; the dataset is created without a grid_mapping attribute
      warnings.warn(
    /home/docs/checkouts/pysteps/checkouts/631/pysteps/xarray_helpers.py:94: UserWarning: No CF grid mapping available for projection 'somerc'; the dataset is created without a grid_mapping attribute
      warnings.warn(
    /home/docs/checkouts/pysteps/checkouts/631/pysteps/xarray_helpers.py:94: UserWarning: No CF grid mapping available for projection 'somerc'; the dataset is created without a grid_mapping attribute
      warnings.warn(
    /home/docs/checkouts/pysteps/checkouts/631/pysteps/xarray_helpers.py:94: UserWarning: No CF grid mapping available for projection 'somerc'; the dataset is created without a grid_mapping attribute
      warnings.warn(




.. GENERATED FROM PYTHON SOURCE LINES 55-57

Preprocess the data
~~~~~~~~~~~~~~~~~~~

.. GENERATED FROM PYTHON SOURCE LINES 57-76

.. code-block:: Python


    # Convert to mm/h
    precip_dataset = conversion.to_rainrate(precip_dataset)
    precip_var = precip_dataset.attrs["precip_var"]

    # Derive the geodata needed by the plotting functions from the dataset
    geodata = geodata_from_dataset(precip_dataset)

    # Store the reference frame (in mm/h, for plotting)
    R_ = precip_dataset[precip_var][-1].copy()

    # Log-transform the data [dBR]
    precip_dataset = transformation.dB_transform(
        precip_dataset, threshold=0.1, zerovalue=-15.0
    )

    # Nicely print the attributes of the precipitation variable
    pprint(precip_dataset[precip_var].attrs)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    {'accutime': 5,
     'long_name': 'instantaneous precipitation rate',
     'standard_name': 'instantaneous_precipitation_rate',
     'threshold': -10.0,
     'transform': 'dB',
     'units': 'mm/h',
     'zerovalue': -15.0,
     'zr_a': 316.0,
     'zr_b': 1.5}




.. GENERATED FROM PYTHON SOURCE LINES 77-85

Lucas-Kanade (LK)
-----------------

The Lucas-Kanade optical flow method implemented in pysteps is a local
tracking approach that relies on the OpenCV package.
Local features are tracked in a sequence of two or more radar images. The
scheme includes a final interpolation step in order to produce a smooth
field of motion vectors.

.. GENERATED FROM PYTHON SOURCE LINES 85-95

.. code-block:: Python


    oflow_method = motion.get_method("LK")
    dataset_lk = oflow_method(precip_dataset.isel(time=slice(-3, None)))
    V1 = np.stack([dataset_lk["velocity_x"].values, dataset_lk["velocity_y"].values])

    # Plot the motion field on top of the reference frame
    plot_precip_field(R_, geodata=geodata, title="LK")
    quiver(V1, geodata=geodata, step=25)
    plt.show()




.. image-sg:: /auto_examples/images/sphx_glr_plot_optical_flow_001.png
   :alt: LK
   :srcset: /auto_examples/images/sphx_glr_plot_optical_flow_001.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 96-105

Variational echo tracking (VET)
-------------------------------

This module implements the VET algorithm presented
by Laroche and Zawadzki (1995) and used in the McGill Algorithm for
Prediction by Lagrangian Extrapolation (MAPLE) described in
Germann and Zawadzki (2002).
The approach essentially consists of a global optimization routine that seeks
at minimizing a cost function between the displaced and the reference image.

.. GENERATED FROM PYTHON SOURCE LINES 105-115

.. code-block:: Python


    oflow_method = motion.get_method("VET")
    dataset_vet = oflow_method(precip_dataset.isel(time=slice(-3, None)))
    V2 = np.stack([dataset_vet["velocity_x"].values, dataset_vet["velocity_y"].values])

    # Plot the motion field
    plot_precip_field(R_, geodata=geodata, title="VET")
    quiver(V2, geodata=geodata, step=25)
    plt.show()




.. image-sg:: /auto_examples/images/sphx_glr_plot_optical_flow_002.png
   :alt: VET
   :srcset: /auto_examples/images/sphx_glr_plot_optical_flow_002.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    Running VET algorithm
    original image shape: (3, 640, 710)
    padded image shape: (3, 640, 710)
    padded template_image image shape: (3, 640, 710)

    Number of sectors: 2,2
    Sector Shape: (320, 355)
    Minimizing

    residuals 3102581.058171572
    smoothness_penalty 0.0
    original image shape: (3, 640, 710)
    padded image shape: (3, 640, 712)
    padded template_image image shape: (3, 640, 712)

    Number of sectors: 4,4
    Sector Shape: (160, 178)
    Minimizing

    residuals 2507935.736544226
    smoothness_penalty 0.4989386451280967
    original image shape: (3, 640, 710)
    padded image shape: (3, 640, 720)
    padded template_image image shape: (3, 640, 720)

    Number of sectors: 16,16
    Sector Shape: (40, 45)
    Minimizing

    residuals 2289251.3959263084
    smoothness_penalty 56.47962040816192
    original image shape: (3, 640, 710)
    padded image shape: (3, 640, 736)
    padded template_image image shape: (3, 640, 736)

    Number of sectors: 32,32
    Sector Shape: (20, 23)
    Minimizing

    residuals 2276571.7684135954
    smoothness_penalty 193.45231752050685




.. GENERATED FROM PYTHON SOURCE LINES 116-125

Dynamic and adaptive radar tracking of storms (DARTS)
-----------------------------------------------------

DARTS uses a spectral approach to optical flow that is based on the discrete
Fourier transform (DFT) of a temporal sequence of radar fields.
The level of truncation of the DFT coefficients controls the degree of
smoothness of the estimated motion field, allowing for an efficient
motion estimation. DARTS requires a longer sequence of radar fields for
estimating the motion, here we are going to use all the available 10 fields.

.. GENERATED FROM PYTHON SOURCE LINES 125-141

.. code-block:: Python


    # Fill missing values with the fill value before running DARTS
    zerovalue = precip_dataset[precip_var].attrs["zerovalue"]
    precip_dataset[precip_var] = precip_dataset[precip_var].where(
        np.isfinite(precip_dataset[precip_var]), zerovalue
    )

    oflow_method = motion.get_method("DARTS")
    dataset_darts = oflow_method(precip_dataset)  # needs longer training sequence
    V3 = np.stack([dataset_darts["velocity_x"].values, dataset_darts["velocity_y"].values])

    # Plot the motion field
    plot_precip_field(R_, geodata=geodata, title="DARTS")
    quiver(V3, geodata=geodata, step=25)
    plt.show()




.. image-sg:: /auto_examples/images/sphx_glr_plot_optical_flow_003.png
   :alt: DARTS
   :srcset: /auto_examples/images/sphx_glr_plot_optical_flow_003.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    Computing the motion field with the DARTS method.
    -----
    DARTS
    -----
      Computing the FFT of the reflectivity fields...Done in 0.15 seconds.
      Constructing the y-vector...Done in 0.06 seconds.
      Constructing the H-matrix...Done in 0.80 seconds.
      Solving the linear systems...Done in 0.08 seconds.
    --- 1.1212835311889648 seconds ---




.. GENERATED FROM PYTHON SOURCE LINES 142-148

Anisotropic diffusion method (Proesmans et al 1994)
---------------------------------------------------

This module implements the anisotropic diffusion method presented in Proesmans
et al. (1994), a robust optical flow technique which employs the notion of
inconsistency during the solution of the optical flow equations.

.. GENERATED FROM PYTHON SOURCE LINES 148-160

.. code-block:: Python


    oflow_method = motion.get_method("proesmans")
    dataset_proesmans = oflow_method(precip_dataset.isel(time=slice(-2, None)))
    V4 = np.stack(
        [dataset_proesmans["velocity_x"].values, dataset_proesmans["velocity_y"].values]
    )

    # Plot the motion field
    plot_precip_field(R_, geodata=geodata, title="Proesmans")
    quiver(V4, geodata=geodata, step=25)
    plt.show()




.. image-sg:: /auto_examples/images/sphx_glr_plot_optical_flow_004.png
   :alt: Proesmans
   :srcset: /auto_examples/images/sphx_glr_plot_optical_flow_004.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 161-168

Farnebäck smoothed method
-------------------------

This module implements the pyramidal decomposition method for motion estimation
of Farnebäck as implemented in OpenCV, with an option for smoothing and
renormalization of the motion fields proposed by Driedger et al.:
https://cmosarchives.ca/Congress_P_A/program_abstracts2022.pdf (p. 392).

.. GENERATED FROM PYTHON SOURCE LINES 168-183

.. code-block:: Python


    oflow_method = motion.get_method("farneback")
    dataset_farneback = oflow_method(
        precip_dataset.isel(time=slice(-2, None)), verbose=True
    )
    V5 = np.stack(
        [dataset_farneback["velocity_x"].values, dataset_farneback["velocity_y"].values]
    )

    # Plot the motion field
    plot_precip_field(R_, geodata=geodata, title="Farneback")
    quiver(V5, geodata=geodata, step=25)
    plt.show()

    # sphinx_gallery_thumbnail_number = 1



.. image-sg:: /auto_examples/images/sphx_glr_plot_optical_flow_005.png
   :alt: Farneback
   :srcset: /auto_examples/images/sphx_glr_plot_optical_flow_005.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    Computing the motion field with the Farneback method.
    mult factor of smoothed motion field= 1.7847746191151432
    --- 0.3319547176361084 seconds ---





.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (0 minutes 32.929 seconds)


.. _sphx_glr_download_auto_examples_plot_optical_flow.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: plot_optical_flow.ipynb <plot_optical_flow.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: plot_optical_flow.py <plot_optical_flow.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: plot_optical_flow.zip <plot_optical_flow.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
