
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "auto_examples/rainfarm_downscale.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_rainfarm_downscale.py>`
        to download the full example code.

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

.. _sphx_glr_auto_examples_rainfarm_downscale.py:


Precipitation downscaling with RainFARM
=======================================

This example script shows how to use the stochastic downscaling method RainFARM
available in pysteps.

RainFARM is a downscaling algorithm for rainfall fields developed by Rebora et
al. (2006). The method can represent the realistic small-scale variability of the
downscaled precipitation field by means of Gaussian random fields.

Steps:
    1. Read the input precipitation data.
    2. Upscale the precipitation field.
    3. Downscale the field to its original resolution using RainFARM with defaults.
    4. Downscale with smoothing.
    5. Downscale with spectral fusion.
    6. Downscale with smoothing and spectral fusion.

References:

    Rebora, N., L. Ferraris, J. von Hardenberg, and A. Provenzale, 2006: RainFARM:
    Rainfall downscaling by a filtered autoregressive model. J. Hydrometeor., 7,
    724–738.

    D D'Onofrio, E Palazzi, J von Hardenberg, A Provenzale, and S Calmanti, 2014:
    Stochastic rainfall downscaling of climate models. J. Hydrometeorol., 15(2):830–843.

.. GENERATED FROM PYTHON SOURCE LINES 30-50

.. code-block:: Python


    import logging
    import os
    from datetime import datetime
    from pprint import pprint

    import matplotlib.pyplot as plt
    import numpy as np

    from pysteps import io, rcparams
    from pysteps.downscaling import rainfarm
    from pysteps.utils import aggregate_fields_space, square_domain, to_rainrate
    from pysteps.visualization import plot_precip_field
    from pysteps.xarray_helpers import geodata_from_dataset

    # Configure logging
    logging.basicConfig(
        level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
    )








.. GENERATED FROM PYTHON SOURCE LINES 51-56

Read the input data
-------------------

As first step, we need to import the precipitation field that we are going
to use in this example.

.. GENERATED FROM PYTHON SOURCE LINES 56-96

.. code-block:: Python



    def read_precipitation_data(file_path):
        """Read and process precipitation data from a file."""
        precip_dataset = io.import_mch_gif(
            file_path, product="AQC", unit="mm", accutime=5.0
        )
        # rainfarm.downscale() requires a time dimension, which a single imported
        # frame does not have.
        precip_dataset = precip_dataset.expand_dims(
            time=[np.datetime64(datetime(2016, 7, 11, 19, 32, 10))]
        )
        precip_dataset = to_rainrate(precip_dataset)
        precip_dataset = square_domain(precip_dataset, "crop")
        return precip_dataset


    # Import the example radar composite
    root_path = rcparams.data_sources["mch"]["root_path"]
    filename = os.path.join(root_path, "20160711", "AQC161932100V_00005.801.gif")

    # Read and process data
    precip_dataset = read_precipitation_data(filename)
    precip_var = precip_dataset.attrs["precip_var"]

    # Nicely print the metadata
    pprint(precip_dataset[precip_var].attrs)

    # Plot the original rainfall field
    plot_precip_field(
        precip_dataset[precip_var].isel(time=0),
        geodata=geodata_from_dataset(precip_dataset),
    )
    plt.title("Original Rainfall Field")
    plt.show()

    # Assign the fill value to all the Nans
    precip = precip_dataset[precip_var].values
    precip[~np.isfinite(precip)] = precip_dataset[precip_var].attrs["zerovalue"]




.. image-sg:: /auto_examples/images/sphx_glr_rainfarm_downscale_001.png
   :alt: Original Rainfall Field
   :srcset: /auto_examples/images/sphx_glr_rainfarm_downscale_001.png
   :class: sphx-glr-single-img


