
    ijC                         d dl Z d dl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 Zd	 Z	 	 dd
Z	 	 	 	 ddZd ZddZd Zd Zd ZddZ ed      d        Zy)    N)backend)tree)keras_export)KerasTensor)canonicalize_axis)to_tuple_or_listc                 $   t        |       } t        |      }| }|}t        |       t        |      kD  rdgt        |       t        |      z
  z  |z   }t        |       t        |      k  rdgt        |      t        |       z
  z  | z   } t        |       }t        t        |             D ]i  }| |   dk(  r	||   ||<   | |   ||   dk(  rdn||   ||<   ,||   dk(  s||   ||   | |   k(  r	| |   ||<   Mt        d| |    d||    d| d| d	       |S )aS  Broadcast input shapes to a unified shape.

    Convert to list for mutability.

    Args:
        shape1: A tuple or list of integers.
        shape2: A tuple or list of integers.

    Returns:
        output_shape (list of integers or `None`): The broadcasted shape.

    Example:
    >>> broadcast_shapes((5, 3), (1, 3))
    [5, 3]
       Nz2Cannot broadcast shape, the failure dim has value z!, which cannot be broadcasted to z. Input shapes are:  and .)listlenrange
ValueError)shape1shape2origin_shape1origin_shape2output_shapeis         r/var/www/html/emotional.easysim.app/public_html/venv/lib/python3.12/site-packages/keras/src/ops/operation_utils.pybroadcast_shapesr      sM     &\F&\FMM
6{S[ Fc&k12V;
6{S[ Fc&k12V;<L3v; !9>$QiLOAY&,Qi1nd&)LOayA~!2fQi6!96L"()Q Hayk!B6!9+ N))6u]O1N      c                 6   t        |       } |t        |       }t        |      }t        |      t        |       z   }|D cg c]  }t        ||       }}t	        |       }t        |      D cg c]  }||v rdn
t        |       }}t        |      S c c}w c c}w )a  Compute the output shape for the `expand_dims` operation.

    Args:
        input_shape: Input shape.
        axis: int or sequence of ints for the axis to expand.

    Returns:
        Tuple of ints: The output shape after the `expand_dims` operation.
    r
   )r   r   r   r   iterr   nexttuple)input_shapeaxisout_ndima
shape_iterax	new_shapes          r    compute_expand_dims_output_shaper%   9   s     {#K|;D!D4y3{++H489qa*9D9k"J8=h24R4ZT*--I   :s   B,Bc                    ||n|}t        |       }t        j                  |       } |dk(  r| dd }n| dd }g }t        t	        |            D ]  }||   	d||<   |j                  |         t        j                  |      }|dk(  r]t        j                  ||z
  |z        dz   }	t        t	        |	            D ]'  }||vs|	|   dk  st        d|  d	| d
| d| d	       n2|dk(  rt        j                  |dz
  |z        dz   }	nt        d|       |	D cg c]  }t        |       }	}|D ]  }d|	|<   	 t        |	      }	|dk(  r|d   f|	z   |d   fz   }
|
S |d   |d   f|	z   }
|
S c c}w )a3  Computes the output shape of pooling operations.

    Args:
        input_shape: Input shape. Must be a tuple of integers.
        pool_size: Size of the pooling operation. Must be a tuple of integers.
        strides: Stride of the pooling operation. Must be a tuple of integers.
            Defaults to `pool_size`.
        padding: Padding method. Available methods are `"valid"` or `"same"`.
            Defaults to `"valid"`.
        data_format: String, either `"channels_last"` or `"channels_first"`.
            The ordering of the dimensions in the inputs. `"channels_last"`
            corresponds to inputs with shape `(batch, height, width, channels)`
            while `"channels_first"` corresponds to inputs with shape
            `(batch, channels, height, weight)`. Defaults to `"channels_last"`.

    Returns:
        Tuple of ints: The output shape of the pooling operation.

    Examples:

    # Basic usage with square pooling on a single image
    >>> compute_pooling_output_shape((1, 4, 4, 1), (2, 2))
    (1, 2, 2, 1)

    # Strided pooling on a single image with strides different from pool_size
    >>> compute_pooling_output_shape((1, 4, 4, 1), (2, 2), strides=(1, 1))
    (1, 3, 3, 1)

    # Pooling on a batch of images
    >>> compute_pooling_output_shape((32, 4, 4, 3), (2, 2))
    (32, 2, 2, 3)
    Nchannels_lastr
      validr   zHComputed output size would be zero or negative. Received: `inputs.shape=z`, `pool_size=`, `strides=`, `padding=`.samezGArgument `padding` must be either 'valid' or 'same'. Received: padding=)
r   nparrayr   r   appendfloorr   intr   )r   	pool_sizestridespaddingdata_formatinput_shape_originspatial_shape	none_dimsr   output_spatial_shaper   s              r   compute_pooling_output_shaper<   P   s   N #?iGk*((;'Ko%#Ab)#ABI3}%&  #  "M!Q  #I'HHmi/7:;a? 	 s/01 	A	!&:1&=&B //:m <""+L	 B  'y, 	 
F	!xx):g(EFJi!
 	
 -AAqCFAA '"&Q' !56o%"$"#!"%'( 	  q!q!
 !!  Bs   E,c                 P   |dk(  r| dd }|| d   |fz   }n| dd }|| d   |fz   }t        |      t        |       k7  rt        d| d|  d      t        |t              r|ft        |      z  }t        |t              r|ft        |      z  }t        |      t        |      k7  rt        d	| d
