
    d6m                        d Z ddlZddlZddlZddlZddlZddl	m
Z
 ddlmZmZ  G d d          Zedk    r&d	Z ej        d
d          Ze                    ej        d ej        d          e          Ze                    ej        d ej        d          e          Ze                    ej        d ej        d          e          Ze                    ej        d ej        d          e          Z ed          Ze                    e           e                                Z ed ee                     e                                  dS dS )zHere is defined the Expr class.    N   )PerformanceWarning)IO_BUFFER_SIZEBUFFER_TIMESc                   `    e Zd ZdZi Z	 ddZddZddZddZdd	Z	d
 Z
d ZddZd Zd ZdS )Expraf  A class for evaluating expressions with arbitrary array-like objects.

    Expr is a class for evaluating expressions containing array-like objects.
    With it, you can evaluate expressions (like "3 * a + 4 * b") that
    operate on arbitrary large arrays while optimizing the resources
    required to perform them (basically main memory and CPU cache memory).
    It is similar to the Numexpr package (see :ref:`[NUMEXPR] <NUMEXPR>`),
    but in addition to NumPy objects, it also accepts disk-based homogeneous
    arrays, like the Array, CArray, EArray and Column PyTables objects.

    .. warning::

        Expr class only offers a subset of the Numexpr features due to the
        complexity of implement some of them when dealing with huge amount of
        data.

    All the internal computations are performed via the Numexpr package,
    so all the broadcast and upcasting rules of Numexpr applies here too.
    These rules are very similar to the NumPy ones, but with some exceptions
    due to the particularities of having to deal with potentially very large
    disk-based arrays.  Be sure to read the documentation of the Expr
    constructor and methods as well as that of Numexpr, if you want to fully
    grasp these particularities.


    Parameters
    ----------
    expr : str
        This specifies the expression to be evaluated, such as "2 * a + 3 * b".
    uservars : dict
        This can be used to define the variable names appearing in *expr*.
        This mapping should consist of identifier-like strings pointing to any
        `Array`, `CArray`, `EArray`, `Column` or NumPy ndarray instances (or
        even others which will tried to be converted to ndarrays).  When
        `uservars` is not provided or `None`, the current local and global
        namespace is sought instead of `uservars`.  It is also possible to pass
        just some of the variables in expression via the `uservars` mapping,
        and the rest will be retrieved from the current local and global
        namespaces.
    kwargs : dict
        This is meant to pass additional parameters to the Numexpr kernel.
        This is basically the same as the kwargs argument in
        Numexpr.evaluate(), and is mainly meant for advanced use.

    Examples
    --------
    The following shows an example of using Expr::

        >>> f = tb.open_file('/tmp/test_expr.h5', 'w')
        >>> a = f.create_array('/', 'a', np.array([1,2,3]))
        >>> b = f.create_array('/', 'b', np.array([3,4,5]))
        >>> c = np.array([4,5,6])
        >>> expr = tb.Expr("2 * a + b * c")   # initialize the expression
        >>> expr.eval()                 # evaluate it
        array([14, 24, 36], dtype=int64)
        >>> sum(expr)                   # use as an iterator
        74

    where you can see that you can mix different containers in
    the expression (whenever shapes are consistent).

    You can also work with multidimensional arrays::

        >>> a2 = f.create_array('/', 'a2', np.array([[1,2],[3,4]]))
        >>> b2 = f.create_array('/', 'b2', np.array([[3,4],[5,6]]))
        >>> c2 = np.array([4,5])           # This will be broadcasted
        >>> expr = tb.Expr("2 * a2 + b2-c2")
        >>> expr.eval()
        array([[1, 3],
               [7, 9]], dtype=int64)
        >>> sum(expr)
        array([ 8, 12], dtype=int64)
        >>> f.close()

    .. rubric:: Expr attributes

    .. attribute:: append_mode

        The append mode for user-provided output containers.

    .. attribute:: maindim

        Common main dimension for inputs in expression.

    .. attribute:: names

        The names of variables in expression (list).

    .. attribute:: out

        The user-provided container (if any) for the expression outcome.

    .. attribute:: o_start

        The start range selection for the user-provided output.

    .. attribute:: o_stop

        The stop range selection for the user-provided output.

    .. attribute:: o_step

        The step range selection for the user-provided output.

    .. attribute:: shape

        Common shape for the arrays in expression.

    .. attribute:: values

        The values of variables in expression (list).

    Nc                    d| _         	 d| _        	 g | _        	 d | _        	 d | _        	 d | _        	 d | _        	 d | _        	 d\  | _        | _	        | _
        d | _        	 d | _	        	 d | _
        	 g | _        	 d | _        	 d | _        	 |                     ||          }t          j                            |          }t          j                            ||          \  | _        }|                                D ]\  }}t)          |          t*          t,          t.          fv r)t1          |t2          j        t2          j        f          s#t9          |d          r`t;          d|z            |j        j        }	|	dvrt;          d|z            |                                D ]O\  }}t1          |t@          j!                  r0|j"        j#        s$|j$        dk    r|%                                }|||<   P| j        }
