U
    9%eL                  
   @   s@  d Z ddlZddlmZ ddlmZ ddlmZmZ ddl	m
Z
 ddlmZ dd	lmZ d
dlmZ ddddddddddg
Zdd ZdZdZdZdddeegZdd Zdd  ZG d!d" d"ZG d#d$ d$Zed%d&d'gZed(d)d*gZG d+d, d,ZG d-d. d.Zd:d/d0Zd1Z d2Z!d3Z"G d4d5 d5Z#G d6d7 d7Z$d8d9 Z%dS );a  
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``,
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 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)OptionalUnion)warn   )
get_config)UnsetMetadataPassedError   )BunchfitZpartial_fitZpredictZpredict_probaZpredict_log_probaZdecision_functionZscoresplitZ	transformZinverse_transformc                   C   s   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.
    Zenable_metadata_routingF)r   get r   r   _/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/sklearn/utils/_metadata_requests.py_routing_enabledj   s    r   z$UNUSED$z$WARN$z$UNCHANGED$FTc                 C   s   | t k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itemr   r   r   request_is_alias   s    r   c                 C   s   | t k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.
    )r   r   r   r   r   request_is_valid   s    r   c                   @   s\   e Zd ZdZdd Zedd Zdd Zdd	 Zd
d Z	dd Z
dd Zdd Zdd ZdS )MethodMetadataRequestab  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.
    c                 C   s   t  | _|| _|| _d S N)dict	_requestsownermethodselfr   r   r   r   r   __init__   s    zMethodMetadataRequest.__init__c                 C   s   | j S )z)Dictionary of the form: ``{key: alias}``.r   r!   r   r   r   requests   s    zMethodMetadataRequest.requestsc                C   sn   t |s&t|s&td| d| d||kr2d}|tkr`|| jkrN| j|= qjtd| dn
|| 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.)r   r   
ValueErrorUNUSEDr   )r!   paramaliasr   r   r   add_request   s    



z!MethodMetadataRequest.add_requestc                    s   t  fd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   s6   | ].\}}t |r|d k	r r*t |s*|n|V  qdS )FN)r   .0propr*   return_aliasr   r   	<genexpr>  s    z9MethodMetadataRequest._get_param_names.<locals>.<genexpr>)setr   items)r!   r0   r   r/   r   _get_param_names  s    z&MethodMetadataRequest._get_param_namesc                   sF    dkri n   fdd| j  D }|D ]}td| d q,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                    s$   h | ]\}}|t kr| kr|qS r   )WARNr,   paramsr   r   	<setcomp>'  s    z8MethodMetadataRequest._check_warnings.<locals>.<setcomp>zSupport for z has recently been added to this class. To maintain backward compatibility, it is ignored now. You can set the request value to False to silence this warning, or to True to consume and use the metadata.)r   r3   r   )r!   r7   Zwarn_paramsr)   r   r6   r   _check_warnings  s    


z%MethodMetadataRequest._check_warningsc                 C   s   | j |d t }dd | D }t }| j D ]l\}}|dks4|tkrPq4q4|dkrn||krn|| ||< q4|dkr||kr|| ||< q4||kr4|| ||< q4|rtddd	d
 |D  d| j d| j	 ||d|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.

        Returns
        -------
        params : Bunch
            A :class:`~utils.Bunch` of {prop: value} which can be given to the
            corresponding method.
        r6   c                 S   s   i | ]\}}|d k	r||qS r   r   )r-   argvaluer   r   r   
<dictcomp>G  s       z7MethodMetadataRequest._route_params.<locals>.<dictcomp>FTN[z, c                 S   s   g | ]}|qS r   r   )r-   keyr   r   r   
<listcomp>U  s     z7MethodMetadataRequest._route_params.<locals>.<listcomp>z@] are passed but are not explicitly set as requested or not for .)messageZunrequested_paramsrouted_params)
r9   r   r3   r   r   r5   r	   joinr   r   )r!   r7   Zunrequestedargsresr.   r*   r   r   r   _route_params4  s(    (	z#MethodMetadataRequest._route_paramsc                 C   s   | j S Serialize the object.

        Returns
        -------
        obj : dict
            A serialized version of the instance in the form of a dictionary.
        r#   r$   r   r   r   
_serialize^  s    z MethodMetadataRequest._serializec                 C   s   t |  S r   r   rI   r$   r   r   r   __repr__h  s    zMethodMetadataRequest.__repr__c                 C   s   t t| S r   r   reprr$   r   r   r   __str__k  s    zMethodMetadataRequest.__str__N)__name__
__module____qualname____doc__r"   propertyr%   r+   r4   r9   rF   rI   rK   rN   r   r   r   r   r      s   
0*
r   c                   @   sN   e Zd ZdZdZdd ZdddZdd	 Zd
d Zdd Z	dd Z
d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                 C   s"   t D ]}t| |t||d qd S )Nr   r   )METHODSsetattrr   r    r   r   r   r"     s    
zMetadataRequest.__init__Nc                 C   s   t | |j|d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/   )getattrr4   )r!   r   r0   ignore_self_requestr   r   r   r4     s    z MetadataRequest._get_param_namesc                C   s   t | |j|dS )ad  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
        ----------
        method : str
            The name of the method for which the parameters are requested and
            routed.

        params : dict
            A dictionary of provided metadata.

        Returns
        -------
        params : Bunch
            A :class:`~utils.Bunch` of {prop: value} which can be given to the
            corresponding method.
        r6   )rY   rF   r!   r   r7   r   r   r   rF     s    zMetadataRequest._route_paramsc                C   s   t | |j|d 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.
        r6   N)rY   r9   r[   r   r   r   r9     s    zMetadataRequest._check_warningsc                 C   s4   t  }tD ]$}t| |}t|jr
| ||< q
|S rG   )r   rW   rY   lenr%   rI   )r!   outputr   mmrr   r   r   rI     s    

zMetadataRequest._serializec                 C   s   t |  S r   rJ   r$   r   r   r   rK     s    zMetadataRequest.__repr__c                 C   s   t t| S r   rL   r$   r   r   r   rN     s    zMetadataRequest.__str__)N)rO   rP   rQ   rR   _typer"   r4   rF   r9   rI   rK   rN   r   r   r   r   rT   o  s   
rT   RouterMappingPairmappingrouter
MethodPaircalleecallerc                   @   sL   e Zd ZdZdd Zdd Zdd Zdd	 Zed
d Z	dd Z
dd ZdS )MethodMappinga  Stores the mapping between callee and caller methods for a router.

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

    Iterating through an instance of this class will yield named
    ``MethodPair(callee, caller)`` tuples.

    .. versionadded:: 1.3
    c                 C   s
   g | _ d S r   )_routesr$   r   r   r   r"      s    zMethodMapping.__init__c                 C   s
   t | jS r   )iterrg   r$   r   r   r   __iter__  s    zMethodMapping.__iter__c                C   sP   |t krtd| dt  |t kr8td| dt  | jt||d | S )ac  Add a method mapping.

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

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

        Returns
        -------
        self : MethodMapping
            Returns self.
        zGiven callee:z+ is not a valid method. Valid methods are: zGiven caller:rd   re   )rW   r'   rg   appendrc   )r!   rd   re   r   r   r   add  s    zMethodMapping.addc                 C   s*   t  }| jD ]}||j|jd q|S )zSerialize the object.

        Returns
        -------
        obj : list
            A serialized version of the instance in the form of a list.
        rj   )listrg   rk   rd   re   )r!   resultrouter   r   r   rI   #  s    
zMethodMapping._serializec                 C   sL   |  }|dkr(t D ]}|j||d qn |t kr@|j||d ntd|S )a  Construct an instance from a string.

        Parameters
        ----------
        route : str
            A string representing the mapping, it can be:

              - `"one-to-one"`: a one to one mapping for all methods.
              - `"method"`: the name of a single method, such as ``fit``,
                ``transform``, ``score``, etc.

        Returns
        -------
        obj : MethodMapping
            A :class:`~sklearn.utils.metadata_routing.MethodMapping` instance
            constructed from the given string.
        
one-to-onerj   z0route should be 'one-to-one' or a single method!)rW   rl   r'   )clsro   Zroutingr   r   r   r   from_str0  s    zMethodMapping.from_strc                 C   s   t |  S r   rJ   r$   r   r   r   rK   M  s    zMethodMapping.__repr__c                 C   s   t t| S r   rL   r$   r   r   r   rN   P  s    zMethodMapping.__str__N)rO   rP   rQ   rR   r"   ri   rl   rI   classmethodrr   rK   rN   r   r   r   r   rf     s   
rf   c                   @   sl   e Zd ZdZdZdd Zdd Zdd Zd	d
 Zdd Z	dd Z
dd Zdd Zdd Zdd Zd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:`~utils.metadata_routing.MetadataRequest` or a
    :class:`~utils.metadata_routing.MetadataRouter` instance.

    .. versionadded:: 1.3

    Parameters
    ----------
    owner : str
        The name of the object to which these requests belong.
    metadata_routerc                 C   s   t  | _d | _|| _d S r   )r   _route_mappings_self_requestr   )r!   r   r   r   r   r"   l  s    zMetadataRouter.__init__c                 C   sB   t |dddkrt|| _n"t|dr6t| | _ntd| S )a5  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:`~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_   NrU   _get_metadata_requestzGiven `obj` is neither a `MetadataRequest` nor does it implement the required API. Inheriting from `BaseEstimator` implements the required API.)rY   r   rw   hasattrrx   r'   )r!   objr   r   r   add_self_requestu  s    
