


'''simple docstring'''

import inspect
import unittest

from transformers import ResNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
							import torch
							from torch import nn

							from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
							from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor
class _lowerCamelCase :



		'''simple docstring'''







		def __init__(      self	:		Dict						,  _A	:		List[Any]						,  _A	:		List[Any]=3						,  _A	:		Tuple=32						,  _A	:		str=3						,  _A	:		Any=10						,  _A	:		List[str]=[10, 20, 30, 40]						,  _A	:		Optional[Any]=[1, 1, 2, 1]						,  _A	:		Dict=True						,  _A	:		int=True						,  _A	:		Dict="relu"						,  _A	:		Any=3						,  _A	:		Union[str, Any]=None						,  _A	:		int=["stage2", "stage3", "stage4"]						,  _A	:		Union[str, Any]=[2, 3, 4]						,  )						->				Union[str, Any]:
			__magic_name__ :					Union[str, Any]  			=  parent
			__magic_name__ :					str  			=  batch_size
			__magic_name__ :					str  			=  image_size
			__magic_name__ :					Optional[Any]  			=  num_channels
			__magic_name__ :					List[str]  			=  embeddings_size
			__magic_name__ :					str  			=  hidden_sizes
			__magic_name__ :					Tuple  			=  depths
			__magic_name__ :					Any  			=  is_training
			__magic_name__ :					Union[str, Any]  			=  use_labels
			__magic_name__ :					List[str]  			=  hidden_act
			__magic_name__ :					Union[str, Any]  			=  num_labels
			__magic_name__ :					Any  			=  scope
			__magic_name__ :					List[Any]  			=  len(_A    )
			__magic_name__ :					Tuple  			=  out_features
			__magic_name__ :					Tuple  			=  out_indices







		def      __lowerCAmelCase	(      self	:		Optional[int]    )						->				str:
			__magic_name__ :					List[str]  			=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

			__magic_name__ :					Dict  			=  None
			if self.use_labels:
				__magic_name__ :					Optional[int]  			=  ids_tensor([self.batch_size]						,  self.num_labels    )

			__magic_name__ :					Any  			=  self.get_config()

			return config, pixel_values, labels







		def      __lowerCAmelCase	(      self	:		Optional[Any]    )						->				Optional[int]:
			return ResNetConfig(
			    num_channels=self.num_channels						,  embeddings_size=self.embeddings_size						,  hidden_sizes=self.hidden_sizes						,  depths=self.depths						,  hidden_act=self.hidden_act						,  num_labels=self.num_labels						,  out_features=self.out_features						,  out_indices=self.out_indices						,  )







		def      __lowerCAmelCase	(      self	:		Dict						,  _A	:		str						,  _A	:		Optional[int]						,  _A	:		List[Any]    )						->				str:
			__magic_name__ :					Any  			=  ResNetModel(config=_A    )
			model.to(_A    )
			model.eval()
			__magic_name__ :					List[Any]  			=  model(_A    )
			# expected last hidden states: B, C, H // 32, W // 32
			self.parent.assertEqual(
			    result.last_hidden_state.shape						,  (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)						,  )







		def      __lowerCAmelCase	(      self	:		Optional[int]						,  _A	:		int						,  _A	:		int						,  _A	:		int    )						->				Optional[Any]:
			__magic_name__ :					Any  			=  self.num_labels
			__magic_name__ :					List[Any]  			=  ResNetForImageClassification(_A    )
			model.to(_A    )
			model.eval()
			__magic_name__ :					Optional[Any]  			=  model(_A						,  labels=_A    )
			self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.num_labels)    )







		def      __lowerCAmelCase	(      self	:		Any						,  _A	:		List[str]						,  _A	:		int						,  _A	:		List[Any]    )						->				int:
			__magic_name__ :					str  			=  ResNetBackbone(config=_A    )
			model.to(_A    )
			model.eval()
			__magic_name__ :					List[str]  			=  model(_A    )

			# verify feature maps
			self.parent.assertEqual(len(result.feature_maps    )						,  len(config.out_features    )    )
			self.parent.assertListEqual(list(result.feature_maps[0].shape    )						,  [self.batch_size, self.hidden_sizes[1], 4, 4]    )

			# verify channels
			self.parent.assertEqual(len(model.channels    )						,  len(config.out_features    )    )
			self.parent.assertListEqual(model.channels						,  config.hidden_sizes[1:]    )

			# verify backbone works with out_features=None
			__magic_name__ :					Union[str, Any]  			=  None
			__magic_name__ :					Optional[int]  			=  ResNetBackbone(config=_A    )
			model.to(_A    )
			model.eval()
			__magic_name__ :					str  			=  model(_A    )

			# verify feature maps
			self.parent.assertEqual(len(result.feature_maps    )						,  1    )
			self.parent.assertListEqual(list(result.feature_maps[0].shape    )						,  [self.batch_size, self.hidden_sizes[-1], 1, 1]    )

			# verify channels
			self.parent.assertEqual(len(model.channels    )						,  1    )
			self.parent.assertListEqual(model.channels						,  [config.hidden_sizes[-1]]    )







		def      __lowerCAmelCase	(      self	:		Any    )						->				Any:
			__magic_name__ :					Dict  			=  self.prepare_config_and_inputs()
			__magic_name__			,       __magic_name__			,       __magic_name__ :					Tuple  			=  config_and_inputs
			__magic_name__ :					Union[str, Any]  			=  {'pixel_values': pixel_values}
			return config, inputs_dict