g }| j        D ]}||         }t9          |d          r|&                    |j'                   nOt9          |d          r|&                    |           n)tA          j(        |          }|&                    |           |
&                    |           d	 tS          | j        |          D             }t          j        j*        ||fi || _        | +                                \  | _        | _        d S )
NFr   NNNdtypezUnsupported variable type: %r)ArrayCArrayEArrayColumnr   atomc                 V    g | ]&\  }}|t           j                            |          f'S  )ne
necompilergetType).0nametype_s      1lib/python3.11/site-packages/tables/expression.py
<listcomp>z!Expr.__init__.<locals>.<listcomp>   sG     C C C&$ BM11%889 C C C    ),append_modemaindimnamesouto_starto_stopo_stepshapestartstopstepvalues_compiled_expr_single_row_out_required_expr_varsr   r   
getContextgetExprNamesitemstypeintfloatstr
isinstancetbLeafr   hasattr	TypeError	__class____name__npndarrayflagsalignedndimcopyappendr   arrayzipNumExpr_guess_shape)selfexpruservarskwargsvars_context_r   varobjnamer'   types_value	signatures                 r   __init__zExpr.__init__   s    B=
:NEDD
8+6(
DIty
6	5	5;"&#< ((x88-**622224AA
A  
	G 
	GID#CyyS%---cBGRY#788 G3((  ?# EFFFm,GEEE ?# EFFF F  		* 		*ID##rz** * y( *x1}}!hhjj&)d J 
	! 
	!D$KEuf%% %ej))))(( %e$$$$ e$$$MM%    C C*-dj&*A*AC C C	 !m3D)NNvNN $(#4#4#6#6 
DLLLr      c                 z   | j         }||vrXt          |          dk    rt          |          dd         D ]}||= t          |dd          }d |j        D             }|||<   n||         }i i }	}|"t          j        |          }
|
j        }|
j        }	i }|D ]}|||v r	||         }n0|||v r	||         }n!|||	v r	|	|         }nt          d|z            t          |d          r*|j        j        d	d         d
k    rt          d|z            t          |d          rt          d|z            |||<   |S )aB  Get the variables required by the `expression`.

        A new dictionary defining the variables used in the `expression`
        is returned.  Required variables are first looked up in the
        `uservars` mapping, then in the set of top-level columns of the
        table.  Unknown variables cause a `NameError` to be raised.

        When `uservars` is `None`, the local and global namespace where
        the API callable which uses this method is called is sought
        instead.  To disable this mechanism, just specify a mapping as
        `uservars`.

        Nested columns and variables with an ``uint64`` type are not
        allowed (`TypeError` and `NotImplementedError` are raised,
        respectively).

        `depth` specifies the depth of the frame in order to reach local
        or global variables.

           N
   z<string>evalc                 @    g | ]}|d vr|t           j        j        v|S ))NoneFalseTrue)r   expressions	functions)r   rK   s     r   r   z,Expr._required_expr_vars.<locals>.<listcomp>  s@     A A A&???r~'??? ???r   zname ``%s`` is not definedr   r   u8zmvariable ``%s`` refers to a 64-bit unsigned integer object, that is not yet supported in expressions, sorry; _v_colpathnameszEvariable ``%s`` refers to a nested column, not allowed in expressions)_exprvars_cachelenlistcompileco_namessys	_getframef_locals	f_globals	NameErrorr5   r   r1   NotImplementedErrorr6   )rD   