zMetadataRouter.add_self_requestc                K   sJ   t |trt|}nt|}| D ]\}}t|t|d| j|< q&| S )ah  Add named objects with their corresponding method mapping.

        Parameters
        ----------
        method_mapping : MethodMapping or str
            The mapping between the child and the parent's methods. If str, the
            output of :func:`~sklearn.utils.metadata_routing.MethodMapping.from_str`
            is used.

        **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`.
        ra   rb   )	r   r   rf   rr   r   r3   r`   get_routing_for_objectrv   )r!   Zmethod_mappingZobjsnamerz   r   r   r   rl     s    
 zMetadataRouter.addc          	   	   C   sn   t  }| jr&|s&|| jj||d}| j D ]8\}}|jD ](\}}||kr>||jj|ddd}q>q0|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   r0   TFr   r0   rZ   )r2   rw   unionr4   rv   r3   ra   rb   )	r!   r   r0   rZ   rE   r~   route_mappingrd   re   r   r   r   r4     s&    
   zMetadataRouter._get_param_namesc                   s   t  }| jr"|| jj||d | j|ddd  fdd| D }t| | D ],}|| || k	r^t	d| j
 d| dq^|| |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
        ----------
        method : str
            The name of the method for which the parameters are requested and
            routed.

        params : dict
            A dictionary of provided metadata.

        Returns
        -------
        params : Bunch
            A :class:`~sklearn.utils.Bunch` of {prop: value} which can be given to the
            corresponding method.
        r7   r   Tr   c                    s   i | ]\}}| kr||qS r   r   )r-   r>   r;   param_namesr   r   r<     s      z0MetadataRouter._route_params.<locals>.<dictcomp>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   rw   updaterF   r4   r3   r2   keysintersectionr'   r   )r!   r7   r   rE   Zchild_paramsr>   r   r   r   rF     s$      

