






"""simple docstring"""

import math
from collections import OrderedDict

import torch
from packaging import version
from torch import Tensor, nn

from .utils import logging


lowercase__      =				logging.get_logger(__name__)


class 	__lowerCamelCase       (				nn.Module    ):





		'''simple docstring'''






		def __init__(     self							:			Optional[Any]			):
				super().__init__()
				if version.parse(torch.__version__			) < version.parse("1.12.0"			):
						raise ImportError(
						    f'''You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use '''
						    "PytorchGELUTanh. Please upgrade torch."			)





		def      lowerCamelCase (     self							:			Any		,    a_							:			Tensor			):
				return nn.functional.gelu(a_		,    approximate="tanh"			)







class 	__lowerCamelCase       (				nn.Module    ):





		'''simple docstring'''






		def      lowerCamelCase (     self							:			Dict		,    a_							:			Tensor			):
				return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi			) * (input + 0.044715 * torch.pow(a_		,    3.0			))			))







class 	__lowerCamelCase       (				nn.Module    ):





		'''simple docstring'''






		def __init__(     self							:			Optional[int]		,    a_							:			bool = False			):
				super().__init__()
				if use_gelu_python:
						lowerCAmelCase_     :							Any             =    self._gelu_python
				else:
						lowerCAmelCase_     :							str             =    nn.functional.gelu





		def      lowerCamelCase (     self							:			str		,    a_							:			Tensor			):
				return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0			)			))





		def      lowerCamelCase (     self							:			Union[str, Any]		,    a_							:			Tensor			):
				return self.act(a_			)







class 	__lowerCamelCase       (				nn.Module    ):





		'''simple docstring'''






		def      lowerCamelCase (     self							:			Optional[int]		,    a_							:			Tensor			):
				return 0.5 * input * (1.0 + torch.tanh(input * 0.7978845608 * (1.0 + 0.044715 * input * input)			))







class 	__lowerCamelCase       (				nn.Module    ):





		'''simple docstring'''






		def      lowerCamelCase (     self							:			Union[str, Any]		,    a_							:			Tensor			):
				return input * torch.sigmoid(1.702 * input			)







class 	__lowerCamelCase       (				nn.Module    ):





		'''simple docstring'''






		def __init__(     self							:			Union[str, Any]		,    a_							:			float		,    a_							:			float			):
				if min > max:
						raise ValueError(f'''min should be < max (got min: {min}, max: {max})'''			)

				super().__init__()
				lowerCAmelCase_     :							List[str]             =    min
				lowerCAmelCase_     :							Dict             =    max





		def      lowerCamelCase (     self							:			int		,    a_							:			Tensor			):
				return torch.clip(gelu(a_			)		,    self.min		,    self.max			)







class 	__lowerCamelCase       (				nn.Module    ):





		'''simple docstring'''






		def __init__(     self							:			List[Any]			):
				super().__init__()
				lowerCAmelCase_     :							Optional[Any]             =    math.sqrt(2 / math.pi			)





		def      lowerCamelCase (     self							:			List[str]		,    a_							:			Tensor			):
				return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.044715 * torch.pow(a_		,    3			))			))







class 	__lowerCamelCase       (				nn.Module    ):





		'''simple docstring'''






		def      lowerCamelCase (     self							:			Tuple		,    a_							:			Tensor			):
				return nn.functional.silu(a_			)







class 	__lowerCamelCase       (				nn.Module    ):





		'''simple docstring'''






		def __init__(     self							:			Optional[Any]			):
				super().__init__()
				if version.parse(torch.__version__			) < version.parse("1.9.0"			):
						lowerCAmelCase_     :							List[str]             =    self._mish_python
				else:
						lowerCAmelCase_     :							int             =    nn.functional.mish





		def      lowerCamelCase (     self							:			Optional[int]		,    a_							:			Tensor			):
				return input * torch.tanh(nn.functional.softplus(a_			)			)





		def      lowerCamelCase (     self							:			int		,    a_							:			Tensor			):
				return self.act(a_			)







class 	__lowerCamelCase       (				nn.Module    ):





		'''simple docstring'''






		def      lowerCamelCase (     self							:			int		,    a_							:			Tensor			):
				return input







class 	__lowerCamelCase       (				nn.Module    ):





		'''simple docstring'''






		def      lowerCamelCase (     self							:			Optional[Any]		,    a_							:			str		,    a_							:			str=0.707107		,    a_							:			str=0.282095			):
				lowerCAmelCase_     :							Any             =    (input - mu).div(sigma * math.sqrt(2.0			)			)
				return 0.5 * (1.0 + torch.erf(a_			))







