



'''simple docstring'''




import argparse
import glob
import logging
import os
import sys
import time
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Tuple

import numpy as np
import pytorch_lightning as pl
import torch
from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback
from torch import nn
from torch.utils.data import DataLoader

from transformers import MBartTokenizer, TaForConditionalGeneration
from transformers.models.bart.modeling_bart import shift_tokens_right
from utils import (
    ROUGE_KEYS,
    LegacySeqaSeqDataset,
    SeqaSeqDataset,
    assert_all_frozen,
    calculate_bleu,
    calculate_rouge,
    check_output_dir,
    flatten_list,
    freeze_embeds,
    freeze_params,
    get_git_info,
    label_smoothed_nll_loss,
    lmap,
    pickle_save,
    save_git_info,
    save_json,
    use_task_specific_params,
)


# need the parent dir module
sys.path.insert(2, str(Path(__file__).resolve().parents[1]))
from lightning_base import BaseTransformer, add_generic_args, generic_train  # noqa


a     :    str      						=					logging.getLogger(__name__)

class     UpperCamelCase_				(							__magic_name__    ):
	lowercase    =				'summarization'
	lowercase    =				['loss']
	lowercase    =				ROUGE_KEYS
	lowercase    =				'rouge2'





	def __init__(						self	,	A	,	**A					)    ->    int:
								if hparams.sortish_sampler and hparams.gpus > 1:
															UpperCAmelCase  :	List[Any]							  =	False
								elif hparams.max_tokens_per_batch is not None:
															if hparams.gpus > 1:
																						raise NotImplementedError("""Dynamic Batch size does not work for multi-gpu training"""					)
															if hparams.sortish_sampler:
																						raise ValueError("""--sortish_sampler and --max_tokens_per_batch may not be used simultaneously"""					)

								super().__init__(A	,	num_labels=A	,	mode=self.mode	,	**A					)
								use_task_specific_params(self.model	,	"""summarization"""					)
								save_git_info(self.hparams.output_dir					)
								UpperCAmelCase  :	Dict							  =	Path(self.output_dir					) / """metrics.json"""
								UpperCAmelCase  :	Dict							  =	Path(self.output_dir					) / """hparams.pkl"""
								pickle_save(self.hparams	,	self.hparams_save_path					)
								UpperCAmelCase  :	int							  =	0
								UpperCAmelCase  :	str							  =	defaultdict(A					)
								UpperCAmelCase  :	List[str]							  =	self.config.model_type
								UpperCAmelCase  :	Any							  =	self.config.tgt_vocab_size if self.model_type == """fsmt""" else self.config.vocab_size

								UpperCAmelCase  :	dict							  =	{
								    "data_dir": self.hparams.data_dir,
								    "max_source_length": self.hparams.max_source_length,
								    "prefix": self.model.config.prefix or "",
								}
								UpperCAmelCase  :	List[str]							  =	{
								    """train""": self.hparams.n_train,
								    """val""": self.hparams.n_val,
								    """test""": self.hparams.n_test,
								}
								UpperCAmelCase  :	Union[str, Any]							  =	{k: v if v >= 0 else None for k, v in n_observations_per_split.items()}

								UpperCAmelCase  :	Union[str, Any]							  =	{
								    """train""": self.hparams.max_target_length,
								    """val""": self.hparams.val_max_target_length,
								    """test""": self.hparams.test_max_target_length,
								}
								assert self.target_lens["train"] <= self.target_lens["val"], f'''target_lens: {self.target_lens}'''
								assert self.target_lens["train"] <= self.target_lens["test"], f'''target_lens: {self.target_lens}'''
								if self.hparams.freeze_embeds:
															freeze_embeds(self.model					)
								if self.hparams.freeze_encoder:
															freeze_params(self.model.get_encoder()					)
															assert_all_frozen(self.model.get_encoder()					)

								UpperCAmelCase  :	Optional[Any]							  =	get_git_info()["""repo_sha"""]
								UpperCAmelCase  :	Union[str, Any]							  =	hparams.num_workers
								UpperCAmelCase  :	List[str]							  =	None  # default to config
								if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer	,	A					):
															UpperCAmelCase  :	Optional[int]							  =	self.tokenizer.lang_code_to_id[hparams.tgt_lang]
															UpperCAmelCase  :	Dict							  =	self.decoder_start_token_id
								UpperCAmelCase  :	Any							  =	(
								    SeqaSeqDataset if hasattr(self.tokenizer	,	"""prepare_seq2seq_batch"""					) else LegacySeqaSeqDataset
								)
								UpperCAmelCase  :	List[str]							  =	False
								UpperCAmelCase  :	Union[str, Any]							  =	self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams
								if self.hparams.eval_max_gen_length is not None:
															UpperCAmelCase  :	int							  =	self.hparams.eval_max_gen_length
								else:
															UpperCAmelCase  :	Dict							  =	self.model.config.max_length
								UpperCAmelCase  :	List[Any]							  =	self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric





	def 				_lowercase(						self	,	A					)    ->    Dict[str, List[str]]:
								UpperCAmelCase  :	Dict							  =	{
								    k: self.tokenizer.batch_decode(v.tolist()					) if """mask""" not in k else v.shape for k, v in batch.items()
								}
								save_json(A	,	Path(self.output_dir					) / """text_batch.json"""					)
								save_json({k: v.tolist() for k, v in batch.items()}	,	Path(self.output_dir					) / """tok_batch.json"""					)

								UpperCAmelCase  :	Tuple							  =	True
								return readable_batch





	def 				_lowercase(						self	,	A	,	**A					)    ->    int:
								return self.model(A	,	**A					)





	def 				_lowercase(						self	,	A					)    ->    Optional[Any]:
								UpperCAmelCase  :	Tuple							  =	self.tokenizer.batch_decode(
								    A	,	skip_special_tokens=A	,	clean_up_tokenization_spaces=A					)
								return lmap(str.strip	,	A					)





	def 				_lowercase(						self	,	A					)    ->    Tuple:
								UpperCAmelCase  :	Optional[int]							  =	self.tokenizer.pad_token_id
								UpperCAmelCase  ,  UpperCAmelCase  :	Optional[int]							  =	batch["""input_ids"""], batch["""attention_mask"""]
								UpperCAmelCase  :	Union[str, Any]							  =	batch["""labels"""]
								if isinstance(self.model	,	A					):
															UpperCAmelCase  :	Any							  =	self.model._shift_right(A					)
								else:
															UpperCAmelCase  :	int							  =	shift_tokens_right(A	,	A					)
								if not self.already_saved_batch:  # This would be slightly better if it only happened on rank zero
															UpperCAmelCase  :	List[str]							  =	decoder_input_ids
															self.save_readable_batch(A					)

								UpperCAmelCase  :	Optional[Any]							  =	self(A	,	attention_mask=A	,	decoder_input_ids=A	,	use_cache=A					)
								UpperCAmelCase  :	Any							  =	outputs["""logits"""]
								if self.hparams.label_smoothing == 0:
															# Same behavior as modeling_bart.py, besides ignoring pad_token_id
															UpperCAmelCase  :	Optional[int]							  =	nn.CrossEntropyLoss(ignore_index=A					)

															assert lm_logits.shape[-1] == self.vocab_size
															UpperCAmelCase  :	int							  =	ce_loss_fct(lm_logits.view(-1	,	lm_logits.shape[-1]					)	,	tgt_ids.view(-1					)					)
								else:
															UpperCAmelCase  :	str							  =	nn.functional.log_softmax(A	,	dim=-1					)
															UpperCAmelCase  ,  UpperCAmelCase  :	Tuple							  =	label_smoothed_nll_loss(
															    A	,	A	,	self.hparams.label_smoothing	,	ignore_index=A					)
								return (loss,)





	@property
	def 				_lowercase(						self					)    ->    int:
								return self.tokenizer.pad_token_id





	def 				_lowercase(						self	,	A	,	A					)    ->    Dict:
								UpperCAmelCase  :	List[Any]							  =	self._step(A					)

								UpperCAmelCase  :	Any							  =	dict(zip(self.loss_names	,	A					)					)
								# tokens per batch
								UpperCAmelCase  :	List[str]							  =	batch["""input_ids"""].ne(self.pad					).sum() + batch["""labels"""].ne(self.pad					).sum()
								UpperCAmelCase  :	Any							  =	batch["""input_ids"""].shape[0]
								UpperCAmelCase  :	Optional[int]							  =	batch["""input_ids"""].eq(self.pad					).sum()
								UpperCAmelCase  :	str							  =	batch["""input_ids"""].eq(self.pad					).float().mean()
								# TODO(SS): make a wandb summary metric for this
								return {"loss": loss_tensors[0], "log": logs}





	def 				_lowercase(						self	,	A	,	A					)    ->    Dict:
								return self._generative_step(A					)





	def 				_lowercase(						self	,	A	,	A="val"					)    ->    Dict:
								self.step_count += 1
								UpperCAmelCase  :	List[Any]							  =	{k: torch.stack([x[k] for x in outputs]					).mean() for k in self.loss_names}
								UpperCAmelCase  :	Union[str, Any]							  =	losses["""loss"""]
								UpperCAmelCase  :	str							  =	{
								    k: np.array([x[k] for x in outputs]					).mean() for k in self.metric_names + ["""gen_time""", """gen_len"""]
								}
								UpperCAmelCase  :	Dict							  =	(
								    generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric]
								)
								UpperCAmelCase  :	torch.FloatTensor							  =	torch.tensor(A					).type_as(A					)
								generative_metrics.update({k: v.item() for k, v in losses.items()}					)
								losses.update(A					)
								UpperCAmelCase  :	str							  =	{f'''{prefix}_avg_{k}''': x for k, x in losses.items()}
								UpperCAmelCase  :	Union[str, Any]							  =	self.step_count
								self.metrics[prefix].append(A					)  # callback writes this to self.metrics_save_path
								UpperCAmelCase  :	List[Any]							  =	flatten_list([x["""preds"""] for x in outputs]					)
								return {
								    "log": all_metrics,
								    "preds": preds,
								    f'''{prefix}_loss''': loss,
								    f'''{prefix}_{self.val_metric}''': metric_tensor,
								}





	def 				_lowercase(						self	,	A	,	A					)    ->    Dict:
								return calculate_rouge(A	,	A					)





	def 				_lowercase(						self	,	A					)    ->    dict:
								UpperCAmelCase  :	Union[str, Any]							  =	time.time()

								# parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens')
								UpperCAmelCase  :	Tuple							  =	self.model.generate(
								    batch["""input_ids"""]	,	attention_mask=batch["""attention_mask"""]	,	use_cache=A	,	decoder_start_token_id=self.decoder_start_token_id	,	num_beams=self.eval_beams	,	max_length=self.eval_max_length	,	)
								UpperCAmelCase  :	str							  =	(time.time() - ta) / batch["""input_ids"""].shape[0]
								UpperCAmelCase  :	List[str]							  =	self.ids_to_clean_text(A					)
								UpperCAmelCase  :	List[str]							  =	self.ids_to_clean_text(batch["""labels"""]					)
								UpperCAmelCase  :	Optional[Any]							  =	self._step(A					)
								UpperCAmelCase  :	Any							  =	dict(zip(self.loss_names	,	A					)					)
								UpperCAmelCase  :	Dict							  =	self.calc_generative_metrics(A	,	A					)
								UpperCAmelCase  :	Any							  =	np.mean(lmap(A	,	A					)					)
								base_metrics.update(gen_time=A	,	gen_len=A	,	preds=A	,	target=A	,	**A					)
								return base_metrics





	def 				_lowercase(						self	,	A	,	A					)    ->    Dict:
								return self._generative_step(A					)





	def 				_lowercase(						self	,	A					)    ->    List[str]:
								return self.validation_epoch_end(A	,	prefix="""test"""					)





	def 				_lowercase(						self	,	A					)    ->    SeqaSeqDataset:
								UpperCAmelCase  :	str							  =	self.n_obs[type_path]
								UpperCAmelCase  :	str							  =	self.target_lens[type_path]
								UpperCAmelCase  :	str							  =	self.dataset_class(
								    self.tokenizer	,	type_path=A	,	n_obs=A	,	max_target_length=A	,	**self.dataset_kwargs	,	)
								return dataset





	def 				_lowercase(						self	,	A	,	A	,	A = False					)    ->    DataLoader:
								UpperCAmelCase  :	Tuple							  =	self.get_dataset(A					)

								if self.hparams.sortish_sampler and type_path != "test" and type_path != "val":
															UpperCAmelCase  :	List[Any]							  =	dataset.make_sortish_sampler(A	,	distributed=self.hparams.gpus > 1					)
															return DataLoader(
															    A	,	batch_size=A	,	collate_fn=dataset.collate_fn	,	shuffle=A	,	num_workers=self.num_workers	,	sampler=A	,	)

								elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val":
															UpperCAmelCase  :	List[str]							  =	dataset.make_dynamic_sampler(
															    self.hparams.max_tokens_per_batch	,	distributed=self.hparams.gpus > 1					)
															return DataLoader(
															    A	,	batch_sampler=A	,	collate_fn=dataset.collate_fn	,	num_workers=self.num_workers	,	)
								else:
															return DataLoader(
															    A	,	batch_size=A	,	collate_fn=dataset.collate_fn	,	shuffle=A	,	num_workers=self.num_workers	,	sampler=A	,	)





	def 				_lowercase(						self					)    ->    DataLoader:
								UpperCAmelCase  :	Optional[Any]							  =	self.get_dataloader("""train"""	,	batch_size=self.hparams.train_batch_size	,	shuffle=A					)
								return dataloader





	def 				_lowercase(						self					)    ->    DataLoader:
								return self.get_dataloader("""val"""	,	batch_size=self.hparams.eval_batch_size					)





	def 				_lowercase(						self					)    ->    DataLoader:
								return self.get_dataloader("""test"""	,	batch_size=self.hparams.eval_batch_size					)






	@staticmethod
	def 				_lowercase(						A	,	A					)    ->    Optional[Any]:
								BaseTransformer.add_model_specific_args(A	,	A					)
								add_generic_args(A	,	A					)
								parser.add_argument(
								    """--max_source_length"""	,	default=1024	,	type=A	,	help=(
								        """The maximum total input sequence length after tokenization. Sequences longer """
								        """than this will be truncated, sequences shorter will be padded."""
								    )	,	)
								parser.add_argument(
								    """--max_target_length"""	,	default=56	,	type=A	,	help=(
								        """The maximum total input sequence length after tokenization. Sequences longer """
								        """than this will be truncated, sequences shorter will be padded."""
								    )	,	)
								parser.add_argument(
								    """--val_max_target_length"""	,	default=142	,	type=A	,	help=(
								        """The maximum total input sequence length after tokenization. Sequences longer """
								        """than this will be truncated, sequences shorter will be padded."""
								    )	,	)
								parser.add_argument(
								    """--test_max_target_length"""	,	default=142	,	type=A	,	help=(
								        """The maximum total input sequence length after tokenization. Sequences longer """
								        """than this will be truncated, sequences shorter will be padded."""
								    )	,	)
								parser.add_argument("""--freeze_encoder"""	,	action="""store_true"""					)
								parser.add_argument("""--freeze_embeds"""	,	action="""store_true"""					)
								parser.add_argument("""--sortish_sampler"""	,	action="""store_true"""	,	default=A					)
								parser.add_argument("""--overwrite_output_dir"""	,	action="""store_true"""	,	default=A					)
								parser.add_argument("""--max_tokens_per_batch"""	,	type=A	,	default=A					)
								parser.add_argument("""--logger_name"""	,	type=A	,	choices=["""default""", """wandb""", """wandb_shared"""]	,	default="""default"""					)
								parser.add_argument("""--n_train"""	,	type=A	,	default=-1	,	required=A	,	help="""# examples. -1 means use all."""					)
								parser.add_argument("""--n_val"""	,	type=A	,	default=500	,	required=A	,	help="""# examples. -1 means use all."""					)
								parser.add_argument("""--n_test"""	,	type=A	,	default=-1	,	required=A	,	help="""# examples. -1 means use all."""					)
								parser.add_argument(
								    """--task"""	,	type=A	,	default="""summarization"""	,	required=A	,	help="""# examples. -1 means use all."""					)
								parser.add_argument("""--label_smoothing"""	,	type=A	,	default=0.0	,	required=A					)
								parser.add_argument("""--src_lang"""	,	type=A	,	default=""""""	,	required=A					)
								parser.add_argument("""--tgt_lang"""	,	type=A	,	default=""""""	,	required=A					)
								parser.add_argument("""--eval_beams"""	,	type=A	,	default=A	,	required=A					)
								parser.add_argument(
								    """--val_metric"""	,	type=A	,	default=A	,	required=A	,	choices=["""bleu""", """rouge2""", """loss""", None]					)
								parser.add_argument("""--eval_max_gen_length"""	,	type=A	,	default=A	,	help="""never generate more than n tokens"""					)
								parser.add_argument("""--save_top_k"""	,	type=A	,	default=1	,	required=A	,	help="""How many checkpoints to save"""					)
								parser.add_argument(
								    """--early_stopping_patience"""	,	type=A	,	default=-1	,	required=A	,	help=(
								        """-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So"""
								        """ val_check_interval will effect it."""
								    )	,	)
								return parser