zMetadataRouter._route_paramsc          
      C   sx   | j r| j j||d t }| j D ]L\}}|j|j }}t ||< |D ]&\}}	|	|krJ|j||d|| |< qJq&|S )a  Return the input parameters requested by child objects.

        The output of this method is a bunch, which includes the inputs for all
        methods of each child object that are 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:`~utils.Bunch` of the form
            ``{"object_name": {"method_name": {prop: value}}}`` which can be
            used to pass the required metadata to corresponding methods or
            corresponding child objects.
        r   )rw   r9   r   rv   r3   rb   ra   rF   )
r!   re   r7   rE   r~   r   rb   ra   Z_calleeZ_callerr   r   r   route_params  s    
 zMetadataRouter.route_paramsc                C   s^   | j |ddd}| jr(| jj |dd}nt }t| | | }|rZt| d| ddS )a  Validate given metadata for a method.

        This raises a ``ValueError`` 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   z got unexpected argument(s) z1, which are not requested metadata in any object.N)r4   rw   r2   r   	TypeError)r!   r   r7   r   Zself_paramsZ
extra_keysr   r   r   validate_metadata?  s        z MetadataRouter.validate_metadatac                 C   s`   t  }| jr| j |d< | j D ]6\}}t  ||< |j || d< |j || d< q$|S )rH   $self_requestra   rb   )r   rw   rI   rv   r3   ra   rb   )r!   rE   r~   r   r   r   r   rI   _  s    
zMetadataRouter._serializec                 c   sB   | j r dttd| j dfV  | j D ]\}}||fV  q*d S )Nr   rp   r|   )rw   r`   rf   rr   rv   r3   )r!   r~   r   r   r   r   ri   q  s     
zMetadataRouter.__iter__c                 C   s   t |  S r   rJ   r$   r   r   r   rK   y  s    zMetadataRouter.__repr__c                 C   s   t t| S r   rL   r$   r   r   r   rN   |  s    zMetadataRouter.__str__N)rO   rP   rQ   rR   r_   r"   r{   rl   r4   rF   r   r   rI   ri   rK   rN   r   r   r   r   rt   T  s   	$,1+ rt   c                 C   s8   t | drt|  S t| dddkr.t| S td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 is already a
            :class:`~sklearn.utils.metadata_routing.MetadataRequest` or a
            :class:`~sklearn.utils.metadata_routing.MetadataRouter`, return a copy
            of that.
        - If the object provides a `get_metadata_routing` method, return a copy
            of the output of that method.
        - 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.
    get_metadata_routingr_   N)rU   ru   r   )ry   r   r   rY   rT   )rz   r   r   r   r}     s
    !
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                   @   s"   e Zd ZdZdddZd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                 C   s   || _ || _|| _d S r   )r~   r   validate_keys)r!   r~   r   r   r   r   r   r"     s    zRequestMethod.__init__c                    s    fdd}dj  d|_tjdtjj|dg}|dd jD  tj||d	|_t	j
j d
}jD ]}|tj
|j d7 }qn|t7 }||_|S )Nc                     s   t  stdjrNt| tj rNtdt| tj  dtj   }t|j}| 	 D ]\}}|t
k	rj|j||d qj| _ 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. Accepted arguments are: r)   r*   )r   RuntimeErrorr   r2   r   r   rx   rY   r~   r3   	UNCHANGEDr+   _metadata_request)kwr%   Zmethod_metadata_requestr.   r*   instancer!   r   r   func	  s    "z#RequestMethod.__get__.<locals>.funcset__requestr!   )r~   kind
annotationc                 S   s0   g | ](}t j|t jjttttd tf  dqS )N)defaultr   )inspect	ParameterKEYWORD_ONLYr   r   r   boolr   )r-   kr   r   r   r?   1  s   z)RequestMethod.__get__.<locals>.<listcomp>)return_annotation)r   )metadatar   )r~   rO   r   r   POSITIONAL_OR_KEYWORDextendr   	Signature__signature__REQUESTER_DOCformatREQUESTER_DOC_PARAMREQUESTER_DOC_RETURNrR   )r!   r   r   r   r7   docr   r   r   r   __get__  s.    
zRequestMethod.__get__N)T)rO   rP   rQ   rR   r"   r   r   r   r   r   r     s    
r   c                       sH   e Zd ZdZ fddZedd Zedd Zdd	 Zd
d Z	  Z
S )_MetadataRequesterzMixin class for adding metadata request functionality.

    ``BaseEstimator`` inherits from this Mixin.

    .. versionadded:: 1.3
    c              	      s   z|   }W n$ tk
