
'''simple docstring'''





import json
import os
from collections.abc import Mapping
from typing import Dict, List, Optional, Union

import numpy as np
import torch

from .imports import is_safetensors_available





def 							snake_case				(		UpperCAmelCase   ,	UpperCAmelCase   ,	UpperCAmelCase   ,	UpperCAmelCase=None						)->      Union[str, Any]:







      """simple docstring"""
      __A													=      None
      # Check the string instead of the dtype to be compatible with versions of PyTorch that don't have bfloat16.
      if str(weight.dtype						) == "torch.bfloat16":
            # Need to reinterpret the underlined data as int16 since NumPy does not handle bfloat16s.
            __A													=      weight.view(torch.intaa						)
            __A													=      'bfloat16'
      __A													=      weight.cpu().numpy()
      __A													=      os.path.join(UpperCAmelCase   ,	f'{weight_name}.dat'						)
      if index is not None:
            if dtype is None:
                  __A													=      str(array.dtype						)
            __A													=      {'dtype': dtype, 'shape': list(array.shape						)}
      if array.ndim == 0:
            __A													=      array[None]
      __A													=      np.memmap(UpperCAmelCase   ,	dtype=array.dtype   ,	mode='w+'   ,	shape=array.shape						)
      __A													=      array[:]
      file_array.flush()
      return index





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







      """simple docstring"""
      __A													=      tuple(weight_info['shape']						)
      if shape == ():
            # NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor
            __A													=      (1,)

      __A													=      weight_info['dtype']
      if dtype == "bfloat16":
            # NumPy does not support bfloat16 so this was saved as a int16
            __A													=      'int16'

      __A													=      np.memmap(UpperCAmelCase   ,	dtype=UpperCAmelCase   ,	shape=UpperCAmelCase   ,	mode='r'						)

      if len(weight_info['shape']						) == 0:
            __A													=      weight[0]
      __A													=      torch.tensor(UpperCAmelCase						)
      if weight_info["dtype"] == "bfloat16":
            __A													=      weight.view(torch.bfloataa						)

      return weight





def 							snake_case				(		UpperCAmelCase   ,	UpperCAmelCase						)->      Optional[int]:







      """simple docstring"""






      if index is None or len(UpperCAmelCase						) == 0:
            # Nothing to save
            return

      __A													=      os.path.join(UpperCAmelCase   ,	'index.json'						)
      if os.path.isfile(UpperCAmelCase						):
            with open(UpperCAmelCase   ,	'r'   ,	encoding='utf-8'						) as f:
                  __A													=      json.load(UpperCAmelCase						)
      else:
            __A													=      {}
      current_index.update(UpperCAmelCase						)

      with open(UpperCAmelCase   ,	'w'   ,	encoding='utf-8'						) as f:
            json.dump(UpperCAmelCase   ,	UpperCAmelCase   ,	indent=2						)





def 							snake_case				(		UpperCAmelCase   ,	UpperCAmelCase						)->      int:







      """simple docstring"""
      os.makedirs(UpperCAmelCase   ,	exist_ok=UpperCAmelCase						)
      __A													=      {}
      for name, parameter in state_dict.items():
            __A													=      offload_weight(UpperCAmelCase   ,	UpperCAmelCase   ,	UpperCAmelCase   ,	index=UpperCAmelCase						)

      # Update index
      save_offload_index(UpperCAmelCase   ,	UpperCAmelCase						)


class 			UpperCamelCase__	(     snake_case__):






 def __init__(      self	:List[str]						,					_A	:Mapping						,					_A	:str      )					->      Dict:







       '''simple docstring'''



       __A													=      dataset
       __A													=      prefix






 def __getitem__(      self	:Dict						,					_A	:Union[str, Any]      )					->      int:







       '''simple docstring'''



       return self.dataset[F'{self.prefix}{key}']






 def __iter__(      self	:Optional[Any]      )					->      Optional[int]:







       '''simple docstring'''



       return iter([key for key in self.dataset if key.startswith(self.prefix      )]      )






 def __len__(      self	:List[str]      )					->      Union[str, Any]:







       '''simple docstring'''



       return len(self.dataset      )


