


"""simple docstring"""







import re
import time
from typing import Optional

import IPython.display as disp

from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length
def _A						(						lowercase		):







    """simple docstring"""
    a 		=int(_lowercase		)
    a 		=t // 36_00, (t // 60) % 60, t % 60
    return f'''{h}:{m:02d}:{s:02d}''' if h != 0 else f'''{m:02d}:{s:02d}'''
def _A						(						lowercase       ,    lowercase       ,    lowercase       ,    lowercase       ,    lowercase=3_00		):







    """simple docstring"""
    return f'''
    <div>
      {prefix}
      <progress value=\'{value}\' max=\'{total}\' style=\'width:{width}px; height:20px; vertical-align: middle;\'></progress>
      {label}
    </div>
    '''
def _A						(						lowercase		):







    """simple docstring"""
    a 		="""<table border=\"1\" class=\"dataframe\">\n"""
    html_code += """  <thead>\n <tr style="text-align: left;">\n"""
    for i in items[0]:
        html_code += f'''      <th>{i}</th>\n'''
    html_code += "    </tr>\n  </thead>\n  <tbody>\n"
    for line in items[1:]:
        html_code += "    <tr>\n"
        for elt in line:
            a 		=f'''{elt:.6f}''' if isinstance(_lowercase       ,    _lowercase		) else str(_lowercase		)
            html_code += f'''      <td>{elt}</td>\n'''
        html_code += "    </tr>\n"
    html_code += "  </tbody>\n</table><p>"
    return html_code






class       __A				:






 """simple docstring"""




 __lowerCAmelCase 					=  5
 __lowerCAmelCase 					=  0.2


 def __init__(		self ,    __A ,    __A = None ,    __A = True ,    __A = None ,    __A = 300 ,    )					->     List[Any]:
     a 		=total
     a 		="""""" if prefix is None else prefix
     a 		=leave
     a 		=parent
     a 		=width
     a 		=None
     a 		=None
     a 		=None


 def       SCREAMING_SNAKE_CASE							(		self ,    __A ,    __A = False ,    __A = None						)					->     Any:
     a 		=value
     if comment is not None:
         a 		=comment
     if self.last_value is None:
         a 		=time.time()
         a 		=value
         a 		=None
         a 		=self.warmup
         a 		=1
         self.update_bar(__A						)
     elif value <= self.last_value and not force_update:
         return
     elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for ,    self.total						):
         if self.first_calls > 0:
             self.first_calls -= 1
         a 		=time.time()
         a 		=current_time - self.start_time
         # We could have value = self.start_value if the update is called twixe with the same start value.
         if value > self.start_value:
             a 		=self.elapsed_time / (value - self.start_value)
         else:
             a 		=None
         if value >= self.total:
             a 		=self.total
             a 		=None
             if not self.leave:
                 self.close()
         elif self.average_time_per_item is not None:
             a 		=self.average_time_per_item * (self.total - value)
         self.update_bar(__A						)
         a 		=value
         a 		=current_time
         if self.average_time_per_item is None:
             a 		=1
         else:
             a 		=max(int(self.update_every / self.average_time_per_item						) ,    1						)


 def       SCREAMING_SNAKE_CASE							(		self ,    __A ,    __A=None						)					->     Dict:
     a 		=""" """ * (len(str(self.total						)						) - len(str(__A						)						)) + str(__A						)
     if self.elapsed_time is None:
         a 		=f'''[{spaced_value}/{self.total} : < :'''
     elif self.predicted_remaining is None:
         a 		=f'''[{spaced_value}/{self.total} {format_time(self.elapsed_time						)}'''
     else:
         a 		=(
             f'''[{spaced_value}/{self.total} {format_time(self.elapsed_time						)} <'''
             f''' {format_time(self.predicted_remaining						)}'''
         )
         self.label += f''', {1/self.average_time_per_item:.2f} it/s'''
     self.label += "]" if self.comment is None or len(self.comment						) == 0 else f''', {self.comment}]'''
     self.display()


 def       SCREAMING_SNAKE_CASE							(		self						)					->     Any:
     a 		=html_progress_bar(self.value ,    self.total ,    self.prefix ,    self.label ,    self.width						)
     if self.parent is not None:
         # If this is a child bar, the parent will take care of the display.
         self.parent.display()
         return
     if self.output is None:
         a 		=disp.display(disp.HTML(self.html_code						) ,    display_id=__A						)
     else:
         self.output.update(disp.HTML(self.html_code						)						)





 def       SCREAMING_SNAKE_CASE							(		self						)					->     Any:
     if self.parent is None and self.output is not None:
         self.output.update(disp.HTML(''''''						)						)






