code: 
  
  
  
  
  
  
  """simple docstring"""
  
  import os
  from argparse import ArgumentParser
  from pathlib import Path
  from shutil import copyfile, rmtree
  from typing import Generator
  
  import datasets.config
  from datasets.builder import DatasetBuilder
  from datasets.commands import BaseDatasetsCLICommand
  from datasets.download.download_manager import DownloadMode
  from datasets.load import dataset_module_factory, import_main_class
  from datasets.utils.filelock import logger as fl_logger
  from datasets.utils.info_utils import VerificationMode
  from datasets.utils.logging import ERROR, get_logger
  
  
  lowercase__      =				get_logger(__name__)
  
  def 	__lowerCamelCase			(						__UpperCamelCase )		->					Optional[int]:
  
  		"""simple docstring"""
  
  
  
  
  
  
  
  		return TestCommand(
  		    args.dataset   , args.name   , args.cache_dir   , args.data_dir   , args.all_configs   , args.save_info or args.save_infos   , args.ignore_verifications   , args.force_redownload   , args.clear_cache   , )
  
  
  
  class 	__lowerCamelCase       (				lowerCAmelCase_    ):
  
  
  
  
  
  		'''simple docstring'''
  
  
  
  
  
  
  		a_			:       Optional[Any]      =							False  # to tell pytest it's not a test class
  
  
  
  
  
  		@staticmethod
  		def      lowerCamelCase (     a_							:			int			):
  				lowerCAmelCase_     :							List[Any]             =    parser.add_parser("test"		,    help="Test dataset implementation."			)
  				test_parser.add_argument("--name"		,    type=lowerCamelCase_		,    default=lowerCamelCase_		,    help="Dataset processing name"			)
  				test_parser.add_argument(
  				    "--cache_dir"		,    type=lowerCamelCase_		,    default=lowerCamelCase_		,    help="Cache directory where the datasets are stored."		,    )
  				test_parser.add_argument(
  				    "--data_dir"		,    type=lowerCamelCase_		,    default=lowerCamelCase_		,    help="Can be used to specify a manual directory to get the files from."		,    )
  				test_parser.add_argument("--all_configs"		,    action="store_true"		,    help="Test all dataset configurations"			)
  				test_parser.add_argument(
  				    "--save_info"		,    action="store_true"		,    help="Save the dataset infos in the dataset card (README.md)"			)
  				test_parser.add_argument(
  				    "--ignore_verifications"		,    action="store_true"		,    help="Run the test without checksums and splits checks."		,    )
  				test_parser.add_argument("--force_redownload"		,    action="store_true"		,    help="Force dataset redownload"			)
  				test_parser.add_argument(
  				    "--clear_cache"		,    action="store_true"		,    help="Remove downloaded files and cached datasets after each config test"		,    )
  				# aliases
  				test_parser.add_argument("--save_infos"		,    action="store_true"		,    help="alias to save_info"			)
  				test_parser.add_argument("dataset"		,    type=lowerCamelCase_		,    help="Name of the dataset to download"			)
  				test_parser.set_defaults(func=_test_command_factory			)
  
  
  
  
  
  		def __init__(     self							:			Tuple		,    a_							:			List[Any]		,    a_							:			Optional[int]		,    a_							:			Optional[Any]		,    a_							:			Union[str, Any]		,    a_							:			List[str]		,    a_							:			List[str]		,    a_							:			List[str]		,    a_							:			str		,    a_							:			List[Any]		,    ):
  				lowerCAmelCase_     :							Optional[int]             =    dataset
  				lowerCAmelCase_     :							List[str]             =    name
  				lowerCAmelCase_     :							Dict             =    cache_dir
  				lowerCAmelCase_     :							Tuple             =    data_dir
  				lowerCAmelCase_     :							List[str]             =    all_configs
  				lowerCAmelCase_     :							Any             =    save_infos
  				lowerCAmelCase_     :							Optional[Any]             =    ignore_verifications
  				lowerCAmelCase_     :							Tuple             =    force_redownload
  				lowerCAmelCase_     :							Any             =    clear_cache
  				if clear_cache and not cache_dir:
  						print(
  						    "When --clear_cache is used, specifying a cache directory is mandatory.\n"
  						    "The 'download' folder of the cache directory and the dataset builder cache will be deleted after each configuration test.\n"
  						    "Please provide a --cache_dir that will be used to test the dataset script."			)
  						exit(1			)
  				if save_infos:
  						lowerCAmelCase_     :							Any             =    True
  
  
  
  
  
  		def      lowerCamelCase (     self							:			Dict			):
  				fl_logger().setLevel(lowerCamelCase_			)
  				if self._name is not None and self._all_configs:
  						print("Both parameters `config` and `all_configs` can't be used at once."			)
  						exit(1			)
  				lowerCAmelCase_       ,			lowerCAmelCase_     :							Any             =    self._dataset, self._name
  				lowerCAmelCase_     :							List[str]             =    dataset_module_factory(lowerCamelCase_			)
  				lowerCAmelCase_     :							List[Any]             =    import_main_class(module.module_path			)
  				lowerCAmelCase_     :							Dict             =    len(builder_cls.BUILDER_CONFIGS			) if self._all_configs and builder_cls.BUILDER_CONFIGS else 1
  
  				def get_builders() -> Generator[DatasetBuilder, None, None]:
  						if self._all_configs and builder_cls.BUILDER_CONFIGS:
  								for i, config in enumerate(builder_cls.BUILDER_CONFIGS			):
  										if "config_name" in module.builder_kwargs:
  												yield builder_cls(
  												    cache_dir=self._cache_dir		,    data_dir=self._data_dir		,    **module.builder_kwargs		,    )
  										else:
  												yield builder_cls(
  												    config_name=config.name		,    cache_dir=self._cache_dir		,    data_dir=self._data_dir		,    **module.builder_kwargs		,    )
  						else:
  								if "config_name" in module.builder_kwargs:
  										yield builder_cls(cache_dir=self._cache_dir		,    data_dir=self._data_dir		,    **module.builder_kwargs			)
  								else:
  										yield builder_cls(
  										    config_name=lowerCamelCase_		,    cache_dir=self._cache_dir		,    data_dir=self._data_dir		,    **module.builder_kwargs		,    )
  
  				for j, builder in enumerate(get_builders()			):
  						print(f'''Testing builder \'{builder.config.name}\' ({j + 1}/{n_builders})'''			)
  						lowerCAmelCase_     :							List[str]             =    os.path.exists(
  						    os.path.join(builder.get_imported_module_dir()		,    datasets.config.DATASETDICT_INFOS_FILENAME			)			)  # record checksums only if we need to update a (deprecated) dataset_infos.json
  						builder.download_and_prepare(
  						    download_mode=DownloadMode.REUSE_CACHE_IF_EXISTS
  						    if not self._force_redownload
  						    else DownloadMode.FORCE_REDOWNLOAD		,    verification_mode=VerificationMode.NO_CHECKS
  						    if self._ignore_verifications
  						    else VerificationMode.ALL_CHECKS		,    try_from_hf_gcs=lowerCamelCase_		,    )
  						builder.as_dataset()
  						if self._save_infos:
  								builder._save_infos()
  
  						# If save_infos=True, the dataset card (README.md) is created next to the loaded module file.
  						# The dataset_infos are saved in the YAML part of the README.md
  
  						# Let's move it to the original directory of the dataset script, to allow the user to
  						# upload them on S3 at the same time afterwards.
  						if self._save_infos:
  								lowerCAmelCase_     :							List[str]             =    os.path.join(builder_cls.get_imported_module_dir()		,    "README.md"			)
  								lowerCAmelCase_     :							int             =    Path(lowerCamelCase_			).name + ".py"
  								lowerCAmelCase_     :							Tuple             =    os.path.join(lowerCamelCase_		,    lowerCamelCase_			)
  								if os.path.isfile(lowerCamelCase_			):
  										lowerCAmelCase_     :							List[Any]             =    os.path.dirname(lowerCamelCase_			)
  								elif os.path.isfile(lowerCamelCase_			):
  										lowerCAmelCase_     :							Union[str, Any]             =    path
  								elif os.path.isdir(lowerCamelCase_			):  # for local directories containing only data files
  										lowerCAmelCase_     :							Tuple             =    path
  								else:  # in case of a remote dataset
  										lowerCAmelCase_     :							Optional[Any]             =    None
  										print(f'''Dataset card saved at {dataset_readme_path}'''			)
  
  								# Move dataset_info back to the user
  								if dataset_dir is not None:
  										lowerCAmelCase_     :							str             =    os.path.join(lowerCamelCase_		,    "README.md"			)
  										copyfile(lowerCamelCase_		,    lowerCamelCase_			)
  										print(f'''Dataset card saved at {user_dataset_readme_path}'''			)
  
              # If clear_cache=True, the download folder and the dataset builder cache directory are deleted
  						if self._clear_cache:
  								if os.path.isdir(builder._cache_dir			):
  										logger.warning(f'''Clearing cache at {builder._cache_dir}'''			)
  										rmtree(builder._cache_dir			)
  								lowerCAmelCase_     :							int             =    os.path.join(self._cache_dir		,    datasets.config.DOWNLOADED_DATASETS_DIR			)
  								if os.path.isdir(lowerCamelCase_			):
  										logger.warning(f'''Clearing cache at {download_dir}'''			)
  										rmtree(lowerCamelCase_			)
  
  				print("Test successful."			)
  
  
  
  
style_context: 
  
  
  
  
  
  
  """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()
  