|  d      g }	t	        j
                  |      }t        t        |            D ]  }
||
   	d||
<   |	j                  |
         t	        j
                  |dd       }t	        j
                  |      }|dk(  rit	        j                  |||dz
  z  z
  dz
  |z        dz   }t        t        |            D ]*  }
|
|	vs||
   dk  st        d|  d| d| d| d| d       n2|dv rt	        j                  |dz
  |z        dz   }nt        d| d      |D 
cg c]  }
t        |
       }}
|	D ]  }
d||
<   	 t        |      }|dk(  r| d   f|z   |d   fz   }|S | d   |d   f|z   }|S c c}
w )z%Compute the output shape of conv ops.r'   r
   r(   r)   NzNKernel shape must have the same length as input, but received kernel of shape z and input of shape r   zlDilation must be None, scalar or tuple/list of length of inputs' spatial shape, but received `dilation_rate=z` and input of shape r*   r   zGComputed output size would be zero or negative. Received `inputs shape=z`, `kernel shape=z`, `dilation_rate=r+   r,   r-   )r.   causalz9`padding` must be either `'valid'` or `'same'`. Received )
r   r   
isinstancer3   r/   r0   r   r1   r2   r   )r   filterskernel_sizer5   r6   r7   dilation_rater9   kernel_shaper:   r   kernel_spatial_shaper;   r   s                 r   compute_conv_output_shaperF      s    o%#Ab)"k"ow%??#AB"k!ng%>>
<C,,+n -)]!-
 	

 -%&(3}+=='3*s=11
=S//+_ -)]!-
 	
 IHH]+M3}%&  #  "M!Q  88L"$56HH]+M'HH2F2J!KKaO 	 	 s/01 		A	!&:1&=&B %%0M 2%%1N 3&&3_ 5  'y )  'y, 		 
