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

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

.. _sphx_glr_auto_examples_parallel_memmap.py:


===============================
NumPy memmap in joblib.Parallel
===============================

This example illustrates some features enabled by using a memory map
(:class:`numpy.memmap`) within :class:`joblib.Parallel`. First, we show that
dumping a huge data array ahead of passing it to :class:`joblib.Parallel`
speeds up computation. Then, we show the possibility to provide write access to
original data.

.. GENERATED FROM PYTHON SOURCE LINES 15-20

Speed up processing of a large data array
#############################################################################

 We create a large data array for which the average is computed for several
 slices.

.. GENERATED FROM PYTHON SOURCE LINES 20-28

.. code-block:: default


    import numpy as np

    data = np.random.random((int(1e7),))
    window_size = int(5e5)
    slices = [slice(start, start + window_size)
              for start in range(0, data.size - window_size, int(1e5))]








.. GENERATED FROM PYTHON SOURCE LINES 29-33

The ``slow_mean`` function introduces a :func:`time.sleep` call to simulate a
more expensive computation cost for which parallel computing is beneficial.
Parallel may not be beneficial for very fast operation, due to extra overhead
(workers creations, communication, etc.).

.. GENERATED FROM PYTHON SOURCE LINES 33-43

.. code-block:: default


    import time


    def slow_mean(data, sl):
        """Simulate a time consuming processing."""
        time.sleep(0.01)
        return data[sl].mean()









.. GENERATED FROM PYTHON SOURCE LINES 44-45

First, we will evaluate the sequential computing on our problem.

.. GENERATED FROM PYTHON SOURCE LINES 45-52

.. code-block:: default


    tic = time.time()
    results = [slow_mean(data, sl) for sl in slices]
    toc = time.time()
    print('\nElapsed time computing the average of couple of slices {:.2f} s'
          .format(toc - tic))





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

 .. code-block:: none


    Elapsed time computing the average of couple of slices 1.03 s




.. GENERATED FROM PYTHON SOURCE LINES 53-55

:class:`joblib.Parallel` is used to compute in parallel the average of all
slices using 2 workers.

.. GENERATED FROM PYTHON SOURCE LINES 55-65

.. code-block:: default


    from joblib import Parallel, delayed


    tic = time.time()
    results = Parallel(n_jobs=2)(delayed(slow_mean)(data, sl) for sl in slices)
    toc = time.time()
    print('\nElapsed time computing the average of couple of slices {:.2f} s'
          .format(toc - tic))





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

 .. code-block:: none


    Elapsed time computing the average of couple of slices 0.69 s




.. GENERATED FROM PYTHON SOURCE LINES 66-69

Parallel processing is already faster than the sequential processing. It is
also possible to remove a bit of overhead by dumping the ``data`` array to a
memmap and pass the memmap to :class:`joblib.Parallel`.

.. GENERATED FROM PYTHON SOURCE LINES 69-89

.. code-block:: default


    import os
    from joblib import dump, load

    folder = './joblib_memmap'
    try:
        os.mkdir(folder)
    except FileExistsError:
        pass

    data_filename_memmap = os.path.join(folder, 'data_memmap')
    dump(data, data_filename_memmap)
    data = load(data_filename_memmap, mmap_mode='r')

    tic = time.time()
    results = Parallel(n_jobs=2)(delayed(slow_mean)(data, sl) for sl in slices)
    toc = time.time()
    print('\nElapsed time computing the average of couple of slices {:.2f} s\n'
          .format(toc - tic))





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

 .. code-block:: none


    Elapsed time computing the average of couple of slices 0.55 s





.. GENERATED FROM PYTHON SOURCE LINES 90-93

Therefore, dumping large ``data`` array ahead of calling
:class:`joblib.Parallel` can speed up the processing by removing some
overhead.

.. GENERATED FROM PYTHON SOURCE LINES 95-101

Writable memmap for shared memory :class:`joblib.Parallel`
##############################################################################

 ``slow_mean_write_output`` will compute the mean for some given slices as in
 the previous example. However, the resulting mean will be directly written on
 the output array.

.. GENERATED FROM PYTHON SOURCE LINES 101-111

.. code-block:: default



    def slow_mean_write_output(data, sl, output, idx):
        """Simulate a time consuming processing."""
        time.sleep(0.005)
        res_ = data[sl].mean()
        print("[Worker %d] Mean for slice %d is %f" % (os.getpid(), idx, res_))
        output[idx] = res_









.. GENERATED FROM PYTHON SOURCE LINES 112-113

Prepare the folder where the memmap will be dumped.

.. GENERATED FROM PYTHON SOURCE LINES 113-116

.. code-block:: default


    output_filename_memmap = os.path.join(folder, 'output_memmap')








.. GENERATED FROM PYTHON SOURCE LINES 117-119

Pre-allocate a writable shared memory map as a container for the results of
the parallel computation.

