o
    i eVH                     @   s   d Z ddl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.Base class for convolutional-recurrent layers.    N)backend)
base_layer	InputSpec)RNN)
conv_utils)generic_utils)tf_utilsc                       sl   e Zd ZdZ					d fdd	Zejdd Zejdd Zd	d
 Z					dddZ
dddZ  ZS )ConvRNNa)  N-Dimensional Base class for convolutional-recurrent layers.

    Args:
      rank: Integer, rank of the convolution, e.g. "2" for 2D convolutions.
      cell: A RNN cell instance. A RNN cell is a class that has: - a
        `call(input_at_t, states_at_t)` method, returning `(output_at_t,
        states_at_t_plus_1)`. The call method of the cell can also take the
        optional argument `constants`, see section "Note on passing external
        constants" below. - a `state_size` attribute. This can be a single
        integer (single state) in which case it is the number of channels of the
        recurrent state (which should be the same as the number of channels of
        the cell output). This can also be a list/tuple of integers (one size
        per state).  In this case, the first entry (`state_size[0]`) should be
        the same as the size of the cell output.
      return_sequences: Boolean. Whether to return the last output. in the
        output sequence, or the full sequence.
      return_state: Boolean. Whether to return the last state in addition to the
        output.
      go_backwards: Boolean (default False). If True, process the input sequence
        backwards and return the reversed sequence.
      stateful: Boolean (default False). If True, the last state for each sample
        at index i in a batch will be used as initial state for the sample of
        index i in the following batch.
      input_shape: Use this argument to specify the shape of the input when this
        layer is the first one in a model.
    Call arguments:
      inputs: A (2 + `rank`)D tensor.
      mask: Binary tensor of shape `(samples, timesteps)` indicating whether a
        given timestep should be masked.
      training: Python boolean indicating whether the layer should behave in
        training mode or in inference mode. This argument is passed to the cell
        when calling it. This is for use with cells that use dropout.
      initial_state: List of initial state tensors to be passed to the first
        call of the cell.
      constants: List of constant tensors to be passed to the cell at each
        timestep.
    Input shape:
      (3 + `rank`)D tensor with shape: `(samples, timesteps, channels,
        img_dimensions...)`
      if data_format='channels_first' or shape: `(samples, timesteps,
        img_dimensions..., channels)` if data_format='channels_last'.
    Output shape:
      - If `return_state`: a list of tensors. The first tensor is the output.
        The remaining tensors are the last states,
        each (2 + `rank`)D tensor with shape: `(samples, filters,
          new_img_dimensions...)` if data_format='channels_first'
        or shape: `(samples, new_img_dimensions..., filters)` if
          data_format='channels_last'. img_dimension values might have changed
          due to padding.
      - If `return_sequences`: (3 + `rank`)D tensor with shape: `(samples,
        timesteps, filters, new_img_dimensions...)` if
        data_format='channels_first'
        or shape: `(samples, timesteps, new_img_dimensions..., filters)` if
          data_format='channels_last'.
      - Else, (2 + `rank`)D tensor with shape: `(samples, filters,
        new_img_dimensions...)` if data_format='channels_first'
        or shape: `(samples, new_img_dimensions..., filters)` if
          data_format='channels_last'.
    Masking: This layer supports masking for input data with a variable number
      of timesteps.
    Note on using statefulness in RNNs: You can set RNN layers to be 'stateful',
      which means that the states computed for the samples in one batch will be
      reused as initial states for the samples in the next batch. This assumes a
      one-to-one mapping between samples in different successive batches.
      To enable statefulness: - Specify `stateful=True` in the layer
      constructor.
        - Specify a fixed batch size for your model, by passing
            - If sequential model: `batch_input_shape=(...)` to the first layer
              in your model.
            - If functional model with 1 or more Input layers:
              `batch_shape=(...)` to all the first layers in your model. This is
              the expected shape of your inputs *including the batch size*. It
              should be a tuple of integers, e.g. `(32, 10, 100, 100, 32)`. for
              rank 2 convolution Note that the image dimensions should be
              specified too. - Specify `shuffle=False` when calling fit(). To
              reset the states of your model, call `.reset_states()` on either a
              specific layer, or on your entire model.
    Note on specifying the initial state of RNNs: You can specify the initial
      state of RNN layers symbolically by calling them with the keyword argument
      `initial_state`. The value of `initial_state` should be a tensor or list
      of tensors representing the initial state of the RNN layer. You can
      specify the initial state of RNN layers numerically by calling
      `reset_states` with the keyword argument `states`. The value of `states`
      should be a numpy array or list of numpy arrays representing the initial
      state of the RNN layer.
    Note on passing external constants to RNNs: You can pass "external"
      constants to the cell using the `constants` keyword argument of
      `RNN.__call__` (as well as `RNN.call`) method. This requires that the
      `cell.call` method accepts the same keyword argument `constants`. Such
      constants can be used to condition the cell transformation on additional
      static inputs (not changing over time), a.k.a. an attention mechanism.
    Fc           	         st   |r	t d| t|ttfrt d| t j||||||fi | || _t|d dg| _d | _	d | _
