
    0Ph=                        d Z ddlZddlmZ ddlmZ ddlmZmZm	Z	 ddl
mZ ddlmZ dd	lmZ d
dlmZ g dZddgddgdZe ee                                          z   Zd Zd Zd Z G d d          ZdZdZdZdddeegZd Zd Z  G d d          Z! G d d           Z" ed!d"d#g          Z# ed$d%d&g          Z$ G d' d(          Z% G d) d*          Z&d4d+Z'd,Z(d-Z)d.Z* G d/ d0          Z+ G d1 d2          Z,d3 Z-dS )5a1  
Metadata Routing Utility

In order to better understand the components implemented in this file, one
needs to understand their relationship to one another.

The only relevant public API for end users are the ``set_{method}_request`` methods,
e.g. ``estimator.set_fit_request(sample_weight=True)``. However, third-party
developers and users who implement custom meta-estimators, need to deal with
the objects implemented in this file.

All estimators (should) implement a ``get_metadata_routing`` method, returning
the routing requests set for the estimator. This method is automatically
implemented via ``BaseEstimator`` for all simple estimators, but needs a custom
implementation for meta-estimators.

In non-routing consumers, i.e. the simplest case, e.g. ``SVM``,
``get_metadata_routing`` returns a ``MetadataRequest`` object.

In routers, e.g. meta-estimators and a multi metric scorer,
``get_metadata_routing`` returns a ``MetadataRouter`` object.

An object which is both a router and a consumer, e.g. a meta-estimator which
consumes ``sample_weight`` and routes ``sample_weight`` to its sub-estimators,
routing information includes both information about the object itself (added
via ``MetadataRouter.add_self_request``), as well as the routing information
for its sub-estimators.

A ``MetadataRequest`` instance includes one ``MethodMetadataRequest`` per
method in ``METHODS``, which includes ``fit``, ``score``, etc.

Request values are added to the routing mechanism by adding them to
``MethodMetadataRequest`` instances, e.g.
``metadatarequest.fit.add(param="sample_weight", alias="my_weights")``. This is
used in ``set_{method}_request`` which are automatically generated, so users
and developers almost never need to directly call methods on a
``MethodMetadataRequest``.

The ``alias`` above in the ``add`` method has to be either a string (an alias),
or a {True (requested), False (unrequested), None (error if passed)}``. There
are some other special values such as ``UNUSED`` and ``WARN`` which are used
for purposes such as warning of removing a metadata in a child class, but not
used by the end users.

``MetadataRouter`` includes information about sub-objects' routing and how
methods are mapped together. For instance, the information about which methods
of a sub-estimator are called in which methods of the meta-estimator are all
stored here. Conceptually, this information looks like:

```
{
    "sub_estimator1": (
        mapping=[(caller="fit", callee="transform"), ...],
        router=MetadataRequest(...),  # or another MetadataRouter
    ),
    ...
}
```

To give the above representation some structure, we use the following objects:

- ``(caller=..., callee=...)`` is a namedtuple called ``MethodPair``

- The list of ``MethodPair`` stored in the ``mapping`` field of a `RouterMappingPair` is
  a ``MethodMapping`` object

- ``(mapping=..., router=...)`` is a namedtuple called ``RouterMappingPair``

The ``set_{method}_request`` methods are dynamically generated for estimators
which inherit from the ``BaseEstimator``. This is done by attaching instances
of the ``RequestMethod`` descriptor to classes, which is done in the
``_MetadataRequester`` class, and ``BaseEstimator`` inherits from this mixin.
This mixin also implements the ``get_metadata_routing``, which meta-estimators
need to override, but it works for simple consumers as is.
    N)