class 	__lowerCamelCase       (				nn.Module    ):





		'''simple docstring'''






		def      lowerCamelCase (     self							:			List[str]		,    a_							:			int			):
				lowerCAmelCase_     :							List[str]             =    nn.functional.relu(a_			)
				lowerCAmelCase_     :							Any             =    torch.square(a_			)
				return squared







class 	__lowerCamelCase       (				A__    ):





		'''simple docstring'''






		def __getitem__(     self							:			Dict		,    a_							:			Tuple			):
				lowerCAmelCase_     :							Optional[Any]             =    super().__getitem__(a_			)
				lowerCAmelCase_     :							List[Any]             =    content if isinstance(a_		,    a_			) else (content, {})
				return cls(**a_			)







lowercase__      =				{
    """gelu""": GELUActivation,
    """gelu_10""": (ClippedGELUActivation, {"""min""": -10, """max""": 10}),
    """gelu_fast""": FastGELUActivation,
    """gelu_new""": NewGELUActivation,
    """gelu_python""": (GELUActivation, {"""use_gelu_python""": True}),
    """gelu_pytorch_tanh""": PytorchGELUTanh,
    """gelu_accurate""": AccurateGELUActivation,
    """laplace""": LaplaceActivation,
    """linear""": LinearActivation,
    """mish""": MishActivation,
    """quick_gelu""": QuickGELUActivation,
    """relu""": nn.ReLU,
    """relu2""": ReLUSquaredActivation,
    """relu6""": nn.ReLUa,
    """sigmoid""": nn.Sigmoid,
    """silu""": SiLUActivation,
    """swish""": SiLUActivation,
    """tanh""": nn.Tanh,
}
lowercase__      =				ClassInstantier(ACTaCLS)

def 	__lowerCamelCase			(						__UpperCamelCase )		->					List[str]:

		"""simple docstring"""







		if activation_string in ACTaFN:
				return ACTaFN[activation_string]
		else:
				raise KeyError(f'''function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}''' )


# For backwards compatibility with: from activations import gelu_python
lowercase__      =				get_activation("""gelu_python""")
lowercase__      =				get_activation("""gelu_new""")
lowercase__      =				get_activation("""gelu""")
lowercase__      =				get_activation("""gelu_fast""")
lowercase__      =				get_activation("""quick_gelu""")
lowercase__      =				get_activation("""silu""")
lowercase__      =				get_activation("""mish""")



lowercase__      =				get_activation("""linear""")











"""simple docstring"""

import warnings

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.metrics import pairwise_distances

warnings.filterwarnings("""ignore""")

lowercase__      =				"""K-MEANS-CLUST/ """

def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase=None )		->					Optional[Any]:

		"""simple docstring"""







		if seed is not None:  # useful for obtaining consistent results
				np.random.seed(__UpperCamelCase )
		lowerCAmelCase_     :							List[Any]             =    data.shape[0]  # number of data points

		# Pick K indices from range [0, N).
		lowerCAmelCase_     :							Optional[Any]             =    np.random.randint(0   , __UpperCamelCase   , __UpperCamelCase )

		# Keep centroids as dense format, as many entries will be nonzero due to averaging.
		# As long as at least one document in a cluster contains a word,
		# it will carry a nonzero weight in the TF-IDF vector of the centroid.
		lowerCAmelCase_     :							List[str]             =    data[rand_indices, :]

		return centroids

def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase )		->					Dict:

		"""simple docstring"""







		return pairwise_distances(__UpperCamelCase   , __UpperCamelCase   , metric="euclidean" )

def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase )		->					List[str]:

		"""simple docstring"""







		lowerCAmelCase_     :							Optional[Any]             =    centroid_pairwise_dist(__UpperCamelCase   , __UpperCamelCase )

		# Compute cluster assignments for each data point:
		# Fill in the blank (RHS only)
		lowerCAmelCase_     :							str             =    np.argmin(__UpperCamelCase   , axis=1 )

		return cluster_assignment

def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase )		->					Dict:

		"""simple docstring"""







		lowerCAmelCase_     :							Tuple             =    []
		for i in range(__UpperCamelCase ):
				# Select all data points that belong to cluster i. Fill in the blank (RHS only)
				lowerCAmelCase_     :							List[Any]             =    data[cluster_assignment == i]
				# Compute the mean of the data points. Fill in the blank (RHS only)
				lowerCAmelCase_     :							List[str]             =    member_data_points.mean(axis=0 )
				new_centroids.append(__UpperCamelCase )
		lowerCAmelCase_     :							Tuple             =    np.array(__UpperCamelCase )

		return new_centroids