.. 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(
    {'accutime': 5.0,
     'long_name': 'instantaneous precipitation rate',
     'standard_name': 'instantaneous_precipitation_rate',
     'threshold': 0.01155375598376629,
     'units': 'mm/h',
     'zerovalue': 0.0,
     'zr_a': 316.0,
     'zr_b': 1.5}




.. GENERATED FROM PYTHON SOURCE LINES 97-104

Upscale the field
-----------------

To test our downscaling method, we first need to upscale the original field to
a lower resolution. This is only for demo purposes, as we need to artificially
create a lower resolution field to apply our downscaling method.
We are going to use a factor of 16 x.

.. GENERATED FROM PYTHON SOURCE LINES 104-124

.. code-block:: Python



    def upscale_field(precip_dataset, scale_factor):
        """Upscale the precipitation field by a given scale factor."""
        upscaled_resolution = precip_dataset.x.attrs["stepsize"] * scale_factor
        return aggregate_fields_space(precip_dataset, upscaled_resolution)


    scale_factor = 16
    precip_dataset_lr = upscale_field(precip_dataset, scale_factor)

    # Plot the upscaled rainfall field
    plt.figure()
    plot_precip_field(
        precip_dataset_lr[precip_var].isel(time=0),
        geodata=geodata_from_dataset(precip_dataset_lr),
    )
    plt.title("Upscaled Rainfall Field")
    plt.show()




.. image-sg:: /auto_examples/images/sphx_glr_rainfarm_downscale_002.png
   :alt: Upscaled Rainfall Field
   :srcset: /auto_examples/images/sphx_glr_rainfarm_downscale_002.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 125-129

Downscale the field
-------------------

We can now use RainFARM to downscale the precipitation field.

.. GENERATED FROM PYTHON SOURCE LINES 129-145

.. code-block:: Python


    # Fixed seed for reproducible stochastic noise fields
    np.random.seed(42)

    # Basic downscaling
    precip_dataset_hr = rainfarm.downscale(precip_dataset_lr, ds_factor=scale_factor)

    # Plot the downscaled rainfall field
    plt.figure()
    plot_precip_field(
        precip_dataset_hr[precip_var].isel(time=0),
        geodata=geodata_from_dataset(precip_dataset),
    )
    plt.title("Downscaled Rainfall Field")
    plt.show()




.. image-sg:: /auto_examples/images/sphx_glr_rainfarm_downscale_003.png
   :alt: Downscaled Rainfall Field
   :srcset: /auto_examples/images/sphx_glr_rainfarm_downscale_003.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 146-150

Downscale with smoothing
------------------------

Add smoothing with a Gaussian kernel during the downscaling process.

.. GENERATED FROM PYTHON SOURCE LINES 150-164

.. code-block:: Python


    precip_dataset_hr_smooth = rainfarm.downscale(
        precip_dataset_lr, ds_factor=scale_factor, kernel_type="gaussian"
    )

    # Plot the downscaled rainfall field with smoothing
    plt.figure()
    plot_precip_field(
        precip_dataset_hr_smooth[precip_var].isel(time=0),
        geodata=geodata_from_dataset(precip_dataset),
    )
    plt.title("Downscaled Rainfall Field with Gaussian Smoothing")
    plt.show()




.. image-sg:: /auto_examples/images/sphx_glr_rainfarm_downscale_004.png
   :alt: Downscaled Rainfall Field with Gaussian Smoothing
   :srcset: /auto_examples/images/sphx_glr_rainfarm_downscale_004.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 165-169

Downscale with spectral fusion
------------------------------

Apply spectral merging as described in D'Onofrio et al. (2014).

.. GENERATED FROM PYTHON SOURCE LINES 169-183

.. code-block:: Python


    precip_dataset_hr_fusion = rainfarm.downscale(
        precip_dataset_lr, ds_factor=scale_factor, spectral_fusion=True
    )

    # Plot the downscaled rainfall field with spectral fusion
    plt.figure()
    plot_precip_field(
        precip_dataset_hr_fusion[precip_var].isel(time=0),
        geodata=geodata_from_dataset(precip_dataset),
    )
    plt.title("Downscaled Rainfall Field with Spectral Fusion")
    plt.show()




.. image-sg:: /auto_examples/images/sphx_glr_rainfarm_downscale_005.png
   :alt: Downscaled Rainfall Field with Spectral Fusion
   :srcset: /auto_examples/images/sphx_glr_rainfarm_downscale_005.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 184-189

Combined Downscale with smoothing and spectral fusion
-----------------------------------------------------

Apply both smoothing with a Gaussian kernel and spectral fusion during the
downscaling process to observe the combined effect.

.. GENERATED FROM PYTHON SOURCE LINES 189-206

.. code-block:: Python


    precip_dataset_hr_combined = rainfarm.downscale(
        precip_dataset_lr,
        ds_factor=scale_factor,
        kernel_type="gaussian",
        spectral_fusion=True,
    )

    # Plot the downscaled rainfall field with smoothing and spectral fusion
    plt.figure()
    plot_precip_field(
        precip_dataset_hr_combined[precip_var].isel(time=0),
        geodata=geodata_from_dataset(precip_dataset),
    )
    plt.title("Downscaled Rainfall Field with Gaussian Smoothing and Spectral Fusion")
    plt.show()




.. image-sg:: /auto_examples/images/sphx_glr_rainfarm_downscale_006.png
   :alt: Downscaled Rainfall Field with Gaussian Smoothing and Spectral Fusion
   :srcset: /auto_examples/images/sphx_glr_rainfarm_downscale_006.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 207-214

Remarks
-------

Currently, the pysteps implementation of RainFARM only covers spatial downscaling.
That is, it can improve the spatial resolution of a rainfall field. However, unlike
the original algorithm from Rebora et al. (2006), it cannot downscale the temporal
dimension.

.. GENERATED FROM PYTHON SOURCE LINES 214-216

.. code-block:: Python


    # sphinx_gallery_thumbnail_number = 2








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

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


.. _sphx_glr_download_auto_examples_rainfarm_downscale.py:

.. only:: html

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

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

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

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

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

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

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


.. only:: html

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

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