`L idZddlZddlmZddlmZddlmZmZm Z ddl m Z ddl m Z dd lmZd d lmZgd Zd dgd dgdZeeej+zZdZd4dZdZGddZdZdZdZdddeegZdZdZ GddZ!Gdd Z"ed!d"d#gZ#ed$d%d&gZ$Gd'd(Z%Gd)d*Z&d4d+Z'd,Z(d-Z)d.Z*Gd/d0Z+Gd1d2Z,d3Z-y)5a 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. The routing is coordinated by building ``MetadataRequest`` objects for objects that consume metadata, and ``MetadataRouter`` objects for objects that can route metadata, which are then aligned during a call to `process_routing()`. This function returns a Bunch object (dictionary-like) with all the information on the consumers and which metadata they had requested and the actual metadata values. A routing method (such as `fit` in a meta-estimator) can now provide the metadata to the relevant consuming method (such as `fit` in a sub-estimator). The ``MetadataRequest`` and ``MetadataRouter`` objects are constructed via a ``get_metadata_routing`` method, which all scikit-learn estimators provide. This method is automatically implemented via ``BaseEstimator`` for all simple estimators, but needs a custom implementation for meta-estimators. MetadataRequest ~~~~~~~~~~~~~~~ In non-routing consumers, the simplest case, e.g. ``SVM``, ``get_metadata_routing`` returns a ``MetadataRequest`` object which is assigned to the consumer's `_metadata_request` attribute. It stores which metadata is required by each method of the consumer by including one ``MethodMetadataRequest`` per method in ``METHODS`` (e. g. ``fit``, ``score``, etc). Users and developers almost never need to directly add a new ``MethodMetadataRequest``, to the consumer's `_metadata_request` attribute, since these are generated automatically. This attribute is modified while running `set_{method}_request` methods (such as `set_fit_request()`), which adds the request via `method_metadata_request.add_request(param=prop, alias=alias)`. The ``alias`` in the ``add_request`` method has to be either a string (an alias), or one of ``[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 ~~~~~~~~~~~~~~ In routers (such as meta-estimators or multi metric scorers), ``get_metadata_routing`` returns a ``MetadataRouter`` object. It provides information about which method, from the router object, calls which method in a consumer's object, and also, which metadata had been requested by the consumer's methods, thus specifying how metadata is to be passed. If a sub-estimator is a router as well, their routing information is also stored in the meta-estimators router. Conceptually, this information looks like: ``` { "sub_estimator1": ( mapping=[(caller="fit", callee="transform"), ...], router=MetadataRequest(...), # or another MetadataRouter ), ... } ``` The `MetadataRouter` objects are never stored and are always recreated anew whenever the object's `get_metadata_routing` method is called. An object that is both a router and a consumer, e.g. a meta-estimator which consumes ``sample_weight`` and routes ``sample_weight`` to its sub-estimators also returns a ``MetadataRouter`` object. Its routing information includes both information about what metadata is required by the object itself (added via ``MetadataRouter.add_self_request``), as well as the routing information for its sub-estimators (added via ``MetadataRouter.add``). Implementation Details ~~~~~~~~~~~~~~~~~~~~~~ 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 ``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_CHECKINGOptionalUnion)warn) get_config)UnsetMetadataPassedError)Bunch) fit partial_fitpredict predict_probapredict_log_probadecision_functionscoresplit transforminverse_transformrrr) fit_transform fit_predictc6tjddS)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 getf/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/utils/_metadata_requests.py_routing_enabledr s <  5u ==rc|r|jjd|n|jj}||ni}ts.|j|z rt d|dt |yy)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". allow : list of str, default=None A list of parameters which are allowed to be passed even if metadata routing is not enabled. Raises ------ ValueError If metadata routing is not enabled and params are passed. .Nz#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 for more details. Extra parameters passed are: ) __class____name__r keys ValueErrorset)paramsownermethodallowcallers r_raise_for_paramsr-s4395?? # # $AfX.eoo>V>V &EBE  6;;=5#81&:67:&k]  D  $9 rc |jDcic] \}}| || }}}trG|rD|jj}t |d|dt |j d|dyycc}}w)amRaise 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. Nr"z cannot accept given metadata (z4) since metadata routing is not yet implemented for )itemsr r#r$NotImplementedErrorr'r%)objr*kwargskeyvaluecls_names r_raise_for_unsupported_routingr6s(,2<<> OZS%U=Nc5j OF Of==))!j&!@V[[]AS@TUBBJ1 N  %Ps A9A9ceZdZdZdZy)_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. cFt|jjd)z[Raise `NotImplementedError`. This estimator does not support metadata routing yet.z* has not implemented metadata routing yet.)r0r#r$selfs rget_metadata_routingz._RoutingNotSupportedMixin.get_metadata_routings'"~~&&''Q R  rN)r$ __module__ __qualname____doc__r<rrrr8r8s  rr8z$UNUSED$z$WARN$z $UNCHANGED$FTcX|tvryt|txr|jS)aCheck if an item is a valid string alias for a metadata. 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 for the metadata. Returns ------- result : bool Whether the given item is a valid alias. F)VALID_REQUEST_VALUES isinstancestr isidentifieritems rrequest_is_aliasrG s-  ## dC 8T%6%6%88rc|tvS)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. )rArEs rrequest_is_validrI s ' ''rcXeZdZdZd dZedZdZdZdZ dZ d Z d Z d Z d Zy)MethodMetadataRequesta+Container for metadata requests associated with a single method. Instances of this class get used within a :class:`MetadataRequest` - one per each public method (`fit`, `transform`, ...) that its owning consumer has. .. 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. NcF|xs t|_||_||_yN)dict _requestsr)r*)r;r)r*requestss r__init__zMethodMetadataRequest.__init__Js!+TV  rc|jS)z)Dictionary of the form: ``{key: alias}``.rOr:s rrPzMethodMetadataRequest.requestsOs~~rct|st|std|d|d||k(rd}|tk(r,||jvr|j|=|Std|d||j|<|S)aNAdd request info for a metadata. Parameters ---------- param : str The metadata for which a request is set. alias : str, or {True, False, None} Specifies which metadata should be routed to the method that owns this `MethodMetadataRequest`. - str: the name (or alias) of metadata given to a meta-estimator that should be routed to the method that owns this `MethodMetadataRequest`. - True: requested - False: not requested - None: error if passed zThe alias you're setting for `zZ` should be either a valid identifier or one of {None, True, False}, but given value is: ``TzTrying to remove parameter z! with UNUSED which doesn't exist.)rGrIr&UNUSEDrO)r;paramaliass r add_requestz!MethodMetadataRequest.add_requestTs4 &/?/F08#WA'  E>E F?&NN5) !1%9 %*DNN5 ! rc\tfd|jjDS)aGet 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 metadata. c3dK|]'\}}t|r|durr t|s|n|)yw)FN)rI).0proprX return_aliass r z9MethodMetadataRequest._get_param_names..s; e#E*e5.@"*:5*AEt K s-0)r'rOr/)r;r^s `r_get_param_namesz&MethodMetadataRequest._get_param_namess," #~~335   rc |in|}|jjDchc]\}}|tk(r||vr|}}}|D]!}td|d|jd|d#ycc}}w)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. Nz 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.)rOr/WARNrr*)r;r(r]rX warn_paramsrWs r_check_warningsz%MethodMetadataRequest._check_warningss~6 $~~335 e}   ! E ug&"kk])E7;$$    sA'c |j|t}|jDcic] \}}| || }}}t}|jjD]@\} } | dus | t k(r| dur | |vr || || <%| | |vr || || <4| |vs9|| || <B|r|j tvrt|j } n |j g} dj| D cgc]} d| d c} } ddj|Dcgc]}|c}d |jd |j d |d |d |j | zd z}t||||Scc}}wcc} wcc}w)aPrepare the given metadata to be passed to the method. The output of this method can be used directly as the input to the corresponding method as **kwargs. 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 {metadata: value} which can be passed to the corresponding method. r(FTz.set_z_request({metadata}=True/False)[, 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. See the Metadata Routing User guide for more information.)messageunrequested_params routed_params) rdrNr/r rOrbr*COMPOSITE_METHODSjoinr)r )r;r(parentr, unrequestedargr4argsresr]rXcallee_methodsr*set_requests_onr3rjs r _route_paramsz#MethodMetadataRequest._route_paramss. F+f -3\\^QzsEu?PU QQg>>//1 (KD%~$$44< JD 44<$(J D!$ KD  ( {{//!24;;!?"&++ gg#1F8#DEODIIk:ss:;<=JJ>//1 KD%} E3'EVO    rc|jSSerialize the object. Returns ------- obj : dict A serialized version of the instance in the form of a dictionary. rSr:s r _serializez MethodMetadataRequest._serialize s~~rc4t|jSrMrCr}r:s r__repr__zMethodMetadataRequest.__repr__4??$%%rc*tt|SrMrCreprr:s r__str__zMethodMetadataRequest.__str__4:rrM)r$r=r>r?rQpropertyrPrYr`rdrvryr}rrrrrrKrK6sJ& /b .4?B,&rrKcLeZdZdZdZdZdZdZd dZdZ d Z d Z d Z d Z y)MetadataRequestaContains 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 X||_tD]}t||t||y)Nr)r*)r)SIMPLE_METHODSsetattrrK)r;r)r*s rrQzMetadataRequest.__init__4s0 $ F %E&A  rc:t||j|S)aCheck whether the given metadata 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. rf)getattrryr;r*r(s rconsumeszMetadataRequest.consumes=s$tV$..f.==rc J|tvr&td|jjd|di}t|D]}t ||}t |j }t |jj }||z}|Dcgc]}|||j|k7s|} }| r:tddj| d|ddjt|d|j|jt|j||Scc}w) N'z' object has no attribute 'z"Conflicting metadata requests for riz" while composing the requests for z*. Metadata with the same name for methods z$ should have the same request value.)r)r*rP)rmAttributeErrorr#r$rr'r%rPrOr&rnupdaterKr)) r;namerPr*mmrexistingupcomingcommonr3 conflictss r __getattr__zMetadataRequest.__getattr__Qs6 ( ( DNN++,,GvQO '- +F$'C8==?+H3<<,,./H(F(.V(3-3==QTCU2UVIV 899M8NO337&9$$(II.?.E$F#GH++ OOCMM * +%4::dXVVWs D )D Nc:t||j|S)aGet 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 metadata. )r^)rr`)r;r*r^ignore_self_requests rr`z MetadataRequest._get_param_namesos0tV$55<5PPrc>t||j|||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 {metadata: value} which can be given to the corresponding method. )r(ror,)rrv)r;r(r*ror,s rrvzMetadataRequest._route_paramss*6tV$22&3  rc<t||j|y)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. rfN)rrdrs rrdzMetadataRequest._check_warningss f--V-r?_typerQrrr`rvrdr}rrrrrrrs=& E>(W<Q4 > = &rrRouterMappingPairmappingrouter MethodPairr,calleec4eZdZdZdZdZdZdZdZdZ y) MethodMappingaStores the mapping between caller and callee methods for a :term:`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 cg|_yrM)_routesr:s rrQzMethodMapping.__init__s  rc,t|jSrM)iterrr:s r__iter__zMethodMapping.__iter__sDLL!!rc|tvrtd|dt|tvrtd|dt|jjt |||S)adAdd 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&rappendr)r;r,rs rrxzMethodMapping.adds|"  x(9   x(9  JfVDE rct}|jD]*}|j|j|jd,|S)zSerialize the object. Returns ------- obj : list A serialized version of the instance in the form of a list. r)listrrr,r)r;resultroutes rr}zMethodMapping._serializes>\\ LE MMU\\U\\J K L rc4t|jSrMrr:s rrzMethodMapping.__repr__rrc*tt|SrMrr:s rrzMethodMapping.__str__rrN) r$r=r>r?rQrrxr}rrrrrrrs% "< &rrc\eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZy)MetadataRouteraCoordinates metadata routing for a :term:`router` object. This class is used by :term:`meta-estimators` or functions that can route metadata, to handle their metadata routing. Routing information is stored in a dictionary-like structure of the form ``{"object_name": RouterMappingPair(mapping, router)}``, where ``mapping`` is an instance of :class:`~sklearn.utils.metadata_routing.MethodMapping` and ``router`` is either a :class:`~sklearn.utils.metadata_routing.MetadataRequest` or another :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>t|_d|_||_yrM)rN_route_mappings _self_requestr))r;r)s rrQzMetadataRouter.__init__;s#v " rct|dddk(rt||_|St|dr t|j |_|St d)agAdd `self` (as a :term:`consumer`) to the `MetadataRouter`. This method is used if the :term:`router` is also a :term:`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 consumer 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`. rNr_get_metadata_requestzGiven `obj` is neither a `MetadataRequest` nor does it implement the required API. Inheriting from `BaseEstimator` implements the required API.)rrrhasattrrr&)r;r1s radd_self_requestzMetadataRouter.add_self_requestDsg0 3 &*< ` to the `MetadataRouter`. The estimators that consume metadata are passed as named objects along with a method mapping, that defines how their methods relate to those of the :term:`router`. Parameters ---------- method_mapping : MethodMapping The mapping between the child (:term:`consumer`) and the parent's (:term:`router`'s) methods. **objs : dict A dictionary of objects, whose requests are extracted by calling :func:`~sklearn.utils.metadata_routing.get_routing_for_object` on them. Returns ------- self : MetadataRouter Returns `self`. rr)rr/rget_routing_for_objectr)r;method_mappingobjsrr1s rrxzMetadataRouter.addhsN,".1 ID#):&/Ec/J*D  &  rc*t}|jr ||jj||z}|jj D]?\}}|j D]+\}}||k(s ||j j||z}-A|S)aCheck whether the given metadata is 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. )r*r()r'rrrr/rr)r;r*r(rs_ route_mappingr,rs rrzMetadataRouter.consumess$e   **336&3QQC $ 4 4 : : <  A}"/"7"7 V# 4 4 = =%f!>!C   rc `t}|jr.|s,|j|jj||}|jj D]L\}}|j D]8\}}||k(s |j|jj|dd}:N|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 metadata. r*r^TFr*r^r)r'runionr`rr/rr) r;r*r^rrsrrr,rs rr`zMetadataRouter._get_param_namess4e   &9))""33! 4C $(#7#7#=#=#?  D-"/"7"7 V#))%,,==#)RW>C   rct}|jr.|j|jj|||||j |dd}|j Dcic] \}}||vs ||} }}t |jj| jD](}| |||ustd|jd|d|j| |Scc}}w)aPrepare the given metadata 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 **kwargs. Parameters ---------- params : dict A dictionary of provided metadata. method : str The name of the method for which the metadata is 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 {metadata: value} which can be given to the corresponding method. r(r*ror,TrzIn 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 estimators' requested metadata.) r rrrvr`r/r'r% intersectionr&r)) r;r(r*ror,rs param_namesr3r4 child_paramss rrvzMetadataRouter._route_paramss<g    JJ""00!!!! 1 ++$, *0 %33+;MCJ  sxxz?// 0A0A0CD CC C0 $**%>seDAA  <   s , C59C5cd|jr|jj||t}|jj D]_\}}|j |j }}t||<|D]0\}} ||k(s |j|| |j|||| <2a|S)aGet the values of metadata requested by :term:`consumers `. Returns a :class:`~sklearn.utils.Bunch` containing the metadata that this :term:`router`'s `caller` method needs to route, organized by each :term:`consumer` and their corresponding methods. This can be used to pass the required metadata to corresponding methods in consumers. Parameters ---------- caller : str The name of the :term:`router`'s method through which the metadata is routed. For example, if called inside the :term:`fit` method of a router, this 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": {metadata: value}}}``. r(r*r) rrdr rr/rrrvr)) r;r,r(rsrrrr_caller_callees r route_paramszMetadataRouter.route_paramss4       . .fV . Lg#'#7#7#=#=#?  D-+22M4I4IGFCI$+  f$)/)=)=%&#zz% *>*CIg&   rc|j|dd}|jr|jj|d}n t}t|j|z |z }|rt |j d|d|dy)aValidate 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 :term:`router`'s method through which the metadata is routed. For example, if called inside the :term:`fit` method of a router, this would be `"fit"`. params : dict A dictionary of provided metadata. Frrr"z got unexpected argument(s) z%, which are not routed to any object.N)r`rr'r% TypeErrorr))r;r*r(r self_params extra_keyss rvalidate_metadataz MetadataRouter.validate_metadata:s ++5,    ,,==E>K%K'+5 C ::,ax'CJ<P11  rcJt}|jr|jj|d<|jj D]R\}}t||<|j j||d<|j j||d<T|S)r| $self_requestrr)rNrr}rr/rr)r;rsrrs rr}zMetadataRouter._serializeZsf   #'#5#5#@#@#BC #'#7#7#=#=#? D D-CI#0#8#8#C#C#ECIi "/"6"6"A"A"CCIh  D  rc#K|jrCt}tD]}|j||dt ||jf|j j D] \}}||f yw)Nrrr)rrrrxrrr/)r;rr*rrs rrzMetadataRouter.__iter__ls   *_N! A""&"@ A !.ASAST $(#7#7#=#=#? ( D-' ' (sA9A;c4t|jSrMrr:s rrzMetadataRouter.__repr__xrrc*tt|SrMrr:s rrzMetadataRouter.__str__{rrN)r$r=r>r?rrQrrxrr`rvrrr}rrrrrrrr"sO, E"H<>*X;z*X@$ (&rrct|drt|jSt|dddvr t|St dS)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 MetadataRouter A ``MetadataRequest`` or a ``MetadataRouter`` taken or created from the given object. r<rN)rrr))rrr<rr)r1s rrrsKBs*+00233 gt $(O O}  &&ra Configure whether metadata should be requested to be passed to the ``{method}`` method. Note that this method is only relevant when this estimator is used as a sub-estimator within a :term:`meta-estimator` and metadata routing is enabled with ``enable_metadata_routing=True`` (see :func:`sklearn.set_config`). Please check the :ref:`User Guide ` 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 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. ceZdZdZddZdZy) RequestMethoda Descriptor for defining `set_{method}_request` methods in estimators. .. 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/ c.||_||_||_yrM)rr% validate_keys)r;rr%rs rrQzRequestMethod.__init__s  *rcfd}djd|_tjdtjj|g}|j j Dcgc]P}tj|tjjttttdtfRc}tj|||_tj!j}j D]&}|t"j!|j z }(|t$z }||_|Scc}w) Nc Zts tdjrqt|tjz rPt dt|tjz dj dtj |d}|dd}n}|r%t dj d t|d |j}t|j }|jD]!\}}|tus|j|| #||_ |S) zUpdates the `_metadata_request` attribute of the consumer (`instance`) for the parameters provided as `**kw`. 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).zUnexpected args: z in z. Accepted arguments are: Nrr set_z+_request() takes 0 positional argument but z were givenrWrX)r RuntimeErrorrr'r%rrrrrr/ UNCHANGEDrY_metadata_request) rrkw _instancerPmethod_metadata_requestr]rXinstancer;s rfuncz#RequestMethod.__get__..funcs@$%"I !!s2wTYY'?'B#dii.(@'Adii[Q//2499~.>@ G ABx$ 499+&D {+/ !668H&-h &B #!xxz Q e )+77d%7P Q+3I ' rr_requestr;)rkind annotation)defaultr)return_annotation)r*)metadatar*)rr$inspect ParameterPOSITIONAL_OR_KEYWORDextendr% KEYWORD_ONLYrrrboolrC Signature __signature__ REQUESTER_DOCformatREQUESTER_DOC_PARAMREQUESTER_DOC_RETURNr?)r;rr)rr(kdocrs`` r__get__zRequestMethod.__get__s,- btyyk2   &&<<       !!%%22%'dD#o(>?   %.. # ""$))"4  SH &--x -R RC S ##  ' s(AEN)T)r$r=r>r?rQrrrrrrs@+ OrrceZdZdZerdZdZdZdZdZ dZ dZ d Z d Z d Zfd Zed ZedZdZdZxZS)_MetadataRequesterzMixin class for adding metadata request functionality. ``BaseEstimator`` inherits from this Mixin. .. versionadded:: 1.3 c yrMrr;r2s rset_fit_requestz"_MetadataRequester.set_fit_requestfrc yrMrrs rset_partial_fit_requestz*_MetadataRequester.set_partial_fit_requestgrrc yrMrrs rset_predict_requestz&_MetadataRequester.set_predict_requesthrrc yrMrrs rset_predict_proba_requestz,_MetadataRequester.set_predict_proba_requestirrc yrMrrs rset_predict_log_proba_requestz0_MetadataRequester.set_predict_log_proba_requestjrrc yrMrrs rset_decision_function_requestz0_MetadataRequester.set_decision_function_requestkrrc yrMrrs rset_score_requestz$_MetadataRequester.set_score_requestlrrc yrMrrs rset_split_requestz$_MetadataRequester.set_split_requestmrrc yrMrrs rset_transform_requestz(_MetadataRequester.set_transform_requestnrrc yrMrrs rset_inverse_transform_requestz0_MetadataRequester.set_inverse_transform_requestorrc T |j}tD]`}t ||}t |js%t|d|dt|t|jjbt| di|y#t$rt| di|YywxYw)aSet 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 Nrrr) _get_default_requests Exceptionsuper__init_subclass__rrrrPrrsortedr%)clsr2rPr*rr#s rr+z$_MetadataRequester.__init_subclass__rs" 002H% F(F+Cs||$ vhh'ffS\\->->-@&AB   !+F+#  G % / /   sB B'&B'ct|j|}t||rtjt ||s|St tjt ||jjdd}|D]B\}}|dvr |j|j|jhvr0|j|dD|S)aqBuild 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. rr N>XYyXtytr)rKr$rr isfunctionrr signature parametersr/rVAR_POSITIONAL VAR_KEYWORDrY)r-rr*rr(pnamerWs r_build_request_for_signaturez/_MetadataRequester._build_request_for_signatures($#,,vFsF#7+=+=gc6>R+SJg''V(<=HHNNPQRSRTU" LE533zze22E4E4EFF OO     rc t|j}tD] }t|||j ||"d}t t j|D]}}t|jD]_\}}||vr ||j|t|zd}|jD]"\}}t||j||$a|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)rr*__metadata_request__Nr)rr$rrr:reversedrgetmrovarsr/indexrrrY) r-rPr*substr base_classattrr4r]rXs rr(z(_MetadataRequester._get_default_requestss#6$ F 000P   ("7>>##67 SJ#J/557 S e%djj03v;>@A#(;;=SKD% Hf-99E9R S S Srclt|drt|j}|S|j}|S)a,Get requested metadata for the instance. Please check :ref:`User Guide ` on how the routing mechanism works. Returns ------- request : MetadataRequest A :class:`~sklearn.utils.metadata_routing.MetadataRequest` instance. r)rrrr()r;rPs rrz(_MetadataRequester._get_metadata_requests; 4, --d.D.DEH113Hrc"|jS)aMGet metadata routing of this object. Please check :ref:`User Guide ` on how the routing mechanism works. Returns ------- routing : MetadataRequest A :class:`~sklearn.utils.metadata_routing.MetadataRequest` encapsulating routing information. )rr:s rr<z'_MetadataRequester.get_metadata_routings))++r)r$r=r>r?rrrrrrrr r"r$r&r+ classmethodr:r(rr< __classcell__)r#s@rrrUsg 295;??337?$,L##J))V$ ,rrc H|sGdd}|St|ds3t|ts#td|jj d|t vrtdt d|dt|}|j|| |j|| }|S) aValidate and route metadata. This function is used inside a :term:`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 :term:`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": {metadata: value}}}`` which can be used to pass the required metadata to A :class:`~sklearn.utils.Bunch` of the form ``{"object_name": {"method_name": {metadata: 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 eZdZddZdZdZy)%process_routing..EmptyRequestNc XtditDcic] }|tc}Scc}wNrr rrN)r;rrr*s rrz)process_routing..EmptyRequest.getA$FWE6EFFE' c XtditDcic] }|tc}Scc}wrLrMr;rr*s r __getitem__z1process_routing..EmptyRequest.__getitem__DrNrOc XtditDcic] }|tc}Scc}wrLrMrQs rrz1process_routing..EmptyRequest.__getattr__GrNrOrM)r$r=r>rrRrrrr EmptyRequestrJ@s G G GrrTr<zThe 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,) rrBrrr#r$rrrrr)_obj_methodr2rTrequest_routingrls rprocess_routingrXsN  G G~ D0 1Zn5U !8!8 ;<* *  gA'K++2)1 6  -T2O%%VG%D#00w0OM rrM).r?r collectionsrcopyrtypingrrrwarningsrrgr exceptionsr _bunchr rrmrr%rr r-r6r8rVrbrrArGrIrKrrrrrrrr r rrrXrrrr_sI_H"111 "[)9% 4 1 6 6 89 9 >& R :  4    tT6489. (,eePllp2Y4IJ x&: ; BBJZZz ''b  B uups,s,@Gr