



"""simple docstring"""
from typing import List, Optional, Union

import numpy as np

from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
from ....feature_extraction_utils import BatchFeature
from ....file_utils import PaddingStrategy, TensorType
from ....utils import logging


__a      =				logging.get_logger(__name__)
class 				lowerCamelCase  (			lowerCAmelCase_				):






					'''simple docstring'''





					_A		:			str						=     ['input_features', 'attention_mask']






					def __init__(       self:							Tuple						,     snake_case:							Any=80						,     snake_case:							Union[str, Any]=16_000						,     snake_case:							Optional[int]=0.0						,     snake_case:							Union[str, Any]=10						,     snake_case:							Optional[int]=25						,     snake_case:							Tuple="hamming_window"						,     snake_case:							Tuple=32_768.0						,     snake_case:							List[Any]=0.9_7						,     snake_case:							List[Any]=1.0						,     snake_case:							List[Any]=True						,     snake_case:							int=True						,     snake_case:							Optional[int]=False						,     **snake_case:							List[str]						,     )   ->	List[str]:
											super().__init__(feature_size=__lowerCAmelCase						,     sampling_rate=__lowerCAmelCase						,     padding_value=__lowerCAmelCase						,     **__lowerCAmelCase						)

											snake_case_ :List[str]						=			feature_size
											snake_case_ :int						=			sampling_rate
											snake_case_ :List[str]						=			padding_value
											snake_case_ :Optional[int]						=			hop_length
											snake_case_ :List[Any]						=			win_length
											snake_case_ :Any						=			frame_signal_scale
											snake_case_ :Union[str, Any]						=			preemphasis_coeff
											snake_case_ :Dict						=			mel_floor
											snake_case_ :List[str]						=			normalize_means
											snake_case_ :Tuple						=			normalize_vars
											snake_case_ :Union[str, Any]						=			win_function
											snake_case_ :Optional[Any]						=			return_attention_mask

											snake_case_ :Tuple						=			win_length * sampling_rate // 1_000
											snake_case_ :int						=			hop_length * sampling_rate // 1_000

											snake_case_ :List[Any]						=			optimal_fft_length(self.sample_size						)
											snake_case_ :Union[str, Any]						=			(self.n_fft // 2) + 1






					def    lowerCAmelCase_				(       self:							Optional[int]						,     snake_case:							np.array						)   ->	Tuple:
											if self.win_function == "hamming_window":
																	snake_case_ :Optional[Any]						=			window_function(window_length=self.sample_size						,     name=self.win_function						,     periodic=__lowerCAmelCase						)
											else:
																	snake_case_ :List[Any]						=			window_function(window_length=self.sample_size						,     name=self.win_function						)

											snake_case_ :Tuple						=			mel_filter_bank(
											    num_frequency_bins=self.n_freqs						,     num_mel_filters=self.feature_size						,     min_frequency=0.0						,     max_frequency=self.sampling_rate / 2.0						,     sampling_rate=self.sampling_rate						,     )

											snake_case_ :Dict						=			spectrogram(
											    one_waveform * self.frame_signal_scale						,     window=__lowerCAmelCase						,     frame_length=self.sample_size						,     hop_length=self.sample_stride						,     fft_length=self.n_fft						,     center=__lowerCAmelCase						,     preemphasis=self.preemphasis_coeff						,     mel_filters=__lowerCAmelCase						,     mel_floor=self.mel_floor						,     log_mel="""log"""						,     )
											return msfc_features.T






					def    lowerCAmelCase_				(       self:							List[Any]						,     snake_case:							List[Any]						,     snake_case:							int						,     snake_case:							int						)   ->	str:
											# make sure we normalize float32 arrays
											if self.normalize_means:
																	snake_case_ :Union[str, Any]						=			x[:input_length].mean(axis=0						)
																	snake_case_ :int						=			np.subtract(__lowerCAmelCase						,     __lowerCAmelCase						)
											if self.normalize_vars:
																	snake_case_ :Optional[int]						=			x[:input_length].std(axis=0						)
																	snake_case_ :str						=			np.divide(__lowerCAmelCase						,     __lowerCAmelCase						)

											if input_length < x.shape[0]:
																	snake_case_ :str						=			padding_value

											# make sure array is in float32
											snake_case_ :List[Any]						=			x.astype(np.floataa						)

											return x






					def    lowerCAmelCase_				(       self:							Optional[int]						,     snake_case:							List[np.ndarray]						,     snake_case:							Optional[np.ndarray] = None						)   ->	List[Any]:
											snake_case_ :Dict						=			attention_mask.sum(-1						) if attention_mask is not None else [x.shape[0] for x in input_features]
											return [self._normalize_one(__lowerCAmelCase						,     __lowerCAmelCase						,     self.padding_value						) for x, n in zip(__lowerCAmelCase						,     __lowerCAmelCase						)]






					def __call__(       self:							Dict						,     snake_case:							Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]						,     snake_case:							Union[bool, str, PaddingStrategy] = False						,     snake_case:							Optional[int] = None						,     snake_case:							bool = False						,     snake_case:							Optional[int] = None						,     snake_case:							Optional[bool] = None						,     snake_case:							Optional[Union[str, TensorType]] = None						,     snake_case:							Optional[int] = None						,     **snake_case:							Optional[int]						,     )   ->	Union[str, Any]:

											if sampling_rate is not None:
																	if sampling_rate != self.sampling_rate:
																							raise ValueError(
																							    f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of"""
																							    f""" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"""
																							    f""" {self.sampling_rate} and not {sampling_rate}."""						)
											else:
																	logger.warning(
																	    """It is strongly recommended to pass the ``sampling_rate`` argument to this function. """
																	    """Failing to do so can result in silent errors that might be hard to debug."""						)

											snake_case_ :Optional[int]						=			isinstance(__lowerCAmelCase						,     np.ndarray						) and len(raw_speech.shape						) > 1
											if is_batched_numpy and len(raw_speech.shape						) > 2:
																	raise ValueError(f"""Only mono-channel audio is supported for input to {self}"""						)
											snake_case_ :Tuple						=			is_batched_numpy or (
											    isinstance(__lowerCAmelCase						,     (list, tuple)						) and (isinstance(raw_speech[0]						,     (np.ndarray, tuple, list)						))
											)

											if is_batched:
																	snake_case_ :Union[str, Any]						=			[np.asarray(__lowerCAmelCase						,     dtype=np.floataa						) for speech in raw_speech]
											elif not is_batched and not isinstance(__lowerCAmelCase						,     np.ndarray						):
																	snake_case_ :int						=			np.asarray(__lowerCAmelCase						,     dtype=np.floataa						)
											elif isinstance(__lowerCAmelCase						,     np.ndarray						) and raw_speech.dtype is np.dtype(np.floataa						):
																	snake_case_ :Tuple						=			raw_speech.astype(np.floataa						)

											# always return batch
											if not is_batched:
																	snake_case_ :Optional[Any]						=			[raw_speech]

											# extract fbank features
											snake_case_ :Optional[Any]						=			[self._extract_mfsc_features(__lowerCAmelCase						) for one_waveform in raw_speech]

											# convert into correct format for padding
											snake_case_ :Any						=			BatchFeature({"""input_features""": features}						)

											snake_case_ :List[str]						=			self.pad(
											    __lowerCAmelCase						,     padding=__lowerCAmelCase						,     max_length=__lowerCAmelCase						,     truncation=__lowerCAmelCase						,     pad_to_multiple_of=__lowerCAmelCase						,     return_attention_mask=__lowerCAmelCase						,     **__lowerCAmelCase						,     )
											# make sure list is in array format
											snake_case_ :Optional[Any]						=			padded_inputs.get("""input_features"""						)
											if isinstance(input_features[0]						,     __lowerCAmelCase						):
																	snake_case_ :Union[str, Any]						=			[np.asarray(__lowerCAmelCase						,     dtype=np.floataa						) for feature in input_features]

											snake_case_ :str						=			padded_inputs.get("""attention_mask"""						)
											if attention_mask is not None:
																	snake_case_ :Tuple						=			[np.asarray(__lowerCAmelCase						,     dtype=np.intaa						) for array in attention_mask]

											if self.normalize_means or self.normalize_vars:
																	snake_case_ :int						=			(
																	    np.array(__lowerCAmelCase						,     dtype=np.intaa						)
																	    if self._get_padding_strategies(__lowerCAmelCase						,     max_length=__lowerCAmelCase						) is not PaddingStrategy.DO_NOT_PAD
																	    and padding
																	    else None
																	)
																	snake_case_ :Tuple						=			self.normalize(
																	    padded_inputs["""input_features"""]						,     attention_mask=__lowerCAmelCase						)

											if return_tensors is not None:
																	snake_case_ :List[str]						=			padded_inputs.convert_to_tensors(__lowerCAmelCase						)

											return padded_inputs

"""simple docstring"""


import math


class 				a :


    def    lowerCAmelCase_     (    self		:     Tuple      , __lowerCAmelCase		:     list[list[float]]      , __lowerCAmelCase		:     list[int]    ):
      _UpperCAmelCase         =					0.0
      _UpperCAmelCase         =					0.0
      for i in range(len(__lowerCAmelCase    )    ):
        da += math.pow((sample[i] - weights[0][i])      , 2    )
        da += math.pow((sample[i] - weights[1][i])      , 2    )
        return 0 if da > da else 1
      return 0


    def    lowerCAmelCase_     (    self		:     Union[str, Any]      , __lowerCAmelCase		:     list[list[int | float]]      , __lowerCAmelCase		:     list[int]      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     float    ):
      for i in range(len(__lowerCAmelCase    )    ):
        weights[j][i] += alpha * (sample[i] - weights[j][i])
      return weights






def 			__UpperCAmelCase    (	):







  """simple docstring"""
  # Training Examples ( m, n )
  _UpperCAmelCase         =					[[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]]

  # weight initialization ( n, C )
  _UpperCAmelCase         =					[[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]]

  # training
  _UpperCAmelCase         =					SelfOrganizingMap()
  _UpperCAmelCase         =					3
  _UpperCAmelCase         =					0.5

  for _ in range(lowercase						):
    for j in range(len(lowercase						)						):
      # training sample
      _UpperCAmelCase         =					training_samples[j]

      # Compute the winning vector
      _UpperCAmelCase         =					self_organizing_map.get_winner(lowercase      ,lowercase						)

      # Update the winning vector
      _UpperCAmelCase         =					self_organizing_map.update(lowercase      ,lowercase      ,lowercase      ,lowercase						)

    # classify test sample
  _UpperCAmelCase         =					[0, 0, 0, 1]
  _UpperCAmelCase         =					self_organizing_map.get_winner(lowercase      ,lowercase						)

  # results
  print(f'''Clusters that the test sample belongs to : {winner}'''						)
  print(f'''Weights that have been trained : {weights}'''						)


# running the main() function
if __name__ == "__main__":
    main()