d S )NzDUnrolling is not possible with convolutional RNNs. Received: unroll=zIt is not possible at the moment tostack convolutional cells. Only pass a single cell instance as the `cell` argument. Received: cell=   )ndim)	TypeError
isinstancelisttuplesuper__init__rankr   
input_specstates_num_constants)	selfr   cellreturn_sequencesreturn_statego_backwardsstatefulunrollkwargs	__class__ Q/var/www/myenv/lib/python3.10/site-packages/keras/src/layers/rnn/base_conv_rnn.pyr   |   s4   	
zConvRNN.__init__c                    s.  t tr	d | j  jdkrdd  n jdkr#dd t fddttD  jdkrEd d  jf  }n jdkrVd d   jf }| jse|d d	 |dd   }| j	r|g} jdkr| fd
dtdD 7 }|S  jdkr| fddtdD 7 }|S )Nr   channels_firstr   channels_last   c              	      s8   g | ]}t j|  j|  j j|  j| d qS ))paddingstridedilation)r   conv_output_lengthkernel_sizer'   stridesdilation_rate).0idx)r   img_dimsr!   r"   
<listcomp>   s    z0ConvRNN.compute_output_shape.<locals>.<listcomp>   c                    s   g | ]}d   j f qS r   filtersr.   _r   input_shapenorm_img_dimsr!   r"   r1          c                    s"   g | ]}d  f  j f qS r3   r4   r6   r8   r!   r"   r1      s    )
r   r   r   data_formatr   rangelenr5   r   r   )r   r9   output_shaper!   )r   r0   r9   r:   r"   compute_output_shape   s<   






	
zConvRNN.compute_output_shapec                    s  | j d ur|| j  d  }nd }t|tr|d }| jr |d nd }t|d f|d| jd   d| jd< t| jtj	r[|d f|dd   }|d urU| j
|g|  n| j
| t| jjdrit| jj}n| jjg}| jd ur| jjdkr|d n| jjdkr| jd   fd	d
| jD |krtddd
 | jD  d| jj n-tdd t| jD | jjdkrÇfdd
|D | _n| jjdkrӇfdd
|D | _| jr|   d| _d S )Nr   r%   r   shape__len__r#   r2   r$   c                    s   g | ]}|j   qS r!   rA   r.   spec)ch_dimr!   r"   r1      s    z!ConvRNN.build.<locals>.<listcomp>zcAn `initial_state` was passed that is not compatible with `cell.state_size`. Received state shapes c                 S   s   g | ]}|j qS r!   rA   rD   r!   r!   r"   r1      s    z. However `cell.state_size` is c                 s   s    | ]}d V  qd S Nr!   r6   r!   r!   r"   	<genexpr>   s    z ConvRNN.build.<locals>.<genexpr>c                    s   g | ]}t d |f  dqS )NrA   r   r.   dimr0   r!   r"   r1      r;   c                    s    g | ]}t d   |f dqS )rG   rA   r   rI   rK   r!   r"   r1     s    T)r   r   r   r   r   r   r   r   r   Layerbuildhasattr
state_size
state_specr<   
ValueErrorr   r=   reset_statesbuilt)r   r9   constants_shape
batch_sizestep_input_shaperO   r!   )rF   r0   r"   rM      sV   