namedtuple)deepcopy)TYPE_CHECKINGOptionalUnion)warn   )
get_config)UnsetMetadataPassedError   )Bunch)
fitpartial_fitpredictpredict_probapredict_log_probadecision_functionscoresplit	transforminverse_transformr   r   r   )fit_transformfit_predictc                  F    t                                          dd          S )zReturn whether metadata routing is enabled.

    .. versionadded:: 1.3

    Returns
    -------
    enabled : bool
        Whether metadata routing is enabled. If the config is not set, it
        defaults to False.
    enable_metadata_routingF)r
   get     `/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/utils/_metadata_requests.py_routing_enabledr    w   s     <<5u===r   c                     |r|j         j         d| n|j         j        }t                      s$| r$t          d| dt	          |                      dS dS )a  Raise an error if metadata routing is not enabled and params are passed.

    .. versionadded:: 1.4

    Parameters
    ----------
    params : dict
        The metadata passed to a method.

    owner : object
        The object to which the method belongs.

    method : str
        The name of the method, e.g. "fit".

    Raises
    ------
    ValueError
        If metadata routing is not enabled and params are passed.
    .z#Passing extra keyword arguments to z is only supported if enable_metadata_routing=True, which you can set using `sklearn.set_config`. See the User Guide <https://scikit-learn.org/stable/metadata_routing.html> for more details. Extra parameters passed are: N)	__class____name__r    
ValueErrorset)paramsownermethodcallers       r   _raise_for_paramsr+      s    , 39V5?#..f...eo>V   
& 
D& D D 7:&kk	D D
 
 	

 
 
 
r   c           
          d |                                 D             }t                      rH|rH| j        j        }t	          | d| dt          |                                           d| d          dS dS )am  Raise when metadata routing is enabled and metadata is passed.

    This is used in meta-estimators which have not implemented metadata routing
    to prevent silent bugs. There is no need to use this function if the
    meta-estimator is not accepting any metadata, especially in `fit`, since
    if a meta-estimator accepts any metadata, they would do that in `fit` as
    well.

    Parameters
    ----------
    obj : estimator
        The estimator for which we're raising the error.

    method : str
        The method where the error is raised.

    **kwargs : dict
        The metadata passed to the method.
    c                     i | ]
\  }}|||S Nr   ).0keyvalues      r   
<dictcomp>z2_raise_for_unsupported_routing.<locals>.<dictcomp>   s#    OOOZS%U=Nc5=N=N=Nr   r"   z cannot accept given metadata (z4) since metadata routing is not yet implemented for N)itemsr    r#   r$   NotImplementedErrorr&   keys)objr)   kwargscls_names       r   _raise_for_unsupported_routingr9      s    ( PO6<<>>OOOF 
f 
=)! N N& N NV[[]]ASAS N NBJN N N
 
 	

 
 
 
r   c                       e Zd ZdZd ZdS )_RoutingNotSupportedMixinzA mixin to be used to remove the default `get_metadata_routing`.

    This is used in meta-estimators where metadata routing is not yet
    implemented.

    This also makes it clear in our rendered documentation that this method
    cannot be used.
    c                 :    t          | j        j         d          )z[Raise `NotImplementedError`.

        This estimator does not support metadata routing yet.z* has not implemented metadata routing yet.)r4   r#   r$   selfs    r   get_metadata_routingz._RoutingNotSupportedMixin.get_metadata_routing   s'     "~&RRR
 
 	
r   N)r$   
__module____qualname____doc__r?   r   r   r   r;   r;      s-         
 
 
 
 
r   r;   z$UNUSED$z$WARN$z$UNCHANGED$FTc                 j    | t           v rdS t          | t                    o|                                 S )av  Check if an item is a valid alias.

    Values in ``VALID_REQUEST_VALUES`` are not considered aliases in this
    context. Only a string which is a valid identifier is.

    Parameters
    ----------
    item : object
        The given item to be checked if it can be an alias.

    Returns
    -------
    result : bool
        Whether the given item is a valid alias.
    F)VALID_REQUEST_VALUES
isinstancestrisidentifieritems    r   request_is_aliasrJ      s8      ###u dC  8T%6%6%8%88r   c                     | t           v S )zCheck if an item is a valid request value (and not an alias).

    Parameters
    ----------
    item : object
        The given item to be checked.

    Returns
    -------
    result : bool
        Whether the given item is valid.
    )rD   rH   s    r   request_is_validrL     s     '''r   c                   `    e Zd ZdZddZed             Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd ZdS )MethodMetadataRequesta  A prescription of how metadata is to be passed to a single method.

    Refer to :class:`MetadataRequest` for how this class is used.

    .. versionadded:: 1.3

    Parameters
    ----------
    owner : str
        A display name for the object owning these requests.

    method : str
        The name of the method to which these requests belong.

    requests : dict of {str: bool, None or str}, default=None
        The initial requests for this method.
    Nc                 L    |pt                      | _        || _        || _        d S r.   )dict	_requestsr(   r)   )r>   r(   r)   requestss       r   __init__zMethodMetadataRequest.__init__-  s$    !+TVV
r   c                     | j         S )z)Dictionary of the form: ``{key: alias}``.rQ   r=   s    r   rR   zMethodMetadataRequest.requests2  s     ~r   c                    t          |          s%t          |          st          d| d| d          ||k    rd}|t          k    r%|| j        v r	| j        |= nt          d| d          || j        |<   | S )a  Add request info for a metadata.

        Parameters
        ----------
        param : str
            The property for which a request is set.

        alias : str, or {True, False, None}
            Specifies which metadata should be routed to `param`

            - str: the name (or alias) of metadata given to a meta-estimator that
              should be routed to this parameter.

            - True: requested

            - False: not requested

            - None: error if passed
        zThe alias you're setting for `zZ` should be either a valid identifier or one of {None, True, False}, but given value is: ``TzTrying to remove parameter z! with UNUSED which doesn't exist.)rJ   rL   r%   UNUSEDrQ   )r>   paramaliass      r   add_requestz!MethodMetadataRequest.add_request7  s    2  && 	/?/F/F 	' ' '#' ' '   E>>EF??&&N5)) %     
 %*DN5!r   c                 h    t          fd| j                                        D                       S )a  Get names of all metadata that can be consumed or routed by this method.

        This method returns the names of all metadata, even the ``False``
        ones.

        Parameters
        ----------
        return_alias : bool
            Controls whether original or aliased names should be returned. If
            ``False``, aliases are ignored and original names are returned.

        Returns
        -------
        names : set of str
            A set of strings with the names of all parameters.
        c              3   n   K   | ]/\  }}t          |          r|d urt          |          s|n|V  0dS )FN)rL   )r/   proprZ   return_aliass      r   	<genexpr>z9MethodMetadataRequest._get_param_names.<locals>.<genexpr>x  sg       
 
e#E**
 /45.@.@ "K*:5*A*AKEEt.@.@.@.@
 
r   )r&   rQ   r3   )r>   r_   s    `r   _get_param_namesz&MethodMetadataRequest._get_param_namesg  sK    "  
 
 
 
#~3355
 
 
 
 
 	
r   c          
          i nfd| j                                         D             }|D ] }t          d| d| j         d| d           !dS )zCheck whether metadata is passed which is marked as WARN.

        If any metadata is passed which is marked as WARN, a warning is raised.

        Parameters
        ----------
        params : dict
            The metadata passed to a method.
        Nc                 8    h | ]\  }}|t           k    |v |S r   )WARN)r/   r^   rZ   r'   s      r   	<setcomp>z8MethodMetadataRequest._check_warnings.<locals>.<setcomp>  s6     
 
 
e}} !/r   zSupport for zj has recently been added to this class. To maintain backward compatibility, it is ignored now. Using `set_z	_request(z={True, False})` on this method of the class, you can set the request value to False to silence this warning, or to True to consume and use the metadata.)rQ   r3   r   r)   )r>   r'   warn_paramsrY   s    `  r   _check_warningsz%MethodMetadataRequest._check_warnings~  s     ~6
 
 
 
#~3355
 
 

 ! 	 	E$u $ $"k$ $49$ $ $   	 	r   c                    |                      |           t                      }d |                                D             }t                      }| j                                        D ]J\  }}|du s|t
          k    r|du r||v r||         ||<   )|||v r||         ||<   ;||v r||         ||<   K|r| j        t          v rt          | j                 }	n| j        g}	d                    d |	D                       }
dd	                    d
 |D                        d| j	         d| j         d| d| d| j	         |
