a
    SicC                     @   s~   d Z ddlm  mZ ddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ dd	lmZ G d
d deZdS )z(Keras base class for convolution layers.    N)activations)constraints)initializers)regularizers)Layer)	InputSpec)
conv_utilsc                       s   e Zd ZdZd% fdd		Zd
d Zdd Zdd Zej	dddd Z
dd Zdd Zdd Zdd Z fddZdd Zdd  Zd!d" Zd#d$ Z  ZS )&Conva  Abstract N-D convolution layer (private, used as implementation base).

    This layer creates a convolution kernel that is convolved
    (actually cross-correlated) with the layer input to produce a tensor of
    outputs. If `use_bias` is True (and a `bias_initializer` is provided),
    a bias vector is created and added to the outputs. Finally, if
    `activation` is not `None`, it is applied to the outputs as well.

    Note: layer attributes cannot be modified after the layer has been called
    once (except the `trainable` attribute).

    Args:
      rank: An integer, the rank of the convolution, e.g. "2" for 2D
        convolution.
      filters: Integer, the dimensionality of the output space (i.e. the number
        of filters in the convolution). Could be "None", eg in the case of
        depth wise convolution.
      kernel_size: An integer or tuple/list of n integers, specifying the
        length of the convolution window.
      strides: An integer or tuple/list of n integers,
        specifying the stride length of the convolution.
        Specifying any stride value != 1 is incompatible with specifying
        any `dilation_rate` value != 1.
      padding: One of `"valid"`,  `"same"`, or `"causal"` (case-insensitive).
        `"valid"` means no padding. `"same"` results in padding with zeros
        evenly to the left/right or up/down of the input such that output has
        the same height/width dimension as the input. `"causal"` results in
        causal (dilated) convolutions, e.g. `output[t]` does not depend on
        `input[t+1:]`.
      data_format: A string, one of `channels_last` (default) or
        `channels_first`.
        The ordering of the dimensions in the inputs.
        `channels_last` corresponds to inputs with shape
        `(batch_size, ..., channels)` while `channels_first` corresponds to
        inputs with shape `(batch_size, channels, ...)`.
      dilation_rate: An integer or tuple/list of n integers, specifying
        the dilation rate to use for dilated convolution.
        Currently, specifying any `dilation_rate` value != 1 is
        incompatible with specifying any `strides` value != 1.
      groups: A positive integer specifying the number of groups in which the
        input is split along the channel axis. Each group is convolved
        separately with `filters / groups` filters. The output is the
        concatenation of all the `groups` results along the channel axis.
        Input channels and `filters` must both be divisible by `groups`.
      activation: Activation function to use.
        If you don't specify anything, no activation is applied.
      use_bias: Boolean, whether the layer uses a bias.
      kernel_initializer: An initializer for the convolution kernel. If None,
        the default initializer (glorot_uniform) will be used.
      bias_initializer: An initializer for the bias vector. If None, the default
        initializer (zeros) will be used.
      kernel_regularizer: Optional regularizer for the convolution kernel.
      bias_regularizer: Optional regularizer for the bias vector.
      activity_regularizer: Optional regularizer function for the output.
      kernel_constraint: Optional projection function to be applied to the
          kernel after being updated by an `Optimizer` (e.g. used to implement
          norm constraints or value constraints for layer weights). The function
          must take as input the unprojected variable and must return the
          projected variable (which must have the same shape). Constraints are
          not safe to use when doing asynchronous distributed training.
      bias_constraint: Optional projection function to be applied to the
          bias after being updated by an `Optimizer`.
       validNTglorot_uniformzerosc                    sZ  t  jf ||t|d| || _t|tr8t|}|d urX|dkrXtd| d|| _	|pdd| _
t||d| _tj||ddd	| _t|| _t|| _t||d
| _t|	| _|
| _t|| _t|| _t|| _t|| _t|| _t|| _t| jd d| _ | !  | jdk| _"| jdk| _#t$| j| jd | _%d S )N)	trainablenameactivity_regularizerr   z[Invalid value for argument `filters`. Expected a strictly positive value. Received filters=.r
   kernel_sizestridesT)
allow_zerodilation_rate   )min_ndimcausalchannels_first)&super__init__r   getrank
isinstancefloatint
ValueErrorfiltersgroupsr   normalize_tupler   r   normalize_paddingpaddingnormalize_data_formatdata_formatr   r   
activationuse_biasr   kernel_initializerbias_initializerkernel_regularizerbias_regularizerr   kernel_constraintbias_constraintr   
input_spec_validate_init
_is_causal_channels_firstconvert_data_format_tf_data_format)selfr   r"   r   r   r&   r(   r   r#   r)   r*   r+   r,   r-   r.   r   r/   r0   r   r   conv_opkwargs	__class__ `/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/layers/convolutional/base_conv.pyr   ^   sX    

zConv.__init__c                 C   s   | j d ur.| j | j dkr.td| j| j t| jsHtd| jf t| jsbtd| jf | jdkrddlm	} ddl
m} t| ||fstdd S )	Nr   zgThe number of filters must be evenly divisible by the number of groups. Received: groups={}, filters={}z<The argument `kernel_size` cannot contain 0(s). Received: %sz9The argument `strides` cannot contains 0(s). Received: %sr   )Conv1D)SeparableConv1DzCCausal padding is only supported for `Conv1D`and `SeparableConv1D`.)r"   r#   r!   formatallr   r   r&   !keras.layers.convolutional.conv1dr>   +keras.layers.convolutional.separable_conv1dr?   r   )r7   r>   r?   r<   r<   r=   r2      s2    


