
"""simple docstring"""

import json
import os
import pickle
import subprocess
from hashlib import mda
from pathlib import Path
from tempfile import gettempdir
from textwrap import dedent
from types import CodeType, FunctionType
from unittest import TestCase
from unittest.mock import patch

import pytest
from multiprocess import Pool
from packaging import version

import datasets
from datasets.fingerprint import Hasher, fingerprint_transform
from datasets.table import InMemoryTable

from .utils import (
    require_regex,
    require_spacy,
    require_spacy_model,
    require_tiktoken,
    require_torch,
    require_transformers,
)
class    _UpperCAmelCase							:




      def __init__(							self      ,				lowercase_							)  ->    List[Any]:
          UpperCAmelCase  	=    foo




      def __call__(							self							)  ->    Tuple:
          return self.foo

class    _UpperCAmelCase							(						datasets.Dataset							):




      @fingerprint_transform(inplace=lowercase_							)
      def 			a_					(							self      ,				lowercase_      ,				*lowercase_      ,				**lowercase_							)  ->    Dict:
          return DatasetChild(self.data      ,				fingerprint=lowercase_							)




      @fingerprint_transform(inplace=lowercase_							)
      def 			a_					(							self      ,				lowercase_      ,				*lowercase_      ,				**lowercase_							)  ->    Dict:
          return DatasetChild(self.data      ,				fingerprint=lowercase_							)

class    _UpperCAmelCase							:




      def __init__(							self      ,				lowercase_							)  ->    str:
          UpperCAmelCase  	=    callable




      def __call__(							self      ,				*lowercase_      ,				**lowercase_							)  ->    Tuple:
          if self.callable is not None:
              return self.callable(*lowercase_      ,				**lowercase_							)




      def __getstate__(							self							)  ->    int:
          raise pickle.PicklingError()

