


import pickle

import numpy as np
from matplotlib import pyplot as plt







class     _lowercase				:


       """simple docstring"""




       def __init__(     self							:    Optional[Any]      ,   __lowerCamelCase							:    List[Any]      ,   __lowerCamelCase							:    List[Any]      ,   __lowerCamelCase							:    int      ,   __lowerCamelCase							:    str      ,   __lowerCamelCase							:    int      ,   __lowerCamelCase							:    int=0.2      ,   __lowerCamelCase							:    Dict=0.2 ):


             '''simple docstring'''



             lowerCamelCase__	:       int					=						bp_numa
             lowerCamelCase__	:       str					=						bp_numa
             lowerCamelCase__	:       List[Any]					=						bp_numa
             lowerCamelCase__	:       int					=						conva_get[:2]
             lowerCamelCase__	:       Dict					=						conva_get[2]
             lowerCamelCase__	:       List[str]					=						size_pa
             lowerCamelCase__	:       List[str]					=						rate_w
             lowerCamelCase__	:       List[str]					=						rate_t
             lowerCamelCase__	:       Tuple					=						[
                 np.mat(-1 * np.random.rand(self.conva[0]      ,   self.conva[0] ) + 0.5 )
                 for i in range(self.conva[1] )
             ]
             lowerCamelCase__	:       Tuple					=						np.mat(-1 * np.random.rand(self.num_bpa      ,   self.num_bpa ) + 0.5 )
             lowerCamelCase__	:       Tuple					=						np.mat(-1 * np.random.rand(self.num_bpa      ,   self.num_bpa ) + 0.5 )
             lowerCamelCase__	:       List[Any]					=						-2 * np.random.rand(self.conva[1] ) + 1
             lowerCamelCase__	:       List[str]					=						-2 * np.random.rand(self.num_bpa ) + 1
             lowerCamelCase__	:       Any					=						-2 * np.random.rand(self.num_bpa ) + 1





       def 		lowerCAmelCase  (     self							:    List[Any]      ,   __lowerCamelCase							:    List[str] ):


             '''simple docstring'''



             lowerCamelCase__	:       Any					=						{
                 "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(__lowerCamelCase      ,   "wb" ) as f:
                   pickle.dump(__lowerCamelCase      ,   __lowerCamelCase )

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





       @classmethod
       def 		lowerCAmelCase  (     cls							:    List[Any]      ,   __lowerCamelCase							:    Any ):


             '''simple docstring'''



             with open(__lowerCamelCase      ,   "rb" ) as f:
                   lowerCamelCase__	:       Any					=						pickle.load(__lowerCamelCase )  # noqa: S301

             lowerCamelCase__	:       Dict					=						model_dic.get("conv1" )
             conv_get.append(model_dic.get("step_conv1" ) )
             lowerCamelCase__	:       str					=						model_dic.get("size_pooling1" )
             lowerCamelCase__	:       str					=						model_dic.get("num_bp1" )
             lowerCamelCase__	:       List[str]					=						model_dic.get("num_bp2" )
             lowerCamelCase__	:       int					=						model_dic.get("num_bp3" )
             lowerCamelCase__	:       Dict					=						model_dic.get("rate_weight" )
             lowerCamelCase__	:       int					=						model_dic.get("rate_thre" )
             # create model instance
             lowerCamelCase__	:       Union[str, Any]					=						CNN(__lowerCamelCase      ,   __lowerCamelCase      ,   __lowerCamelCase      ,   __lowerCamelCase      ,   __lowerCamelCase      ,   __lowerCamelCase      ,   __lowerCamelCase )
             # modify model parameter
             lowerCamelCase__	:       Optional[int]					=						model_dic.get("w_conv1" )
             lowerCamelCase__	:       Union[str, Any]					=						model_dic.get("wkj" )
             lowerCamelCase__	:       Union[str, Any]					=						model_dic.get("vji" )
             lowerCamelCase__	:       Optional[Any]					=						model_dic.get("thre_conv1" )
             lowerCamelCase__	:       str					=						model_dic.get("thre_bp2" )
             lowerCamelCase__	:       int					=						model_dic.get("thre_bp3" )
             return conv_ins





       def 		lowerCAmelCase  (     self							:    Dict      ,   __lowerCamelCase							:    Union[str, Any] ):


             '''simple docstring'''



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





       def 		lowerCAmelCase  (     self							:    Optional[Any]      ,   __lowerCamelCase							:    Optional[Any] ):


             '''simple docstring'''



             return round(__lowerCamelCase      ,   3 )





       def 		lowerCAmelCase  (     self							:    Dict      ,   __lowerCamelCase							:    Dict      ,   __lowerCamelCase							:    Tuple      ,   __lowerCamelCase							:    Optional[Any]      ,   __lowerCamelCase							:    Tuple      ,   __lowerCamelCase							:    List[Any] ):


             '''simple docstring'''



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

             # expanding the data slice to One dimenssion
             lowerCamelCase__	:       Optional[int]					=						[]
             for each_focus in data_focus:
                   focusa_list.extend(self.Expand_Mat(__lowerCamelCase ) )
             lowerCamelCase__	:       List[str]					=						np.asarray(__lowerCamelCase )
             return focus_list, data_featuremap





       def 		lowerCAmelCase  (     self							:    Tuple      ,   __lowerCamelCase							:    int      ,   __lowerCamelCase							:    int      ,   __lowerCamelCase							:    Any="average_pool" ):


             '''simple docstring'''



             lowerCamelCase__	:       List[str]					=						len(featuremaps[0] )
             lowerCamelCase__	:       Optional[int]					=						int(size_map / size_pooling )
             lowerCamelCase__	:       Dict					=						[]
             for i_map in range(len(__lowerCamelCase ) ):
                   lowerCamelCase__	:       Optional[int]					=						featuremaps[i_map]
                   lowerCamelCase__	:       Dict					=						[]
                   for i_focus in range(0      ,   __lowerCamelCase      ,   __lowerCamelCase ):
                         for j_focus in range(0      ,   __lowerCamelCase      ,   __lowerCamelCase ):
                               lowerCamelCase__	:       int					=						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(__lowerCamelCase ) )
                               elif pooling_type == "max_pooling":
                                     # max pooling
                                     map_pooled.append(np.max(__lowerCamelCase ) )
                   lowerCamelCase__	:       List[Any]					=						np.asmatrix(__lowerCamelCase ).reshape(__lowerCamelCase      ,   __lowerCamelCase )
                   featuremap_pooled.append(__lowerCamelCase )
             return featuremap_pooled





       def 		lowerCAmelCase  (     self							:    Dict      ,   __lowerCamelCase							:    List[str] ):


             '''simple docstring'''



             lowerCamelCase__	:       Tuple					=						[]
             for i in range(len(__lowerCamelCase ) ):
                   lowerCamelCase__	:       List[str]					=						np.shape(data[i] )
                   lowerCamelCase__	:       Tuple					=						data[i].reshape(1      ,   shapes[0] * shapes[1] )
                   lowerCamelCase__	:       Optional[Any]					=						data_listed.getA().tolist()[0]
                   data_expanded.extend(__lowerCamelCase )
             lowerCamelCase__	:       Union[str, Any]					=						np.asarray(__lowerCamelCase )
             return data_expanded





       def 		lowerCAmelCase  (     self							:    int      ,   __lowerCamelCase							:    Optional[int] ):


             '''simple docstring'''



             lowerCamelCase__	:       int					=						np.asarray(__lowerCamelCase )
             lowerCamelCase__	:       Any					=						np.shape(__lowerCamelCase )
             lowerCamelCase__	:       Optional[int]					=						data_mat.reshape(1      ,   shapes[0] * shapes[1] )
             return data_expanded





       def 		lowerCAmelCase  (     self							:    Dict      ,   __lowerCamelCase							:    str      ,   __lowerCamelCase							:    Optional[int]      ,   __lowerCamelCase							:    List[Any]      ,   __lowerCamelCase							:    Dict      ,   __lowerCamelCase							:    List[str] ):


             '''simple docstring'''



             lowerCamelCase__	:       List[Any]					=						[]
             lowerCamelCase__	:       Optional[Any]					=						0
             for i_map in range(__lowerCamelCase ):
                   lowerCamelCase__	:       Tuple					=						np.ones((size_map, size_map) )
                   for i in range(0      ,   __lowerCamelCase      ,   __lowerCamelCase ):
                         for j in range(0      ,   __lowerCamelCase      ,   __lowerCamelCase ):
                               lowerCamelCase__	:       Optional[int]					=						pd_pool[
                                   i_pool
                               ]
                               lowerCamelCase__	:       Optional[Any]					=						i_pool + 1
                   lowerCamelCase__	:       List[Any]					=						np.multiply(
                       __lowerCamelCase      ,   np.multiply(out_map[i_map]      ,   (1 - out_map[i_map]) ) )
                   pd_all.append(__lowerCamelCase )
             return pd_all





       def 		lowerCAmelCase  (     self							:    Optional[Any]      ,   __lowerCamelCase							:    Tuple      ,   __lowerCamelCase							:    str      ,   __lowerCamelCase							:    Dict      ,   __lowerCamelCase							:    Tuple      ,   __lowerCamelCase							:    Any      ,   __lowerCamelCase							:    Optional[int]=bool ):


             '''simple docstring'''



             print("----------------------Start Training-------------------------" )
             print((" - - Shape: Train_Data  ", np.shape(__lowerCamelCase )) )
             print((" - - Shape: Teach_Data  ", np.shape(__lowerCamelCase )) )
             lowerCamelCase__	:       Any					=						0
             lowerCamelCase__	:       Union[str, Any]					=						[]
             lowerCamelCase__	:       Optional[Any]					=						10000
             while rp < n_repeat and mse >= error_accuracy:
                   lowerCamelCase__	:       Optional[int]					=						0
                   print(f"-------------Learning Time {rp}--------------" )
                   for p in range(len(__lowerCamelCase ) ):
                         # print('------------Learning Image: %d--------------'%p)
                         lowerCamelCase__	:       Dict					=						np.asmatrix(datas_train[p] )
                         lowerCamelCase__	:       List[Any]					=						np.asarray(datas_teach[p] )
                         lowerCamelCase__					,     lowerCamelCase__	:       str					=						self.convolute(
                             __lowerCamelCase      ,   self.conva      ,   self.w_conva      ,   self.thre_conva      ,   conv_step=self.step_conva      ,   )
                         lowerCamelCase__	:       int					=						self.pooling(__lowerCamelCase      ,   self.size_poolinga )
                         lowerCamelCase__	:       Union[str, Any]					=						np.shape(__lowerCamelCase )
                         lowerCamelCase__	:       Union[str, Any]					=						self._expand(__lowerCamelCase )
                         lowerCamelCase__	:       str					=						data_bp_input

                         lowerCamelCase__	:       str					=						np.dot(__lowerCamelCase      ,   self.vji.T ) - self.thre_bpa
                         lowerCamelCase__	:       int					=						self.sig(__lowerCamelCase )
                         lowerCamelCase__	:       Any					=						np.dot(__lowerCamelCase      ,   self.wkj.T ) - self.thre_bpa
                         lowerCamelCase__	:       Any					=						self.sig(__lowerCamelCase )

                         # --------------Model Leaning ------------------------
                         # calculate error and gradient---------------
                         lowerCamelCase__	:       Dict					=						np.multiply(
                             (data_teach - bp_outa)      ,   np.multiply(__lowerCamelCase      ,   (1 - bp_outa) ) )
                         lowerCamelCase__	:       str					=						np.multiply(
                             np.dot(__lowerCamelCase      ,   self.wkj )      ,   np.multiply(__lowerCamelCase      ,   (1 - bp_outa) ) )
                         lowerCamelCase__	:       Tuple					=						np.dot(__lowerCamelCase      ,   self.vji )

                         lowerCamelCase__	:       Optional[Any]					=						pd_i_all / (self.size_poolinga * self.size_poolinga)
                         lowerCamelCase__	:       List[str]					=						pd_conva_pooled.T.getA().tolist()
                         lowerCamelCase__	:       Any					=						self._calculate_gradient_from_pool(
                             __lowerCamelCase      ,   __lowerCamelCase      ,   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__	:       Optional[int]					=						self._expand_mat(pd_conva_all[k_conv] )
                               lowerCamelCase__	:       Optional[int]					=						self.rate_weight * np.dot(__lowerCamelCase      ,   __lowerCamelCase )

                               lowerCamelCase__	:       Dict					=						self.w_conva[k_conv] + delta_w.reshape(
                                   (self.conva[0], self.conva[0]) )

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

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

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





       def 		lowerCAmelCase  (     self							:    str      ,   __lowerCamelCase							:    Any ):


             '''simple docstring'''



             lowerCamelCase__	:       Union[str, Any]					=						[]
             print("-------------------Start Testing-------------------------" )
             print((" - - Shape: Test_Data  ", np.shape(__lowerCamelCase )) )
             for p in range(len(__lowerCamelCase ) ):
                   lowerCamelCase__	:       Union[str, Any]					=						np.asmatrix(datas_test[p] )
                   lowerCamelCase__					,     lowerCamelCase__	:       List[Any]					=						self.convolute(
                       __lowerCamelCase      ,   self.conva      ,   self.w_conva      ,   self.thre_conva      ,   conv_step=self.step_conva      ,   )
                   lowerCamelCase__	:       Optional[Any]					=						self.pooling(__lowerCamelCase      ,   self.size_poolinga )
                   lowerCamelCase__	:       Optional[Any]					=						self._expand(__lowerCamelCase )

                   lowerCamelCase__	:       Optional[Any]					=						data_bp_input
                   lowerCamelCase__	:       Tuple					=						bp_outa * self.vji.T - self.thre_bpa
                   lowerCamelCase__	:       List[str]					=						self.sig(__lowerCamelCase )
                   lowerCamelCase__	:       Any					=						bp_outa * self.wkj.T - self.thre_bpa
                   lowerCamelCase__	:       Optional[int]					=						self.sig(__lowerCamelCase )
                   produce_out.extend(bp_outa.getA().tolist() )
             lowerCamelCase__	:       List[str]					=						[list(map(self.do_round      ,   __lowerCamelCase ) ) for each in produce_out]
             return np.asarray(__lowerCamelCase )





       def 		lowerCAmelCase  (     self							:    Optional[int]      ,   __lowerCamelCase							:    Tuple ):


             '''simple docstring'''



             lowerCamelCase__	:       str					=						np.asmatrix(__lowerCamelCase )
             lowerCamelCase__					,     lowerCamelCase__	:       Any					=						self.convolute(
                 __lowerCamelCase      ,   self.conva      ,   self.w_conva      ,   self.thre_conva      ,   conv_step=self.step_conva      ,   )
             lowerCamelCase__	:       Tuple					=						self.pooling(__lowerCamelCase      ,   self.size_poolinga )

             return data_conveda, data_pooleda


if __name__ == "__main__":
    pass






from __future__ import annotations

import time

import numpy as np

A   :					Dict	=      [8, 5, 9, 7]
A   :					Optional[Any]	=      [
    [2, 0, 1, 1],
    [0, 1, 2, 1],
    [4, 0, 0, 3],
    [0, 2, 1, 0],
    [1, 0, 3, 0],
]
A   :					Any	=      [
    [3, 2, 1, 4],
    [0, 2, 5, 2],
    [5, 1, 0, 5],
    [1, 5, 3, 0],
    [3, 0, 3, 3],
]







class     _lowercase				:


       """simple docstring"""




       def __init__(     self							:    str      ,   __lowerCamelCase							:    list[int]      ,   __lowerCamelCase							:    list[list[int]]      ,   __lowerCamelCase							:    list[list[int]]      ,   ):


             '''simple docstring'''



             lowerCamelCase__	:       int					=						claim_vector
             lowerCamelCase__	:       str					=						allocated_resources_table
             lowerCamelCase__	:       int					=						maximum_claim_table





       def 		lowerCAmelCase  (     self							:    Union[str, Any] ):


             '''simple docstring'''



             return [
                 sum(p_item[i] for p_item in self.__allocated_resources_table )
                 for i in range(len(self.__allocated_resources_table[0] ) )
             ]





       def 		lowerCAmelCase  (     self							:    Optional[int] ):


             '''simple docstring'''



             return np.array(self.__claim_vector ) - np.array(
                 self.__processes_resource_summation() )





       def 		lowerCAmelCase  (     self							:    List[str] ):


             '''simple docstring'''



             return [
                 list(np.array(self.__maximum_claim_table[i] ) - np.array(__lowerCamelCase ) )
                 for i, allocated_resource in enumerate(self.__allocated_resources_table )
             ]





       def 		lowerCAmelCase  (     self							:    Tuple ):


             '''simple docstring'''



             return {self.__need().index(__lowerCamelCase ): i for i in self.__need()}





       def 		lowerCAmelCase  (     self							:    List[str]      ,   **__lowerCamelCase							:    Union[str, Any] ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[Any]					=						self.__need()
             lowerCamelCase__	:       str					=						self.__allocated_resources_table
             lowerCamelCase__	:       List[Any]					=						self.__available_resources()
             lowerCamelCase__	:       str					=						self.__need_index_manager()
             for kw, val in kwargs.items():
                   if kw and val is True:
                         self.__pretty_data()
             print("_" * 50 + "\n" )
             while need_list:
                   lowerCamelCase__	:       int					=						False
                   for each_need in need_list:
                         lowerCamelCase__	:       Dict					=						True
                         for index, need in enumerate(__lowerCamelCase ):
                               if need > available_resources[index]:
                                     lowerCamelCase__	:       str					=						False
                                     break
                         if execution:
                               lowerCamelCase__	:       Tuple					=						True
                               # get the original index of the process from ind_ctrl db
                               for original_need_index, need_clone in need_index_manager.items():
                                     if each_need == need_clone:
                                           lowerCamelCase__	:       Any					=						original_need_index
                               print(f"Process {process_number + 1} is executing." )
                               # remove the process run from stack
                               need_list.remove(__lowerCamelCase )
                               # update available/freed resources stack
                               lowerCamelCase__	:       Union[str, Any]					=						np.array(__lowerCamelCase ) + np.array(
                                   alloc_resources_table[process_number] )
                               print(
                                   "Updated available resource stack for processes: "
                                   + " ".join([str(__lowerCamelCase ) for x in available_resources] ) )
                               break
                   if safe:
                         print("The process is in a safe state.\n" )
                   else:
                         print("System in unsafe state. Aborting...\n" )
                         break





       def 		lowerCAmelCase  (     self							:    Optional[int] ):


             '''simple docstring'''



             print(" " * 9 + "Allocated Resource Table" )
             for item in self.__allocated_resources_table:
                   print(
                       f"P{self.__allocated_resources_table.index(__lowerCamelCase ) + 1}"
                       + " ".join(f"{it:>8}" for it in item )
                       + "\n" )
             print(" " * 9 + "System Resource Table" )
             for item in self.__maximum_claim_table:
                   print(
                       f"P{self.__maximum_claim_table.index(__lowerCamelCase ) + 1}"
                       + " ".join(f"{it:>8}" for it in item )
                       + "\n" )
             print(
                 "Current Usage by Active Processes: "
                 + " ".join(str(__lowerCamelCase ) for x in self.__claim_vector ) )
             print(
                 "Initial Available Resources:       "
                 + " ".join(str(__lowerCamelCase ) for x in self.__available_resources() ) )
             time.sleep(1 )


if __name__ == "__main__":
    import doctest

    doctest.testmod()