zConv._validate_initc              	   C   s   t |}| |}|| j dkr6td| j||| j|| j | jf }| | | j	d|| j
| j| jd| jd| _| jr| j	d| jf| j| j| jd| jd| _nd | _|  }t| jd ||id| _d| _d S )	Nr   zThe number of input channels must be evenly divisible by the number of groups. Received groups={}, but the input has {} channels (full input shape is {}).kernelT)r   shapeinitializerregularizer
constraintr   dtypebiasr   )r   axes)tfTensorShape_get_input_channelr#   r!   r@   r   r"   compute_output_shape
add_weightr+   r-   r/   rI   rD   r*   r,   r.   r0   rJ   _get_channel_axisr   r   r1   built)r7   input_shapeinput_channelkernel_shapechannel_axisr<   r<   r=   build   sL    


	

z
Conv.buildc              	   C   sZ   | j dkrd}nt| j tr(| j  }n| j }tjj||t| j|t| j	| j
| jjdS )Nr   VALID)r   r&   	dilationsr(   r   )r&   r   strupperrL   nnconvolutionlistr   r   r6   r;   __name__)r7   inputsrD   
tf_paddingr<   r<   r=   convolution_op   s    
zConv.convolution_op)jit_compilec                 C   s   |  ||S )N)rb   )r7   r`   rD   r<   r<   r=   _jit_compiled_convolution_op  s    z!Conv._jit_compiled_convolution_opc                    s  |j } jrt| |} jdkr> |t j}n 	| j} j
r|j j} jdkr jrt jd jdf}||7 }nP|d ur|d j krć fdd}tj|| jd d}ntjj| j jd}t s |}||  jd ur |S |S )Nr
   r   c                    s   t jj|  j jdS )Nr(   )rL   r\   bias_addrJ   r6   )or7   r<   r=   	_apply_fn'  s    
zConv.call.<locals>._apply_fn)
inner_rankre   )rE   r3   rL   pad_compute_causal_paddingr#   rd   convert_to_tensorrD   rb   r*   r   r4   reshaperJ   r"   r   squeeze_batch_dimsr\   rf   r6   executing_eagerlyrO   	set_shaper)   )r7   r`   rS   outputsoutput_rankrJ   ri   	out_shaper<   rh   r=   call  s6    





z	Conv.callc                    s    fddt |D S )Nc              	      s8   g | ]0\}}t j| j|  j j|  j| d qS ))r&   stridedilation)r   conv_output_lengthr   r&   r   r   ).0ilengthrh   r<   r=   
<listcomp>>  s   z.Conv._spatial_output_shape.<locals>.<listcomp>)	enumerate)r7   spatial_input_shaper<   rh   r=   _spatial_output_shape=  s    
zConv._spatial_output_shapec              	   C   s   t | }t|| j d }zn| jdkrZt |d | | ||d  | jg W S t |d | | jg | ||d d   W S W n* ty   td| j	 d| dY n0 d S )Nr
   channels_lastzCOne of the dimensions in the output is <= 0 due to downsampling in z;. Consider increasing the input size. Received input shape zO which would produce output shape with a zero or negative value in a dimension.)
rL   rM   as_listlenr   r(   r   r"   r!   r   )r7   rS   
batch_rankr<   r<   r=   rO   I  s4    



zConv.compute_output_shapec                 C   s   dS )NFr<   )r7   r`   r<   r<   r=   _recreate_conv_opd  s    zConv._recreate_conv_opc                    s   | j | j| j| j| j| j| jt| j	| j
t| jt| jt| jt| jt| jt| jt| jd}t  }tt| t|  S )N)r"   r   r   r&   r(   r   r#   r)   r*   r+   r,   r-   r.   r   r/   r0   )r"   r   r   r&   r(   r   r#   r   	serializer)   r*   r   r+   r,   r   r-   r.   r   r   r/   r0   r   
get_configdictr^   items)r7   configbase_configr:   r<   r=   r   g  s2    





zConv.get_configc                 C   s   | j d | jd d  }t|jdddu r0d}nt|jd }| jdkrhddgg| |dgddgg }nddgg| ddg|dgg }|S )z;Calculates padding for 'causal' option for 1-d conv layers.r   r
   ndimsNr   r   )r   r   getattrrE   r   r(   )r7   r`   left_padr   causal_paddingr<   r<   r=   rl     s    
 zConv._compute_causal_paddingc                 C   s   | j dkrd| j S dS d S )Nr   r   )r(   r   rh   r<   r<   r=   rQ     s    

zConv._get_channel_axisc                 C   s:   |   }|j| jd u r.td| d| dt|| S )NzSThe channel dimension of the inputs should be defined. The input_shape received is z, where axis z> (0-based) is the channel dimension, which found to be `None`.)rQ   dimsvaluer!   r    )r7   rS   rV   r<   r<   r=   rN     s    zConv._get_input_channelc                 C   s0   | j dkrd}n| j }t|ttfs,| }|S )Nr   r   )r&   r   r^   tupler[   )r7   
op_paddingr<   r<   r=   _get_padding_op  s    
zConv._get_padding_op)r
   r   Nr
   r
   NTr   r   NNNNNTNN)r_   
__module____qualname____doc__r   r2   rW   rb   rL   functionrd   ru   r   rO   r   r   rl   rQ   rN   r   __classcell__r<   r<   r:   r=   r	      sB   E                 H"/

-r	   )r   tensorflow.compat.v2compatv2rL   kerasr   r   r   r   keras.engine.base_layerr   keras.engine.input_specr   keras.utilsr   r	   r<   r<   r<   r=   <module>   s   