import logging

import numpy as np
import pytest
from scipy.linalg import eigh

logging.basicConfig(level=logging.INFO, format='''%(message)s''')




def    lowerCAmelCase_  (		lowercase:				np.ndarray		)     ->					np.ndarray:







 '''simple docstring'''
 return input_array.reshape((input_array.size, 1)		)




def    lowerCAmelCase_  (		lowercase:				np.ndarray	,       lowercase:				np.ndarray	,       lowercase:				int		)     ->					np.ndarray:







 '''simple docstring'''
 _UpperCamelCase:  Dict    						=			np.nan
 for i in range(lowercase		):
  _UpperCamelCase:  Any    						=			features[:, labels == i]
  _UpperCamelCase:  Union[str, Any]    						=			data.mean(1		)
  # Centralize the data of class i
  _UpperCamelCase:  Dict    						=			data - column_reshape(lowercase		)
  if i > 0:
   # If covariance_sum is not None
   covariance_sum += np.dot(lowercase	,       centered_data.T		)
  else:
   # If covariance_sum is np.nan (i.e. first loop)
   _UpperCamelCase:  int    						=			np.dot(lowercase	,       centered_data.T		)

 return covariance_sum / features.shape[1]




def    lowerCAmelCase_  (		lowercase:				np.ndarray	,       lowercase:				np.ndarray	,       lowercase:				int		)     ->					np.ndarray:







 '''simple docstring'''
 _UpperCamelCase:  List[str]    						=			features.mean(1		)
 _UpperCamelCase:  List[str]    						=			np.nan
 for i in range(lowercase		):
  _UpperCamelCase:  int    						=			features[:, labels == i]
  _UpperCamelCase:  List[str]    						=			data.shape[1]
  _UpperCamelCase:  Optional[Any]    						=			data.mean(1		)
  if i > 0:
   # If covariance_sum is not None
   covariance_sum += device_data * np.dot(
       column_reshape(lowercase		) - column_reshape(lowercase		)	,       (column_reshape(lowercase		) - column_reshape(lowercase		)).T	,       )
  else:
   # If covariance_sum is np.nan (i.e. first loop)
   _UpperCamelCase:  Dict    						=			device_data * np.dot(
       column_reshape(lowercase		) - column_reshape(lowercase		)	,       (column_reshape(lowercase		) - column_reshape(lowercase		)).T	,       )

 return covariance_sum / features.shape[1]




def    lowerCAmelCase_  (		lowercase:				np.ndarray	,       lowercase:				int		)     ->					np.ndarray:







 '''simple docstring'''

 # Check if the features have been loaded
 if features.any():
  _UpperCamelCase:  List[str]    						=			features.mean(1		)
  # Center the dataset
  _UpperCamelCase:  List[Any]    						=			features - np.reshape(lowercase	,       (data_mean.size, 1)		)
  _UpperCamelCase:  Tuple    						=			np.dot(lowercase	,       centered_data.T		) / features.shape[1]
  _UpperCamelCase						,				_UpperCamelCase:  str    						=			np.linalg.eigh(lowercase		)
  # Take all the columns in the reverse order (-1), and then takes only the first
  _UpperCamelCase:  List[str]    						=			eigenvectors[:, ::-1][:, 0:dimensions]
  # Project the database on the new space
  _UpperCamelCase:  str    						=			np.dot(filtered_eigenvectors.T	,       lowercase		)
  logging.info('''Principal Component Analysis computed'''		)

  return projected_data
 else:
  logging.basicConfig(level=logging.ERROR	,       format='''%(message)s'''	,       force=lowercase		)
  logging.error('''Dataset empty'''		)
  raise AssertionError




def    lowerCAmelCase_  (		lowercase:				np.ndarray	,       lowercase:				np.ndarray	,       lowercase:				int	,       lowercase:				int		)     ->					np.ndarray:







 '''simple docstring'''
 assert classes > dimensions

 # Check if features have been already loaded
 if features.any:
  _UpperCamelCase						,				_UpperCamelCase:  Tuple    						=			eigh(
      covariance_between_classes(lowercase	,       lowercase	,       lowercase		)	,       covariance_within_classes(lowercase	,       lowercase	,       lowercase		)	,       )
  _UpperCamelCase:  Optional[Any]    						=			eigenvectors[:, ::-1][:, :dimensions]
  _UpperCamelCase						,				_UpperCamelCase						,				_UpperCamelCase:  Tuple    						=			np.linalg.svd(lowercase		)
  _UpperCamelCase:  Any    						=			svd_matrix[:, 0:dimensions]
  _UpperCamelCase:  int    						=			np.dot(filtered_svd_matrix.T	,       lowercase		)
  logging.info('''Linear Discriminant Analysis computed'''		)

  return projected_data
 else:
  logging.basicConfig(level=logging.ERROR	,       format='''%(message)s'''	,       force=lowercase		)
  logging.error('''Dataset empty'''		)
  raise AssertionError




