_param_validation.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. import functools
  2. import math
  3. import operator
  4. import re
  5. import warnings
  6. from abc import ABC, abstractmethod
  7. from collections.abc import Iterable
  8. from inspect import signature
  9. from numbers import Integral, Real
  10. import numpy as np
  11. from scipy.sparse import csr_matrix, issparse
  12. from .._config import config_context, get_config
  13. from .validation import _is_arraylike_not_scalar
  14. class InvalidParameterError(ValueError, TypeError):
  15. """Custom exception to be raised when the parameter of a class/method/function
  16. does not have a valid type or value.
  17. """
  18. # Inherits from ValueError and TypeError to keep backward compatibility.
  19. def validate_parameter_constraints(parameter_constraints, params, caller_name):
  20. """Validate types and values of given parameters.
  21. Parameters
  22. ----------
  23. parameter_constraints : dict or {"no_validation"}
  24. If "no_validation", validation is skipped for this parameter.
  25. If a dict, it must be a dictionary `param_name: list of constraints`.
  26. A parameter is valid if it satisfies one of the constraints from the list.
  27. Constraints can be:
  28. - an Interval object, representing a continuous or discrete range of numbers
  29. - the string "array-like"
  30. - the string "sparse matrix"
  31. - the string "random_state"
  32. - callable
  33. - None, meaning that None is a valid value for the parameter
  34. - any type, meaning that any instance of this type is valid
  35. - an Options object, representing a set of elements of a given type
  36. - a StrOptions object, representing a set of strings
  37. - the string "boolean"
  38. - the string "verbose"
  39. - the string "cv_object"
  40. - the string "nan"
  41. - a MissingValues object representing markers for missing values
  42. - a HasMethods object, representing method(s) an object must have
  43. - a Hidden object, representing a constraint not meant to be exposed to the user
  44. params : dict
  45. A dictionary `param_name: param_value`. The parameters to validate against the
  46. constraints.
  47. caller_name : str
  48. The name of the estimator or function or method that called this function.
  49. """
  50. for param_name, param_val in params.items():
  51. # We allow parameters to not have a constraint so that third party estimators
  52. # can inherit from sklearn estimators without having to necessarily use the
  53. # validation tools.
  54. if param_name not in parameter_constraints:
  55. continue
  56. constraints = parameter_constraints[param_name]
  57. if constraints == "no_validation":
  58. continue
  59. constraints = [make_constraint(constraint) for constraint in constraints]
  60. for constraint in constraints:
  61. if constraint.is_satisfied_by(param_val):
  62. # this constraint is satisfied, no need to check further.
  63. break
  64. else:
  65. # No constraint is satisfied, raise with an informative message.
  66. # Ignore constraints that we don't want to expose in the error message,
  67. # i.e. options that are for internal purpose or not officially supported.
  68. constraints = [
  69. constraint for constraint in constraints if not constraint.hidden
  70. ]
  71. if len(constraints) == 1:
  72. constraints_str = f"{constraints[0]}"
  73. else:
  74. constraints_str = (
  75. f"{', '.join([str(c) for c in constraints[:-1]])} or"
  76. f" {constraints[-1]}"
  77. )
  78. raise InvalidParameterError(
  79. f"The {param_name!r} parameter of {caller_name} must be"
  80. f" {constraints_str}. Got {param_val!r} instead."
  81. )
  82. def make_constraint(constraint):
  83. """Convert the constraint into the appropriate Constraint object.
  84. Parameters
  85. ----------
  86. constraint : object
  87. The constraint to convert.
  88. Returns
  89. -------
  90. constraint : instance of _Constraint
  91. The converted constraint.
  92. """
  93. if isinstance(constraint, str) and constraint == "array-like":
  94. return _ArrayLikes()
  95. if isinstance(constraint, str) and constraint == "sparse matrix":
  96. return _SparseMatrices()
  97. if isinstance(constraint, str) and constraint == "random_state":
  98. return _RandomStates()
  99. if constraint is callable:
  100. return _Callables()
  101. if constraint is None:
  102. return _NoneConstraint()
  103. if isinstance(constraint, type):
  104. return _InstancesOf(constraint)
  105. if isinstance(
  106. constraint, (Interval, StrOptions, Options, HasMethods, MissingValues)
  107. ):
  108. return constraint
  109. if isinstance(constraint, str) and constraint == "boolean":
  110. return _Booleans()
  111. if isinstance(constraint, str) and constraint == "verbose":
  112. return _VerboseHelper()
  113. if isinstance(constraint, str) and constraint == "cv_object":
  114. return _CVObjects()
  115. if isinstance(constraint, Hidden):
  116. constraint = make_constraint(constraint.constraint)
  117. constraint.hidden = True
  118. return constraint
  119. if isinstance(constraint, str) and constraint == "nan":
  120. return _NanConstraint()
  121. raise ValueError(f"Unknown constraint type: {constraint}")
  122. def validate_params(parameter_constraints, *, prefer_skip_nested_validation):
  123. """Decorator to validate types and values of functions and methods.
  124. Parameters
  125. ----------
  126. parameter_constraints : dict
  127. A dictionary `param_name: list of constraints`. See the docstring of
  128. `validate_parameter_constraints` for a description of the accepted constraints.
  129. Note that the *args and **kwargs parameters are not validated and must not be
  130. present in the parameter_constraints dictionary.
  131. prefer_skip_nested_validation : bool
  132. If True, the validation of parameters of inner estimators or functions
  133. called by the decorated function will be skipped.
  134. This is useful to avoid validating many times the parameters passed by the
  135. user from the public facing API. It's also useful to avoid validating
  136. parameters that we pass internally to inner functions that are guaranteed to
  137. be valid by the test suite.
  138. It should be set to True for most functions, except for those that receive
  139. non-validated objects as parameters or that are just wrappers around classes
  140. because they only perform a partial validation.
  141. Returns
  142. -------
  143. decorated_function : function or method
  144. The decorated function.
  145. """
  146. def decorator(func):
  147. # The dict of parameter constraints is set as an attribute of the function
  148. # to make it possible to dynamically introspect the constraints for
  149. # automatic testing.
  150. setattr(func, "_skl_parameter_constraints", parameter_constraints)
  151. @functools.wraps(func)
  152. def wrapper(*args, **kwargs):
  153. global_skip_validation = get_config()["skip_parameter_validation"]
  154. if global_skip_validation:
  155. return func(*args, **kwargs)
  156. func_sig = signature(func)
  157. # Map *args/**kwargs to the function signature
  158. params = func_sig.bind(*args, **kwargs)
  159. params.apply_defaults()
  160. # ignore self/cls and positional/keyword markers
  161. to_ignore = [
  162. p.name
  163. for p in func_sig.parameters.values()
  164. if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD)
  165. ]
  166. to_ignore += ["self", "cls"]
  167. params = {k: v for k, v in params.arguments.items() if k not in to_ignore}
  168. validate_parameter_constraints(
  169. parameter_constraints, params, caller_name=func.__qualname__
  170. )
  171. try:
  172. with config_context(
  173. skip_parameter_validation=(
  174. prefer_skip_nested_validation or global_skip_validation
  175. )
  176. ):
  177. return func(*args, **kwargs)
  178. except InvalidParameterError as e:
  179. # When the function is just a wrapper around an estimator, we allow
  180. # the function to delegate validation to the estimator, but we replace
  181. # the name of the estimator by the name of the function in the error
  182. # message to avoid confusion.
  183. msg = re.sub(
  184. r"parameter of \w+ must be",
  185. f"parameter of {func.__qualname__} must be",
  186. str(e),
  187. )
  188. raise InvalidParameterError(msg) from e
  189. return wrapper
  190. return decorator
  191. class RealNotInt(Real):
  192. """A type that represents reals that are not instances of int.
  193. Behaves like float, but also works with values extracted from numpy arrays.
  194. isintance(1, RealNotInt) -> False
  195. isinstance(1.0, RealNotInt) -> True
  196. """
  197. RealNotInt.register(float)
  198. def _type_name(t):
  199. """Convert type into human readable string."""
  200. module = t.__module__
  201. qualname = t.__qualname__
  202. if module == "builtins":
  203. return qualname
  204. elif t == Real:
  205. return "float"
  206. elif t == Integral:
  207. return "int"
  208. return f"{module}.{qualname}"
  209. class _Constraint(ABC):
  210. """Base class for the constraint objects."""
  211. def __init__(self):
  212. self.hidden = False
  213. @abstractmethod
  214. def is_satisfied_by(self, val):
  215. """Whether or not a value satisfies the constraint.
  216. Parameters
  217. ----------
  218. val : object
  219. The value to check.
  220. Returns
  221. -------
  222. is_satisfied : bool
  223. Whether or not the constraint is satisfied by this value.
  224. """
  225. @abstractmethod
  226. def __str__(self):
  227. """A human readable representational string of the constraint."""
  228. class _InstancesOf(_Constraint):
  229. """Constraint representing instances of a given type.
  230. Parameters
  231. ----------
  232. type : type
  233. The valid type.
  234. """
  235. def __init__(self, type):
  236. super().__init__()
  237. self.type = type
  238. def is_satisfied_by(self, val):
  239. return isinstance(val, self.type)
  240. def __str__(self):
  241. return f"an instance of {_type_name(self.type)!r}"
  242. class _NoneConstraint(_Constraint):
  243. """Constraint representing the None singleton."""
  244. def is_satisfied_by(self, val):
  245. return val is None
  246. def __str__(self):
  247. return "None"
  248. class _NanConstraint(_Constraint):
  249. """Constraint representing the indicator `np.nan`."""
  250. def is_satisfied_by(self, val):
  251. return isinstance(val, Real) and math.isnan(val)
  252. def __str__(self):
  253. return "numpy.nan"
  254. class _PandasNAConstraint(_Constraint):
  255. """Constraint representing the indicator `pd.NA`."""
  256. def is_satisfied_by(self, val):
  257. try:
  258. import pandas as pd
  259. return isinstance(val, type(pd.NA)) and pd.isna(val)
  260. except ImportError:
  261. return False
  262. def __str__(self):
  263. return "pandas.NA"
  264. class Options(_Constraint):
  265. """Constraint representing a finite set of instances of a given type.
  266. Parameters
  267. ----------
  268. type : type
  269. options : set
  270. The set of valid scalars.
  271. deprecated : set or None, default=None
  272. A subset of the `options` to mark as deprecated in the string
  273. representation of the constraint.
  274. """
  275. def __init__(self, type, options, *, deprecated=None):
  276. super().__init__()
  277. self.type = type
  278. self.options = options
  279. self.deprecated = deprecated or set()
  280. if self.deprecated - self.options:
  281. raise ValueError("The deprecated options must be a subset of the options.")
  282. def is_satisfied_by(self, val):
  283. return isinstance(val, self.type) and val in self.options
  284. def _mark_if_deprecated(self, option):
  285. """Add a deprecated mark to an option if needed."""
  286. option_str = f"{option!r}"
  287. if option in self.deprecated:
  288. option_str = f"{option_str} (deprecated)"
  289. return option_str
  290. def __str__(self):
  291. options_str = (
  292. f"{', '.join([self._mark_if_deprecated(o) for o in self.options])}"
  293. )
  294. return f"a {_type_name(self.type)} among {{{options_str}}}"
  295. class StrOptions(Options):
  296. """Constraint representing a finite set of strings.
  297. Parameters
  298. ----------
  299. options : set of str
  300. The set of valid strings.
  301. deprecated : set of str or None, default=None
  302. A subset of the `options` to mark as deprecated in the string
  303. representation of the constraint.
  304. """
  305. def __init__(self, options, *, deprecated=None):
  306. super().__init__(type=str, options=options, deprecated=deprecated)
  307. class Interval(_Constraint):
  308. """Constraint representing a typed interval.
  309. Parameters
  310. ----------
  311. type : {numbers.Integral, numbers.Real, RealNotInt}
  312. The set of numbers in which to set the interval.
  313. If RealNotInt, only reals that don't have the integer type
  314. are allowed. For example 1.0 is allowed but 1 is not.
  315. left : float or int or None
  316. The left bound of the interval. None means left bound is -∞.
  317. right : float, int or None
  318. The right bound of the interval. None means right bound is +∞.
  319. closed : {"left", "right", "both", "neither"}
  320. Whether the interval is open or closed. Possible choices are:
  321. - `"left"`: the interval is closed on the left and open on the right.
  322. It is equivalent to the interval `[ left, right )`.
  323. - `"right"`: the interval is closed on the right and open on the left.
  324. It is equivalent to the interval `( left, right ]`.
  325. - `"both"`: the interval is closed.
  326. It is equivalent to the interval `[ left, right ]`.
  327. - `"neither"`: the interval is open.
  328. It is equivalent to the interval `( left, right )`.
  329. Notes
  330. -----
  331. Setting a bound to `None` and setting the interval closed is valid. For instance,
  332. strictly speaking, `Interval(Real, 0, None, closed="both")` corresponds to
  333. `[0, +∞) U {+∞}`.
  334. """
  335. def __init__(self, type, left, right, *, closed):
  336. super().__init__()
  337. self.type = type
  338. self.left = left
  339. self.right = right
  340. self.closed = closed
  341. self._check_params()
  342. def _check_params(self):
  343. if self.type not in (Integral, Real, RealNotInt):
  344. raise ValueError(
  345. "type must be either numbers.Integral, numbers.Real or RealNotInt."
  346. f" Got {self.type} instead."
  347. )
  348. if self.closed not in ("left", "right", "both", "neither"):
  349. raise ValueError(
  350. "closed must be either 'left', 'right', 'both' or 'neither'. "
  351. f"Got {self.closed} instead."
  352. )
  353. if self.type is Integral:
  354. suffix = "for an interval over the integers."
  355. if self.left is not None and not isinstance(self.left, Integral):
  356. raise TypeError(f"Expecting left to be an int {suffix}")
  357. if self.right is not None and not isinstance(self.right, Integral):
  358. raise TypeError(f"Expecting right to be an int {suffix}")
  359. if self.left is None and self.closed in ("left", "both"):
  360. raise ValueError(
  361. f"left can't be None when closed == {self.closed} {suffix}"
  362. )
  363. if self.right is None and self.closed in ("right", "both"):
  364. raise ValueError(
  365. f"right can't be None when closed == {self.closed} {suffix}"
  366. )
  367. else:
  368. if self.left is not None and not isinstance(self.left, Real):
  369. raise TypeError("Expecting left to be a real number.")
  370. if self.right is not None and not isinstance(self.right, Real):
  371. raise TypeError("Expecting right to be a real number.")
  372. if self.right is not None and self.left is not None and self.right <= self.left:
  373. raise ValueError(
  374. f"right can't be less than left. Got left={self.left} and "
  375. f"right={self.right}"
  376. )
  377. def __contains__(self, val):
  378. if np.isnan(val):
  379. return False
  380. left_cmp = operator.lt if self.closed in ("left", "both") else operator.le
  381. right_cmp = operator.gt if self.closed in ("right", "both") else operator.ge
  382. left = -np.inf if self.left is None else self.left
  383. right = np.inf if self.right is None else self.right
  384. if left_cmp(val, left):
  385. return False
  386. if right_cmp(val, right):
  387. return False
  388. return True
  389. def is_satisfied_by(self, val):
  390. if not isinstance(val, self.type):
  391. return False
  392. return val in self
  393. def __str__(self):
  394. type_str = "an int" if self.type is Integral else "a float"
  395. left_bracket = "[" if self.closed in ("left", "both") else "("
  396. left_bound = "-inf" if self.left is None else self.left
  397. right_bound = "inf" if self.right is None else self.right
  398. right_bracket = "]" if self.closed in ("right", "both") else ")"
  399. # better repr if the bounds were given as integers
  400. if not self.type == Integral and isinstance(self.left, Real):
  401. left_bound = float(left_bound)
  402. if not self.type == Integral and isinstance(self.right, Real):
  403. right_bound = float(right_bound)
  404. return (
  405. f"{type_str} in the range "
  406. f"{left_bracket}{left_bound}, {right_bound}{right_bracket}"
  407. )
  408. class _ArrayLikes(_Constraint):
  409. """Constraint representing array-likes"""
  410. def is_satisfied_by(self, val):
  411. return _is_arraylike_not_scalar(val)
  412. def __str__(self):
  413. return "an array-like"
  414. class _SparseMatrices(_Constraint):
  415. """Constraint representing sparse matrices."""
  416. def is_satisfied_by(self, val):
  417. return issparse(val)
  418. def __str__(self):
  419. return "a sparse matrix"
  420. class _Callables(_Constraint):
  421. """Constraint representing callables."""
  422. def is_satisfied_by(self, val):
  423. return callable(val)
  424. def __str__(self):
  425. return "a callable"
  426. class _RandomStates(_Constraint):
  427. """Constraint representing random states.
  428. Convenience class for
  429. [Interval(Integral, 0, 2**32 - 1, closed="both"), np.random.RandomState, None]
  430. """
  431. def __init__(self):
  432. super().__init__()
  433. self._constraints = [
  434. Interval(Integral, 0, 2**32 - 1, closed="both"),
  435. _InstancesOf(np.random.RandomState),
  436. _NoneConstraint(),
  437. ]
  438. def is_satisfied_by(self, val):
  439. return any(c.is_satisfied_by(val) for c in self._constraints)
  440. def __str__(self):
  441. return (
  442. f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
  443. f" {self._constraints[-1]}"
  444. )
  445. class _Booleans(_Constraint):
  446. """Constraint representing boolean likes.
  447. Convenience class for
  448. [bool, np.bool_, Integral (deprecated)]
  449. """
  450. def __init__(self):
  451. super().__init__()
  452. self._constraints = [
  453. _InstancesOf(bool),
  454. _InstancesOf(np.bool_),
  455. _InstancesOf(Integral),
  456. ]
  457. def is_satisfied_by(self, val):
  458. # TODO(1.4) remove support for Integral.
  459. if isinstance(val, Integral) and not isinstance(val, bool):
  460. warnings.warn(
  461. (
  462. "Passing an int for a boolean parameter is deprecated in version"
  463. " 1.2 and won't be supported anymore in version 1.4."
  464. ),
  465. FutureWarning,
  466. )
  467. return any(c.is_satisfied_by(val) for c in self._constraints)
  468. def __str__(self):
  469. return (
  470. f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
  471. f" {self._constraints[-1]}"
  472. )
  473. class _VerboseHelper(_Constraint):
  474. """Helper constraint for the verbose parameter.
  475. Convenience class for
  476. [Interval(Integral, 0, None, closed="left"), bool, numpy.bool_]
  477. """
  478. def __init__(self):
  479. super().__init__()
  480. self._constraints = [
  481. Interval(Integral, 0, None, closed="left"),
  482. _InstancesOf(bool),
  483. _InstancesOf(np.bool_),
  484. ]
  485. def is_satisfied_by(self, val):
  486. return any(c.is_satisfied_by(val) for c in self._constraints)
  487. def __str__(self):
  488. return (
  489. f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
  490. f" {self._constraints[-1]}"
  491. )
  492. class MissingValues(_Constraint):
  493. """Helper constraint for the `missing_values` parameters.
  494. Convenience for
  495. [
  496. Integral,
  497. Interval(Real, None, None, closed="both"),
  498. str, # when numeric_only is False
  499. None, # when numeric_only is False
  500. _NanConstraint(),
  501. _PandasNAConstraint(),
  502. ]
  503. Parameters
  504. ----------
  505. numeric_only : bool, default=False
  506. Whether to consider only numeric missing value markers.
  507. """
  508. def __init__(self, numeric_only=False):
  509. super().__init__()
  510. self.numeric_only = numeric_only
  511. self._constraints = [
  512. _InstancesOf(Integral),
  513. # we use an interval of Real to ignore np.nan that has its own constraint
  514. Interval(Real, None, None, closed="both"),
  515. _NanConstraint(),
  516. _PandasNAConstraint(),
  517. ]
  518. if not self.numeric_only:
  519. self._constraints.extend([_InstancesOf(str), _NoneConstraint()])
  520. def is_satisfied_by(self, val):
  521. return any(c.is_satisfied_by(val) for c in self._constraints)
  522. def __str__(self):
  523. return (
  524. f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
  525. f" {self._constraints[-1]}"
  526. )
  527. class HasMethods(_Constraint):
  528. """Constraint representing objects that expose specific methods.
  529. It is useful for parameters following a protocol and where we don't want to impose
  530. an affiliation to a specific module or class.
  531. Parameters
  532. ----------
  533. methods : str or list of str
  534. The method(s) that the object is expected to expose.
  535. """
  536. @validate_params(
  537. {"methods": [str, list]},
  538. prefer_skip_nested_validation=True,
  539. )
  540. def __init__(self, methods):
  541. super().__init__()
  542. if isinstance(methods, str):
  543. methods = [methods]
  544. self.methods = methods
  545. def is_satisfied_by(self, val):
  546. return all(callable(getattr(val, method, None)) for method in self.methods)
  547. def __str__(self):
  548. if len(self.methods) == 1:
  549. methods = f"{self.methods[0]!r}"
  550. else:
  551. methods = (
  552. f"{', '.join([repr(m) for m in self.methods[:-1]])} and"
  553. f" {self.methods[-1]!r}"
  554. )
  555. return f"an object implementing {methods}"
  556. class _IterablesNotString(_Constraint):
  557. """Constraint representing iterables that are not strings."""
  558. def is_satisfied_by(self, val):
  559. return isinstance(val, Iterable) and not isinstance(val, str)
  560. def __str__(self):
  561. return "an iterable"
  562. class _CVObjects(_Constraint):
  563. """Constraint representing cv objects.
  564. Convenient class for
  565. [
  566. Interval(Integral, 2, None, closed="left"),
  567. HasMethods(["split", "get_n_splits"]),
  568. _IterablesNotString(),
  569. None,
  570. ]
  571. """
  572. def __init__(self):
  573. super().__init__()
  574. self._constraints = [
  575. Interval(Integral, 2, None, closed="left"),
  576. HasMethods(["split", "get_n_splits"]),
  577. _IterablesNotString(),
  578. _NoneConstraint(),
  579. ]
  580. def is_satisfied_by(self, val):
  581. return any(c.is_satisfied_by(val) for c in self._constraints)
  582. def __str__(self):
  583. return (
  584. f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
  585. f" {self._constraints[-1]}"
  586. )
  587. class Hidden:
  588. """Class encapsulating a constraint not meant to be exposed to the user.
  589. Parameters
  590. ----------
  591. constraint : str or _Constraint instance
  592. The constraint to be used internally.
  593. """
  594. def __init__(self, constraint):
  595. self.constraint = constraint
  596. def generate_invalid_param_val(constraint):
  597. """Return a value that does not satisfy the constraint.
  598. Raises a NotImplementedError if there exists no invalid value for this constraint.
  599. This is only useful for testing purpose.
  600. Parameters
  601. ----------
  602. constraint : _Constraint instance
  603. The constraint to generate a value for.
  604. Returns
  605. -------
  606. val : object
  607. A value that does not satisfy the constraint.
  608. """
  609. if isinstance(constraint, StrOptions):
  610. return f"not {' or '.join(constraint.options)}"
  611. if isinstance(constraint, MissingValues):
  612. return np.array([1, 2, 3])
  613. if isinstance(constraint, _VerboseHelper):
  614. return -1
  615. if isinstance(constraint, HasMethods):
  616. return type("HasNotMethods", (), {})()
  617. if isinstance(constraint, _IterablesNotString):
  618. return "a string"
  619. if isinstance(constraint, _CVObjects):
  620. return "not a cv object"
  621. if isinstance(constraint, Interval) and constraint.type is Integral:
  622. if constraint.left is not None:
  623. return constraint.left - 1
  624. if constraint.right is not None:
  625. return constraint.right + 1
  626. # There's no integer outside (-inf, +inf)
  627. raise NotImplementedError
  628. if isinstance(constraint, Interval) and constraint.type in (Real, RealNotInt):
  629. if constraint.left is not None:
  630. return constraint.left - 1e-6
  631. if constraint.right is not None:
  632. return constraint.right + 1e-6
  633. # bounds are -inf, +inf
  634. if constraint.closed in ("right", "neither"):
  635. return -np.inf
  636. if constraint.closed in ("left", "neither"):
  637. return np.inf
  638. # interval is [-inf, +inf]
  639. return np.nan
  640. raise NotImplementedError
  641. def generate_valid_param(constraint):
  642. """Return a value that does satisfy a constraint.
  643. This is only useful for testing purpose.
  644. Parameters
  645. ----------
  646. constraint : Constraint instance
  647. The constraint to generate a value for.
  648. Returns
  649. -------
  650. val : object
  651. A value that does satisfy the constraint.
  652. """
  653. if isinstance(constraint, _ArrayLikes):
  654. return np.array([1, 2, 3])
  655. if isinstance(constraint, _SparseMatrices):
  656. return csr_matrix([[0, 1], [1, 0]])
  657. if isinstance(constraint, _RandomStates):
  658. return np.random.RandomState(42)
  659. if isinstance(constraint, _Callables):
  660. return lambda x: x
  661. if isinstance(constraint, _NoneConstraint):
  662. return None
  663. if isinstance(constraint, _InstancesOf):
  664. if constraint.type is np.ndarray:
  665. # special case for ndarray since it can't be instantiated without arguments
  666. return np.array([1, 2, 3])
  667. if constraint.type in (Integral, Real):
  668. # special case for Integral and Real since they are abstract classes
  669. return 1
  670. return constraint.type()
  671. if isinstance(constraint, _Booleans):
  672. return True
  673. if isinstance(constraint, _VerboseHelper):
  674. return 1
  675. if isinstance(constraint, MissingValues) and constraint.numeric_only:
  676. return np.nan
  677. if isinstance(constraint, MissingValues) and not constraint.numeric_only:
  678. return "missing"
  679. if isinstance(constraint, HasMethods):
  680. return type(
  681. "ValidHasMethods", (), {m: lambda self: None for m in constraint.methods}
  682. )()
  683. if isinstance(constraint, _IterablesNotString):
  684. return [1, 2, 3]
  685. if isinstance(constraint, _CVObjects):
  686. return 5
  687. if isinstance(constraint, Options): # includes StrOptions
  688. for option in constraint.options:
  689. return option
  690. if isinstance(constraint, Interval):
  691. interval = constraint
  692. if interval.left is None and interval.right is None:
  693. return 0
  694. elif interval.left is None:
  695. return interval.right - 1
  696. elif interval.right is None:
  697. return interval.left + 1
  698. else:
  699. if interval.type is Real:
  700. return (interval.left + interval.right) / 2
  701. else:
  702. return interval.left + 1
  703. raise ValueError(f"Unknown constraint type: {constraint}")