
"""simple docstring"""






import pickle

import numpy as np
from matplotlib import pyplot as plt



class 			lowercase					:






			def __init__(self  :	Dict      ,SCREAMING_SNAKE_CASE_  :	Dict      ,SCREAMING_SNAKE_CASE_  :	List[str]      ,SCREAMING_SNAKE_CASE_  :	int      ,SCREAMING_SNAKE_CASE_  :	str      ,SCREAMING_SNAKE_CASE_  :	Union[str, Any]      ,SCREAMING_SNAKE_CASE_  :	List[str]=0.2      ,SCREAMING_SNAKE_CASE_  :	Union[str, Any]=0.2			)       ->	Tuple:





				"""simple docstring"""


				lowerCAmelCase												=  bp_numa
				lowerCAmelCase												=  bp_numa
				lowerCAmelCase												=  bp_numa
				lowerCAmelCase												=  conva_get[:2]
				lowerCAmelCase												=  conva_get[2]
				lowerCAmelCase												=  size_pa
				lowerCAmelCase												=  rate_w
				lowerCAmelCase												=  rate_t
				lowerCAmelCase												=  [
				    np.mat(-1 * np.random.rand(self.conva[0]      ,self.conva[0]			) + 0.5			)
				    for i in range(self.conva[1]			)
				]
				lowerCAmelCase												=  np.mat(-1 * np.random.rand(self.num_bpa      ,self.num_bpa			) + 0.5			)
				lowerCAmelCase												=  np.mat(-1 * np.random.rand(self.num_bpa      ,self.num_bpa			) + 0.5			)
				lowerCAmelCase												=  -2 * np.random.rand(self.conva[1]			) + 1
				lowerCAmelCase												=  -2 * np.random.rand(self.num_bpa			) + 1
				lowerCAmelCase												=  -2 * np.random.rand(self.num_bpa			) + 1






			def 					UpperCAmelCase							(self  :	Tuple      ,SCREAMING_SNAKE_CASE_  :	Tuple			)       ->	Tuple:





				"""simple docstring"""


				lowerCAmelCase												=  {
				    '''num_bp1''': self.num_bpa,
				    '''num_bp2''': self.num_bpa,
				    '''num_bp3''': self.num_bpa,
				    '''conv1''': self.conva,
				    '''step_conv1''': self.step_conva,
				    '''size_pooling1''': self.size_poolinga,
				    '''rate_weight''': self.rate_weight,
				    '''rate_thre''': self.rate_thre,
				    '''w_conv1''': self.w_conva,
				    '''wkj''': self.wkj,
				    '''vji''': self.vji,
				    '''thre_conv1''': self.thre_conva,
				    '''thre_bp2''': self.thre_bpa,
				    '''thre_bp3''': self.thre_bpa,
				}
				with open(SCREAMING_SNAKE_CASE_      ,'''wb'''			) as f:
					pickle.dump(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)

				print(F"""Model saved： {save_path}"""			)






			@classmethod
			def 					UpperCAmelCase							(cls  :	Optional[Any]      ,SCREAMING_SNAKE_CASE_  :	str			)       ->	Dict:





				"""simple docstring"""


				with open(SCREAMING_SNAKE_CASE_      ,'''rb'''			) as f:
					lowerCAmelCase												=  pickle.load(SCREAMING_SNAKE_CASE_			)  # noqa: S301

				lowerCAmelCase												=  model_dic.get('''conv1'''			)
				conv_get.append(model_dic.get('''step_conv1'''			)			)
				lowerCAmelCase												=  model_dic.get('''size_pooling1'''			)
				lowerCAmelCase												=  model_dic.get('''num_bp1'''			)
				lowerCAmelCase												=  model_dic.get('''num_bp2'''			)
				lowerCAmelCase												=  model_dic.get('''num_bp3'''			)
				lowerCAmelCase												=  model_dic.get('''rate_weight'''			)
				lowerCAmelCase												=  model_dic.get('''rate_thre'''			)
				# create model instance
				lowerCAmelCase												=  CNN(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)
				# modify model parameter
				lowerCAmelCase												=  model_dic.get('''w_conv1'''			)
				lowerCAmelCase												=  model_dic.get('''wkj'''			)
				lowerCAmelCase												=  model_dic.get('''vji'''			)
				lowerCAmelCase												=  model_dic.get('''thre_conv1'''			)
				lowerCAmelCase												=  model_dic.get('''thre_bp2'''			)
				lowerCAmelCase												=  model_dic.get('''thre_bp3'''			)
				return conv_ins






			def 					UpperCAmelCase							(self  :	Union[str, Any]      ,SCREAMING_SNAKE_CASE_  :	Optional[Any]			)       ->	Dict:





				"""simple docstring"""


				return 1 / (1 + np.exp(-1 * x			))






			def 					UpperCAmelCase							(self  :	List[Any]      ,SCREAMING_SNAKE_CASE_  :	Optional[Any]			)       ->	int:





				"""simple docstring"""


				return round(SCREAMING_SNAKE_CASE_      ,3			)






			def 					UpperCAmelCase							(self  :	Dict      ,SCREAMING_SNAKE_CASE_  :	Optional[int]      ,SCREAMING_SNAKE_CASE_  :	Tuple      ,SCREAMING_SNAKE_CASE_  :	Optional[int]      ,SCREAMING_SNAKE_CASE_  :	Optional[Any]      ,SCREAMING_SNAKE_CASE_  :	Optional[int]			)       ->	Tuple:





				"""simple docstring"""


				lowerCAmelCase												=  convs[0]
				lowerCAmelCase												=  convs[1]
				lowerCAmelCase												=  np.shape(SCREAMING_SNAKE_CASE_			)[0]
				# get the data slice of original image data, data_focus
				lowerCAmelCase												=  []
				for i_focus in range(0      ,size_data - size_conv + 1      ,SCREAMING_SNAKE_CASE_			):
					for j_focus in range(0      ,size_data - size_conv + 1      ,SCREAMING_SNAKE_CASE_			):
						lowerCAmelCase												=  data[
						    i_focus : i_focus + size_conv, j_focus : j_focus + size_conv
						]
						data_focus.append(SCREAMING_SNAKE_CASE_			)
        # calculate the feature map of every single kernel, and saved as list of matrix
				lowerCAmelCase												=  []
				lowerCAmelCase												=  int((size_data - size_conv) / conv_step + 1			)
				for i_map in range(SCREAMING_SNAKE_CASE_			):
					lowerCAmelCase												=  []
					for i_focus in range(len(SCREAMING_SNAKE_CASE_			)			):
						lowerCAmelCase												=  (
						    np.sum(np.multiply(data_focus[i_focus]      ,w_convs[i_map]			)			)
						    - thre_convs[i_map]
						)
						featuremap.append(self.sig(SCREAMING_SNAKE_CASE_			)			)
					lowerCAmelCase												=  np.asmatrix(SCREAMING_SNAKE_CASE_			).reshape(
					    SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)
					data_featuremap.append(SCREAMING_SNAKE_CASE_			)

				# expanding the data slice to One dimenssion
				lowerCAmelCase												=  []
				for each_focus in data_focus:
					focusa_list.extend(self.Expand_Mat(SCREAMING_SNAKE_CASE_			)			)
				lowerCAmelCase												=  np.asarray(SCREAMING_SNAKE_CASE_			)
				return focus_list, data_featuremap






			def 					UpperCAmelCase							(self  :	int      ,SCREAMING_SNAKE_CASE_  :	Optional[Any]      ,SCREAMING_SNAKE_CASE_  :	int      ,SCREAMING_SNAKE_CASE_  :	Tuple="average_pool"			)       ->	Optional[int]:





				"""simple docstring"""


				lowerCAmelCase												=  len(featuremaps[0]			)
				lowerCAmelCase												=  int(size_map / size_pooling			)
				lowerCAmelCase												=  []
				for i_map in range(len(SCREAMING_SNAKE_CASE_			)			):
					lowerCAmelCase												=  featuremaps[i_map]
					lowerCAmelCase												=  []
					for i_focus in range(0      ,SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			):
						for j_focus in range(0      ,SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			):
							lowerCAmelCase												=  feature_map[
							    i_focus : i_focus + size_pooling,
							    j_focus : j_focus + size_pooling,
							]
							if pooling_type == "average_pool":
								# average pooling
								map_pooled.append(np.average(SCREAMING_SNAKE_CASE_			)			)
							elif pooling_type == "max_pooling":
								# max pooling
								map_pooled.append(np.max(SCREAMING_SNAKE_CASE_			)			)
					lowerCAmelCase												=  np.asmatrix(SCREAMING_SNAKE_CASE_			).reshape(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)
					featuremap_pooled.append(SCREAMING_SNAKE_CASE_			)
				return featuremap_pooled






			def 					UpperCAmelCase							(self  :	int      ,SCREAMING_SNAKE_CASE_  :	Any			)       ->	Optional[Any]:





				"""simple docstring"""


				lowerCAmelCase												=  []
				for i in range(len(SCREAMING_SNAKE_CASE_			)			):
					lowerCAmelCase												=  np.shape(data[i]			)
					lowerCAmelCase												=  data[i].reshape(1      ,shapes[0] * shapes[1]			)
					lowerCAmelCase												=  data_listed.getA().tolist()[0]
					data_expanded.extend(SCREAMING_SNAKE_CASE_			)
				lowerCAmelCase												=  np.asarray(SCREAMING_SNAKE_CASE_			)
				return data_expanded






			def 					UpperCAmelCase							(self  :	Union[str, Any]      ,SCREAMING_SNAKE_CASE_  :	int			)       ->	Union[str, Any]:





				"""simple docstring"""


				lowerCAmelCase												=  np.asarray(SCREAMING_SNAKE_CASE_			)
				lowerCAmelCase												=  np.shape(SCREAMING_SNAKE_CASE_			)
				lowerCAmelCase												=  data_mat.reshape(1      ,shapes[0] * shapes[1]			)
				return data_expanded






			def 					UpperCAmelCase							(self  :	str      ,SCREAMING_SNAKE_CASE_  :	List[Any]      ,SCREAMING_SNAKE_CASE_  :	str      ,SCREAMING_SNAKE_CASE_  :	Any      ,SCREAMING_SNAKE_CASE_  :	Any      ,SCREAMING_SNAKE_CASE_  :	Dict			)       ->	Tuple:





				"""simple docstring"""


				lowerCAmelCase												=  []
				lowerCAmelCase												=  0
				for i_map in range(SCREAMING_SNAKE_CASE_			):
					lowerCAmelCase												=  np.ones((size_map, size_map)			)
					for i in range(0      ,SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			):
						for j in range(0      ,SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			):
							lowerCAmelCase												=  pd_pool[
							    i_pool
							]
							lowerCAmelCase												=  i_pool + 1
					lowerCAmelCase												=  np.multiply(
					    SCREAMING_SNAKE_CASE_      ,np.multiply(out_map[i_map]      ,(1 - out_map[i_map])			)			)
					pd_all.append(SCREAMING_SNAKE_CASE_			)
				return pd_all






			def 					UpperCAmelCase							(self  :	Any      ,SCREAMING_SNAKE_CASE_  :	Optional[Any]      ,SCREAMING_SNAKE_CASE_  :	Union[str, Any]      ,SCREAMING_SNAKE_CASE_  :	List[str]      ,SCREAMING_SNAKE_CASE_  :	Union[str, Any]      ,SCREAMING_SNAKE_CASE_  :	int      ,SCREAMING_SNAKE_CASE_  :	Tuple=bool			)       ->	List[str]:





				"""simple docstring"""


				print('''----------------------Start Training-------------------------'''			)
				print((''' - - Shape: Train_Data  ''', np.shape(SCREAMING_SNAKE_CASE_			))			)
				print((''' - - Shape: Teach_Data  ''', np.shape(SCREAMING_SNAKE_CASE_			))			)
				lowerCAmelCase												=  0
				lowerCAmelCase												=  []
				lowerCAmelCase												=  10_000
				while rp < n_repeat and mse >= error_accuracy:
					lowerCAmelCase												=  0
					print(F"""-------------Learning Time {rp}--------------"""			)
					for p in range(len(SCREAMING_SNAKE_CASE_			)			):
						# print('------------Learning Image: %d--------------'%p)
						lowerCAmelCase												=  np.asmatrix(datas_train[p]			)
						lowerCAmelCase												=  np.asarray(datas_teach[p]			)
						lowerCAmelCase							,       lowerCAmelCase												=  self.convolute(
						    SCREAMING_SNAKE_CASE_      ,self.conva      ,self.w_conva      ,self.thre_conva      ,conv_step=self.step_conva      ,)
						lowerCAmelCase												=  self.pooling(SCREAMING_SNAKE_CASE_      ,self.size_poolinga			)
						lowerCAmelCase												=  np.shape(SCREAMING_SNAKE_CASE_			)
						lowerCAmelCase												=  self._expand(SCREAMING_SNAKE_CASE_			)
						lowerCAmelCase												=  data_bp_input

						lowerCAmelCase												=  np.dot(SCREAMING_SNAKE_CASE_      ,self.vji.T			) - self.thre_bpa
						lowerCAmelCase												=  self.sig(SCREAMING_SNAKE_CASE_			)
						lowerCAmelCase												=  np.dot(SCREAMING_SNAKE_CASE_      ,self.wkj.T			) - self.thre_bpa
						lowerCAmelCase												=  self.sig(SCREAMING_SNAKE_CASE_			)

						# --------------Model Leaning ------------------------
						# calculate error and gradient---------------
						lowerCAmelCase												=  np.multiply(
						    (data_teach - bp_outa)      ,np.multiply(SCREAMING_SNAKE_CASE_      ,(1 - bp_outa)			)			)
						lowerCAmelCase												=  np.multiply(
						    np.dot(SCREAMING_SNAKE_CASE_      ,self.wkj			)      ,np.multiply(SCREAMING_SNAKE_CASE_      ,(1 - bp_outa)			)			)
						lowerCAmelCase												=  np.dot(SCREAMING_SNAKE_CASE_      ,self.vji			)

						lowerCAmelCase												=  pd_i_all / (self.size_poolinga * self.size_poolinga)
						lowerCAmelCase												=  pd_conva_pooled.T.getA().tolist()
						lowerCAmelCase												=  self._calculate_gradient_from_pool(
						    SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_      ,shape_featuremapa[0]      ,shape_featuremapa[1]      ,self.size_poolinga      ,)
						# weight and threshold learning process---------
						# convolution layer
						for k_conv in range(self.conva[1]			):
							lowerCAmelCase												=  self._expand_mat(pd_conva_all[k_conv]			)
							lowerCAmelCase												=  self.rate_weight * np.dot(SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_			)

							lowerCAmelCase												=  self.w_conva[k_conv] + delta_w.reshape(
							    (self.conva[0], self.conva[0])			)

							lowerCAmelCase												=  (
							    self.thre_conva[k_conv]
							    - np.sum(pd_conva_all[k_conv]			) * self.rate_thre
							)
						# all connected layer
						lowerCAmelCase												=  self.wkj + pd_k_all.T * bp_outa * self.rate_weight
						lowerCAmelCase												=  self.vji + pd_j_all.T * bp_outa * self.rate_weight
						lowerCAmelCase												=  self.thre_bpa - pd_k_all * self.rate_thre
						lowerCAmelCase												=  self.thre_bpa - pd_j_all * self.rate_thre
						# calculate the sum error of all single image
						lowerCAmelCase												=  np.sum(abs(data_teach - bp_outa			)			)
						error_count += errors
						# print('   ----Teach      ',data_teach)
						# print('   ----BP_output  ',bp_out3)
					lowerCAmelCase												=  rp + 1
					lowerCAmelCase												=  error_count / patterns
					all_mse.append(SCREAMING_SNAKE_CASE_			)

				def draw_error():
					lowerCAmelCase												=  [error_accuracy for i in range(int(n_repeat * 1.2			)			)]
					plt.plot(SCREAMING_SNAKE_CASE_      ,'''+-'''			)
					plt.plot(SCREAMING_SNAKE_CASE_      ,'''r--'''			)
					plt.xlabel('''Learning Times'''			)
					plt.ylabel('''All_mse'''			)
					plt.grid(SCREAMING_SNAKE_CASE_      ,alpha=0.5			)
					plt.show()

				print('''------------------Training Complished---------------------'''			)
				print((''' - - Training epoch: ''', rp, F"""     - - Mse: {mse:.6f}""")			)
				if draw_e:
					draw_error()
				return mse






			def 					UpperCAmelCase							(self  :	List[Any]      ,SCREAMING_SNAKE_CASE_  :	int			)       ->	Dict:





				"""simple docstring"""


				lowerCAmelCase												=  []
				print('''-------------------Start Testing-------------------------'''			)
				print((''' - - Shape: Test_Data  ''', np.shape(SCREAMING_SNAKE_CASE_			))			)
				for p in range(len(SCREAMING_SNAKE_CASE_			)			):
					lowerCAmelCase												=  np.asmatrix(datas_test[p]			)
					lowerCAmelCase							,       lowerCAmelCase												=  self.convolute(
					    SCREAMING_SNAKE_CASE_      ,self.conva      ,self.w_conva      ,self.thre_conva      ,conv_step=self.step_conva      ,)
					lowerCAmelCase												=  self.pooling(SCREAMING_SNAKE_CASE_      ,self.size_poolinga			)
					lowerCAmelCase												=  self._expand(SCREAMING_SNAKE_CASE_			)

					lowerCAmelCase												=  data_bp_input
					lowerCAmelCase												=  bp_outa * self.vji.T - self.thre_bpa
					lowerCAmelCase												=  self.sig(SCREAMING_SNAKE_CASE_			)
					lowerCAmelCase												=  bp_outa * self.wkj.T - self.thre_bpa
					lowerCAmelCase												=  self.sig(SCREAMING_SNAKE_CASE_			)
					produce_out.extend(bp_outa.getA().tolist()			)
				lowerCAmelCase												=  [list(map(self.do_round      ,SCREAMING_SNAKE_CASE_			)			) for each in produce_out]
				return np.asarray(SCREAMING_SNAKE_CASE_			)






			def 					UpperCAmelCase							(self  :	Union[str, Any]      ,SCREAMING_SNAKE_CASE_  :	List[Any]			)       ->	Union[str, Any]:





				"""simple docstring"""


				lowerCAmelCase												=  np.asmatrix(SCREAMING_SNAKE_CASE_			)
				lowerCAmelCase							,       lowerCAmelCase												=  self.convolute(
				    SCREAMING_SNAKE_CASE_      ,self.conva      ,self.w_conva      ,self.thre_conva      ,conv_step=self.step_conva      ,)
				lowerCAmelCase												=  self.pooling(SCREAMING_SNAKE_CASE_      ,self.size_poolinga			)

				return data_conveda, data_pooleda


if __name__ == "__main__":
					pass




"""simple docstring"""






UpperCAmelCase        =				8.3_144_598




def __magic_name__	(				_lowerCamelCase:		float,					_lowerCamelCase:		float			)					->						float:

	'''simple docstring'''




	if temperature < 0:
		raise Exception('''Temperature cannot be less than 0 K'''			)
	if molar_mass <= 0:
		raise Exception('''Molar mass cannot be less than or equal to 0 kg/mol'''			)
	else:
		return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5


if __name__ == "__main__":
					import doctest

					# run doctest
					doctest.testmod()

					# example
					UpperCAmelCase        =				3_0_0
					UpperCAmelCase        =				2_8
					UpperCAmelCase        =				rms_speed_of_molecule(temperature, molar_mass)
					print(f"""Vrms of Nitrogen gas at 300 K is {vrms} m/s""")


