
    чoe7                     T   d 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Zd	Zd
ZdZdZd Zd Zd Zd Zd Zd Zd Zd Z G d d          Z e            Ze                    de	dee           e                    de
dee           e                    dedee           e                    dedee           e                    dedee           e                    dedee           e                    d edee           d! Zd" Zd# Zd$ Zd% Zed&             Z d'S )(a  Error profile

The error profile object to define different error types and handling within
BIOM. The following types are registered with the associated default states

empty : 'ignore'
    Treatment of an empty table (e.g., if Table.is_empty() is True). If a
    callable is provided, it implies 'call' and will set the callback function.

obssize : 'raise'
    Treatment of a table in which the number of observation ids does not match
    the size of the data.

sampsize : 'raise'
    Treatment of a table in which the number of sample ids does not match the
    size of the data.

obsdup : 'raise'
    Treatment of duplicate observation IDs.

sampdup : 'raise'
    Treatment of duplicate sample IDs.

obsmdsize : 'raise'
    Treatment of a table in which the number of observation metadata elements
    differs from the size of the data.

sampmdsize : 'raise'
    Treatment of a table in which the number of sample metadata elements
    differs from the size of the data.

Examples
--------

Use `seterr` to change how empty tables are handled:

>>> from numpy import inf
>>> from biom.err import seterr
>>> from biom import example_table
>>> make_empty_f = lambda v, i, md: v.sum() > inf
>>> _ = example_table.filter(make_empty_f, inplace=False)
>>> old_state = seterr(empty='raise')
>>> example_table.filter(make_empty_f, inplace=False)
Traceback (most recent call last):
...
TableException: Empty table!
>>> _ = seterr(**old_state)

    warn)stdout)contextmanager)TableExceptionzEmpty table!z3Number of observation IDs differs from matrix size!z.Number of sample IDs differs from matrix size!zDuplicate observation IDszDuplicate sample IDs!z6Size of observation metadata differs from matrix size!z1Size of sample metadata differs from matrix size!c                 *    |                                  S )zCheck if t is empty)is_emptyts    ]/mounts/lovelace/software/anaconda3/envs/kraken-biom/lib/python3.11/site-packages/biom/err.py_zz_test_emptyr   O   s    ::<<    c                 f    | j         d         t          |                     d                    k    S )z3Check if the number of observations match data sizer   observationaxisshapelenidsr
   s    r   _test_obssizer   T   s)    71:QUUU667777r   c                 f    | j         d         t          |                     d                    k    S )z.Check if the number of samples match data size   sampler   r   r
   s    r   _test_sampsizer   Y   s)    71:QUUU112222r   c                     | j         d         t          t          |                     d                              k    S )z)Check if there are duplicate observationsr   r   r   r   r   setr   r
   s    r   _test_obsdupr   ^   s1    71:SM!:!:;;<<<<r   c                     | j         d         t          t          |                     d                              k    S )z$Check if there are duplicate samplesr   r   r   r   r
   s    r   _test_sampdupr!   c   s1    71:SH!5!5667777r   c                 r    |                      d          }|| j        d         t          |          k    ndS )z?Check if the size of the observation metadata matches data sizer   r   Nr   Fmetadatar   r   r   mds     r   _test_obsmdsizer'   h   s5    	
	'	'B$&N171:R  =r   c                 r    |                      d          }|| j        d         t          |          k    ndS )z:Check if the size of the sample metadata matches data sizer   r   Nr   Fr#   r%   s     r   _test_sampmdsizer)   n   s5    	
	"	"B$&N171:R  =r   c                 6     d  fd fd||nd  fddS )zCreate error statesc                     d S N xs    r   <lambda>z&_create_error_states.<locals>.<lambda>v   s     r   c                 "    t                    S r,   r   r/   msgs    r   r0   z&_create_error_states.<locals>.<lambda>w   s    d3ii r   c                                S r,   r-   )r/   	exceptionr3   s    r   r0   z&_create_error_states.<locals>.<lambda>x   s    yy~~ r   Nc                     d S r,   r-   r.   s    r   r0   z&_create_error_states.<locals>.<lambda>y   s    D r   c                 2    t          j        dz             S )N
)r   writer2   s    r   r0   z&_create_error_states.<locals>.<lambda>z   s    v|C$J77 r   )ignorer   raisecallprintr-   )r3   callbackr5   s   ` `r   _create_error_statesr?   t   sM    $n''''----- ( 4HH..7777	9 9 9r   c                       e Zd ZdZ eg d          Zd ZdefdZd Z	e
d             Zej        d             Zd	 Zd
 Zd Zd Zd ZdS )ErrorProfilezAn error profile

    The error profile defines the types of errors that can be optionally
    handled, how those errors are handled, and performs the handling of the
    errors.
    )r;   r:   r<   r=   r   c                 0    i | _         i | _        i | _        d S r,   )_profile_state_testselfs    r   __init__zErrorProfile.__init__   s    


r   Nc                     || v rt          d|z            || j        vrt          d|z            t          |||          | j        |<   || j        |<   || j        |<   dS )a  Register an error type

        Paramters
        ---------
        errtype : str
            A name for the error, must be unique.
        msg : str
            An error message.
        state : {'raise', 'ignore', 'call', 'print', 'warn'}
            The default state.
        test : function
            A function to test for error.
        callback : function, optional
            A callback function for use with state 'call'
        exception : Exception, optional
            An exception to throw in state 'raises'.

        Raises
        ------
        KeyError
            If the errtype already exists
        KeyError
            If the state is invalid

        zAlready registered: %szUnknown state: %sN)KeyError_valid_statesr?   rC   rD   rE   )rG   errtyper3   statetestr>   r5   s          r   registerzErrorProfile.register   sy    6 d??3g=>>>***.6777!5c8Y!O!Og$G"
7r   c                     || vrt          d|z            | j                            |          }| j                            |          }| j                            |          }|||fS )a  Unregister an error type

        Parameters
        ----------
        errtype : str
            The error type to unregister

        Raises
        ------
        KeyError
            If the error type is unknown

        Returns
        -------
        dict
            The profile associated with the error.
        function
            The test function associated with the error.
        str
            The state at time of unregistering associated with the error

        Unknown error type: %s)rJ   rC   poprE   rD   )rG   rL   proffuncrM   s        r   
unregisterzErrorProfile.unregister   sk    . $3g=>>>}  ))z~~g&&((dE""r   c                     | j         S )zReturn current staterD   rF   s    r   rM   zErrorProfile.state   s     {r   c                     dv rfd| j         D             }n                                }|D ]E\  }| j        vrt          dz            || j         vrt          d|z            | j         |<   FdS )zUpdate current stateallc                 $    g | ]}|d          fS )rY   r-   ).0err	new_states     r   
<listcomp>z&ErrorProfile.state.<locals>.<listcomp>   s#    HHHS#y/0HHHr   zUnknown state type: %srQ   N)rD   itemsrK   rJ   )rG   r]   	to_updaterL   s    `  r   rM   zErrorProfile.state   s     IHHHHDKHHHII!))I"+ 	- 	-GY 2227)CDDDdk))7'ABBB#,DK  	- 	-r   c                     || j         v S )zCheck if an error type existsrW   rG   rL   s     r   __contains__zErrorProfile.__contains__   s    $+%%r   c                     |s| j                                         }t          |          D ]A}| j                             |d           } ||          r|                     ||          c S BdS )a  Test for an error

        Parameters
        ----------
        item : object
            An item to test for error
        *args : list, optional
            Error types to check, if not provided, all known error types are
            checked.

        Examples
        --------
        >>> from biom import example_table
        >>> from biom.err import __errprof
        >>> __errprof.test(example_table, 'empty')

        c                      d S r,   r-   r-   r   r   r0   z#ErrorProfile.test.<locals>.<lambda>   s    4 r   N)rE   keyssortedget_handle_error)rG   itemargsrL   rN   s        r   rN   zErrorProfile.test   s    $  	%:??$$Dd|| 	9 	9G:>>'<<88DtDzz 9))'4888889	9 	9r   c                 X    | j         |         }| j        |         } ||         |          S )zHandle an error)rD   rC   )rG   rL   rj   rM   profiles        r   ri   zErrorProfile._handle_error  s.    G$-(wu~d###r   c                 x    || vrt          d|z            | j        |         d         }|| j        |         d<   |S )a{  Set a function callback

        Parameters
        ----------
        errtype : str
            The error type to set a callback for.
        func : function
            The callback function. This function must accept a single
            parameter. The result of this function will be returned through
            the handler.

        Raises
        ------
        KeyError
            If an unknown error type is specified.

        Examples
        --------
        >>> from biom.err import __errprof
        >>> oldcall = __errprof.setcall('empty', lambda item: 123)
        >>> _ = __errprof.setcall('empty', oldcall)

        rQ   r<   rJ   rC   )rG   rL   rT   old_calls       r   setcallzErrorProfile.setcall
  sJ    0 $3g=>>>=)&1)-gv&r   c                 T    || vrt          d|z            | j        |         d         S )aL  Get a function callback

        Parameters
        ----------
        errtype : str
            The error type to get the callback for.

        Raises
        ------
        KeyError
            If the error type is unknown.

        Returns
        -------
        function
            The associated callback function.

        rQ   r<   ro   rb   s     r   getcallzErrorProfile.getcall)  s5    & $3g=>>>}W%f--r   )__name__
__module____qualname____doc__	frozensetrK   rH   	ExceptionrO   rU   propertyrM   setterrc   rN   ri   rq   rs   r-   r   r   rA   rA   }   s          IJJJKKM  
 <@$## ## ## ##J# # #@   X \- - \-& & &9 9 96$ $ $  >. . . . .r   rA   emptyr:   )r5   obssizer;   sampsizeobsdupsampdup	obsmdsize
sampmdsizec                  >    t           j                                        S )z'Returns the current error profile state	__errprofrM   copyr-   r   r   geterrr   S  s    ?!!!r   c                      t           j                                        }d| v rd| d         it           _        n| t           _        |S )az  How table errors are handled, API based on numpy's seterr

    Notes
    ----------
    all : {'ignore', 'warn', 'raise', 'call', 'print'}, optional
        Set treatment for all error types

        - ignore: Take no action when the exception occurs.
        - warn: Print a `RuntimeWarning` (via the Python `warnings` module).
        - raise: Raise a `TableException`.
        - call: Call a function specified using the `seterrcall` function.
        - print: Print a warning directly to ``stdout``.

    Returns
    -------
    old_settings: dict
        Dictionary containing the old settings

    See also
    --------
    geterr
    seterrcall
    geterrcall
    errstate

    Examples
    --------

    >>> from numpy import inf
    >>> from biom.err import seterr
    >>> from biom import example_table
    >>> make_empty_f = lambda v, i, md: v.sum() > inf
    >>> _ = example_table.filter(make_empty_f, inplace=False)
    >>> old_state = seterr(empty='raise')
    >>> example_table.filter(make_empty_f, inplace=False)
    Traceback (most recent call last):
    ...
    TableException: Empty table!
    >>> _ = seterr(**old_state)

    rY   r   kwargs	old_states     r   seterrr   X  s@    T $$&&I &-0	 	r   c                 n    | t           vrt          d| z            t                               | |          S )a  Set an error callback function

    This is similar to numpy's seterrcall, except that we define it by error
    type. The justification is that numpy's errors are focused specifically on
    floating point errors, while the types of errors we support in BIOM are
    more broad.

    Parameters
    ----------
    errtype : str
        Must be a valid key in biom.__errprof
    func : callable
        A function that is called if the given error is encountered and if the
        current error profile indicates 'call' for the error type.

    Returns
    -------
    callable or None
        The old error handler

    Raises
    ------
    KeyError
        If the errtype specified is not in the error profile.

    rQ   )r   rJ   rq   )rL   rT   s     r   
seterrcallr     s9    6 i/'9:::  $///r   c                 l    | t           vrt          d| z            t                               |           S )aU  Get the current callback function associated with an error type

    Parameters
    ----------
    errtype : str
        Must be a valid key in the error profile

    Returns
    -------
    callable
        The current callback function

    Raises
    ------
    KeyError
        If the errtype specified is not in the error profile.

    rQ   )r   rJ   rs   )rL   s    r   
geterrcallr     s7    & i/'9:::  )))r   c                 X    t          j        | g|R  }t          |t                    r||S )a  Check if there is an error, and respond appropriately

    Parameters
    ----------
    table : Table
        The table to check
    errtypes : vargs of str, if not specified, defaults to all errors
        Errors to test

    Notes
    -----
    If an error type has 'raises' as its state, the exception is raised from
    here to avoid cluttering the traceback.

    Returns
    -------
    dependent on error state and setting

    )r   rN   
isinstancery   )tableerrtypesrets      r   errcheckr     s7    ( .
*
*
*
*C#y!! 	
r   c               +   B   K   t          di | }dV  t          di | dS )a  Context manager for error handling

    Using an instance of `errstate` as a context manager allows statements in
    that context to execute with a known error handling behavior. Upon entering
    the context the error handling is set with `seterr`, and upon exiting it is
    reset to what it was before. Please note, this text was taken near verbatim
    from numpy's errstate method.

    Parameters
    ----------
    kwargs : {empty}
        Keyword arguments. The valid error types that are defined. Each keyword
        should have a string or callable for the particular error. Values are:
        {'ignore', 'warn', 'raise', 'call', 'print'}

    See Also
    --------
    seterr, geterr, seterrcall, geterrcall

    Nr-   )r   r   s     r   errstater     s>      ,     I	EEE
Yr   N)!rw   warningsr   sysr   
contextlibr   biom.exceptionr   EMPTYOBSSIZESAMPSIZEOBSDUPSAMPDUP	OBSMDSIZE
SAMPMDSIZEr   r   r   r   r!   r'   r)   r?   rA   r   rO   r   r   r   r   r   r   r-   r   r   <module>r      s  0 0t             % % % % % % ) ) ) ) ) ) 	
?;	$
!D	@
  
8 8 8
3 3 3
= = =
8 8 8
> > >> > >9 9 9B. B. B. B. B. B. B. B.J LNN	 	  7E8^+  - - - 	  9gw+  - - - 	  :x.+  - - - 	  8VWl+  - - - 	  9gw+  - - - 	  ;	7O+  - - - 	  <W6F+  - - -" " "
/ / /d0 0 0B* * *2  6     r   