z   dz   }t          |||          |S )a  Prepare the given parameters to be passed to the method.

        The output of this method can be used directly as the input to the
        corresponding method as extra props.

        Parameters
        ----------
        params : dict
            A dictionary of provided metadata.

        parent : object
            Parent class object, that routes the metadata.

        caller : str
            Method from the parent class object, where the metadata is routed from.

        Returns
        -------
        params : Bunch
            A :class:`~sklearn.utils.Bunch` of {prop: value} which can be given to the
            corresponding method.
        r'   c                     i | ]
\  }}|||S r.   r   )r/   argr1   s      r   r2   z7MethodMetadataRequest._route_params.<locals>.<dictcomp>  s#    QQQzsEu?PU?P?P?Pr   FTN c                     g | ]}d | d	S )z.set_z_request({metadata}=True/False)r   r/   r)   s     r   
<listcomp>z7MethodMetadataRequest._route_params.<locals>.<listcomp>  s4        FFEEE  r   [, c                     g | ]}|S r   r   )r/   r0   s     r   ro   z7MethodMetadataRequest._route_params.<locals>.<listcomp>  s    :::ss:::r   zJ] are passed but are not explicitly set as requested or not requested for r"   z, which is used within z. Call `z/` for each metadata you want to request/ignore.)messageunrequested_paramsrouted_params)rg   rP   r3   r   rQ   rd   r)   COMPOSITE_METHODSjoinr(   r   )r>   r'   parentr*   unrequestedargsresr^   rZ   callee_methodsset_requests_onrs   s               r   _route_paramsz#MethodMetadataRequest._route_params  s   . 	F+++ffQQV\\^^QQQgg>//11 	( 	(KD%~~$$44<< JD		44<<$(JD!!$ KD	 	{///!24;!?"&+ gg "0   O:DII::k:::;; : :J: :!%: : : : $: : .2Z: : "	"
 DD  +#.!   
 
r   c                    t          |          }t                      }| j                                        D ]Q\  }}|du r||v r|                    |           #t	          |t
                    r||v r|                    |           R|S )aB  Check whether the given parameters are consumed by this method.

        Parameters
        ----------
        params : iterable of str
            An iterable of parameters to check.

        Returns
        -------
        consumed : set of str
            A set of parameters which are consumed by this method.
        T)r&   rQ   r3   addrE   rF   )r>   r'   r{   r^   rZ   s        r   	_consumeszMethodMetadataRequest._consumes  s     Vee>//11 	 	KD%}}E3'' EVOO
r   c                     | j         S Serialize the object.

        Returns
        -------
        obj : dict
            A serialized version of the instance in the form of a dictionary.
        rU   r=   s    r   