class       __A				(       _lowerCAmelCase			):






 """simple docstring"""




 def __init__(		self ,    __A ,    __A=None						)					->     Any:
     super().__init__(__A						)
     a 		=None if column_names is None else [column_names]
     a 		=None


 def       SCREAMING_SNAKE_CASE							(		self						)					->     List[Any]:
     a 		=html_progress_bar(self.value ,    self.total ,    self.prefix ,    self.label ,    self.width						)
     if self.inner_table is not None:
         self.html_code += text_to_html_table(self.inner_table						)
     if self.child_bar is not None:
         self.html_code += self.child_bar.html_code
     if self.output is None:
         a 		=disp.display(disp.HTML(self.html_code						) ,    display_id=__A						)
     else:
         self.output.update(disp.HTML(self.html_code						)						)


 def       SCREAMING_SNAKE_CASE							(		self ,    __A						)					->     List[Any]:
     if self.inner_table is None:
         a 		=[list(values.keys()						), list(values.values()						)]
     else:
         a 		=self.inner_table[0]
         if len(self.inner_table						) == 1:
             # We give a chance to update the column names at the first iteration
             for key in values.keys():
                 if key not in columns:
                     columns.append(__A						)
             a 		=columns
         self.inner_table.append([values[c] for c in columns]						)


 def       SCREAMING_SNAKE_CASE							(		self ,    __A ,    __A=None ,    __A=300						)					->     Any:
     a 		=NotebookProgressBar(__A ,    prefix=__A ,    parent=self ,    width=__A						)
     return self.child_bar





 def       SCREAMING_SNAKE_CASE							(		self						)					->     Any:
     a 		=None
     self.display()