@require_torch
class _lowerCamelCase (		lowercase__	,  lowercase__	,  unittest.TestCase							):



		'''simple docstring'''







		A_			:    Tuple   					=       (
		    (
		        ResNetModel,
		        ResNetForImageClassification,
		        ResNetBackbone,
		    )
		    if is_torch_available()
		    else ()
		)
		A_			:    Any   					=       (
		    {"""feature-extraction""": ResNetModel, """image-classification""": ResNetForImageClassification}
		    if is_torch_available()
		    else {}
		)

		A_			:    int   					=       True
		A_			:    Dict   					=       False
		A_			:    Tuple   					=       False
		A_			:    str   					=       False
		A_			:    List[Any]   					=       False







		def      __lowerCAmelCase	(      self	:		Tuple    )						->				Union[str, Any]:
			__magic_name__ :					Optional[Any]  			=  ResNetModelTester(self    )
			__magic_name__ :					Any  			=  ConfigTester(self						,  config_class=_A						,  has_text_modality=_A    )







		def      __lowerCAmelCase	(      self	:		Optional[int]    )						->				str:
			self.create_and_test_config_common_properties()
			self.config_tester.create_and_test_config_to_json_string()
			self.config_tester.create_and_test_config_to_json_file()
			self.config_tester.create_and_test_config_from_and_save_pretrained()
			self.config_tester.create_and_test_config_with_num_labels()
			self.config_tester.check_config_can_be_init_without_params()
			self.config_tester.check_config_arguments_init()







		def      __lowerCAmelCase	(      self	:		Optional[Any]    )						->				Tuple:
			return







		@unittest.skip(reason='ResNet does not use inputs_embeds'    )
		def      __lowerCAmelCase	(      self	:		int    )						->				Tuple:
			pass







		@unittest.skip(reason='ResNet does not support input and output embeddings'    )
		def      __lowerCAmelCase	(      self	:		Dict    )						->				Optional[Any]:
			pass







		def      __lowerCAmelCase	(      self	:		Optional[Any]    )						->				Optional[int]:
			__magic_name__			,       __magic_name__ :					Optional[int]  			=  self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
				__magic_name__ :					Optional[Any]  			=  model_class(_A    )
				__magic_name__ :					List[str]  			=  inspect.signature(model.forward    )
				# signature.parameters is an OrderedDict => so arg_names order is deterministic
				__magic_name__ :					Dict  			=  [*signature.parameters.keys()]

				__magic_name__ :					int  			=  ['pixel_values']
				self.assertListEqual(arg_names[:1]						,  _A    )







		def      __lowerCAmelCase	(      self	:		str    )						->				int:
			__magic_name__ :					Union[str, Any]  			=  self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*_A    )







		def      __lowerCAmelCase	(      self	:		str    )						->				Dict:
			__magic_name__ :					List[Any]  			=  self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_backbone(*_A    )







		def      __lowerCAmelCase	(      self	:		Dict    )						->				int:
			__magic_name__			,       __magic_name__ :					List[Any]  			=  self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
				__magic_name__ :					List[Any]  			=  model_class(config=_A    )
				for name, module in model.named_modules():
					if isinstance(_A						,  (nn.BatchNormad, nn.GroupNorm)    ):
						self.assertTrue(
						    torch.all(module.weight == 1    )						,  msg=F'Parameter {name} of model {model_class} seems not properly initialized'						,  )
						self.assertTrue(
						    torch.all(module.bias == 0    )						,  msg=F'Parameter {name} of model {model_class} seems not properly initialized'						,  )







		def      __lowerCAmelCase	(      self	:		Any    )						->				List[str]:
			def check_hidden_states_output(_A	:		Optional[Any]						,  _A	:		Optional[Any]						,  _A	:		str    ):
				__magic_name__ :					str  			=  model_class(_A    )
				model.to(_A    )
				model.eval()

				with torch.no_grad():
					__magic_name__ :					Any  			=  model(**self._prepare_for_class(_A						,  _A    )    )

				__magic_name__ :					int  			=  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

				__magic_name__ :					Optional[Any]  			=  self.model_tester.num_stages
				self.assertEqual(len(_A    )						,  expected_num_stages + 1    )

				# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
				self.assertListEqual(
				    list(hidden_states[0].shape[-2:]    )						,  [self.model_tester.image_size // 4, self.model_tester.image_size // 4]						,  )

			__magic_name__			,       __magic_name__ :					Dict  			=  self.model_tester.prepare_config_and_inputs_for_common()
			__magic_name__ :					int  			=  ['basic', 'bottleneck']
			for model_class in self.all_model_classes:
				for layer_type in layers_type:
					__magic_name__ :					Any  			=  layer_type
					__magic_name__ :					str  			=  True
					check_hidden_states_output(_A						,  _A						,  _A    )

					# check that output_hidden_states also work using config
					del inputs_dict["output_hidden_states"]
					__magic_name__ :					Dict  			=  True

					check_hidden_states_output(_A						,  _A						,  _A    )







		@unittest.skip(reason='ResNet does not use feedforward chunking'    )
		def      __lowerCAmelCase	(      self	:		List[Any]    )						->				int:
			pass







		def      __lowerCAmelCase	(      self	:		int    )						->				Tuple:
			__magic_name__ :					List[str]  			=  self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_classification(*_A    )







		@slow
		def      __lowerCAmelCase	(      self	:		List[str]    )						->				Tuple:
			for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				__magic_name__ :					Optional[Any]  			=  ResNetModel.from_pretrained(_A    )
				self.assertIsNotNone(_A    )







def lowerCamelCase    (    ):





	"""simple docstring"""







	__magic_name__ :					List[str]  			=  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
	return image
@require_torch
@require_vision
class _lowerCamelCase (		unittest.TestCase							):



		'''simple docstring'''







		@cached_property
		def      __lowerCAmelCase	(      self	:		Tuple    )						->				List[Any]:
			return (
			    AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )
			    if is_vision_available()
			    else None
			)







		@slow
		def      __lowerCAmelCase	(      self	:		Any    )						->				Tuple:
			__magic_name__ :					Any  			=  ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    ).to(_A    )

			__magic_name__ :					int  			=  self.default_image_processor
			__magic_name__ :					str  			=  prepare_img()
			__magic_name__ :					Optional[Any]  			=  image_processor(images=_A						,  return_tensors='pt'    ).to(_A    )

			# forward pass
			with torch.no_grad():
				__magic_name__ :					Tuple  			=  model(**_A    )

			# verify the logits
			__magic_name__ :					Optional[Any]  			=  torch.Size((1, 1000)    )
			self.assertEqual(outputs.logits.shape						,  _A    )

			__magic_name__ :					int  			=  torch.tensor([-11.1069, -9.7877, -8.3777]    ).to(_A    )

			self.assertTrue(torch.allclose(outputs.logits[0, :3]						,  _A						,  atol=1E-4    )    )