class     UpperCamelCase_				(							__magic_name__    ):
	lowercase    =				'translation'
	lowercase    =				['loss']
	lowercase    =				['bleu']
	lowercase    =				'bleu'





	def __init__(						self	,	A	,	**A					)    ->    List[str]:
								super().__init__(A	,	**A					)
								UpperCAmelCase  :	Dict							  =	hparams.src_lang
								UpperCAmelCase  :	Dict							  =	hparams.tgt_lang






	def 				_lowercase(						self	,	A	,	A					)    ->    dict:
								return calculate_bleu(A	,	A					)




def    __lowerCamelCase						(      _lowercase			,       _lowercase=None	)   ->    SummarizationModule:
							Path(args.output_dir	).mkdir(exist_ok=_lowercase	)
							check_output_dir(_lowercase			,       expected_items=3	)

							if model is None:
														if "summarization" in args.task:
																					UpperCAmelCase  :	SummarizationModule							  =	SummarizationModule(_lowercase	)
														else:
																					UpperCAmelCase  :	SummarizationModule							  =	TranslationModule(_lowercase	)
							UpperCAmelCase  :	Tuple							  =	Path(args.data_dir	).name
							if (
							    args.logger_name == "default"
							    or args.fast_dev_run
							    or str(args.output_dir	).startswith("""/tmp"""	)
							    or str(args.output_dir	).startswith("""/var"""	)
							):
														UpperCAmelCase  :	Optional[int]							  =	True  # don't pollute wandb logs unnecessarily
							elif args.logger_name == "wandb":
														from pytorch_lightning.loggers import WandbLogger

														UpperCAmelCase  :	Any							  =	os.environ.get("""WANDB_PROJECT"""			,       _lowercase	)
														UpperCAmelCase  :	Tuple							  =	WandbLogger(name=model.output_dir.name			,       project=_lowercase	)

							elif args.logger_name == "wandb_shared":
														from pytorch_lightning.loggers import WandbLogger

														UpperCAmelCase  :	List[str]							  =	WandbLogger(name=model.output_dir.name			,       project=F'''hf_{dataset}'''	)

							if args.early_stopping_patience >= 0:
														UpperCAmelCase  :	str							  =	get_early_stopping_callback(model.val_metric			,       args.early_stopping_patience	)
							else:
														UpperCAmelCase  :	Any							  =	False

							UpperCAmelCase  :	int							  =	args.val_metric == """loss"""
							UpperCAmelCase  :	pl.Trainer							  =	generic_train(
							    _lowercase			,       _lowercase			,       logging_callback=SeqaSeqLoggingCallback()			,       checkpoint_callback=get_checkpoint_callback(
							        args.output_dir			,       model.val_metric			,       args.save_top_k			,       _lowercase	)			,       early_stopping_callback=_lowercase			,       logger=_lowercase			,       )
							pickle_save(model.hparams			,       model.output_dir / """hparams.pkl"""	)
							if not args.do_predict:
														return model

							UpperCAmelCase  :	Tuple							  =	""""""
							UpperCAmelCase  :	Optional[int]							  =	sorted(glob.glob(os.path.join(args.output_dir			,       """*.ckpt"""	)			,       recursive=_lowercase	)	)
							if checkpoints:
														UpperCAmelCase  :	List[Any]							  =	checkpoints[-1]
														UpperCAmelCase  :	Optional[Any]							  =	checkpoints[-1]
							trainer.logger.log_hyperparams(model.hparams	)

							# test() without a model tests using the best checkpoint automatically
							trainer.test()
							return model