class       __A				(       _lowerCAmelCase			):






 """simple docstring"""




 def __init__(		self						)					->     Any:
     a 		=None
     a 		=None
     a 		=False


 def       SCREAMING_SNAKE_CASE							(		self ,    __A ,    __A ,    __A ,    **__A						)					->     Tuple:
     a 		="""Epoch""" if args.evaluation_strategy == IntervalStrategy.EPOCH else """Step"""
     a 		=0
     a 		=0
     a 		=[self.first_column] + ["""Training Loss"""]
     if args.evaluation_strategy != IntervalStrategy.NO:
         column_names.append('''Validation Loss'''						)
     a 		=NotebookTrainingTracker(state.max_steps ,    __A						)


 def       SCREAMING_SNAKE_CASE							(		self ,    __A ,    __A ,    __A ,    **__A						)					->     Optional[int]:
     a 		=int(state.epoch						) if int(state.epoch						) == state.epoch else f'''{state.epoch:.2f}'''
     self.training_tracker.update(
         state.global_step + 1 ,    comment=f'''Epoch {epoch}/{state.num_train_epochs}''' ,    force_update=self._force_next_update ,    )
     a 		=False


 def       SCREAMING_SNAKE_CASE							(		self ,    __A ,    __A ,    __A ,    __A=None ,    **__A						)					->     Any:
     if not has_length(__A						):
         return
     if self.prediction_bar is None:
         if self.training_tracker is not None:
             a 		=self.training_tracker.add_child(len(__A						)						)
         else:
             a 		=NotebookProgressBar(len(__A						)						)
         self.prediction_bar.update(1						)
     else:
         self.prediction_bar.update(self.prediction_bar.value + 1						)


 def       SCREAMING_SNAKE_CASE							(		self ,    __A ,    __A ,    __A ,    **__A						)					->     Any:
     if self.prediction_bar is not None:
         self.prediction_bar.close()
     a 		=None


 def       SCREAMING_SNAKE_CASE							(		self ,    __A ,    __A ,    __A ,    __A=None ,    **__A						)					->     Any:
     # Only for when there is no evaluation
     if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
         a 		={"""Training Loss""": logs["""loss"""]}
         # First column is necessarily Step sine we're not in epoch eval strategy
         a 		=state.global_step
         self.training_tracker.write_line(__A						)


 def       SCREAMING_SNAKE_CASE							(		self ,    __A ,    __A ,    __A ,    __A=None ,    **__A						)					->     List[Any]:
     if self.training_tracker is not None:
         a 		={"""Training Loss""": """No log""", """Validation Loss""": """No log"""}
         for log in reversed(state.log_history						):
             if "loss" in log:
                 a 		=log["""loss"""]
                 break

         if self.first_column == "Epoch":
             a 		=int(state.epoch						)
         else:
             a 		=state.global_step
         a 		="""eval"""
         for k in metrics:
             if k.endswith('''_loss'''						):
                 a 		=re.sub(r'''\_loss$''' ,    '''''' ,    __A						)
         a 		=metrics.pop('''total_flos''' ,    __A						)
         a 		=metrics.pop('''epoch''' ,    __A						)
         a 		=metrics.pop(f'''{metric_key_prefix}_runtime''' ,    __A						)
         a 		=metrics.pop(f'''{metric_key_prefix}_samples_per_second''' ,    __A						)
         a 		=metrics.pop(f'''{metric_key_prefix}_steps_per_second''' ,    __A						)
         a 		=metrics.pop(f'''{metric_key_prefix}_jit_compilation_time''' ,    __A						)
         for k, v in metrics.items():
             if k == f'''{metric_key_prefix}_loss''':
                 a 		=v
             else:
                 a 		=k.split('''_'''						)
                 a 		=""" """.join([part.capitalize() for part in splits[1:]]						)
                 a 		=v
         self.training_tracker.write_line(__A						)
         self.training_tracker.remove_child()
         a 		=None
         # Evaluation takes a long time so we should force the next update.
         a 		=True





 def       SCREAMING_SNAKE_CASE							(		self ,    __A ,    __A ,    __A ,    **__A						)					->     Any:
     self.training_tracker.update(
         state.global_step ,    comment=f'''Epoch {int(state.epoch						)}/{state.num_train_epochs}''' ,    force_update=__A						)
     a 		=None




"""simple docstring"""
import math
class 				lowerCamelCase  :






					'''simple docstring'''





					def    lowerCAmelCase_				(       self:							Tuple						,     snake_case:							list[list[float]]						,     snake_case:							list[int]						)   ->	int:
											snake_case_ :Any						=			0.0
											snake_case_ :Tuple						=			0.0
											for i in range(len(snake_case						)						):
																	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:							Optional[int]						,     snake_case:							list[list[int | float]]						,     snake_case:							list[int]						,     snake_case:							int						,     snake_case:							float						)   ->	list[list[int | float]]:
											for i in range(len(snake_case						)						):
																	weights[j][i] += alpha * (sample[i] - weights[j][i])
											return weights

def    A_  (			):







						'''simple docstring'''


						snake_case_ :Dict						=			[[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]]

						# weight initialization ( n, C )
						snake_case_ :List[Any]						=			[[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]]

						# training
						snake_case_ :Optional[Any]						=			SelfOrganizingMap()
						snake_case_ :Dict						=			3
						snake_case_ :Dict						=			0.5

						for _ in range(_lowercase	):
												for j in range(len(_lowercase	)	):
																		# training sample
																		snake_case_ :List[Any]						=			training_samples[j]

																		# Compute the winning vector
																		snake_case_ :Optional[int]						=			self_organizing_map.get_winner(_lowercase,					_lowercase	)

																		# Update the winning vector
																		snake_case_ :List[str]						=			self_organizing_map.update(_lowercase,					_lowercase,					_lowercase,					_lowercase	)

    # classify test sample
						snake_case_ :str						=			[0, 0, 0, 1]
						snake_case_ :List[Any]						=			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()