def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase )		->					int:

		"""simple docstring"""







		lowerCAmelCase_     :							Union[str, Any]             =    0.0
		for i in range(__UpperCamelCase ):
				# Select all data points that belong to cluster i. Fill in the blank (RHS only)
				lowerCAmelCase_     :							List[str]             =    data[cluster_assignment == i, :]

				if member_data_points.shape[0] > 0:  # check if i-th cluster is non-empty
						# Compute distances from centroid to data points (RHS only)
						lowerCAmelCase_     :							int             =    pairwise_distances(
						    __UpperCamelCase   , [centroids[i]]   , metric="euclidean" )
						lowerCAmelCase_     :							Optional[int]             =    distances**2
						heterogeneity += np.sum(__UpperCamelCase )

		return heterogeneity

def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase )		->					Dict:

		"""simple docstring"""







		plt.figure(figsize=(7, 4) )
		plt.plot(__UpperCamelCase   , linewidth=4 )
		plt.xlabel("# Iterations" )
		plt.ylabel("Heterogeneity" )
		plt.title(f'''Heterogeneity of clustering over time, K={k:d}''' )
		plt.rcParams.update({"font.size": 16} )
		plt.show()

def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase=500   , __UpperCamelCase=None   , __UpperCamelCase=False )		->					List[Any]:

		"""simple docstring"""







		lowerCAmelCase_     :							Dict             =    initial_centroids[:]
		lowerCAmelCase_     :							Optional[int]             =    None

		for itr in range(__UpperCamelCase ):
				if verbose:
						print(__UpperCamelCase   , end="" )

				# 1. Make cluster assignments using nearest centroids
				lowerCAmelCase_     :							Optional[Any]             =    assign_clusters(__UpperCamelCase   , __UpperCamelCase )

				# 2. Compute a new centroid for each of the k clusters, averaging all data
				#    points assigned to that cluster.
				lowerCAmelCase_     :							Tuple             =    revise_centroids(__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase )

				# Check for convergence: if none of the assignments changed, stop
				if (
				    prev_cluster_assignment is not None
				    and (prev_cluster_assignment == cluster_assignment).all()
				):
						break

				# Print number of new assignments
				if prev_cluster_assignment is not None:
						lowerCAmelCase_     :							Union[str, Any]             =    np.sum(prev_cluster_assignment != cluster_assignment )
						if verbose:
								print(
								    f'''    {num_changed:5d} elements changed their cluster assignment.''' )

        # Record heterogeneity convergence metric
				if record_heterogeneity is not None:
						# YOUR CODE HERE
						lowerCAmelCase_     :							Tuple             =    compute_heterogeneity(__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase )
						record_heterogeneity.append(__UpperCamelCase )

				lowerCAmelCase_     :							str             =    cluster_assignment[:]

		return centroids, cluster_assignment


# Mock test below
if False:  # change to true to run this test case.
					from sklearn import datasets as ds

					lowercase__      =				ds.load_iris()
					lowercase__      =				3
					lowercase__      =				[]
					lowercase__      =				get_initial_centroids(dataset["""data"""], k, seed=0)
					lowercase__ ,     lowercase__      =				kmeans(
					    dataset["""data"""],
					    k,
					    initial_centroids,
					    maxiter=400,
					    record_heterogeneity=heterogeneity,
					    verbose=True,
					)
					plot_heterogeneity(heterogeneity, k)