expressionrF   depthexprvars_cachekcexprexprvarsuser_localsuser_globals
user_framereqvarsrK   vals                 r   r*   zExpr._required_expr_vars   s   . -^++>""S((n--crc2 * *A&q))J
F;;EA Au~ A A AH *2N:&&%j1H %'\u--J$-K%/L  	 	C#xsm!c[&8&8!#&!c\&9&9"3' <s BCCC sG$$ 8qrr):d)B)B)@BEFG G G /00 8
  13678 8 8 GCLLr   c                 0    || _         || _        || _        dS )a  Define a range for all inputs in expression.

        The computation will only take place for the range defined by
        the start, stop and step parameters in the main dimension of
        inputs (or the leading one, if the object lacks the concept of
        main dimension, like a NumPy container).  If not a common main
        dimension exists for all inputs, the leading dimension will be
        used instead.

        N)r$   r%   r&   rD   r$   r%   r&   s       r   set_inputs_rangezExpr.set_inputs_range1  s     
				r   Fc                     t          |d          rt          |d          st          d          || _        |rt          |d          st          d          || _        dS )a  Set out as container for output as well as the append_mode.

        The out must be a container that is meant to keep the outcome of
        the expression.  It should be an homogeneous type container and
        can typically be an Array, CArray, EArray, Column or a NumPy ndarray.

        The append_mode specifies the way of which the output is filled.
        If true, the rows of the outcome are *appended* to the out container.
        Of course, for doing this it is necessary that out would have an
        append() method (like an EArray, for example).

        If append_mode is false, the output is set via the __setitem__()
        method (see the Expr.set_output_range() for info on how to select
        the rows to be updated).  If out is smaller than what is required
        by the expression, only the computations that are needed to fill
        up the container are carried out.  If it is larger, the excess
        elements are unaffected.

        r#   __setitem__z@You need to pass a settable multidimensional container as outputr?   zfFor activating the ``append`` mode, you need a container with an `append()` method (like the `EArray`)N)r5   
ValueErrorr   r   )rD   r   r   s      r   
set_outputzExpr.set_outputA  s    * W%% 	'#}*E*E 	    	AwsH55 	A@A A A 'r   c                 \    | j         t          d          || _        || _        || _        dS )aI  Define a range for user-provided output object.

        The output object will only be modified in the range specified by the
        start, stop and step parameters in the main dimension of output (or the
        leading one, if the object does not have the concept of main dimension,
        like a NumPy container).

        Nz5You need to pass an output object to `setOut()` first)r   