if __name__ == "__main__":
							a     :    List[str]      						=					argparse.ArgumentParser()
							a     :    List[str]      						=					pl.Trainer.add_argparse_args(parser)
							a     :    str      						=					SummarizationModule.add_model_specific_args(parser, os.getcwd())

							a     :    int      						=					parser.parse_args()

							main(args)






'''simple docstring'''




import math
import random
from typing import Any

from .hill_climbing import SearchProblem



def    __lowerCamelCase						(      _lowercase			,       _lowercase = True			,       _lowercase = math.inf			,       _lowercase = -math.inf			,       _lowercase = math.inf			,       _lowercase = -math.inf			,       _lowercase = False			,       _lowercase = 1_0_0			,       _lowercase = 0.01			,       _lowercase = 1			,       )   ->    Any:
							UpperCAmelCase  :	Optional[int]							  =	False
							UpperCAmelCase  :	Any							  =	search_prob
							UpperCAmelCase  :	Any							  =	start_temperate
							UpperCAmelCase  :	Optional[Any]							  =	[]
							UpperCAmelCase  :	Optional[Any]							  =	0
							UpperCAmelCase  :	Optional[Any]							  =	None

							while not search_end:
														UpperCAmelCase  :	List[str]							  =	current_state.score()
														if best_state is None or current_score > best_state.score():
																					UpperCAmelCase  :	List[Any]							  =	current_state
														scores.append(_lowercase	)
														iterations += 1
														UpperCAmelCase  :	Dict							  =	None
														UpperCAmelCase  :	Union[str, Any]							  =	current_state.get_neighbors()
														while (
														    next_state is None and neighbors
														):  # till we do not find a neighbor that we can move to
																					UpperCAmelCase  :	int							  =	random.randint(0			,       len(_lowercase	) - 1	)  # picking a random neighbor
																					UpperCAmelCase  :	int							  =	neighbors.pop(_lowercase	)
																					UpperCAmelCase  :	Tuple							  =	picked_neighbor.score() - current_score

																					if (
																					    picked_neighbor.x > max_x
																					    or picked_neighbor.x < min_x
																					    or picked_neighbor.y > max_y
																					    or picked_neighbor.y < min_y
																					):
																												continue  # neighbor outside our bounds

																					if not find_max:
																												UpperCAmelCase  :	Union[str, Any]							  =	change * -1  # in case we are finding minimum
																					if change > 0:  # improves the solution
																												UpperCAmelCase  :	int							  =	picked_neighbor
																					else:
																												UpperCAmelCase  :	Optional[Any]							  =	(math.e) ** (
																												    change / current_temp
																												)  # probability generation function
																												if random.random() < probability:  # random number within probability
																																			UpperCAmelCase  :	Optional[int]							  =	picked_neighbor
														UpperCAmelCase  :	List[Any]							  =	current_temp - (current_temp * rate_of_decrease)

														if current_temp < threshold_temp or next_state is None:
																					# temperature below threshold, or could not find a suitable neighbor
																					UpperCAmelCase  :	Optional[int]							  =	True
														else:
																					UpperCAmelCase  :	Optional[int]							  =	next_state

							if visualization:
														from matplotlib import pyplot as plt

														plt.plot(range(_lowercase	)			,       _lowercase	)
														plt.xlabel("""Iterations"""	)
														plt.ylabel("""Function values"""	)
														plt.show()
							return best_state