zConvRNN.buildc                    s~   t | t j dd t| jj}| jj|d< | jj t	t
| j| jjd t| jjdr< fdd| jjD S  gS )Nr2   )axisr&   )r'   rC   c                    s   g | ]} qS r!   r!   r6   initial_stater!   r"   r1     s    z-ConvRNN.get_initial_state.<locals>.<listcomp>)r   
zeros_likesumr   r   kernel_shaper5   
input_convtfzerosr   dtyper'   rN   rO   )r   inputsrB   r!   rX   r"   get_initial_state  s   
zConvRNN.get_initial_stateNc              
      s$   |||\}}}t|tr|d }t|d }i  tjjdr(| d< |rEtjjds=t	dj d|  fdd}n fd	d}tj
||||j||jd
\}}	}
jrqdd tj|
D }| jrw|	}n|}jrt|
ttfs|
g}
nt|
}
|g|
 S |S )Nr   r2   training	constantsz	RNN cell z1 does not support constants. Received: constants=c                    s:   |j  d  }|d j   }jj| |fd|i S )Nrd   )r   r   call)ra   r   rd   r   r   r!   r"   step;  s   zConvRNN.call.<locals>.stepc                    s   j j| |fi  S rG   )r   re   )ra   r   rf   r!   r"   rg   D  s   )rd   r   maskinput_lengthreturn_all_outputsc                 S   s   g | ]
\}}t ||qS r!   )r   update)r.   
self_statestater!   r!   r"   r1   R  s    
z ConvRNN.call.<locals>.<listcomp>)_process_inputsr   r   r   	int_shaper   has_argr   re   rQ   rnnr   r   r   zipr   
add_updater   r   )r   ra   rh   rc   rY   rd   	timestepsrg   last_outputoutputsr   updatesoutputr!   rf   r"   re     sT   



	



zConvRNN.callc              	      s  j stdjd j}|jrd jr)d d dd  d v r1tdfdd j	d d u rat
jjdrT fd	d
jjD _	d S t jjg_	d S |d u rt
jjdrtj	jjD ]\}}t|t | qtd S tj	d t jj d S t|ttfs|g}t|tj	krtdj dtj	 dt| d| tt|j	D ]6\}\}}t
jjdr݈jj| }njj}|j |krtdj d | d|j t|| qd S )NzLayer must be stateful.r   r2   r%   a  If a RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: 
- If using a Sequential model, specify the batch size by passing a `batch_input_shape` argument to your first layer.
- If using the functional API, specify the time dimension by passing a `batch_shape` argument to your Input layer.
The same thing goes for the number of rows and columns.c                    sX   t } jjdkr| |d< t|S  jjdkr#| | jd < t|S td jj )Nr#   r2   r$   z`Cell data format must be one of {"channels_first", "channels_last"}. Received: cell.data_format=)r   r   r<   r   KeyErrorr   )nb_channelsresult)r   state_shaper!   r"   get_tuple_shape  s   	z-ConvRNN.reset_states.<locals>.get_tuple_shaperC   c                    s   g | ]	}t  |qS r!   )r   r_   rI   )r}   r!   r"   r1     s    z(ConvRNN.reset_states.<locals>.<listcomp>zLayer z	 expects z states, but it received z  state values. States received: z)State {index} is incompatible with layer z: expected shape=z, found shape=)r   AttributeErrorr   rB   r@   r   r   concatenaterQ   r   rN   r   rO   r   r_   rr   	set_valuenpr   r   r   r>   name	enumerate)r   r   r9   rm   rJ   indexvaluer!   )r}   r   r|   r"   rR   e  sn   


zConvRNN.reset_states)FFFFF)NNNNrG   )__name__
__module____qualname____doc__r   r	   shape_type_conversionr@   rM   rb   re   rR   __classcell__r!   r!   r   r"   r
      s&    a&
-
;
Gr
   )r   numpyr   tensorflow.compat.v2compatv2r^   	keras.srcr   keras.src.enginer   keras.src.engine.input_specr   keras.src.layers.rnn.base_rnnr   keras.src.utilsr   r   r	   r
   r!   r!   r!   r"   <module>   s   