IndexErrorr    r!   r"   ru   s       r   set_output_rangezExpr.set_output_rangea  s=     8GI I Ir   c                    t          |j                  }|rd|d<   t          j        |          |j        j        z  }t          dz  }||z  }|dk    r6d}t          |z  }||k    r$t          j	        dt          |fz  t                     |S )z7Calculate the number of rows that will fit in a buffer.r   r      a4  The object ``%s`` is exceeding the maximum recommended rowsize (%d
bytes); be ready to see PyTables asking for *lots* of memory and
possibly slow I/O.  You may want to reduce the rowsize by trimming the
value of dimensions that are orthogonal (and preferably close) to the
*leading* dimension of this object.)r`   r#   r9   prodr   itemsizer   r   warningswarnobjectr   )rD   object_shape_rowsize
buffersize
nrowsinbuf
maxrowsizes          r   _calc_nrowsinbufzExpr._calc_nrowsinbuft  s     gm$$ 	F1I'&//GM$::
 $a'
7*
 ??J%
2J## ' "( 45 12 2 2 r   c                    d}g }| j         D ]X}t          |j                  |k    rt          |j                  }t          |d          r|                    |j                   Y|dk    r | j        | j          x| _        }dS |r&|d         gt          |          z  |k    r	|d         }nd}t          d          f|z  dz   }g }g }| j         D ]}|j        }	|	dk    r?|	|         dk    r3|                    |dd                    |                    d           Nt          |	          |k     r|                    |           w|                    |	                    |                     |                    |	|                    t          |          }
 | j        | x| _        }t          |j                  }	|
dk    r|	                    ||
           |	|fS )z0Guess the shape of the output of the expression.r   r   )r   NN)r   r   )r'   r_   r#   r5   r?   r   r(   r)   slice__getitem__minr`   insert)rD   maxndimmaindimsrs   r   r   slicesvalslensr#   minlens              r   rC   zExpr._guess_shape  s   
 ; 	- 	-C39~~''ci..sI&& -,,,a<<)<)<dk)JJD 38 	!H5AAqkGG G ++')D0 ; 	, 	,CIE {{uW~22CF###AUg%%C    COOF33444E'N++++T%8T%8$%??sSYA::LL&)))g~r   c                    |{t          | j        | j        | j                                      ||                   \  }}}t          ||         t          t          |||                              ||<   ||         }nd\  }}}d}|s`d}| j        8t          j
        || j        j                  }	|d||         d}}}
n'd\  }
}}n| j        }	t          |	d          r|	j        }t          |	j                  }t          | j        | j        | j                  }|                    ||                   \  }
}}t          ||         t          t          |
||                              ||<   t          |          }|                    |          }t          |          }||                    |          }nd}||k    rt+          d          | j        s||k     r
|||<   ||z   }t          |          fd	t/          | j                  D             }d}t/          | j                  D ]&\  }}||v r|                     |          }||k    r|}'|s|||||||	||
||fS ||||||fS )
z?Return various info needed for evaluating the computation loop.N)r   r   Nr   )r   r   )r   r   r   r   z1Shape for out container does not match expressionc                 J    g | ]\  }}t          |j                  k    | S r   )r_   r#   )r   irs   r=   s      r   r   z"Expr._get_info.<locals>.<listcomp>  s9     0 0 061cCI$.. ...r   )r   r$   r%   r&   indicesr   r_   ranger   r9   emptyr)   r   r5   r   r`   r#   r    r!   r"   popry   r   	enumerater'   r   )rD   r#   r   itermoder$   r%   r&   i_nrows	o_maindimr   r    r!   r"   o_shapes	tr_oshapeolen_tr_shapelen_	slice_posr   r   rs   nrowsr=   s                           @r   	_get_infozExpr._get_info  s    "'
DIty#2 #229'%.2I2I  UD$ gE%t$<$< = =? ?E'NGnGG *E4G '	)IxhuD,@,FGGG&12E'NAffWW09-Wfffh3	** , #I
 sy//$,T[AA*+))GI4F*G*G'%();),U7FF-K-K)L)L&N &N	" !MM	!i00;;&#<<	22DDD(($KM M M ' )EDLL',E)$ 5=D 5zz0 0 0 0Yt{%;%; 0 0 0	 
,, 	' 	'FAsI~~--c22:%%!&J 	GYtT:GVV= = YtT:FFr   c                    | j         | j        | j        }}}|                     ||          \  }}}}}}	}
}}}}|dk    r||k    r	| j        |
S | j        S t          d          g|dz   z  }t          d          g|dz   z  }|D ]}t          |d          rd|_        t          ||||	z            D ]}|||	z  z   }||k    r|}t          |||          ||<   g }t          |          D ]T\  }}||v r6|                    |                    t          |                               ?|                    |           U | j        | }| j        r|
                    |           |||z
  |z  z   }||	|z  z   }||k    r|}t          |||          ||<   ||