_serializez MethodMetadataRequest._serialize  s     ~r   c                 D    t          |                                           S r.   rF   r   r=   s    r   __repr__zMethodMetadataRequest.__repr__      4??$$%%%r   c                 :    t          t          |                     S r.   rF   reprr=   s    r   __str__zMethodMetadataRequest.__str__      4::r   r.   )r$   r@   rA   rB   rS   propertyrR   r[   ra   rg   r~   r   r   r   r   r   r   r   rN   rN     s         $   
   X. . .`
 
 
.  4< < <|  ,  & & &    r   rN   c                   N    e Zd ZdZdZd Zd Zd ZddZd Z	d	 Z
d
 Zd Zd ZdS )MetadataRequesta  Contains the metadata request info of a consumer.

    Instances of `MethodMetadataRequest` are used in this class for each
    available method under `metadatarequest.{method}`.

    Consumer-only classes such as simple estimators return a serialized
    version of this class as the output of `get_metadata_routing()`.

    .. versionadded:: 1.3

    Parameters
    ----------
    owner : str
        The name of the object to which these requests belong.
    metadata_requestc           	      h    || _         t          D ]"}t          | |t          ||                     #d S )Nr(   r)   )r(   SIMPLE_METHODSsetattrrN   )r>   r(   r)   s      r   rS   zMetadataRequest.__init__  sO    
$ 	 	F%E&AAA   	 	r   c                 J    t          | |                              |          S )  Check whether the given parameters are consumed by the given method.

        .. versionadded:: 1.4

        Parameters
        ----------
        method : str
            The name of the method to check.

        params : iterable of str
            An iterable of parameters to check.

        Returns
        -------
        consumed : set of str
            A set of parameters which are consumed by the given method.
        ri   )getattrr   r>   r)   r'   s      r   consumeszMetadataRequest.consumes  s%    $ tV$$..f.===r   c                 L   |t           vr t          d| j        j         d| d          i t           |         D ]}t	          | |          t                                                    }t          j                                                  }||z  }fd|D             }|rJt          dd	                    |           d| dd	                    t           |                    d          
                    j                   t          | j        |	          S )
N'z' object has no attribute 'c                 B    g | ]}|         j         |         k    |S r   rU   )r/   r0   mmrrR   s     r   ro   z/MetadataRequest.__getattr__.<locals>.<listcomp>C  s/    VVV(3-3=QTCU2U2U2U2U2Ur   z"Conflicting metadata requests for rq   z" while composing the requests for z*. Metadata with the same name for methods z$ should have the same request value.)r(   r)   rR   )rv   AttributeErrorr#   r$   r   r&   r5   rR   r%   rw   updaterQ   rN   r(   )	r>   namer)   existingupcomingcommon	conflictsr   rR   s	          @@r   __getattr__zMetadataRequest.__getattr__0  sW    ((( ODN+OOOOO   '- 	+ 	+F$''C8==??++H3<,,..//H(FVVVVVVVVI  +99M9M + +37+ +$(II.?.E$F$F+ + +   OOCM****$4:dXVVVVr   Nc                 J    t          | |                              |          S )a  Get names of all metadata that can be consumed or routed by specified             method.

        This method returns the names of all metadata, even the ``False``
        ones.

        Parameters
        ----------
        method : str
            The name of the method for which metadata names are requested.

        return_alias : bool
            Controls whether original or aliased names should be returned. If
            ``False``, aliases are ignored and original names are returned.

        ignore_self_request : bool
            Ignored. Present for API compatibility.

        Returns
        -------
        names : set of str
            A set of strings with the names of all parameters.
        )r_   )r   ra   )r>   r)   r_   ignore_self_requests       r   ra   z MetadataRequest._get_param_namesN  s%    0 tV$$55<5PPPr   c                N    t          | |                              |||          S )a*  Prepare the given parameters to be passed to the method.

        The output of this method can be used directly as the input to the
        corresponding method as extra keyword arguments to pass metadata.

        Parameters
        ----------
        params : dict
            A dictionary of provided metadata.

        method : str
            The name of the method for which the parameters are requested and
            routed.

        parent : object
            Parent class object, that routes the metadata.

        caller : str
            Method from the parent class object, where the metadata is routed from.

        Returns
        -------
        params : Bunch
            A :class:`~sklearn.utils.Bunch` of {prop: value} which can be given to the
            corresponding method.
        )r'   rx   r*   )r   r~   )r>   r'   r)   rx   r*   s        r   r~   zMetadataRequest._route_paramsh  s2    6 tV$$22& 3 
 
 	
r   c                N    t          | |                              |           dS )a`  Check whether metadata is passed which is marked as WARN.

        If any metadata is passed which is marked as WARN, a warning is raised.

        Parameters
        ----------
        method : str
            The name of the method for which the warnings should be checked.

        params : dict
            The metadata passed to a method.
        ri   N)r   rg   r   s      r   rg   zMetadataRequest._check_warnings  s+     	f--V-<<<<<r   c                     t                      }t          D ]=}t          | |          }t          |j                  r|                                ||<   >|S r   )rP   r   r   lenrR   r   )r>   outputr)   r   s       r   r   zMetadataRequest._serialize  sV     $ 	2 	2F$''C3<   2!$!1!1vr   c                 D    t          |                                           S r.   r   r=   s    r   r   zMetadataRequest.__repr__  r   r   c                 :    t          t          |                     S r.   r   r=   s    r   r   zMetadataRequest.__str__  r   r   r.   )r$   r@   rA   rB   _typerS   r   r   ra   r~   rg   r   r   r   r   r   r   r   r     s         & E  > > >(W W W<Q Q Q Q4
 
 
>= = =  & & &    r   r   RouterMappingPairmappingrouter
MethodPairr*   calleec                   6    e Zd ZdZd Zd Zd Zd Zd Zd Z	dS )	MethodMappinga  Stores the mapping between caller and callee methods for a router.

    This class is primarily used in a ``get_metadata_routing()`` of a router
    object when defining the mapping between the router's methods and a sub-object (a
    sub-estimator or a scorer).

    Iterating through an instance of this class yields
    ``MethodPair(caller, callee)`` instances.

    .. versionadded:: 1.3
    c                     g | _         d S r.   )_routesr=   s    r   rS   zMethodMapping.__init__  s    r   c                 *    t          | j                  S r.   )iterr   r=   s    r   __iter__zMethodMapping.__iter__  s    DL!!!r   c                    |t           vrt          d| dt                      |t           vrt          d| dt                      | j                            t	          ||                     | S )ad  Add a method mapping.

        Parameters
        ----------

        caller : str
            Parent estimator's method name in which the ``callee`` is called.

        callee : str
            Child object's method name. This method is called in ``caller``.

        Returns
        -------
        self : MethodMapping
            Returns self.
        zGiven caller:z+ is not a valid method. Valid methods are: zGiven callee:r*   r   )METHODSr%   r   appendr   )r>   r*   r   s      r   r   zMethodMapping.add  s    "                 	JfVDDDEEEr   c                 z    t                      }| j        D ]$}|                    |j        |j        d           %|S )zSerialize the object.

        Returns
        -------
        obj : list
            A serialized version of the instance in the form of a list.
        r   )listr   r   r*   r   )r>   resultroutes      r   r   zMethodMapping._serialize  sF     \ 	L 	LEMMU\U\JJKKKKr   c                 D    t          |                                           S r.   r   r=   s    r   r   zMethodMapping.__repr__  r   r   c                 :    t          t          |                     S r.   r   r=   s    r   r   zMethodMapping.__str__  r   r   N)