def 	__lowerCamelCase			(						__UpperCamelCase   , __UpperCamelCase   , __UpperCamelCase=None )		->					pd.DataFrame:

		"""simple docstring"""







		if fill_missing_report:
				lowerCAmelCase_     :							str             =    df.fillna(value=__UpperCamelCase )
		lowerCAmelCase_     :							Optional[int]             =    1
		lowerCAmelCase_     :							Optional[int]             =    df.select_dtypes(np.number ).columns
		lowerCAmelCase_     :							Dict             =    (
		    df.groupby(["Cluster"] )[  # construct report dataframe
		        numeric_cols
		    ]  # group by cluster number
		    .agg(
		        [
		            ("sum", np.sum),
		            ("mean_with_zeros", lambda __UpperCamelCase : np.mean(np.nan_to_num(__UpperCamelCase ) )),
		            ("mean_without_zeros", lambda __UpperCamelCase : x.replace(0   , np.NaN ).mean()),
		            (
		                "mean_25-75",
		                lambda __UpperCamelCase : np.mean(
		                    np.nan_to_num(
		                        sorted(__UpperCamelCase )[
		                            round(len(__UpperCamelCase ) * 25 / 100 ) : round(len(__UpperCamelCase ) * 75 / 100 )
		                        ] ) ),
		            ),
		            ("mean_with_na", np.mean),
		            ("min", lambda __UpperCamelCase : x.min()),
		            ("5%", lambda __UpperCamelCase : x.quantile(0.05 )),
		            ("25%", lambda __UpperCamelCase : x.quantile(0.25 )),
		            ("50%", lambda __UpperCamelCase : x.quantile(0.50 )),
		            ("75%", lambda __UpperCamelCase : x.quantile(0.75 )),
		            ("95%", lambda __UpperCamelCase : x.quantile(0.95 )),
		            ("max", lambda __UpperCamelCase : x.max()),
		            ("count", lambda __UpperCamelCase : x.count()),
		            ("stdev", lambda __UpperCamelCase : x.std()),
		            ("mode", lambda __UpperCamelCase : x.mode()[0]),
		            ("median", lambda __UpperCamelCase : x.median()),
		            ("# > 0", lambda __UpperCamelCase : (x > 0).sum()),
		        ] )
		    .T.reset_index()
		    .rename(index=__UpperCamelCase   , columns={"level_0": "Features", "level_1": "Type"} )
		)  # rename columns
		# calculate the size of cluster(count of clientID's)
		lowerCAmelCase_     :							Optional[Any]             =    report[
		    (report["Features"] == "dummy") & (report["Type"] == "count")
		].copy()  # avoid SettingWithCopyWarning
		lowerCAmelCase_     :							List[Any]             =    (
		    "ClusterSize"  # rename created cluster df to match report column names
		)
		lowerCAmelCase_     :							Dict             =    "# of Customers"
		lowerCAmelCase_     :							List[str]             =    pd.DataFrame(
		    clustersize.iloc[:, 2:].values
		    / clustersize.iloc[:, 2:].values.sum() )
		lowerCAmelCase_     :							Optional[Any]             =    "% of Customers"  # rename created cluster df to match report column names
		lowerCAmelCase_     :							Dict             =    "ClusterProportion"
		lowerCAmelCase_     :							Optional[Any]             =    clusterproportion.columns.tolist()
		lowerCAmelCase_     :							Optional[Any]             =    cols[-2:] + cols[:-2]
		lowerCAmelCase_     :							Dict             =    clusterproportion[cols]  # rearrange columns to match report
		lowerCAmelCase_     :							Union[str, Any]             =    report.columns
		lowerCAmelCase_     :							Dict             =    pd.DataFrame(
		    abs(
		        report[report["Type"] == "count"].iloc[:, 2:].values
		        - clustersize.iloc[:, 2:].values ) )  # generating df with count of nan values
		lowerCAmelCase_     :							Union[str, Any]             =    0
		lowerCAmelCase_     :							Any             =    "# of nan"
		lowerCAmelCase_     :							Dict             =    report[
		    report["Type"] == "count"
		].Features.tolist()  # filling values in order to match report
		lowerCAmelCase_     :							Optional[Any]             =    a.columns.tolist()
		lowerCAmelCase_     :							Optional[Any]             =    cols[-2:] + cols[:-2]
		lowerCAmelCase_     :							str             =    a[cols]  # rearrange columns to match report
		lowerCAmelCase_     :							Tuple             =    report.columns  # rename columns to match report
		lowerCAmelCase_     :							List[str]             =    report.drop(
		    report[report.Type == "count"].index )  # drop count values except cluster size
		lowerCAmelCase_     :							Tuple             =    pd.concat(
		    [report, a, clustersize, clusterproportion]   , axis=0 )  # concat report with clustert size and nan values
		lowerCAmelCase_     :							List[Any]             =    report["Features"].isin(__UpperCamelCase )
		lowerCAmelCase_     :							Tuple             =    report.columns.tolist()
		lowerCAmelCase_     :							List[str]             =    cols[0:2] + cols[-1:] + cols[2:-1]
		lowerCAmelCase_     :							List[str]             =    report[cols]
		lowerCAmelCase_     :							str             =    {
		    "ClusterSize": 9,
		    "ClusterProportion": 8,
		    "mean_with_zeros": 7,
		    "mean_with_na": 6,
		    "max": 5,
		    "50%": 4,
		    "min": 3,
		    "25%": 2,
		    "75%": 1,
		    "# of nan": 0,
		    "# > 0": -1,
		    "sum_with_na": -2,
		}
		lowerCAmelCase_     :							List[str]             =    (
		    report.assign(
		        Sortera=lambda __UpperCamelCase : x.Type.map(__UpperCamelCase )   , Sortera=lambda __UpperCamelCase : list(reversed(range(len(__UpperCamelCase ) ) ) )   , )
		    .sort_values(["Sorter1", "Mark", "Sorter2"]   , ascending=__UpperCamelCase )
		    .drop(["Sorter1", "Sorter2"]   , axis=1 )
		)
		lowerCAmelCase_     :							str             =    ""
		lowerCAmelCase_     :							Any             =    report.reset_index()
		lowerCAmelCase_     :							Any             =    report.drop(columns=["index"] )
		return report


if __name__ == "__main__":
					import doctest

					doctest.testmod()