&	&!xx):g(EFJGiq
 	
 -AAqCFAA '"&Q' !56o%^ 44R8H7JJ 	
  $AR(89<PP Bs   H#c                    t        |       dk(  }t        |      dk(  }|rd| d   f} |r|d   df}| d   "|d   | d   |d   k7  rt        d|  d| d      t        | dd |dd       }| d   |d   g}||z   }|r|d= |r|d= t        |      S )	zCompute the output shape of a `matmul` operation.

    Args:
        shape1: Shape of the left operand.
        shape2: Shape of the right operand.

    Returns:
        Tuple of ints: The output shape for the `matmul` operation.
    r
   r   r(   Nr>   z[Inner dimensions (`x1.shape[-1]` and `x2.shape[-2]`) must be equal, but received `x1.shape=z` and `x2.shape=r-   )r   r   r   r   )r   r   x1_is_1dx2_is_1dleading_shapelast_2_dims_shaper   s          r   compute_matmul_output_shaperL      s     6{aH6{aHVAY)Qr
2J"2J&*$--3H 5$
 	
 %VCR[&"+>MVBZ0 #44Lr   c           
      "   t        j                  |       st        | t              ryd}| D ]H  }t        |t        t
        j                  f      s$|dk  rt        d| d| d|  d      |dk(  sD|dz  }J |dkD  rt        d	| d
| d|  d      y)a9  Validate the `newshape` argument of `reshape`.

    Each dimension that is a concrete Python int must be either non-negative
    or `-1` (with at most one `-1`). Dynamic dimensions (e.g. backend tensor
    scalars resolved at runtime, such as `torch.SymInt` under `torch.compile`)
    are not validated here.
    Nr   r(   zEach dimension in `zT` must be a non-negative integer, or `-1` for a single unknown dimension. Received: =r   r
   z5There must be at most one unknown dimension (-1) in `z`. Received: )r   	is_tensorr@   r   r3   r/   integerr   )newshapenewshape_arg_nameneg_one_countdims       r   validate_reshape_shaperU   &  s     "j;&GM 
#RZZ018%&7%8 9((9':!H:QH 
 BYQM
 q!"- !8*A/
 	
 r   c           
         t        ||       t        j                  |      st        |t              r+t        |dd      }|rt        |      dk(  r|d   d|d   z  S yt        d |D              }|j                  d      }d| v sd|v rt        d |D              S t        j                  |       }|dk(  r.|t        j                  |      k7  rt        d	|  d
| d|       |S d}d}t        |      D ]  \  }}	|	dk(  r|}||	z  } |dk(  s||z  dk7  rt        d| d|  d
| d|       t        |      }
||z  |
|<   t        |
      S )zConverts `-1` in `newshape` to either an actual dimension or `None`.

    This utility does not special case the 0th dimension (batch size).
    shapeNr
   r   Nc              3   d   K   | ](  }t        |t        t        j                  f      r|nd  * y wrX   )r@   r3   r/   rP   .0rT   s     r   	<genexpr>z/compute_reshape_output_shape.<locals>.<genexpr>V  s,      @Cz#RZZ01t;s   .0r(   c              3   .   K   | ]  }|d k7  r|nd  yw)r(   N rZ   s     r   r\   z/compute_reshape_output_shape.<locals>.<genexpr>^  s     DCC2IS4/Ds   zFThe total size of the tensor must be unchanged. Received: input_shape=, rN   zyThe total size of the tensor must be unchanged, however, the input size cannot by divided by the specified dimensions in z. Received: input_shape=)rU   r   rO   r@   r   getattrr   r   countmathprodr   	enumerater   )r   rQ   rR   rW   unknown_dim_count
input_sizeknown_output_sizeunknown_dim_indexindexrT   r   s              r   compute_reshape_output_shaperj   F  s   
 8%67 "j;&G'40SZ1_q)=U1X%%  GO H !r* {dh.D8DDD;'JA8,,*m2.?-@(M   ) %
s"9 %$	% A.?!?1!DK !!9+b !8*.
 	
 >L&04E&EL"#r   c                     t                |t         ddd         S t               }t        |      |k7  rt        d| dt        |       d      g }|D ]O  }t	        |t
              r|| k  s||k\  rt        d| d| dt        |       d      |j                  ||z         Q t        t        |            |k7  rt        d	t        |       d
| d      t         fd|D              S )a  Compute the output shape for the `transpose` operation.

    Args:
        input_shape: Input shape.
        axes: Permutation of the dimensions for the `transpose` operation.

    Returns:
        Tuple of ints: The output shape after the `transpose` operation.
    Nr(   zDaxis must be a list of the same length as the input shape, expected z, but received r   z,Each axis in `axes` must be an integer in [-r_   z). Received: axes=z[`axes` must be a valid permutation of the input dimensions (no duplicates). Received: axes=z for input of rank c              3   (   K   | ]	  }|     y wrX   r^   )r[   r#   r   s     r   r\   z1compute_transpose_output_shape.<locals>.<genexpr>  s     ;RR;s   )r   r   r   r   r@   r3   r1   set)r   axesndimnormalized_axesr#   s   `    r   compute_transpose_output_shaperq     s+    {#K|[2&''{D
4yDv_SYKq:
 	
 O *"c"bD5jB$JF"TF"4T$ZLC  	rDy)* 3 D(//3Dzl ;6
 	

 ;?;;;r   c                    t        |       } t        |      }|d | v rd gnt        j                  |       g} t        |       t        |      k7  rt	        d|  d| d      |t        |t        |             }nd}||   | |<   t        | |      }|S )NzM`x` and `indices` must have the same number of dimensions, but receive shape r   r   r   )r   rb   rc   r   r   r   r   )r   indices_shaper   r   s       r   $compute_take_along_axis_output_shapert     s    {#K'M|k)TF		+0F/G 	 ;3}--!!,U=/D
 	

  s;'78%d+K#K?Lr   c                 4    t                |&|rt         D cg c]  }d c}      S t        g       S t        |t              r|f}t         fd|D              }|r|D ]  }d |<   	 t               S t	        |d      D ]  } |=  t               S c c}w )Nr
   c              3   H   K   | ]  }t        |t                      y wrX   )r   r   )r[   r!   rW   s     r   r\   zreduce_shape.<locals>.<genexpr>  s     @a"1c%j1@s   "T)reverse)r   r   r@   r3   sorted)rW   r   keepdims_r#   s   `    r   reduce_shaper{     s    KE|U+!+,,9	D#	w@4@@D 	BE"I	U|t, 	Bb		U| ,s   	Bzkeras.utils.get_source_inputsc                 p   t        | d      s| S | j                  \  }}}|r|j                  s| gS |j                  |   }|j                  rt	        j
                  |j                        S g }|j                  D ]:  } t        |       }|D ](  t        fd|D              s|j                         * < |S )zReturns the list of input tensors necessary to compute `tensor`.

    Output will always be a list of tensors
    (potentially with 1 element).

    Args:
        tensor: The tensor to start from.

    Returns:
        List of input tensors.
    _keras_historyc              3   &   K   | ]  }|u 
 y wrX   r^   )r[   txs     r   r\   z$get_source_inputs.<locals>.<genexpr>  s     >!1A:>s   )hasattrr}   _inbound_nodesis_inputr   flattenoutput_tensorsinput_tensorsget_source_inputsallr1   )tensor	operation
node_indexrz   nodesource_tensorsprevious_sourcesr   s          @r   r   r     s     6+,%44Iz1I44x''
3==<< 3 344N,, 1#4V#< ) 1A>~>>&--a011 "!r   )r*   r'   )r
   r*   r'   r
   )rQ   )NF)rb   numpyr/   	keras.srcr   r   keras.src.api_exportr   keras.src.backendr   &keras.src.backend.common.backend_utilsr   r   r   r%   r<   rF   rL   rU   rj   rq   rt   r{   r   r^   r   r   <module>r      s        - ) D C)X6 X~ Pf%P
@7t"<J., -." /"r   