




"""simple docstring"""




import logging

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

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



def 					a__				(       snake_case__       )		->      np.ndarray:
			return input_array.reshape((input_array.size, 1)       )



def 					a__				(       snake_case__ ,				snake_case__ ,				snake_case__       )		->      np.ndarray:
			lowerCamelCase       =      np.nan
			for i in range(snake_case__       ):
						lowerCamelCase       =      features[:, labels == i]
						lowerCamelCase       =      data.mean(1       )
						# Centralize the data of class i
						lowerCamelCase       =      data - column_reshape(snake_case__       )
						if i > 0:
									# If covariance_sum is not None
									covariance_sum += np.dot(snake_case__ ,				centered_data.T       )
						else:
									# If covariance_sum is np.nan (i.e. first loop)
									lowerCamelCase       =      np.dot(snake_case__ ,				centered_data.T       )

			return covariance_sum / features.shape[1]



def 					a__				(       snake_case__ ,				snake_case__ ,				snake_case__       )		->      np.ndarray:
			lowerCamelCase       =      features.mean(1       )
			lowerCamelCase       =      np.nan
			for i in range(snake_case__       ):
						lowerCamelCase       =      features[:, labels == i]
						lowerCamelCase       =      data.shape[1]
						lowerCamelCase       =      data.mean(1       )
						if i > 0:
									# If covariance_sum is not None
									covariance_sum += device_data * np.dot(
									    column_reshape(snake_case__       ) - column_reshape(snake_case__       ) ,				(column_reshape(snake_case__       ) - column_reshape(snake_case__       )).T ,				)
						else:
									# If covariance_sum is np.nan (i.e. first loop)
									lowerCamelCase       =      device_data * np.dot(
									    column_reshape(snake_case__       ) - column_reshape(snake_case__       ) ,				(column_reshape(snake_case__       ) - column_reshape(snake_case__       )).T ,				)

			return covariance_sum / features.shape[1]



def 					a__				(       snake_case__ ,				snake_case__       )		->      np.ndarray:

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

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



def 					a__				(       snake_case__ ,				snake_case__ ,				snake_case__ ,				snake_case__       )		->      np.ndarray:
			assert classes > dimensions

			# Check if features have been already loaded
			if features.any:
						lowerCamelCase   ,     lowerCamelCase       =      eigh(
						    covariance_between_classes(snake_case__ ,				snake_case__ ,				snake_case__       ) ,				covariance_within_classes(snake_case__ ,				snake_case__ ,				snake_case__       ) ,				)
						lowerCamelCase       =      eigenvectors[:, ::-1][:, :dimensions]
						lowerCamelCase   ,     lowerCamelCase   ,     lowerCamelCase       =      np.linalg.svd(snake_case__       )
						lowerCamelCase       =      svd_matrix[:, 0:dimensions]
						lowerCamelCase       =      np.dot(filtered_svd_matrix.T ,				snake_case__       )
						logging.info("""Linear Discriminant Analysis computed"""       )

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



def 					a__				(       )		->      None:
			# Create dummy dataset with 2 classes and 3 features
			lowerCamelCase       =      np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]       )
			lowerCamelCase       =      np.array([0, 0, 0, 1, 1]       )
			lowerCamelCase       =      2
			lowerCamelCase       =      2

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



def 					a__				(       )		->      None:
			lowerCamelCase       =      np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]       )
			lowerCamelCase       =      2
			lowerCamelCase       =      np.array([[6.9282_0323, 8.6602_5404, 10.3923_0485], [3.0, 3.0, 3.0]]       )

			with pytest.raises(snake_case__       ) as error_info:
						lowerCamelCase       =      principal_component_analysis(snake_case__ ,				snake_case__       )
						if not np.allclose(snake_case__ ,				snake_case__       ):
									raise AssertionError
						assert error_info.type is AssertionError


if __name__ == "__main__":
					import doctest

					doctest.testmod()









"""simple docstring"""




from operator import delitem, getitem, setitem

import pytest

from data_structures.hashing.hash_map import HashMap



def 					a__				(       snake_case__       )		->      List[str]:
			return getitem, k



def 					a__				(       snake_case__ ,				snake_case__       )		->      Optional[Any]:
			return setitem, k, v



def 					a__				(       snake_case__       )		->      str:
			return delitem, k



def 					a__				(       snake_case__ ,				snake_case__ ,				*snake_case__       )		->      Union[str, Any]:
			try:
						return fun(snake_case__ ,				*snake_case__       ), None
			except Exception as e:
						return None, e


lowerCAmelCase							:    Optional[int]  							=							(
    _set("""key_a""", """val_a"""),
    _set("""key_b""", """val_b"""),
)

lowerCAmelCase							:    List[Any]  							=							[
    _set("""key_a""", """val_a"""),
    _set("""key_a""", """val_b"""),
]

lowerCAmelCase							:    List[Any]  							=							[
    _set("""key_a""", """val_a"""),
    _set("""key_b""", """val_b"""),
    _del("""key_a"""),
    _del("""key_b"""),
    _set("""key_a""", """val_a"""),
    _del("""key_a"""),
]

lowerCAmelCase							:    List[Any]  							=							[
    _get("""key_a"""),
    _del("""key_a"""),
    _set("""key_a""", """val_a"""),
    _del("""key_a"""),
    _del("""key_a"""),
    _get("""key_a"""),
]

lowerCAmelCase							:    Tuple  							=							[
    *[_set(x, x) for x in range(5)],  # guaranteed upsize
]

lowerCAmelCase							:    Tuple  							=							[
    *[_set(x, x) for x in range(5)],  # guaranteed upsize
    *[_del(x) for x in range(5)],
    _set("""key_a""", """val_b"""),
]



@pytest.mark.parametrize(
    """operations""" ,				(
        pytest.param(_add_items ,				id="""add items"""       ),
        pytest.param(_overwrite_items ,				id="""overwrite items"""       ),
        pytest.param(_delete_items ,				id="""delete items"""       ),
        pytest.param(_access_absent_items ,				id="""access absent items"""       ),
        pytest.param(_add_with_resize_up ,				id="""add with resize up"""       ),
        pytest.param(_add_with_resize_down ,				id="""add with resize down"""       ),
    ) ,				)
def 					a__				(       snake_case__       )		->      Any:
			lowerCamelCase       =      HashMap(initial_block_size=4       )
			lowerCamelCase       =      {}
			for _, (fun, *args) in enumerate(snake_case__       ):
						lowerCamelCase   ,     lowerCamelCase       =      _run_operation(snake_case__ ,				snake_case__ ,				*snake_case__       )
						lowerCamelCase   ,     lowerCamelCase       =      _run_operation(snake_case__ ,				snake_case__ ,				*snake_case__       )
						assert my_res == py_res
						assert str(snake_case__       ) == str(snake_case__       )
						assert set(snake_case__       ) == set(snake_case__       )
						assert len(snake_case__       ) == len(snake_case__       )
						assert set(my.items()       ) == set(py.items()       )



def 					a__				(       )		->      int:
			def is_public(snake_case__       ) -> bool:
						return not name.startswith("""_"""       )

			lowerCamelCase       =      {name for name in dir({}       ) if is_public(snake_case__       )}
			lowerCamelCase       =      {name for name in dir(HashMap()       ) if is_public(snake_case__       )}

			assert dict_public_names > hash_public_names