.. GENERATED FROM PYTHON SOURCE LINES 119-123

.. code-block:: default


    output = np.memmap(output_filename_memmap, dtype=data.dtype,
                       shape=len(slices), mode='w+')








.. GENERATED FROM PYTHON SOURCE LINES 124-126

``data`` is replaced by its memory mapped version. Note that the buffer has
already been dumped in the previous section.

.. GENERATED FROM PYTHON SOURCE LINES 126-129

.. code-block:: default


    data = load(data_filename_memmap, mmap_mode='r')








.. GENERATED FROM PYTHON SOURCE LINES 130-131

Fork the worker processes to perform computation concurrently

.. GENERATED FROM PYTHON SOURCE LINES 131-135

.. code-block:: default


    Parallel(n_jobs=2)(delayed(slow_mean_write_output)(data, sl, output, idx)
                       for idx, sl in enumerate(slices))





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

 .. code-block:: none


    [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]



.. GENERATED FROM PYTHON SOURCE LINES 136-137

Compare the results from the output buffer with the expected results

.. GENERATED FROM PYTHON SOURCE LINES 137-143

.. code-block:: default


    print("\nExpected means computed in the parent process:\n {}"
          .format(np.array(results)))
    print("\nActual means computed by the worker processes:\n {}"
          .format(output))





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

 .. code-block:: none


    Expected means computed in the parent process:
     [0.49938772 0.49957731 0.49981388 0.49998068 0.50033405 0.50058459
     0.50084974 0.50052782 0.5002998  0.49981188 0.49973585 0.49930386
     0.49946966 0.49982362 0.49989812 0.50005761 0.50022813 0.50036417
     0.50037863 0.50061658 0.50047023 0.50033409 0.49992437 0.49983956
     0.49960614 0.49970635 0.4998021  0.50005365 0.49981809 0.50006805
     0.49986537 0.50010355 0.49994625 0.4996919  0.49924693 0.4992618
     0.49913705 0.49965271 0.50007203 0.50011949 0.50031926 0.50007936
     0.49976376 0.50012115 0.50065917 0.50079988 0.50082599 0.50090394
     0.50033628 0.50031667 0.50023669 0.50023348 0.49979201 0.49993107
     0.49995423 0.49985516 0.49998951 0.50021489 0.49989346 0.49955447
     0.49958276 0.49944213 0.49918285 0.49961539 0.49988597 0.49972303
     0.50004012 0.50041844 0.50037167 0.50037686 0.50020504 0.49996269
     0.49981202 0.49993143 0.49967857 0.49968687 0.49989744 0.49991846
     0.49983875 0.49986864 0.50031798 0.5001349  0.50016377 0.50028003
     0.50033192 0.5001601  0.5000785  0.49979277 0.49959958 0.49982407
     0.49967283 0.49960507 0.4999387  0.49983152 0.49953925]

    Actual means computed by the worker processes:
     [0.49938772 0.49957731 0.49981388 0.49998068 0.50033405 0.50058459
     0.50084974 0.50052782 0.5002998  0.49981188 0.49973585 0.49930386
     0.49946966 0.49982362 0.49989812 0.50005761 0.50022813 0.50036417
     0.50037863 0.50061658 0.50047023 0.50033409 0.49992437 0.49983956
     0.49960614 0.49970635 0.4998021  0.50005365 0.49981809 0.50006805
     0.49986537 0.50010355 0.49994625 0.4996919  0.49924693 0.4992618
     0.49913705 0.49965271 0.50007203 0.50011949 0.50031926 0.50007936
     0.49976376 0.50012115 0.50065917 0.50079988 0.50082599 0.50090394
     0.50033628 0.50031667 0.50023669 0.50023348 0.49979201 0.49993107
     0.49995423 0.49985516 0.49998951 0.50021489 0.49989346 0.49955447
     0.49958276 0.49944213 0.49918285 0.49961539 0.49988597 0.49972303
     0.50004012 0.50041844 0.50037167 0.50037686 0.50020504 0.49996269
     0.49981202 0.49993143 0.49967857 0.49968687 0.49989744 0.49991846
     0.49983875 0.49986864 0.50031798 0.5001349  0.50016377 0.50028003
     0.50033192 0.5001601  0.5000785  0.49979277 0.49959958 0.49982407
     0.49967283 0.49960507 0.4999387  0.49983152 0.49953925]




.. GENERATED FROM PYTHON SOURCE LINES 144-149

Clean-up the memmap
##############################################################################

 Remove the different memmap that we created. It might fail in Windows due
 to file permissions.

.. GENERATED FROM PYTHON SOURCE LINES 149-156

.. code-block:: default


    import shutil

    try:
        shutil.rmtree(folder)
    except:  # noqa
        print('Could not clean-up automatically.')








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

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


.. _sphx_glr_download_auto_examples_parallel_memmap.py:

.. only:: html

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




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

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

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

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


.. only:: html

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

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