r$   r@   rA   rB   rS   r   r   r   r   r   r   r   r   r   r     sx        
 
  " " "  <  & & &    r   r   c                   ^    e 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dS )MetadataRoutera  Stores and handles metadata routing for a router object.

    This class is used by router objects to store and handle metadata routing.
    Routing information is stored as a dictionary of the form ``{"object_name":
    RouteMappingPair(method_mapping, routing_info)}``, where ``method_mapping``
    is an instance of :class:`~sklearn.utils.metadata_routing.MethodMapping` and
    ``routing_info`` is either a
    :class:`~sklearn.utils.metadata_routing.MetadataRequest` or a
    :class:`~sklearn.utils.metadata_routing.MetadataRouter` instance.

    .. versionadded:: 1.3

    Parameters
    ----------
    owner : str
        The name of the object to which these requests belong.
    metadata_routerc                 H    t                      | _        d | _        || _        d S r.   )rP   _route_mappings_self_requestr(   )r>   r(   s     r   rS   zMetadataRouter.__init__  s#    #vv
 "


r   c                     t          |dd          dk    rt          |          | _        nFt          |d          r't          |                                          | _        nt          d          | S )a=  Add `self` (as a consumer) to the routing.

        This method is used if the router is also a consumer, and hence the
        router itself needs to be included in the routing. The passed object
        can be an estimator or a
        :class:`~sklearn.utils.metadata_routing.MetadataRequest`.

        A router should add itself using this method instead of `add` since it
        should be treated differently than the other objects to which metadata
        is routed by the router.

        Parameters
        ----------
        obj : object
            This is typically the router instance, i.e. `self` in a
            ``get_metadata_routing()`` implementation. It can also be a
            ``MetadataRequest`` instance.

        Returns
        -------
        self : MetadataRouter
            Returns `self`.
        r   Nr   _get_metadata_requestzGiven `obj` is neither a `MetadataRequest` nor does it implement the required API. Inheriting from `BaseEstimator` implements the required API.)r   r   r   hasattrr   r%   )r>   r6   s     r   add_self_requestzMetadataRouter.add_self_request"  s}    0 3&&*<<<!)#DS122 	!)#*C*C*E*E!F!FD  
 r   c                    t          |          }|                                D ]+\  }}t          |t          |                    | j        |<   ,| S )a  Add named objects with their corresponding method mapping.

        Parameters
        ----------
        method_mapping : MethodMapping
            The mapping between the child and the parent's methods.

        **objs : dict
            A dictionary of objects from which metadata is extracted by calling
            :func:`~sklearn.utils.metadata_routing.get_routing_for_object` on them.

        Returns
        -------
        self : MetadataRouter
            Returns `self`.
        r   r   )r   r3   r   get_routing_for_objectr   )r>   method_mappingobjsr   r6   s        r   r   zMetadataRouter.addF  s`    " ".11 	 	ID#):&/Ec/J/J* * *D && r   c                    t                      }| j        r|| j                            ||          z  }| j                                        D ]7\  }}|j        D ]*\  }}||k    r||j                            ||          z  }+8|S )r   )r)   r'   )r&   r   r   r   r3   r   r   )r>   r)   r'   r{   _route_mappingr*   r   s           r   r   zMetadataRouter.consumes_  s    $ ee 	R*336&3QQQC $ 4 : : < < 	 	A}"/"7  V## 4 = =%f !> ! ! C 
r   c          	      V   t                      }| j        r1|s/|                    | j                            ||                    }| j                                        D ]H\  }}|j        D ];\  }}||k    r0|                    |j                            |dd                    }<I|S )a`  Get names of all metadata that can be consumed or routed by specified             method.

        This method returns the names of all metadata, even the ``False``
        ones.

        Parameters
        ----------
        method : str
            The name of the method for which metadata names are requested.

        return_alias : bool
            Controls whether original or aliased names should be returned,
            which only applies to the stored `self`. If no `self` routing
            object is stored, this parameter has no effect.

        ignore_self_request : bool
            If `self._self_request` should be ignored. This is used in `_route_params`.
            If ``True``, ``return_alias`` has no effect.

        Returns
        -------
        names : set of str
            A set of strings with the names of all parameters.
        r)   r_   TFr)   r_   r   )r&   r   unionra   r   r3   r   r   )	r>   r)   r_   r   r{   r   r   r*   r   s	            r   ra   zMetadataRouter._get_param_names~  s    4 ee 	&9 	))"33! 4   C $(#7#=#=#?#? 	 	D-"/"7  V##))%,==#)RW >   C 
r   c                   t                      }| j        r1|                    | j                            ||||                     |                     |dd          fd|                                D             }t          |                                                              |                                          D ]-}||         ||         urt          d| j
         d| d          .|                    |           |S )a  Prepare the given parameters to be passed to the method.

        This is used when a router is used as a child object of another router.
        The parent router then passes all parameters understood by the child
        object to it and delegates their validation to the child.

        The output of this method can be used directly as the input to the
        corresponding method as extra props.

        Parameters
        ----------
        params : dict
            A dictionary of provided metadata.

        method : str
            The name of the method for which the parameters are requested and
            routed.

        parent : object
            Parent class object, that routes the metadata.

        caller : str
            Method from the parent class object, where the metadata is routed from.

        Returns
        -------
        params : Bunch
            A :class:`~sklearn.utils.Bunch` of {prop: value} which can be given to the
            corresponding method.
        r'   r)   rx   r*   Tr   c                 $    i | ]\  }}|v 	||S r   r   )r/   r0   r1   param_namess      r   r2   z0MetadataRouter._route_params.<locals>.<dictcomp>  s0     
 
 
%33+;M;MC;M;M;Mr   zIn z, there is a conflict on z between what is requested for this estimator and what is requested by its children. You can resolve this conflict by using an alias for the child estimator(s) requested metadata.)r   r   r   r~   ra   r3   r&   r5   intersectionr%   r(   )	r>   r'   r)   rx   r*   r{   child_paramsr0   r   s	           @r   r~   zMetadataRouter._route_params  sR   > gg 	JJ"00!!!!	 1     ++$ , 
 

 
 
 
)/
 
 
 sxxzz??//0A0A0C0CDD 		 		C C C00 B$* B Bs B B B   1 	

<   
r   c                N   | j         r| j                             ||           t                      }| j                                        D ]Y\  }}|j        |j        }}t                      ||<   |D ]2\  }}	||k    r'|                    ||	| j        |          ||         |	<   3Z|S )a  Return the input parameters requested by child objects.

        The output of this method is a :class:`~sklearn.utils.Bunch`, which includes the
        metadata for all methods of each child object that is used in the router's
        `caller` method.

        If the router is also a consumer, it also checks for warnings of
        `self`'s/consumer's requested metadata.

        Parameters
        ----------
        caller : str
            The name of the method for which the parameters are requested and
            routed. If called inside the :term:`fit` method of a router, it
            would be `"fit"`.

        params : dict
            A dictionary of provided metadata.

        Returns
        -------
        params : Bunch
            A :class:`~sklearn.utils.Bunch` of the form
            ``{"object_name": {"method_name": {params: value}}}`` which can be
            used to pass the required metadata to corresponding methods or
            corresponding child objects.
        r'   r)   r   )	r   rg   r   r   r3   r   r   r~   r(   )
r>   r*   r'   r{   r   r   r   r   _caller_callees
             r   route_paramszMetadataRouter.route_params  s    8  	M..fV.LLLgg#'#7#=#=#?#? 	 	D-+2M4IGFCI$+   f$$)/)=)=%&#z%	 *> * *CIg& 
r   c                &   |                      |dd          }| j        r| j                             |d          }nt                      }t          |                                          |z
  |z
  }|rt	          | j         d| d| d          dS )a  Validate given metadata for a method.

        This raises a ``TypeError`` if some of the passed metadata are not
        understood by child objects.

        Parameters
        ----------
        method : str
            The name of the method for which the parameters are requested and
            routed. If called inside the :term:`fit` method of a router, it
            would be `"fit"`.

        params : dict
            A dictionary of provided metadata.
        Fr   r   r"   z got unexpected argument(s) z%, which are not routed to any object.N)ra   r   r&   r5   	TypeErrorr(   )r>   r)   r'   r   self_params