def    lowerCAmelCase_  (		)     ->					None:







 '''simple docstring'''
 # Create dummy dataset with 2 classes and 3 features
 _UpperCamelCase:  str    						=			np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]		)
 _UpperCamelCase:  int    						=			np.array([0, 0, 0, 1, 1]		)
 _UpperCamelCase:  str    						=			2
 _UpperCamelCase:  List[str]    						=			2

 # Assert that the function raises an AssertionError if dimensions > classes
 with pytest.raises(lowercase		) as error_info:
  _UpperCamelCase:  str    						=			linear_discriminant_analysis(
      lowercase	,       lowercase	,       lowercase	,       lowercase		)
  if isinstance(lowercase	,       np.ndarray		):
   raise AssertionError(
       '''Did not raise AssertionError for dimensions > classes'''		)
  assert error_info.type is AssertionError




def    lowerCAmelCase_  (		)     ->					None:







 '''simple docstring'''
 _UpperCamelCase:  Dict    						=			np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]		)
 _UpperCamelCase:  Optional[Any]    						=			2
 _UpperCamelCase:  str    						=			np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]]		)

 with pytest.raises(lowercase		) as error_info:
  _UpperCamelCase:  List[str]    						=			principal_component_analysis(lowercase	,       lowercase		)
  if not np.allclose(lowercase	,       lowercase		):
   raise AssertionError
  assert error_info.type is AssertionError


if __name__ == "__main__":
  import doctest

  doctest.testmod()
import unittest

import numpy as np

from transformers import AlbertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
  import jax.numpy as jnp

  from transformers.models.albert.modeling_flax_albert import (
      FlaxAlbertForMaskedLM,
      FlaxAlbertForMultipleChoice,
      FlaxAlbertForPreTraining,
      FlaxAlbertForQuestionAnswering,
      FlaxAlbertForSequenceClassification,
      FlaxAlbertForTokenClassification,
      FlaxAlbertModel,
  )