@require_torch
class _lowerCamelCase (		lowercase__	,  unittest.TestCase							):



		'''simple docstring'''







		A_			:    Tuple   					=       (ResNetBackbone,) if is_torch_available() else ()
		A_			:    int   					=       False
		A_			:    Optional[Any]   					=       ResNetConfig







		def      __lowerCAmelCase	(      self	:		Union[str, Any]    )						->				str:
			__magic_name__ :					Optional[Any]  			=  ResNetModelTester(self    )



'''simple docstring'''

lowerCAmelCase   :int								=    [
    ['''ab-e1''', '''ac-e3''', '''ad-e5''', '''bc-e4''', '''bd-e2''', '''be-e6''', '''bh-e12''', '''cd-e2''', '''ce-e4''',
     '''de-e1''', '''df-e8''', '''dg-e5''', '''dh-e10''', '''ef-e3''', '''eg-e2''', '''fg-e6''', '''gh-e6''', '''hi-e3'''],
    ['''ab-e1''', '''ac-e3''', '''ad-e5''', '''bc-e4''', '''bd-e2''', '''be-e6''', '''cd-e2''', '''de-e1''', '''df-e8''',
     '''ef-e3''', '''eg-e2''', '''fg-e6'''],
    ['''ab-e1''', '''ac-e3''', '''bc-e4''', '''bd-e2''', '''de-e1''', '''df-e8''', '''dg-e5''', '''ef-e3''', '''eg-e2''',
     '''eh-e12''', '''fg-e6''', '''fh-e10''', '''gh-e6'''],
    ['''ab-e1''', '''ac-e3''', '''bc-e4''', '''bd-e2''', '''bh-e12''', '''cd-e2''', '''df-e8''', '''dh-e10'''],
    ['''ab-e1''', '''ac-e3''', '''ad-e5''', '''bc-e4''', '''bd-e2''', '''cd-e2''', '''ce-e4''', '''de-e1''', '''df-e8''',
     '''dg-e5''', '''ef-e3''', '''eg-e2''', '''fg-e6''']
]





