
from typing import SupportsIndex

import numpy as np
from scipy.ndimage import convolve


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		,   __lowerCAmelCase		)	->  np.ndarray:
    __lowercase						:     Dict		      =    np.stack((horizontal_flow, vertical_flow)		,   2		)

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

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

    __lowercase						:     Optional[int]		      =    image[grid[:, :, 1], grid[:, :, 0]]

    # Set pixels at invalid locations to 0
    __lowercase						:     Optional[Any]		      =    0

    return warped


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		,   __lowerCAmelCase		,   __lowerCAmelCase = None		,   )	->  tuple[np.ndarray, np.ndarray]:
    if alpha is None:
        __lowercase						:     Optional[int]		      =    0.1

    # Initialize flow
    __lowercase						:     Dict		      =    np.zeros_like(__lowerCAmelCase		)
    __lowercase						:     Dict		      =    np.zeros_like(__lowerCAmelCase		)

    # Prepare kernels for the calculation of the derivatives and the average velocity
    __lowercase						:     List[Any]		      =    np.array([[-1, 1], [-1, 1]]		) * 0.25
    __lowercase						:     List[Any]		      =    np.array([[-1, -1], [1, 1]]		) * 0.25
    __lowercase						:     str		      =    np.array([[1, 1], [1, 1]]		) * 0.25
    __lowercase						:     Any		      =    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		):
        __lowercase						:     Dict		      =    warp(__lowerCAmelCase		,   __lowerCAmelCase		,   __lowerCAmelCase		)
        __lowercase						:     List[Any]		      =    convolve(__lowerCAmelCase		,   __lowerCAmelCase		) + convolve(__lowerCAmelCase		,   __lowerCAmelCase		)
        __lowercase						:     Optional[int]		      =    convolve(__lowerCAmelCase		,   __lowerCAmelCase		) + convolve(__lowerCAmelCase		,   __lowerCAmelCase		)
        __lowercase						:     Optional[int]		      =    convolve(__lowerCAmelCase		,   __lowerCAmelCase		) + convolve(__lowerCAmelCase		,   -kernel_t		)

        __lowercase						:     int		      =    convolve(__lowerCAmelCase		,   __lowerCAmelCase		)
        __lowercase						:     Any		      =    convolve(__lowerCAmelCase		,   __lowerCAmelCase		)

        # This updates the flow as proposed in the paper (Step 12)
        __lowercase						:     List[Any]		      =    (
            derivative_x * avg_horizontal_velocity
            + derivative_y * avg_vertical_velocity
            + derivative_t
        )
        __lowercase						:     Union[str, Any]		      =    update / (alpha**2 + derivative_x**2 + derivative_y**2)

        __lowercase						:     int		      =    avg_horizontal_velocity - derivative_x * update
        __lowercase						:     Optional[Any]		      =    avg_vertical_velocity - derivative_y * update

    return horizontal_flow, vertical_flow


if __name__ == "__main__":
 import doctest

 doctest.testmod()




import importlib.metadata
import sys

from transformers.testing_utils import TestCasePlus
from transformers.utils.versions import require_version, require_version_core


__lowerCAmelCase   :     Optional[Any]      =						importlib.metadata.version("numpy")
__lowerCAmelCase   :     Any      =						".".join([str(x) for x in sys.version_info[:3]])


class   __lowerCAmelCase		(		lowerCAmelCase_ ):



      """simple docstring"""







      def 						snake_case_     ( self						:    List[Any]			):
          # lt + different version strings
          require_version_core('''numpy<1000.4.5'''			)
          require_version_core('''numpy<1000.4'''			)
          require_version_core('''numpy<1000'''			)

          # le
          require_version_core('''numpy<=1000.4.5'''			)
          require_version_core(F'numpy<={numpy_ver}'			)

          # eq
          require_version_core(F'numpy=={numpy_ver}'			)

          # ne
          require_version_core('''numpy!=1000.4.5'''			)

          # ge
          require_version_core('''numpy>=1.0'''			)
          require_version_core('''numpy>=1.0.0'''			)
          require_version_core(F'numpy>={numpy_ver}'			)

          # gt
          require_version_core('''numpy>1.0.0'''			)

          # mix
          require_version_core('''numpy>1.0.0,<1000'''			)

          # requirement w/o version
          require_version_core('''numpy'''			)

          # unmet requirements due to version conflict
          for req in ["numpy==1.0.0", "numpy>=1000.0.0", F'numpy<{numpy_ver}']:
              try:
                  require_version_core(_snake_case			)
              except ImportError as e:
                  self.assertIn(F'{req} is required'			,    str(_snake_case			)			)
                  self.assertIn('''but found'''			,    str(_snake_case			)			)

        # unmet requirements due to missing module
          for req in ["numpipypie>1", "numpipypie2"]:
              try:
                  require_version_core(_snake_case			)
              except importlib.metadata.PackageNotFoundError as e:
                  self.assertIn(F'The \'{req}\' distribution was not found and is required by this application'			,    str(_snake_case			)			)
                  self.assertIn('''Try: pip install transformers -U'''			,    str(_snake_case			)			)

        # bogus requirements formats:
        # 1. whole thing
          for req in ["numpy??1.0.0", "numpy1.0.0"]:
              try:
                  require_version_core(_snake_case			)
              except ValueError as e:
                  self.assertIn('''requirement needs to be in the pip package format'''			,    str(_snake_case			)			)
        # 2. only operators
          for req in ["numpy=1.0.0", "numpy == 1.00", "numpy<>1.0.0", "numpy><1.00", "numpy>>1.0.0"]:
              try:
                  require_version_core(_snake_case			)
              except ValueError as e:
                  self.assertIn('''need one of '''			,    str(_snake_case			)			)




      def 						snake_case_     ( self						:    List[str]			):
          # matching requirement
          require_version('''python>=3.6.0'''			)

          # not matching requirements
          for req in ["python>9.9.9", "python<3.0.0"]:
              try:
                  require_version_core(_snake_case			)
              except ImportError as e:
                  self.assertIn(F'{req} is required'			,    str(_snake_case			)			)
                  self.assertIn(F'but found python=={python_ver}'			,    str(_snake_case			)			)