t          |          <   |D ]}t          |d          rd|_        |
S )a  Evaluate the expression and return the outcome.

        Because of performance reasons, the computation order tries to go along
        the common main dimension of all inputs.  If not such a common main
        dimension is found, the iteration will go along the leading dimension
        instead.

        For non-consistent shapes in inputs (i.e. shapes having a different
        number of dimensions), the regular NumPy broadcast rules applies.
        There is one exception to this rule though: when the dimensions
        orthogonal to the main dimension of the expression are consistent, but
        the main dimension itself differs among the inputs, then the shortest
        one is chosen for doing the computations.  This is so because trying to
        expand very large on-disk arrays could be too expensive or simply not
        possible.

        Also, the regular Numexpr casting rules (which are similar to those of
        NumPy, although you should check the Numexpr manual for the exceptions)
        are applied to determine the output type.

        Finally, if the setOuput() method specifying a user container has
        already been called, the output is sent to this user-provided
        container.  If not, a fresh NumPy container is returned instead.

        .. warning::

            When dealing with large on-disk inputs, failing to specify an
            on-disk container may consume all your available memory.

        r   Nr   r   FT)r'   r#   r   r   r$   r)   r   r5   
_v_convertr   r   r?   r   tupler(   r   )rD   r'   r#   r   r   r   r$   r%   r&   r   r   r   r    r!   r"   i_sliceso_slicesrs   start2stop2r   r   routstart3stop3s                            r   rU   z	Expr.eval  s?   @ "&dj$,w
 NN5'**	2)UD$
	i&& a<<}}!7
++ $KK=GaK0$KK=IM2  	' 	'CsI&& '!& E4
):;; 	, 	,FTJ..Et|| %feT : :HWD#F++ % %3	>>KKh @ @AAAA KK$$$$&4&-D 
,

4     !FUNt#;;f!446>>"E&+FE6&B&B#'+E(OO$$  	& 	&CsI&& &!%
r   c           	   #     K   | j         | j        | j        }}}|                     ||d          \  }}}}}}	|dk    rdS t	          d          g|dz   z  }
|D ]}t          |d          rd|_        t          ||||	z            D ]}|||	z  z   }||k    r|}t	          |||          |
|<   g }t          |          D ]T\  }}||v r6|	                    |
                    t          |
                               ?|	                    |           U | j        | }|E d{V  |D ]}t          |d          rd|_        dS )zIterate over the rows of the outcome of the expression.

        This iterator always returns rows as NumPy objects, so a possible out
        container specified in :meth:`Expr.set_output` method is ignored here.

        T)r   r   Nr   r   F)r'   r#   r   r   r   r5   r   r   r   r?   r   r   r(   )rD   r'   r#   r   r   r   r$   r%   r&   r   r   rs   r   r   r   r   r   s                    r   __iter__zExpr.__iter__s  s      "&dj$,w NN5'DN99 	<)UD$
 a<<F $KK=GaK0  	' 	'CsI&& '!& E4
):;; 	 	FTJ..Et|| %feT : :HWD#F++ % %3	>>KKh @ @AAAA KK$$$$&4&-DOOOOOOOO  	& 	&CsI&& &!%	& 	&r   )N)rQ   r
   )F)r8   
__module____qualname____doc__r^   rP   r*   rv   rz   r}   r   rC   r   rU   r   r   r   r   r   r      s        p pd OX7 X7 X7 X7xK K K KZ    ' ' ' '@   &  B. . .`MG MG MG MG^] ] ]~4& 4& 4& 4& 4&r   r   __main__)rT   i'  z/tmp/expression.h5wa)dflt)r   r#   brQ   c   r   z	a * b + czreturned-->)!r   rc   r   numexprr   numpyr9   tablesr3   
exceptionsr   
parametersr   r   r   r8   r#   	open_filefcreate_carrayrootFloat32Atomr   r   r   r   rE   rz   rU   dprintreprcloser   r   r   <module>r      s   % % 



              * * * * * * 4 4 4 4 4 4 4 4Y
& Y
& Y
& Y
& Y
& Y
& Y
& Y
&x z E)3//A 	
.".a*@*@*@NNA	.".a*@*@*@NNA	.".a*@*@*@NNA
//!&%nbn!.D.D.D %  ' 'C 4DOOC		A	E-a!!! GGIIIII+ r   