def lowerCamelCase    (    lowerCAmelCase       :			Tuple	):





	"""simple docstring"""







	__magic_name__ :					Union[str, Any]  			=  set()
	for row in edge_array:
		for item in row:
			distinct_edge.add(item[0]	)
	return list(lowerCAmelCase	)





def lowerCamelCase    (    lowerCAmelCase       :			List[str]	,	lowerCAmelCase       :			Optional[int]	):





	"""simple docstring"""







	__magic_name__ :					List[Any]  			=  ['0'] * len(lowerCAmelCase	)
	for i, row in enumerate(lowerCAmelCase	):
		for item in row:
			if distinct_edge in item[0]:
				__magic_name__ :					str  			=  '1'
				break
	return "".join(lowerCAmelCase	)





def lowerCamelCase    (    lowerCAmelCase       :			Tuple	):





	"""simple docstring"""







	__magic_name__ :					Any  			=  get_distinct_edge(lowerCAmelCase	)
	__magic_name__ :					Union[str, Any]  			=  {}

	for item in distinct_edge:
		__magic_name__ :					Union[str, Any]  			=  get_bitcode(lowerCAmelCase	,	lowerCAmelCase	)
		# print('bit',bit)
		# bt=''.join(bit)
		__magic_name__ :					Dict  			=  bit.count('1'	)
		__magic_name__ :					Dict  			=  [s, bit]
	# Store [Distinct edge, WT(Bitcode), Bitcode] in descending order
	__magic_name__ :					Optional[Any]  			=  [
	    [k, v[0], v[1]]
	    for k, v in sorted(frequency_table.items()	,	key=lambda lowerCAmelCase	: v[1][0]	,	reverse=lowerCAmelCase	)
	]
	return sorted_frequency_table





def lowerCamelCase    (    lowerCAmelCase       :			List[str]	):





	"""simple docstring"""







	__magic_name__ :					Tuple  			=  {}
	for _, item in enumerate(lowerCAmelCase	):
		nodes.setdefault(item[2]	,	[]	).append(item[0]	)
	return nodes





def lowerCamelCase    (    lowerCAmelCase       :			List[str]	):





	"""simple docstring"""







	__magic_name__ :					str  			=  {}
	for key, value in nodes.items():
		__magic_name__ :					Union[str, Any]  			=  value
	return cluster





def lowerCamelCase    (    lowerCAmelCase       :			List[str]	):





	"""simple docstring"""







	return [i * 100 / len(lowerCAmelCase	) for i in cluster]





def lowerCamelCase    (    ):





	"""simple docstring"""







	print('\nNodes\n'	)
	for key, value in nodes.items():
		print(lowerCAmelCase	,	lowerCAmelCase	)
	print('\nSupport\n'	)
	print(lowerCAmelCase	)
	print('\n Cluster \n'	)
	for key, value in sorted(cluster.items()	,	reverse=lowerCAmelCase	):
		print(lowerCAmelCase	,	lowerCAmelCase	)
	print('\n Graph\n'	)
	for key, value in graph.items():
		print(lowerCAmelCase	,	lowerCAmelCase	)
	print('\n Edge List of Frequent subgraphs \n'	)
	for edge_list in freq_subgraph_edge_list:
		print(lowerCAmelCase	)