class 			UpperCamelCase__	(     snake_case__):






 def __init__(      self	:str						,					_A	:Dict[str, torch.Tensor] = None						,					_A	:Optional[Union[str, os.PathLike]] = None						,					_A	:Mapping = None						,					_A	:List[str]=None						,					)					->      List[str]:







       '''simple docstring'''



       if state_dict is None and save_folder is None:
             raise ValueError('Need either a `state_dict` or a `save_folder` containing offloaded weights.'      )

       __A													=      {} if state_dict is None else state_dict
       __A													=      save_folder
       if index is None and save_folder is not None:
             with open(os.path.join(_A						,					'index.json'      )      ) as f:
                   __A													=      json.load(_A      )
       __A													=      {} if index is None else index
       __A													=      list(self.state_dict.keys()      )
       self.all_keys.extend([key for key in self.index if key not in self.all_keys]      )
       __A													=      device






 def __getitem__(      self	:List[str]						,					_A	:str      )					->      Optional[Any]:







       '''simple docstring'''



       if key in self.state_dict:
             return self.state_dict[key]
       __A													=      self.index[key]
       if weight_info.get('safetensors_file'      ) is not None:
             if not is_safetensors_available():
                   raise ImportError('These offloaded weights require the use of safetensors: `pip install safetensors`.'      )

             from safetensors import safe_open

             __A													=      'cpu' if self.device is None else self.device
             with safe_open(weight_info['safetensors_file']						,					framework='pt'						,					device=_A      ) as f:
                   __A													=      f.get_tensor(weight_info.get('weight_name'						,					_A      )      )

             if "dtype" in weight_info:
                   return tensor.to(getattr(_A						,					weight_info['dtype']      )      )
             else:
                   return tensor

       __A													=      os.path.join(self.save_folder						,					F'{key}.dat'      )
       return load_offloaded_weight(_A						,					_A      )






 def __iter__(      self	:List[str]      )					->      List[str]:







       '''simple docstring'''



       return iter(self.all_keys      )






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







       '''simple docstring'''



       return len(self.all_keys      )





def 							snake_case				(		UpperCAmelCase   ,	UpperCAmelCase						)->      Optional[int]:







      """simple docstring"""
      __A													=      {}
      for module_name in submodule_names:
            # We want to catch module_name parameter (module_name.xxx) or potentially module_name, but not any of the
            # submodules that could being like module_name (transformers.h.1 and transformers.h.10 for instance)
            result.update(
                {
                    key: param
                    for key, param in state_dict.items()
                    if key == module_name or key.startswith(module_name + '.'						)
                }						)
      return result









from typing import SupportsIndex

import numpy as np
from scipy.ndimage import convolve







def _a					(			SCREAMING_SNAKE_CASE						:     np.ndarray       ,   SCREAMING_SNAKE_CASE						:     np.ndarray       ,   SCREAMING_SNAKE_CASE						:     np.ndarray						)       ->       np.ndarray:

 """simple docstring"""






 __lowerCAmelCase:  Any        = np.stack((horizontal_flow, vertical_flow)       ,   2						)

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

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

 __lowerCAmelCase:  List[str]        = image[grid[:, :, 1], grid[:, :, 0]]

 # Set pixels at invalid locations to 0
 __lowerCAmelCase:  List[str]        = 0

 return warped







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

 """simple docstring"""






 if alpha is None:
  __lowerCAmelCase:  Tuple        = 0.1

 # Initialize flow
 __lowerCAmelCase:  Optional[int]        = np.zeros_like(SCREAMING_SNAKE_CASE						)
 __lowerCAmelCase:  Dict        = np.zeros_like(SCREAMING_SNAKE_CASE						)

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

  __lowerCAmelCase:  Any        = convolve(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						)
  __lowerCAmelCase:  Dict        = convolve(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE						)

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

  __lowerCAmelCase:  List[Any]        = avg_horizontal_velocity - derivative_x * update
  __lowerCAmelCase:  Union[str, Any]        = avg_vertical_velocity - derivative_y * update

 return horizontal_flow, vertical_flow


if __name__ == "__main__":
  import doctest

  doctest.testmod()