r0   t jf | Y dS X tD ]>}t||}t|jsPq6t| d| dt	|t
|j  q6t jf | 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   )_get_default_requests	Exceptionsuper__init_subclass__rW   rY   r\   r%   rX   r   sortedr   )rq   kwargsr%   r   r^   	__class__r   r   r   O  s    


z$_MetadataRequester.__init_subclass__c                 C   s   t | j|d}t| |r(tt| |s,|S ttt| |j	 dd }|D ]4\}}|dkrdqR|j
|j|jhkrxqR|j|dd qR|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.
        rV   r
   N>   YyXytXtr   )r   rO   ry   r   
isfunctionrY   rm   	signature
parametersr3   r   VAR_POSITIONALVAR_KEYWORDr+   )rq   rb   r   r^   r7   Zpnamer)   r   r   r   _build_request_for_signatureu  s    "z/_MetadataRequester._build_request_for_signaturec                 C   s   t | jd}tD ]}t||| j||d qt }tt| D ]$}dd t	|
 D }|| q@tt|
 }|
 D ]L\}}d}|||t| d }|
 D ]\}	}
t||j|	|
d qq~|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   )rb   r   c                 S   s   i | ]\}}d |kr||qS )__metadata_request__r   )r-   attrr;   r   r   r   r<     s    z<_MetadataRequester._get_default_requests.<locals>.<dictcomp>r   Nr   )rT   rO   rW   rX   r   r   reversedr   getmrovarsr3   r   r   indexr\   rY   r+   )rq   r%   r   defaultsZ
base_classZbase_defaultsr   r;   substrr.   r*   r   r   r   r     s(    
z(_MetadataRequester._get_default_requestsc                 C   s"   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   )ry   r}   r   r   )r!   r%   r   r   r   rx     s    
z(_MetadataRequester._get_metadata_requestc                 C   s   |   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.
        )rx   r$   r   r   r   r     s    z'_MetadataRequester.get_metadata_routing)rO   rP   rQ   rR   r   rs   r   r   rx   r   __classcell__r   r   r   r   r   G  s   &
%
-r   c                 K   s   t | ds"tdt| jj d|tkr@tdt d| d|dk	rL|nt }|| t	| }|j
||d |j||d	}|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: ``fit(self, X, y, sample_weight=None, **fit_params)``,
    a call to this function would be:
    ``process_routing(self, fit_params, sample_weight=sample_weight)``.

    .. 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.

    other_params : dict
        A dictionary of extra parameters passed to the router's method,
        e.g. ``**fit_params`` passed to a meta-estimator's :term:`fit`.

    **kwargs : dict
        Parameters explicitly accepted and included in the router's method
        signature.

    Returns
    -------
    routed_params : Bunch
        A :class:`~utils.Bunch` of the form ``{"object_name": {"method_name":
        {prop: 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()`.
    r   zThis z? has not implemented the routing method `get_metadata_routing`.z3Can only route and process input on these methods: z, while the passed method is: r@   Nr   )r7   re   )ry   AttributeErrorrM   r   rO   rW   r   r   r   r}   r   r   )rz   r   Zother_paramsr   
all_paramsZrequest_routingrB   r   r   r   process_routing  s    %


r   )N)&rR   r   collectionsr   copyr   typingr   r   warningsr    r   
exceptionsr	   Z_bunchr   rW   r   r(   r5   r   r   r   r   r   rT   r`   rc   rf   rt   r}   r   r   r   r   r   r   r   r   r   r   <module>   sV   O 5|b  .
1$f *