class 			__magic_name__	(		unittest.TestCase     ):





   """simple docstring"""




   def __init__(						self       :	Any		,	_lowercase       :	Optional[int]		,	_lowercase       :	Tuple=13		,	_lowercase       :	str=7		,	_lowercase       :	List[Any]=True		,	_lowercase       :	Optional[int]=True		,	_lowercase       :	str=True		,	_lowercase       :	Optional[int]=True		,	_lowercase       :	Dict=99		,	_lowercase       :	List[Any]=32		,	_lowercase       :	List[str]=5		,	_lowercase       :	str=4		,	_lowercase       :	int=37		,	_lowercase       :	List[str]="gelu"		,	_lowercase       :	Any=0.1		,	_lowercase       :	Optional[int]=0.1		,	_lowercase       :	Dict=512		,	_lowercase       :	int=16		,	_lowercase       :	Optional[Any]=2		,	_lowercase       :	Dict=0.02		,	_lowercase       :	List[Any]=4		,	):



    """simple docstring"""



    _UpperCamelCase:  List[str]    						=			parent
    _UpperCamelCase:  int    						=			batch_size
    _UpperCamelCase:  List[str]    						=			seq_length
    _UpperCamelCase:  Optional[int]    						=			is_training
    _UpperCamelCase:  Optional[Any]    						=			use_attention_mask
    _UpperCamelCase:  Any    						=			use_token_type_ids
    _UpperCamelCase:  List[str]    						=			use_labels
    _UpperCamelCase:  Optional[int]    						=			vocab_size
    _UpperCamelCase:  List[str]    						=			hidden_size
    _UpperCamelCase:  Union[str, Any]    						=			num_hidden_layers
    _UpperCamelCase:  Any    						=			num_attention_heads
    _UpperCamelCase:  List[str]    						=			intermediate_size
    _UpperCamelCase:  Union[str, Any]    						=			hidden_act
    _UpperCamelCase:  Dict    						=			hidden_dropout_prob
    _UpperCamelCase:  List[str]    						=			attention_probs_dropout_prob
    _UpperCamelCase:  str    						=			max_position_embeddings
    _UpperCamelCase:  Dict    						=			type_vocab_size
    _UpperCamelCase:  Tuple    						=			type_sequence_label_size
    _UpperCamelCase:  List[Any]    						=			initializer_range
    _UpperCamelCase:  str    						=			num_choices



   def 	lowerCAmelCase    (						self       :	str				):



    """simple docstring"""



    _UpperCamelCase:  str    						=			ids_tensor([self.batch_size, self.seq_length]		,	self.vocab_size				)

    _UpperCamelCase:  Any    						=			None
    if self.use_attention_mask:
     _UpperCamelCase:  List[str]    						=			random_attention_mask([self.batch_size, self.seq_length]				)

    _UpperCamelCase:  Optional[Any]    						=			None
    if self.use_token_type_ids:
     _UpperCamelCase:  Optional[Any]    						=			ids_tensor([self.batch_size, self.seq_length]		,	self.type_vocab_size				)

    _UpperCamelCase:  Tuple    						=			AlbertConfig(
        vocab_size=self.vocab_size		,	hidden_size=self.hidden_size		,	num_hidden_layers=self.num_hidden_layers		,	num_attention_heads=self.num_attention_heads		,	intermediate_size=self.intermediate_size		,	hidden_act=self.hidden_act		,	hidden_dropout_prob=self.hidden_dropout_prob		,	attention_probs_dropout_prob=self.attention_probs_dropout_prob		,	max_position_embeddings=self.max_position_embeddings		,	type_vocab_size=self.type_vocab_size		,	is_decoder=_lowercase		,	initializer_range=self.initializer_range		,	)

    return config, input_ids, token_type_ids, attention_mask



   def 	lowerCAmelCase    (						self       :	int				):



    """simple docstring"""



    _UpperCamelCase:  List[Any]    						=			self.prepare_config_and_inputs()
    _UpperCamelCase						,				_UpperCamelCase						,				_UpperCamelCase						,				_UpperCamelCase:  int    						=			config_and_inputs
    _UpperCamelCase:  int    						=			{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
    return config, inputs_dict




@require_flax
class 			__magic_name__	(		__a   ,						unittest.TestCase     ):





   """simple docstring"""




   lowerCAmelCase   :     Any	      = (
       (
           FlaxAlbertModel,
           FlaxAlbertForPreTraining,
           FlaxAlbertForMaskedLM,
           FlaxAlbertForMultipleChoice,
           FlaxAlbertForQuestionAnswering,
           FlaxAlbertForSequenceClassification,
           FlaxAlbertForTokenClassification,
           FlaxAlbertForQuestionAnswering,
       )
       if is_flax_available()
       else ()
   )



   def 	lowerCAmelCase    (						self       :	Union[str, Any]				):



    """simple docstring"""



    _UpperCamelCase:  Optional[int]    						=			FlaxAlbertModelTester(self				)



   @slow
   def 	lowerCAmelCase    (						self       :	Union[str, Any]				):



    """simple docstring"""



    for model_class_name in self.all_model_classes:
     _UpperCamelCase:  int    						=			model_class_name.from_pretrained('''albert-base-v2'''				)
     _UpperCamelCase:  List[Any]    						=			model(np.ones((1, 1)				)				)
     self.assertIsNotNone(_lowercase				)




@require_flax
class 			__magic_name__	(		unittest.TestCase     ):





   """simple docstring"""




   @slow
   def 	lowerCAmelCase    (						self       :	int				):



    """simple docstring"""



    _UpperCamelCase:  Optional[int]    						=			FlaxAlbertModel.from_pretrained('''albert-base-v2'''				)
    _UpperCamelCase:  List[Any]    						=			np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]				)
    _UpperCamelCase:  Optional[int]    						=			np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]				)
    _UpperCamelCase:  Optional[int]    						=			model(_lowercase		,	attention_mask=_lowercase				)[0]
    _UpperCamelCase:  Tuple    						=			(1, 11, 768)
    self.assertEqual(output.shape		,	_lowercase				)
    _UpperCamelCase:  Tuple    						=			np.array(
        [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]]				)

    self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]		,	_lowercase		,	atol=1E-4				)				)