class    _UpperCAmelCase							(						SCREAMING_SNAKE_CASE_							):




      @require_transformers
      @pytest.mark.integration
      def 			a_					(							self							)  ->    str:
          from transformers import AutoTokenizer

          def encode(lowercase_							):
              return tokenizer(lowercase_							)

          # TODO: add hash consistency tests across sessions
          UpperCAmelCase  	=    AutoTokenizer.from_pretrained('bert-base-uncased'							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lambda lowercase_							: tokenizer(lowercase_							)							)							).hexdigest()
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    AutoTokenizer.from_pretrained('bert-base-cased'							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lambda lowercase_							: tokenizer(lowercase_							)							)							).hexdigest()
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    AutoTokenizer.from_pretrained('bert-base-uncased'							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lambda lowercase_							: tokenizer(lowercase_							)							)							).hexdigest()
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)




      @require_transformers
      @pytest.mark.integration
      def 			a_					(							self							)  ->    Any:
          from transformers import AutoTokenizer

          UpperCAmelCase  	=    AutoTokenizer.from_pretrained('gpt2'							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          tokenizer('Hello world !'							)  # call once to change the tokenizer's cache
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          self.assertEqual(lowercase_      ,				lowercase_							)




      @require_regex
      def 			a_					(							self							)  ->    int:
          import regex

          UpperCAmelCase  	=    regex.Regex('foo'							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    regex.Regex('bar'							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    regex.Regex('foo'							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)

class    _UpperCAmelCase							(						SCREAMING_SNAKE_CASE_							):




      def 			a_					(							self							)  ->    Tuple:
          def func():
              return foo

          UpperCAmelCase  	=    [0]
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    [1]
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    [0]
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)




      def 			a_					(							self							)  ->    Optional[Any]:
          def func():
              pass

          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()

          def func():
              pass

          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          self.assertEqual(lowercase_      ,				lowercase_							)




      def 			a_					(							self							)  ->    List[str]:
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(Foo([0]							)							)							).hexdigest()
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(Foo([1]							)							)							).hexdigest()
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(Foo([0]							)							)							).hexdigest()
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)




      def 			a_					(							self							)  ->    Optional[Any]:
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(Foo([0]							).__call__							)							).hexdigest()
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(Foo([1]							).__call__							)							).hexdigest()
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(Foo([0]							).__call__							)							).hexdigest()
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)




      def 			a_					(							self							)  ->    Union[str, Any]:
          UpperCAmelCase  	=    (
              'co_argcount',
              'co_kwonlyargcount',
              'co_nlocals',
              'co_stacksize',
              'co_flags',
              'co_code',
              'co_consts',
              'co_names',
              'co_varnames',
              'co_filename',
              'co_name',
              'co_firstlineno',
              'co_lnotab',
              'co_freevars',
              'co_cellvars',
          )

          def _create_code_pyaa(*lowercase_							):
              if hasattr(args[-3]      ,				'encode'							):
                  UpperCAmelCase  	=    list(lowercase_							)
                  UpperCAmelCase  	=    args[-3].encode()  # co_lnotab
                  UpperCAmelCase  	=    args[-1_0].encode()  # co_code
              if hasattr(lowercase_      ,				'co_posonlyargcount'							):
                  if len(lowercase_							) == 1_6:
                      return CodeType(*lowercase_							)
                  elif len(lowercase_							) == 1_5:
                      return CodeType(args[0]      ,				0      ,				*args[1:]							)
                  return CodeType(args[0]      ,				0      ,				0      ,				*args[1:]							)
              elif hasattr(lowercase_      ,				'co_kwonlyargcount'							):
                  if len(lowercase_							) == 1_6:
                      return CodeType(args[0]      ,				*args[2:]							)
                  elif len(lowercase_							) == 1_5:
                      return CodeType(*lowercase_							)
                  return CodeType(args[0]      ,				0      ,				*args[1:]							)
              if len(lowercase_							) == 1_6:
                  return CodeType(args[0]      ,				*args[3:]							)
              elif len(lowercase_							) == 1_5:
                  return CodeType(args[0]      ,				*args[2:]							)
              return CodeType(*lowercase_							)

          def create_ipython_func(lowercase_      ,				lowercase_							):
              def func():
                  return returned_obj

              UpperCAmelCase  	=    func.__code__
              # Use _create_code from dill in order to make it work for different python versions
              if datasets.config.PY_VERSION < version.parse('3.8'							):
                  UpperCAmelCase  	=    _create_code_pyaa(
                      *[getattr(lowercase_      ,				lowercase_							) if k != 'co_filename' else co_filename for k in code_args_pyaa]							)
              else:
                  UpperCAmelCase  	=    code.replace(co_filename=lowercase_							)
              return FunctionType(lowercase_      ,				func.__globals__      ,				func.__name__      ,				func.__defaults__      ,				func.__closure__							)

          UpperCAmelCase	,							UpperCAmelCase  	=    '<ipython-input-2-e0383a102aae>', [0]
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(create_ipython_func(lowercase_      ,				lowercase_							)							)							).hexdigest()
          UpperCAmelCase	,							UpperCAmelCase  	=    '<ipython-input-2-e0383a102aae>', [1]
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(create_ipython_func(lowercase_      ,				lowercase_							)							)							).hexdigest()
          UpperCAmelCase	,							UpperCAmelCase  	=    '<ipython-input-5-713f6613acf3>', [0]
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(create_ipython_func(lowercase_      ,				lowercase_							)							)							).hexdigest()
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)

          UpperCAmelCase	,							UpperCAmelCase  	=    os.path.join(gettempdir()      ,				'ipykernel_12345'      ,				'321456789.py'							), [0]
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(create_ipython_func(lowercase_      ,				lowercase_							)							)							).hexdigest()
          UpperCAmelCase	,							UpperCAmelCase  	=    os.path.join(gettempdir()      ,				'ipykernel_12345'      ,				'321456789.py'							), [1]
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(create_ipython_func(lowercase_      ,				lowercase_							)							)							).hexdigest()
          UpperCAmelCase	,							UpperCAmelCase  	=    os.path.join(gettempdir()      ,				'ipykernel_12345'      ,				'654123987.py'							), [0]
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(create_ipython_func(lowercase_      ,				lowercase_							)							)							).hexdigest()
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)




      def 			a_					(							self							)  ->    str:
          UpperCAmelCase	,							UpperCAmelCase  	=    [0], [1]

          def func():
              return foo, bar

          UpperCAmelCase  	=    '__main__'

          def globalvars_mocka_side_effect(lowercase_      ,				*lowercase_      ,				**lowercase_							):
              return {"foo": foo, "bar": bar}

          def globalvars_mocka_side_effect(lowercase_      ,				*lowercase_      ,				**lowercase_							):
              return {"bar": bar, "foo": foo}

          with patch('dill.detect.globalvars'      ,				side_effect=lowercase_							) as globalvars_mocka:
              UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
              self.assertGreater(globalvars_mocka.call_count      ,				0							)
          with patch('dill.detect.globalvars'      ,				side_effect=lowercase_							) as globalvars_mocka:
              UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
              self.assertGreater(globalvars_mocka.call_count      ,				0							)
          self.assertEqual(lowercase_      ,				lowercase_							)

