-
-
Notifications
You must be signed in to change notification settings - Fork 25.7k
/
Copy path_metadata_requests.py
1593 lines (1289 loc) · 54.8 KB
/
_metadata_requests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
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.
"""
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
import inspect
from collections import namedtuple
from copy import deepcopy
from typing import TYPE_CHECKING, Optional, Union
from warnings import warn
from .. import get_config
from ..exceptions import UnsetMetadataPassedError
from ._bunch import Bunch
# Only the following methods are supported in the routing mechanism. Adding new
# methods at the moment involves monkeypatching this list.
# Note that if this list is changed or monkeypatched, the corresponding method
# needs to be added under a TYPE_CHECKING condition like the one done here in
# _MetadataRequester
SIMPLE_METHODS = [
"fit",
"partial_fit",
"predict",
"predict_proba",
"predict_log_proba",
"decision_function",
"score",
"split",
"transform",
"inverse_transform",
]
# These methods are a composite of other methods and one cannot set their
# requests directly. Instead they should be set by setting the requests of the
# simple methods which make the composite ones.
COMPOSITE_METHODS = {
"fit_transform": ["fit", "transform"],
"fit_predict": ["fit", "predict"],
}
METHODS = SIMPLE_METHODS + list(COMPOSITE_METHODS.keys())
def _routing_enabled():
"""Return 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.
"""
return get_config().get("enable_metadata_routing", False)
def _raise_for_params(params, owner, method):
"""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.
"""
caller = (
f"{owner.__class__.__name__}.{method}" if method else owner.__class__.__name__
)
if not _routing_enabled() and params:
raise ValueError(
f"Passing extra keyword arguments to {caller} 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"
f" details. Extra parameters passed are: {set(params)}"
)
def _raise_for_unsupported_routing(obj, method, **kwargs):
"""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.
"""
kwargs = {key: value for key, value in kwargs.items() if value is not None}
if _routing_enabled() and kwargs:
cls_name = obj.__class__.__name__
raise NotImplementedError(
f"{cls_name}.{method} cannot accept given metadata ({set(kwargs.keys())})"
f" since metadata routing is not yet implemented for {cls_name}."
)
class _RoutingNotSupportedMixin:
"""A 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.
"""
def get_metadata_routing(self):
"""Raise `NotImplementedError`.
This estimator does not support metadata routing yet."""
raise NotImplementedError(
f"{self.__class__.__name__} has not implemented metadata routing yet."
)
# Request values
# ==============
# Each request value needs to be one of the following values, or an alias.
# this is used in `__metadata_request__*` attributes to indicate that a
# metadata is not present even though it may be present in the
# corresponding method's signature.
UNUSED = "$UNUSED$"
# this is used whenever a default value is changed, and therefore the user
# should explicitly set the value, otherwise a warning is shown. An example
# is when a meta-estimator is only a router, but then becomes also a
# consumer in a new release.
WARN = "$WARN$"
# this is the default used in `set_{method}_request` methods to indicate no
# change requested by the user.
UNCHANGED = "$UNCHANGED$"
VALID_REQUEST_VALUES = [False, True, None, UNUSED, WARN]
def request_is_alias(item):
"""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.
"""
if item in VALID_REQUEST_VALUES:
return False
# item is only an alias if it's a valid identifier
return isinstance(item, str) and item.isidentifier()
def request_is_valid(item):
"""Check 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.
"""
return item in VALID_REQUEST_VALUES
# Metadata Request for Simple Consumers
# =====================================
# This section includes MethodMetadataRequest and MetadataRequest which are
# used in simple consumers.
class MethodMetadataRequest:
"""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.
"""
def __init__(self, owner, method, requests=None):
self._requests = requests or dict()
self.owner = owner
self.method = method
@property
def requests(self):
"""Dictionary of the form: ``{key: alias}``."""
return self._requests
def add_request(
self,
*,
param,
alias,
):
"""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
"""
if not request_is_alias(alias) and not request_is_valid(alias):
raise ValueError(
f"The alias you're setting for `{param}` should be either a "
"valid identifier or one of {None, True, False}, but given "
f"value is: `{alias}`"
)
if alias == param:
alias = True
if alias == UNUSED:
if param in self._requests:
del self._requests[param]
else:
raise ValueError(
f"Trying to remove parameter {param} with UNUSED which doesn't"
" exist."
)
else:
self._requests[param] = alias
return self
def _get_param_names(self, return_alias):
"""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.
"""
return set(
alias if return_alias and not request_is_valid(alias) else prop
for prop, alias in self._requests.items()
if not request_is_valid(alias) or alias is not False
)
def _check_warnings(self, *, params):
"""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
----------
params : dict
The metadata passed to a method.
"""
params = {} if params is None else params
warn_params = {
prop
for prop, alias in self._requests.items()
if alias == WARN and prop in params
}
for param in warn_params:
warn(
f"Support for {param} has recently been added to this class. "
"To maintain backward compatibility, it is ignored now. "
f"Using `set_{self.method}_request({param}={{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."
)
def _route_params(self, params, parent, caller):
"""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.
"""
self._check_warnings(params=params)
unrequested = dict()
args = {arg: value for arg, value in params.items() if value is not None}
res = Bunch()
for prop, alias in self._requests.items():
if alias is False or alias == WARN:
continue
elif alias is True and prop in args:
res[prop] = args[prop]
elif alias is None and prop in args:
unrequested[prop] = args[prop]
elif alias in args:
res[prop] = args[alias]
if unrequested:
if self.method in COMPOSITE_METHODS:
callee_methods = COMPOSITE_METHODS[self.method]
else:
callee_methods = [self.method]
set_requests_on = "".join(
[
f".set_{method}_request({{metadata}}=True/False)"
for method in callee_methods
]
)
message = (
f"[{', '.join([key for key in unrequested])}] are passed but are not"
" explicitly set as requested or not requested for"
f" {self.owner}.{self.method}, which is used within"
f" {parent}.{caller}. Call `{self.owner}"
+ set_requests_on
+ "` for each metadata you want to request/ignore."
)
raise UnsetMetadataPassedError(
message=message,
unrequested_params=unrequested,
routed_params=res,
)
return res
def _consumes(self, params):
"""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.
"""
params = set(params)
res = set()
for prop, alias in self._requests.items():
if alias is True and prop in params:
res.add(prop)
elif isinstance(alias, str) and alias in params:
res.add(alias)
return res
def _serialize(self):
"""Serialize the object.
Returns
-------
obj : dict
A serialized version of the instance in the form of a dictionary.
"""
return self._requests
def __repr__(self):
return str(self._serialize())
def __str__(self):
return str(repr(self))
class MetadataRequest:
"""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.
"""
# this is here for us to use this attribute's value instead of doing
# `isinstance` in our checks, so that we avoid issues when people vendor
# this file instead of using it directly from scikit-learn.
_type = "metadata_request"
def __init__(self, owner):
self.owner = owner
for method in SIMPLE_METHODS:
setattr(
self,
method,
MethodMetadataRequest(owner=owner, method=method),
)
def consumes(self, method, params):
"""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.
"""
return getattr(self, method)._consumes(params=params)
def __getattr__(self, name):
# Called when the default attribute access fails with an AttributeError
# (either __getattribute__() raises an AttributeError because name is
# not an instance attribute or an attribute in the class tree for self;
# or __get__() of a name property raises AttributeError). This method
# should either return the (computed) attribute value or raise an
# AttributeError exception.
# https://docs.python.org/3/reference/datamodel.html#object.__getattr__
if name not in COMPOSITE_METHODS:
raise AttributeError(
f"'{self.__class__.__name__}' object has no attribute '{name}'"
)
requests = {}
for method in COMPOSITE_METHODS[name]:
mmr = getattr(self, method)
existing = set(requests.keys())
upcoming = set(mmr.requests.keys())
common = existing & upcoming
conflicts = [key for key in common if requests[key] != mmr._requests[key]]
if conflicts:
raise ValueError(
f"Conflicting metadata requests for {', '.join(conflicts)} while"
f" composing the requests for {name}. Metadata with the same name"
f" for methods {', '.join(COMPOSITE_METHODS[name])} should have the"
" same request value."
)
requests.update(mmr._requests)
return MethodMetadataRequest(owner=self.owner, method=name, requests=requests)
def _get_param_names(self, method, return_alias, ignore_self_request=None):
"""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.
"""
return getattr(self, method)._get_param_names(return_alias=return_alias)
def _route_params(self, *, params, method, parent, caller):
"""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.
"""
return getattr(self, method)._route_params(
params=params, parent=parent, caller=caller
)
def _check_warnings(self, *, method, params):
"""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.
"""
getattr(self, method)._check_warnings(params=params)
def _serialize(self):
"""Serialize the object.
Returns
-------
obj : dict
A serialized version of the instance in the form of a dictionary.
"""
output = dict()
for method in SIMPLE_METHODS:
mmr = getattr(self, method)
if len(mmr.requests):
output[method] = mmr._serialize()
return output
def __repr__(self):
return str(self._serialize())
def __str__(self):
return str(repr(self))
# Metadata Request for Routers
# ============================
# This section includes all objects required for MetadataRouter which is used
# in routers, returned by their ``get_metadata_routing``.
# `RouterMappingPair` is used to store a (mapping, router) tuple where `mapping` is a
# `MethodMapping` object and `router` is the output of `get_metadata_routing`.
# `MetadataRouter` stores a collection of `RouterMappingPair` objects in its
# `_route_mappings` attribute.
RouterMappingPair = namedtuple("RouterMappingPair", ["mapping", "router"])
# `MethodPair` is used to store a single method routing. `MethodMapping` stores a list
# of `MethodPair` objects in its `_routes` attribute.
MethodPair = namedtuple("MethodPair", ["caller", "callee"])
class MethodMapping:
"""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
"""
def __init__(self):
self._routes = []
def __iter__(self):
return iter(self._routes)
def add(self, *, caller, callee):
"""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.
"""
if caller not in METHODS:
raise ValueError(
f"Given caller:{caller} is not a valid method. Valid methods are:"
f" {METHODS}"
)
if callee not in METHODS:
raise ValueError(
f"Given callee:{callee} is not a valid method. Valid methods are:"
f" {METHODS}"
)
self._routes.append(MethodPair(caller=caller, callee=callee))
return self
def _serialize(self):
"""Serialize the object.
Returns
-------
obj : list
A serialized version of the instance in the form of a list.
"""
result = list()
for route in self._routes:
result.append({"caller": route.caller, "callee": route.callee})
return result
def __repr__(self):
return str(self._serialize())
def __str__(self):
return str(repr(self))
class MetadataRouter:
"""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.
"""
# this is here for us to use this attribute's value instead of doing
# `isinstance`` in our checks, so that we avoid issues when people vendor
# this file instead of using it directly from scikit-learn.
_type = "metadata_router"
def __init__(self, owner):
self._route_mappings = dict()
# `_self_request` is used if the router is also a consumer.
# _self_request, (added using `add_self_request()`) is treated
# differently from the other objects which are stored in
# _route_mappings.
self._self_request = None
self.owner = owner
def add_self_request(self, obj):
"""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`.
"""
if getattr(obj, "_type", None) == "metadata_request":
self._self_request = deepcopy(obj)
elif hasattr(obj, "_get_metadata_request"):
self._self_request = deepcopy(obj._get_metadata_request())
else:
raise ValueError(
"Given `obj` is neither a `MetadataRequest` nor does it implement the"
" required API. Inheriting from `BaseEstimator` implements the required"
" API."
)
return self
def add(self, *, method_mapping, **objs):
"""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`.
"""
method_mapping = deepcopy(method_mapping)
for name, obj in objs.items():
self._route_mappings[name] = RouterMappingPair(
mapping=method_mapping, router=get_routing_for_object(obj)
)
return self
def consumes(self, method, params):
"""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.
"""
res = set()
if self._self_request:
res = res | self._self_request.consumes(method=method, params=params)
for _, route_mapping in self._route_mappings.items():
for caller, callee in route_mapping.mapping:
if caller == method:
res = res | route_mapping.router.consumes(
method=callee, params=params
)
return res
def _get_param_names(self, *, method, return_alias, ignore_self_request):
"""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.
"""
res = set()
if self._self_request and not ignore_self_request:
res = res.union(
self._self_request._get_param_names(
method=method, return_alias=return_alias
)
)
for name, route_mapping in self._route_mappings.items():
for caller, callee in route_mapping.mapping:
if caller == method:
res = res.union(
route_mapping.router._get_param_names(
method=callee, return_alias=True, ignore_self_request=False
)
)
return res
def _route_params(self, *, params, method, parent, caller):
"""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.
"""
res = Bunch()
if self._self_request:
res.update(
self._self_request._route_params(
params=params,
method=method,
parent=parent,
caller=caller,
)
)
param_names = self._get_param_names(
method=method, return_alias=True, ignore_self_request=True
)
child_params = {
key: value for key, value in params.items() if key in param_names
}
for key in set(res.keys()).intersection(child_params.keys()):
# conflicts are okay if the passed objects are the same, but it's
# an issue if they're different objects.
if child_params[key] is not res[key]:
raise ValueError(
f"In {self.owner}, there is a conflict on {key} 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."
)
res.update(child_params)
return res
def route_params(self, *, caller, params):