extra_keyss         r   validate_metadataz MetadataRouter.validate_metadata  s      ++5 , 
 
  	 ,==E >  KK %%K''+5C
 	: 1 1 1 1J 1 1 1  	 	r   c                 P   t                      }| j        r| j                                        |d<   | j                                        D ]Z\  }}t                      ||<   |j                                        ||         d<   |j                                        ||         d<   [|S )r   $self_requestr   r   )rP   r   r   r   r3   r   r   )r>   r{   r   r   s       r   r   zMetadataRouter._serialize6  s     ff 	C#'#5#@#@#B#BC #'#7#=#=#?#? 	D 	DD-CI#0#8#C#C#E#ECIi "/"6"A"A"C"CCIh
r   c              #      K   | j         rIt                      }t          D ]}|                    ||           dt	          || j                   fV  | j                                        D ]\  }}||fV  d S )Nr   r   r   )r   r   r   r   r   r   r3   )r>   r   r)   r   r   s        r   r   zMetadataRouter.__iter__H  s       	*__N! A A""&"@@@@!#4&t/A$ $ $     $(#7#=#=#?#? 	( 	(D-'''''	( 	(r   c                 D    t          |                                           S r.   r   r=   s    r   r   zMetadataRouter.__repr__S  r   r   c                 :    t          t          |                     S r.   r   r=   s    r   r   zMetadataRouter.__str__V  r   r   N)r$   r@   rA   rB   r   rS   r   r   r   ra   r~   r   r   r   r   r   r   r   r   r   r   r     s         * E  " " "H  2  >* * *X< < <|, , ,\  @  $	( 	( 	(& & &    r   r   c                     t          | d          r!t          |                                           S t          | dd          dv rt          |           S t	          d          S )a]  Get a ``Metadata{Router, Request}`` instance from the given object.

    This function returns a
    :class:`~sklearn.utils.metadata_routing.MetadataRouter` or a
    :class:`~sklearn.utils.metadata_routing.MetadataRequest` from the given input.

    This function always returns a copy or an instance constructed from the
    input, such that changing the output of this function will not change the
    original object.

    .. versionadded:: 1.3

    Parameters
    ----------
    obj : object
        - If the object provides a `get_metadata_routing` method, return a copy
            of the output of that method.
        - If the object is already a
            :class:`~sklearn.utils.metadata_routing.MetadataRequest` or a
            :class:`~sklearn.utils.metadata_routing.MetadataRouter`, return a copy
            of that.
        - Returns an empty :class:`~sklearn.utils.metadata_routing.MetadataRequest`
            otherwise.

    Returns
    -------
    obj : MetadataRequest or MetadataRouting
        A ``MetadataRequest`` or a ``MetadataRouting`` taken or created from
        the given object.
    r?   r   N)r   r   r(   )r   r   r?   r   r   )r6   s    r   r   r   Z  sg    B s*++ 0022333	gt	$	$(O	O	O}}&&&&r   a          Request metadata passed to the ``{method}`` method.

        Note that this method is only relevant if
        ``enable_metadata_routing=True`` (see :func:`sklearn.set_config`).
        Please see :ref:`User Guide <metadata_routing>` on how the routing
        mechanism works.

        The options for each parameter are:

        - ``True``: metadata is requested, and passed to ``{method}`` if provided. The request is ignored if metadata is not provided.

        - ``False``: metadata is not requested and the meta-estimator will not pass it to ``{method}``.

        - ``None``: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

        - ``str``: metadata should be passed to the meta-estimator with this given alias instead of the original name.

        The default (``sklearn.utils.metadata_routing.UNCHANGED``) retains the
        existing request. This allows you to change the request for some
        parameters and not others.

        .. versionadded:: 1.3

        .. note::
            This method is only relevant if this estimator is used as a
            sub-estimator of a meta-estimator, e.g. used inside a
            :class:`~sklearn.pipeline.Pipeline`. Otherwise it has no effect.

        Parameters
        ----------
z        {metadata} : str, True, False, or None,                     default=sklearn.utils.metadata_routing.UNCHANGED
            Metadata routing for ``{metadata}`` parameter in ``{method}``.

zV        Returns
        -------
        self : object
            The updated object.
c                        e Zd ZdZddZd ZdS )RequestMethodas  
    A descriptor for request methods.

    .. versionadded:: 1.3

    Parameters
    ----------
    name : str
        The name of the method for which the request function should be
        created, e.g. ``"fit"`` would create a ``set_fit_request`` function.

    keys : list of str
        A list of strings which are accepted parameters by the created
        function, e.g. ``["sample_weight"]`` if the corresponding method
        accepts it as a metadata.

    validate_keys : bool, default=True
        Whether to check if the requested parameters fit the actual parameters
        of the method.

    Notes
    -----
    This class is a descriptor [1]_ and uses PEP-362 to set the signature of
    the returned function [2]_.

    References
    ----------
    .. [1] https://docs.python.org/3/howto/descriptor.html

    .. [2] https://www.python.org/dev/peps/pep-0362/
    Tc                 0    || _         || _        || _        d S r.   )r   r5   validate_keys)r>   r   r5   r   s       r   rS   zRequestMethod.__init__  s    		*r   c                      fd}d j          d|_        t          j        dt          j        j        |          g}|                    d  j        D                        t          j        ||          |_        t          
                     j                   } j        D ]&}|t          
                    | j         	          z  }'|t          z  }||_        |S )