def lowerCamelCase    (    lowerCAmelCase       :			int	,	lowerCAmelCase       :			str	,	lowerCAmelCase       :			Optional[Any]	,	lowerCAmelCase       :			int	):





	"""simple docstring"""







	for i in cluster[ca]:
		__magic_name__ :					Tuple  			=  0
		__magic_name__ :					Any  			=  ca + 1
		while ca < max(cluster.keys()	):
			for j in cluster[ca]:
				if int(lowerCAmelCase	,	2	) & int(lowerCAmelCase	,	2	) == int(lowerCAmelCase	,	2	):
					if tuple(nodes[i]	) in graph:
						graph[tuple(nodes[i]	)].append(nodes[j]	)
					else:
						__magic_name__ :					List[Any]  			=  [nodes[j]]
					count += 1
			if count == 0:
				__magic_name__ :					Tuple  			=  ca + 1
			else:
				break





def lowerCamelCase    (    lowerCAmelCase       :			Any	,	lowerCAmelCase       :			List[Any]	):





	"""simple docstring"""







	__magic_name__ :					str  			=  cluster[max(cluster.keys()	)]
	__magic_name__ :					Dict  			=  'Header'
	__magic_name__ :					Optional[Any]  			=  {}
	for i in x:
		if (["Header"],) in graph:
			graph[(["Header"],)].append(x[i]	)
		else:
			__magic_name__ :					List[str]  			=  [x[i]]
	for i in x:
		__magic_name__ :					Union[str, Any]  			=  [['Header']]
	__magic_name__ :					List[str]  			=  1
	while i < max(lowerCAmelCase	) - 1:
		create_edge(lowerCAmelCase	,	lowerCAmelCase	,	lowerCAmelCase	,	lowerCAmelCase	)
		__magic_name__ :					Dict  			=  i + 1
	return graph





def lowerCamelCase    (    lowerCAmelCase       :			Dict	,	lowerCAmelCase       :			Tuple	,	lowerCAmelCase       :			List[Any]	,	lowerCAmelCase       :			Union[str, Any]=None	):





	"""simple docstring"""







	__magic_name__ :					str  			=  (path or []) + [start]
	if start == end:
		paths.append(lowerCAmelCase	)
	for node in graph[start]:
		if tuple(lowerCAmelCase	) not in path:
			my_dfs(lowerCAmelCase	,	tuple(lowerCAmelCase	)	,	lowerCAmelCase	,	lowerCAmelCase	)





def lowerCamelCase    (    lowerCAmelCase       :			Optional[Any]	,	lowerCAmelCase       :			Tuple	,	lowerCAmelCase       :			Union[str, Any]	):





	"""simple docstring"""







	__magic_name__ :					Union[str, Any]  			=  int(s / 100 * (len(lowerCAmelCase	) - 1)	)
	for i in cluster[k]:
		my_dfs(lowerCAmelCase	,	tuple(cluster[k][i]	)	,	(['Header'],)	)





def lowerCamelCase    (    lowerCAmelCase       :			Optional[int]	):





	"""simple docstring"""







	__magic_name__ :					str  			=  []
	for edges in paths:
		__magic_name__ :					List[Any]  			=  []
		for j in range(len(lowerCAmelCase	) - 1	):
			__magic_name__ :					List[str]  			=  list(edges[j]	)
			for e in temp:
				__magic_name__ :					Optional[int]  			=  (e[0], e[1])
				el.append(lowerCAmelCase	)
		freq_sub_el.append(lowerCAmelCase	)
	return freq_sub_el





def lowerCamelCase    (    lowerCAmelCase       :			str	):





	"""simple docstring"""







	for i in range(len(lowerCAmelCase	)	):
		for j in range(len(edge_array[i]	)	):
			__magic_name__ :					Any  			=  edge_array[i][j].split('-'	)
			__magic_name__ :					Tuple  			=  t


if __name__ == "__main__":
							preprocess(edge_array)
							lowerCAmelCase   :List[str]								=    get_frequency_table(edge_array)
							lowerCAmelCase   :List[str]								=    get_nodes(frequency_table)
							lowerCAmelCase   :Optional[int]								=    get_cluster(nodes)
							lowerCAmelCase   :Tuple								=    get_support(cluster)
							lowerCAmelCase   :Tuple								=    construct_graph(cluster, nodes)
							find_freq_subgraph_given_support(6_0, cluster, graph)
							lowerCAmelCase   :list								=    []
							lowerCAmelCase   :str								=    freq_subgraphs_edge_list(paths)
							print_all()