class    _UpperCAmelCase							(						SCREAMING_SNAKE_CASE_							):




      def 			a_					(							self							)  ->    int:
          UpperCAmelCase  	=    Hasher.hash('hello'							)
          UpperCAmelCase  	=    Hasher.hash('hello'							)
          UpperCAmelCase  	=    Hasher.hash('there'							)
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)




      def 			a_					(							self							)  ->    int:
          UpperCAmelCase  	=    Hasher.hash(Foo('hello'							)							)
          UpperCAmelCase  	=    Hasher.hash(Foo('hello'							)							)
          UpperCAmelCase  	=    Hasher.hash(Foo('there'							)							)
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)




      def 			a_					(							self							)  ->    int:
          UpperCAmelCase  	=    Hasher()
          for x in ["hello", Foo('hello'							)]:
              hasher.update(lowercase_							)
          UpperCAmelCase  	=    hasher.hexdigest()
          UpperCAmelCase  	=    Hasher()
          for x in ["hello", Foo('hello'							)]:
              hasher.update(lowercase_							)
          UpperCAmelCase  	=    hasher.hexdigest()
          UpperCAmelCase  	=    Hasher()
          for x in ["there", Foo('there'							)]:
              hasher.update(lowercase_							)
          UpperCAmelCase  	=    hasher.hexdigest()
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)




      def 			a_					(							self							)  ->    Optional[Any]:
          with self.assertRaises(pickle.PicklingError							):
              Hasher.hash(UnpicklableCallable(Foo('hello'							)							)							)




      def 			a_					(							self							)  ->    List[Any]:
          UpperCAmelCase  	=    'abc'
          UpperCAmelCase  	=    [string, string]  # two strings have the same ids
          UpperCAmelCase  	=    [string, string]
          UpperCAmelCase  	=    json.loads(F"[\"{string}\", \"{string}\"]"							)  # two strings have different ids
          self.assertIs(obja[0]      ,				lowercase_							)
          self.assertIs(obja[0]      ,				obja[1]							)
          self.assertIs(obja[0]      ,				lowercase_							)
          self.assertIs(obja[0]      ,				obja[1]							)
          self.assertIsNot(obja[0]      ,				lowercase_							)
          self.assertIsNot(obja[0]      ,				obja[1]							)
          UpperCAmelCase  	=    Hasher.hash(lowercase_							)
          UpperCAmelCase  	=    Hasher.hash(lowercase_							)
          UpperCAmelCase  	=    Hasher.hash(lowercase_							)
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertEqual(lowercase_      ,				lowercase_							)




      @require_tiktoken
      def 			a_					(							self							)  ->    Union[str, Any]:
          import tiktoken

          UpperCAmelCase  	=    tiktoken.get_encoding('gpt2'							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    tiktoken.get_encoding('r50k_base'							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    tiktoken.get_encoding('gpt2'							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)




      @require_torch
      def 			a_					(							self							)  ->    Optional[Any]:
          import torch

          UpperCAmelCase  	=    torch.tensor([1.0]							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    torch.tensor([2.0]							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    torch.tensor([1.0]							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)




      @require_spacy
      @require_spacy_model('en_core_web_sm'							)
      @require_spacy_model('fr_core_news_sm'							)
      @pytest.mark.integration
      def 			a_					(							self							)  ->    Dict:
          import spacy

          UpperCAmelCase  	=    spacy.load('en_core_web_sm'							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    spacy.load('fr_core_news_sm'							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          UpperCAmelCase  	=    spacy.load('en_core_web_sm'							)
          UpperCAmelCase  	=    mda(datasets.utils.py_utils.dumps(lowercase_							)							).hexdigest()
          self.assertEqual(lowercase_      ,				lowercase_							)
          self.assertNotEqual(lowercase_      ,				lowercase_							)




@pytest.mark.integration
def 			lowercase__  (    lowerCAmelCase :    Path       )       ->					List[Any]:






    """simple docstring"""




    UpperCAmelCase  	=    tmp_path / 'dir1'
    UpperCAmelCase  	=    tmp_path / 'dir2'
    dira.mkdir()
    dira.mkdir()
    UpperCAmelCase  	=    'script.py'
    UpperCAmelCase  	=    dedent(
        '\n    from datasets.fingerprint import Hasher\n    def foo():\n        pass\n    print(Hasher.hash(foo))\n    '       )
    UpperCAmelCase  	=    dira / script_filename
    UpperCAmelCase  	=    dira / script_filename
    with script_patha.open('w'       ) as f:
        f.write(lowerCAmelCase       )
    with script_patha.open('w'       ) as f:
        f.write(lowerCAmelCase       )
    UpperCAmelCase  	=    subprocess.check_output(['python', str(lowerCAmelCase       )]       )
    UpperCAmelCase  	=    subprocess.check_output(['python', str(lowerCAmelCase       )]       )
    assert fingerprinta == fingerprinta




def 			lowercase__  (    )       ->					Union[str, Any]:






    """simple docstring"""




    UpperCAmelCase  	=    {'a': [0, 1, 2]}
    UpperCAmelCase  	=    DatasetChild(InMemoryTable.from_pydict(lowerCAmelCase       )       )
    UpperCAmelCase  	=    dataset.funca()._fingerprint
    assert expected_fingerprint == dataset.funca()._fingerprint
    assert expected_fingerprint != dataset.funca()._fingerprint

    with Pool(2       ) as p:
        assert expected_fingerprint == p.apply_async(dataset.funca       ).get()._fingerprint
        assert expected_fingerprint != p.apply_async(dataset.funca       ).get()._fingerprint




def 			lowercase__  (    )       ->					Tuple:






    """simple docstring"""




    UpperCAmelCase  	=    {'a': [0, 1, 2]}
    class    _UpperCAmelCase							(						datasets.Dataset							):




          @fingerprint_transform(inplace=lowercase_							)
          def 			a_					(							self      ,				lowercase_							)  ->    Optional[int]:
              return DummyDatasetChild(self.data      ,				fingerprint=lowercase_							)

    UpperCAmelCase  	=    DummyDatasetChild(InMemoryTable.from_pydict(lowerCAmelCase       )       ).func()
    class    _UpperCAmelCase							(						datasets.Dataset							):




          @fingerprint_transform(inplace=lowercase_      ,				version='1.0.0'							)
          def 			a_					(							self      ,				lowercase_							)  ->    int:
              return DummyDatasetChild(self.data      ,				fingerprint=lowercase_							)

    UpperCAmelCase  	=    DummyDatasetChild(InMemoryTable.from_pydict(lowerCAmelCase       )       ).func()
    class    _UpperCAmelCase							(						datasets.Dataset							):




          @fingerprint_transform(inplace=lowercase_      ,				version='2.0.0'							)
          def 			a_					(							self      ,				lowercase_							)  ->    Dict:
              return DummyDatasetChild(self.data      ,				fingerprint=lowercase_							)

    UpperCAmelCase  	=    DummyDatasetChild(InMemoryTable.from_pydict(lowerCAmelCase       )       ).func()

    assert len({fingeprint_no_version, fingeprint_a, fingeprint_a}       ) == 3







def 			lowercase__  (    )       ->					Optional[Any]:






    """simple docstring"""




    UpperCAmelCase  	=    Hasher()
    hasher.update(lambda lowerCAmelCase       : x       )





"""simple docstring"""

from typing import SupportsIndex

import numpy as np
from scipy.ndimage import convolve




def 			lowercase__  (    lowerCAmelCase :    np.ndarray       , lowerCAmelCase :    np.ndarray       , lowerCAmelCase :    np.ndarray       )       ->					np.ndarray:






    """simple docstring"""




    UpperCAmelCase  	=    np.stack((horizontal_flow, vertical_flow)       , 2       )

    # Create a grid of all pixel coordinates and subtract the flow to get the
    # target pixels coordinates
    UpperCAmelCase  	=    np.stack(
        np.meshgrid(np.arange(0       , image.shape[1]       )       , np.arange(0       , image.shape[0]       )       )       , 2       )
    UpperCAmelCase  	=    np.round(grid - flow       ).astype(np.intaa       )

    # Find the locations outside of the original image
    UpperCAmelCase  	=    (grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]]       ))
    UpperCAmelCase  	=    0

    UpperCAmelCase  	=    image[grid[:, :, 1], grid[:, :, 0]]

    # Set pixels at invalid locations to 0
    UpperCAmelCase  	=    0

    return warped




def 			lowercase__  (    lowerCAmelCase :    np.ndarray       , lowerCAmelCase :    np.ndarray       , lowerCAmelCase :    SupportsIndex       , lowerCAmelCase :    float | None = None       , )       ->					tuple[np.ndarray, np.ndarray]:






    """simple docstring"""




    if alpha is None:
        UpperCAmelCase  	=    0.1

    # Initialize flow
    UpperCAmelCase  	=    np.zeros_like(lowerCAmelCase       )
    UpperCAmelCase  	=    np.zeros_like(lowerCAmelCase       )

    # Prepare kernels for the calculation of the derivatives and the average velocity
    UpperCAmelCase  	=    np.array([[-1, 1], [-1, 1]]       ) * 0.25
    UpperCAmelCase  	=    np.array([[-1, -1], [1, 1]]       ) * 0.25
    UpperCAmelCase  	=    np.array([[1, 1], [1, 1]]       ) * 0.25
    UpperCAmelCase  	=    np.array(
        [[1 / 12, 1 / 6, 1 / 12], [1 / 6, 0, 1 / 6], [1 / 12, 1 / 6, 1 / 12]]       )

    # Iteratively refine the flow
    for _ in range(lowerCAmelCase       ):
        UpperCAmelCase  	=    warp(lowerCAmelCase       , lowerCAmelCase       , lowerCAmelCase       )
        UpperCAmelCase  	=    convolve(lowerCAmelCase       , lowerCAmelCase       ) + convolve(lowerCAmelCase       , lowerCAmelCase       )
        UpperCAmelCase  	=    convolve(lowerCAmelCase       , lowerCAmelCase       ) + convolve(lowerCAmelCase       , lowerCAmelCase       )
        UpperCAmelCase  	=    convolve(lowerCAmelCase       , lowerCAmelCase       ) + convolve(lowerCAmelCase       , -kernel_t       )

        UpperCAmelCase  	=    convolve(lowerCAmelCase       , lowerCAmelCase       )
        UpperCAmelCase  	=    convolve(lowerCAmelCase       , lowerCAmelCase       )

        # This updates the flow as proposed in the paper (Step 12)
        UpperCAmelCase  	=    (
            derivative_x * avg_horizontal_velocity
            + derivative_y * avg_vertical_velocity
            + derivative_t
        )
        UpperCAmelCase  	=    update / (alpha**2 + derivative_x**2 + derivative_y**2)

        UpperCAmelCase  	=    avg_horizontal_velocity - derivative_x * update
        UpperCAmelCase  	=    avg_vertical_velocity - derivative_y * update

    return horizontal_flow, vertical_flow


if __name__ == "__main__":
   import doctest

   doctest.testmod()