Nc            
         t                      st          d          j        rut          |          t          j                  z
  rQt          dt          |          t          j                  z
   dj         dt          j                             | d         }| dd         } n}| r(t          dj         d	t          |            d
          |                                }t          |j                  }|
                                D ]%\  }}|t          ur|                    ||           &||_        |S )zUpdates the request for provided parameters

            This docstring is overwritten below.
            See REQUESTER_DOC for expected functionality
            zThis method is only available when metadata routing is enabled. You can enable it using sklearn.set_config(enable_metadata_routing=True).zUnexpected args: z in z. Accepted arguments are: Nr   r   set_z+_request() takes 0 positional argument but z were givenrY   rZ   )r    RuntimeErrorr   r&   r5   r   r   r   r   r   r3   	UNCHANGEDr[   _metadata_request)	rz   kw	_instancerR   method_metadata_requestr^   rZ   instancer>   s	          r   funcz#RequestMethod.__get__.<locals>.func  s    $%% "I   ! s2wwTY'? @B#di..(@ @ @di @ @/249~~@ @    G	ABBx$	  /49 / /D		/ / /  
 !6688H&-h	&B&B#!xxzz Q Qe	))+77d%7PPP*2I'r   r   _requestr>   )r   kind
annotationc                     g | ]Q}t          j        |t           j        j        t          t          t
          t          d t          f                            RS )N)defaultr  )inspect	ParameterKEYWORD_ONLYr   r   r   boolrF   )r/   ks     r   ro   z)RequestMethod.__get__.<locals>.<listcomp>  s^         !%2%'dD#o(>?	    r   )return_annotation)r)   )metadatar)   )r   r$   r
  r  POSITIONAL_OR_KEYWORDextendr5   	Signature__signature__REQUESTER_DOCformatREQUESTER_DOC_PARAMREQUESTER_DOC_RETURNrB   )r>   r  r(   r  r'   docr  s   ``     r   __get__zRequestMethod.__get__  s$   ,	 ,	 ,	 ,	 ,	 ,	` 3ty222&<   
 	    
	
 
	
 
	
 %.#
 
 
 ""$)"44	 	S 	SH&--x	-RRRCC##r   N)T)r$   r@   rA   rB   rS   r  r   r   r   r   r     sG         @+ + + +
N N N N Nr   r   c                        e Zd ZdZerd Zd Zd Zd Zd Z	d Z
d Zd	 Zd
 Zd Z fdZed             Zed             Zd Zd Z xZS )_MetadataRequesterzMixin class for adding metadata request functionality.

    ``BaseEstimator`` inherits from this Mixin.

    .. versionadded:: 1.3
    c                     d S r.   r   r>   r7   s     r   set_fit_requestz"_MetadataRequester.set_fit_requestC        r   c                     d S r.   r   r  s     r   set_partial_fit_requestz*_MetadataRequester.set_partial_fit_requestD  r   r   c                     d S r.   r   r  s     r   set_predict_requestz&_MetadataRequester.set_predict_requestE  r   r   c                     d S r.   r   r  s     r   set_predict_proba_requestz,_MetadataRequester.set_predict_proba_requestF  r   r   c                     d S r.   r   r  s     r   set_predict_log_proba_requestz0_MetadataRequester.set_predict_log_proba_requestG  r   r   c                     d S r.   r   r  s     r   set_decision_function_requestz0_MetadataRequester.set_decision_function_requestH  r   r   c                     d S r.   r   r  s     r   set_score_requestz$_MetadataRequester.set_score_requestI  r   r   c                     d S r.   r   r  s     r   set_split_requestz$_MetadataRequester.set_split_requestJ  r   r   c                     d S r.   r   r  s     r   set_transform_requestz(_MetadataRequester.set_transform_requestK  r   r   c                     d S r.   r   r  s     r   set_inverse_transform_requestz0_MetadataRequester.set_inverse_transform_requestL  r   r   c                    	 |                                  }n*# t          $ r  t                      j        di | Y dS w xY wt          D ]n}t          ||          }t          |j                  s't          | d| dt          |t          |j                                                                       o t                      j        di | dS )a  Set the ``set_{method}_request`` methods.

        This uses PEP-487 [1]_ to set the ``set_{method}_request`` methods. It
        looks for the information available in the set default values which are
        set using ``__metadata_request__*`` class attributes, or inferred
        from method signatures.

        The ``__metadata_request__*`` class attributes are used when a method
        does not explicitly accept a metadata through its arguments or if the
        developer would like to specify a request value for those metadata
        which are different from the default ``None``.

        References
        ----------
        .. [1] https://www.python.org/dev/peps/pep-0487
        Nr   r  r   )_get_default_requests	Exceptionsuper__init_subclass__r   r   r   rR   r   r   sortedr5   )clsr7   rR   r)   r   r#   s        r   r7  z$_MetadataRequester.__init_subclass__O  s   "	0022HH 	 	 	 &EGG%/////FF	 % 		 		F(F++Cs|$$ 'v'''ffS\->->-@-@&A&ABB   
 	"!++F+++++s    #??c                    t          | j        |          }t          | |          r"t          j        t          | |                    s|S t          t          j        t          | |                    j        	                                          dd         }|D ]7\  }}|dv r
|j
        |j        |j        hv r |                    |d           8|S )aq  Build the `MethodMetadataRequest` for a method using its signature.

        This method takes all arguments from the method signature and uses
        ``None`` as their default request value, except ``X``, ``y``, ``Y``,
        ``Xt``, ``yt``, ``*args``, and ``**kwargs``.

        Parameters
        ----------
        router : MetadataRequest
            The parent object for the created `MethodMetadataRequest`.
        method : str
            The name of the method.

        Returns
        -------
        method_request : MethodMetadataRequest
            The prepared request using the method's signature.
        r   r   N>   XYyXtytr   )rN   r$   r   r
  
isfunctionr   r   	signature
parametersr3   r  VAR_POSITIONALVAR_KEYWORDr[   )r9  r   r)   r   r'   pnamerY   s          r   _build_request_for_signaturez/_MetadataRequester._build_request_for_signatureu  s    ( $#,vFFF sF## 	7+=gc6>R>R+S+S 	Jg'V(<(<==HNNPPQQRSRTRTU" 	 	LE5333ze2E4EFFFOO      
r   c           	         t          | j                  }t          D ](}t          |||                     ||                     )d}t          t          j        |                     D ]}t          |          	                                D ]v\  }}||vr
||
                    |          t          |          z   d         }|	                                D ]*\  }}t          ||                              ||           +w|S )zCollect default request values.

        This method combines the information present in ``__metadata_request__*``
        class attributes, as well as determining request keys from method
        signatures.
        r   )r   r)   __metadata_request__Nr   )r   r$   r   r   rF  reversedr
  getmrovarsr3   indexr   r   r[   )	r9  rR   r)   substr