if __name__ == "__main__":



							def    __lowerCamelCase						(      _lowercase			,       _lowercase	)   ->    str:
														return (x**2) + (y**2)

							# starting the problem with initial coordinates (12, 47)
							a     :    Dict      						=					SearchProblem(x=1_2, y=4_7, step_size=1, function_to_optimize=test_fa)
							a     :    Dict      						=					simulated_annealing(
							    prob, find_max=False, max_x=1_0_0, min_x=5, max_y=5_0, min_y=-5, visualization=True
							)
							print(
							    """The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 """
							    F'''and 50 > y > - 5 found via hill climbing: {local_min.score()}'''
							)

							# starting the problem with initial coordinates (12, 47)
							a     :    List[str]      						=					SearchProblem(x=1_2, y=4_7, step_size=1, function_to_optimize=test_fa)
							a     :    Dict      						=					simulated_annealing(
							    prob, find_max=True, max_x=1_0_0, min_x=5, max_y=5_0, min_y=-5, visualization=True
							)
							print(
							    """The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 """
							    F'''and 50 > y > - 5 found via hill climbing: {local_min.score()}'''
							)



							def    __lowerCamelCase						(      _lowercase			,       _lowercase	)   ->    Optional[Any]:
														return (3 * x**2) - (6 * y)

							a     :    Tuple      						=					SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa)
							a     :    Any      						=					simulated_annealing(prob, find_max=False, visualization=True)
							print(
							    """The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: """
							    F'''{local_min.score()}'''
							)

							a     :    List[Any]      						=					SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa)
							a     :    Dict      						=					simulated_annealing(prob, find_max=True, visualization=True)


							print(
							    """The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: """
							    F'''{local_min.score()}'''
							)