base_classattrr1   r^   rZ   s	            r   r4  z(_MetadataRequester._get_default_requests  s:    #666$ 	 	F000PP    ("7>##6#677 	S 	SJ#J//5577 S Se%% djj003v;;>@@A#(;;== S SKD% Hf--99E9RRRRSS r   c                 x    t          | d          rt          | j                  }n|                                 }|S )a"  Get requested data properties.

        Please check :ref:`User Guide <metadata_routing>` on how the routing
        mechanism works.

        Returns
        -------
        request : MetadataRequest
            A :class:`~sklearn.utils.metadata_routing.MetadataRequest` instance.
        r   )r   r   r   r4  )r>   rR   s     r   r   z(_MetadataRequester._get_metadata_request  s?     4,-- 	4-d.DEEHH1133Hr   c                 *    |                                  S )aM  Get metadata routing of this object.

        Please check :ref:`User Guide <metadata_routing>` on how the routing
        mechanism works.

        Returns
        -------
        routing : MetadataRequest
            A :class:`~sklearn.utils.metadata_routing.MetadataRequest` encapsulating
            routing information.
        )r   r=   s    r   r?   z'_MetadataRequester.get_metadata_routing  s     ))+++r   )r$   r@   rA   rB   r   r  r"  r$  r&  r(  r*  r,  r.  r0  r2  r7  classmethodrF  r4  r   r?   __classcell__)r#   s   @r   r  r  2  s           @ 	211999555;;;??????333333777???$, $, $, $, $,L # # [#J ) ) [)V  $, , , , , , ,r   r  c                   |s G d d          } |            S t          | d          s?t          | t                    s*t          dt	          | j        j                   d          |t          vrt          dt           d| d          t          |           }|
                    ||	           |                    ||
          }|S )a  Validate and route input parameters.

    This function is used inside a router's method, e.g. :term:`fit`,
    to validate the metadata and handle the routing.

    Assuming this signature of a router's fit method:
    ``fit(self, X, y, sample_weight=None, **fit_params)``,
    a call to this function would be:
    ``process_routing(self, "fit", sample_weight=sample_weight, **fit_params)``.

    Note that if routing is not enabled and ``kwargs`` is empty, then it
    returns an empty routing where ``process_routing(...).ANYTHING.ANY_METHOD``
    is always an empty dictionary.

    .. versionadded:: 1.3

    Parameters
    ----------
    _obj : object
        An object implementing ``get_metadata_routing``. Typically a
        meta-estimator.

    _method : str
        The name of the router's method in which this function is called.

    **kwargs : dict
        Metadata to be routed.

    Returns
    -------
    routed_params : Bunch
        A :class:`~utils.Bunch` of the form ``{"object_name": {"method_name":
        {params: value}}}`` which can be used to pass the required metadata to
        A :class:`~sklearn.utils.Bunch` of the form ``{"object_name": {"method_name":
        {params: value}}}`` which can be used to pass the required metadata to
        corresponding methods or corresponding child objects. The object names
        are those defined in `obj.get_metadata_routing()`.
    c                   "    e Zd ZddZd Zd ZdS )%process_routing.<locals>.EmptyRequestNc                 8    t          di d t          D             S )Nc                 ,    i | ]}|t                      S r   rP   rn   s     r   r2   z=process_routing.<locals>.EmptyRequest.get.<locals>.<dictcomp>      EEE6EEEr   r   r   r   )r>   r   r	  s      r   r   z)process_routing.<locals>.EmptyRequest.get  %    FFEEWEEEFFFr   c                 8    t          di d t          D             S )Nc                 ,    i | ]}|t                      S r   rY  rn   s     r   r2   zEprocess_routing.<locals>.EmptyRequest.__getitem__.<locals>.<dictcomp>"  rZ  r   r   r[  r>   r   s     r   __getitem__z1process_routing.<locals>.EmptyRequest.__getitem__!  r\  r   c                 8    t          di d t          D             S )Nc                 ,    i | ]}|t                      S r   rY  rn   s     r   r2   zEprocess_routing.<locals>.EmptyRequest.__getattr__.<locals>.<dictcomp>%  rZ  r   r   r[  r_  s     r   r   z1process_routing.<locals>.EmptyRequest.__getattr__$  r\  r   r.   )r$   r@   rA   r   r`  r   r   r   r   EmptyRequestrV    sR        G G G GG G GG G G G Gr   rc  r?   zThe given object (zh) needs to either implement the routing method `get_metadata_routing` or be a `MetadataRouter` instance.z3Can only route and process input on these methods: z, while the passed method is: r"   r   )r'   r*   )r   rE   r   r   r   r#   r$   r   r   r   r   r   )_obj_methodr7   rc  request_routingru   s         r   process_routingrg    s,   N  	G 	G 	G 	G 	G 	G 	G 	G |~~D011 
Zn5U5U 
*dn&=!>!> * * *
 
 	

 g6' 6 6+26 6 6
 
 	

 -T22O%%VG%DDD#00w0OOMr   r.   ).rB   r
  collectionsr   copyr   typingr   r   r   warningsr   rl   r
   
exceptionsr   _bunchr   r   rv   r   r5   r   r    r+   r9   r;   rX   rd   r   rD   rJ   rL   rN   r   r   r   r   r   r   r  r  r  r   r  rg  r   r   r   <module>rn     s7  J J^  " " " " " "       1 1 1 1 1 1 1 1 1 1             1 1 1 1 1 1        " [)9%  
 44 1 6 6 8 899
9> > >
 
 
D
 
 
:
 
 
 
 
 
 
 
4 
  	tT648 9 9 9.( ( (,` ` ` ` ` ` ` `Fl l l l l l l lp J2Y4IJJ  Zx&:;;
B B B B B B B BJV V V V V V V Vr
'' '' '' ''b#H 
 t t t t t t t tns, s, s, s, s, s, s, s,@G G G G Gr   