jonghanko commited on
Commit
ec2ec75
·
verified ·
1 Parent(s): ab7493f

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/artifacts/_list_artifact_meta.py +102 -0
  2. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__init__.py +110 -0
  3. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/__init__.cpython-310.pyc +0 -0
  4. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/_base.cpython-310.pyc +0 -0
  5. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/_mean_decrease_impurity.cpython-310.pyc +0 -0
  6. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__init__.py +4 -0
  7. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__pycache__/__init__.cpython-310.pyc +0 -0
  8. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__pycache__/_tree.cpython-310.pyc +0 -0
  9. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/_fanova.py +108 -0
  10. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__init__.py +4 -0
  11. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/__init__.cpython-310.pyc +0 -0
  12. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/evaluator.cpython-310.pyc +0 -0
  13. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/scott_parzen_estimator.cpython-310.pyc +0 -0
  14. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/evaluator.py +227 -0
  15. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/scott_parzen_estimator.py +157 -0
  16. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/search_space/__init__.py +12 -0
  17. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/search_space/__pycache__/group_decomposed.cpython-310.pyc +0 -0
  18. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__init__.py +28 -0
  19. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/__init__.cpython-310.pyc +0 -0
  20. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/callback.cpython-310.pyc +0 -0
  21. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/erroreval.cpython-310.pyc +0 -0
  22. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/median_erroreval.cpython-310.pyc +0 -0
  23. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/terminator.cpython-310.pyc +0 -0
  24. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/callback.py +73 -0
  25. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/erroreval.py +129 -0
  26. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__init__.py +0 -0
  27. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/__init__.cpython-310.pyc +0 -0
  28. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/emmr.cpython-310.pyc +0 -0
  29. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/evaluator.cpython-310.pyc +0 -0
  30. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/emmr.py +354 -0
  31. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/evaluator.py +238 -0
  32. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/median_erroreval.py +86 -0
  33. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/terminator.py +136 -0
  34. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/__init__.py +0 -0
  35. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/objectives.py +10 -0
  36. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/pruners.py +11 -0
  37. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/samplers.py +35 -0
  38. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/storages.py +189 -0
  39. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/tempfile_pool.py +46 -0
  40. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/threading.py +22 -0
  41. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/trials.py +34 -0
  42. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/visualization.py +67 -0
  43. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__init__.py +16 -0
  44. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/__init__.cpython-310.pyc +0 -0
  45. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_fixed.cpython-310.pyc +0 -0
  46. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_frozen.cpython-310.pyc +0 -0
  47. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_state.cpython-310.pyc +0 -0
  48. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_trial.cpython-310.pyc +0 -0
  49. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_base.py +132 -0
  50. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_fixed.py +187 -0
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/artifacts/_list_artifact_meta.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import TYPE_CHECKING
5
+
6
+ from optuna.artifacts._upload import ArtifactMeta
7
+ from optuna.artifacts._upload import ARTIFACTS_ATTR_PREFIX
8
+ from optuna.study import Study
9
+ from optuna.trial import FrozenTrial
10
+ from optuna.trial import Trial
11
+
12
+
13
+ if TYPE_CHECKING:
14
+ from optuna.storages import BaseStorage
15
+
16
+
17
+ def get_all_artifact_meta(
18
+ study_or_trial: Trial | FrozenTrial | Study, *, storage: BaseStorage | None = None
19
+ ) -> list[ArtifactMeta]:
20
+ """List the associated artifact information of the provided trial or study.
21
+
22
+ Args:
23
+ study_or_trial:
24
+ A :class:`~optuna.trial.Trial` object, a :class:`~optuna.trial.FrozenTrial`, or
25
+ a :class:`~optuna.study.Study` object.
26
+ storage:
27
+ A storage object. This argument is required only if ``study_or_trial`` is
28
+ :class:`~optuna.trial.FrozenTrial`.
29
+
30
+ Example:
31
+ An example where this function is useful:
32
+
33
+ .. code::
34
+
35
+ import os
36
+
37
+ import optuna
38
+
39
+
40
+ # Get the storage that contains the study of interest.
41
+ storage = optuna.storages.get_storage(storage=...)
42
+
43
+ # Instantiate the artifact store used for the study.
44
+ # Optuna does not provide the API that stores the used artifact store information, so
45
+ # please manage the information in the user side.
46
+ artifact_store = ...
47
+
48
+ # Load study that contains the artifacts of interest.
49
+ study = optuna.load_study(study_name=..., storage=storage)
50
+
51
+ # Fetch the best trial.
52
+ best_trial = study.best_trial
53
+
54
+ # Fetch all the artifact meta connected to the best trial.
55
+ artifact_metas = optuna.artifacts.get_all_artifact_meta(best_trial, storage=storage)
56
+
57
+ download_dir_path = "./best_trial_artifacts/"
58
+ os.makedirs(download_dir_path, exist_ok=True)
59
+
60
+ for artifact_meta in artifact_metas:
61
+ download_file_path = os.path.join(download_dir_path, artifact_meta.filename)
62
+ # Download the artifacts to ``download_file_path``.
63
+ optuna.artifacts.download_artifact(
64
+ artifact_store=artifact_store,
65
+ artifact_id=artifact_meta.artifact_id,
66
+ file_path=download_file_path,
67
+ )
68
+
69
+ Returns:
70
+ The list of artifact meta in the trial or study.
71
+ Each artifact meta includes ``artifact_id``, ``filename``, ``mimetype``, and ``encoding``.
72
+ Note that if :class:`~optuna.study.Study` is provided, we return the information of the
73
+ artifacts uploaded to ``study``, but not to all the trials in the study.
74
+ """
75
+ if isinstance(study_or_trial, Trial) and storage is None:
76
+ storage = study_or_trial.storage
77
+ elif isinstance(study_or_trial, Study) and storage is None:
78
+ storage = study_or_trial._storage
79
+
80
+ if storage is None:
81
+ raise ValueError("storage is required for FrozenTrial.")
82
+
83
+ if isinstance(study_or_trial, (Trial, FrozenTrial)):
84
+ system_attrs = storage.get_trial_system_attrs(study_or_trial._trial_id)
85
+ else:
86
+ system_attrs = storage.get_study_system_attrs(study_or_trial._study_id)
87
+
88
+ artifact_meta_list: list[ArtifactMeta] = []
89
+ for attr_key, attr_json_string in system_attrs.items():
90
+ if not attr_key.startswith(ARTIFACTS_ATTR_PREFIX):
91
+ continue
92
+
93
+ attr_content = json.loads(attr_json_string)
94
+ artifact_meta = ArtifactMeta(
95
+ artifact_id=attr_content["artifact_id"],
96
+ filename=attr_content["filename"],
97
+ mimetype=attr_content["mimetype"],
98
+ encoding=attr_content["encoding"],
99
+ )
100
+ artifact_meta_list.append(artifact_meta)
101
+
102
+ return artifact_meta_list
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__init__.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+
5
+ from optuna._experimental import warn_experimental_argument
6
+ from optuna.importance._base import BaseImportanceEvaluator
7
+ from optuna.importance._fanova import FanovaImportanceEvaluator
8
+ from optuna.importance._mean_decrease_impurity import MeanDecreaseImpurityImportanceEvaluator
9
+ from optuna.importance._ped_anova import PedAnovaImportanceEvaluator
10
+ from optuna.study import Study
11
+ from optuna.trial import FrozenTrial
12
+
13
+
14
+ __all__ = [
15
+ "BaseImportanceEvaluator",
16
+ "FanovaImportanceEvaluator",
17
+ "MeanDecreaseImpurityImportanceEvaluator",
18
+ "PedAnovaImportanceEvaluator",
19
+ "get_param_importances",
20
+ ]
21
+
22
+
23
+ def get_param_importances(
24
+ study: Study,
25
+ *,
26
+ evaluator: BaseImportanceEvaluator | None = None,
27
+ params: list[str] | None = None,
28
+ target: Callable[[FrozenTrial], float] | None = None,
29
+ normalize: bool = True,
30
+ ) -> dict[str, float]:
31
+ """Evaluate parameter importances based on completed trials in the given study.
32
+
33
+ The parameter importances are returned as a dictionary where the keys consist of parameter
34
+ names and their values importances.
35
+ The importances are represented by non-negative floating point numbers, where higher values
36
+ mean that the parameters are more important.
37
+ The returned dictionary is ordered by its values in a descending order.
38
+ By default, the sum of the importance values are normalized to 1.0.
39
+
40
+ If ``params`` is :obj:`None`, all parameter that are present in all of the completed trials are
41
+ assessed.
42
+ This implies that conditional parameters will be excluded from the evaluation.
43
+ To assess the importances of conditional parameters, a :obj:`list` of parameter names can be
44
+ specified via ``params``.
45
+ If specified, only completed trials that contain all of the parameters will be considered.
46
+ If no such trials are found, an error will be raised.
47
+
48
+ If the given study does not contain completed trials, an error will be raised.
49
+
50
+ .. note::
51
+
52
+ If ``params`` is specified as an empty list, an empty dictionary is returned.
53
+
54
+ .. seealso::
55
+
56
+ See :func:`~optuna.visualization.plot_param_importances` to plot importances.
57
+
58
+ Args:
59
+ study:
60
+ An optimized study.
61
+ evaluator:
62
+ An importance evaluator object that specifies which algorithm to base the importance
63
+ assessment on.
64
+ Defaults to
65
+ :class:`~optuna.importance.FanovaImportanceEvaluator`.
66
+ params:
67
+ A list of names of parameters to assess.
68
+ If :obj:`None`, all parameters that are present in all of the completed trials are
69
+ assessed.
70
+ target:
71
+ A function to specify the value to evaluate importances.
72
+ If it is :obj:`None` and ``study`` is being used for single-objective optimization,
73
+ the objective values are used. ``target`` must be specified if ``study`` is being
74
+ used for multi-objective optimization.
75
+
76
+ .. note::
77
+ Specify this argument if ``study`` is being used for multi-objective
78
+ optimization. For example, to get the hyperparameter importance of the first
79
+ objective, use ``target=lambda t: t.values[0]`` for the target parameter.
80
+ normalize:
81
+ A boolean option to specify whether the sum of the importance values should be
82
+ normalized to 1.0.
83
+ Defaults to :obj:`True`.
84
+
85
+ .. note::
86
+ Added in v3.0.0 as an experimental feature. The interface may change in newer
87
+ versions without prior notice. See
88
+ https://github.com/optuna/optuna/releases/tag/v3.0.0.
89
+
90
+ Returns:
91
+ A :obj:`dict` where the keys are parameter names and the values are assessed importances.
92
+
93
+ """
94
+ if evaluator is None:
95
+ evaluator = FanovaImportanceEvaluator()
96
+
97
+ if not isinstance(evaluator, BaseImportanceEvaluator):
98
+ raise TypeError("Evaluator must be a subclass of BaseImportanceEvaluator.")
99
+
100
+ res = evaluator.evaluate(study, params=params, target=target)
101
+ if normalize:
102
+ s = sum(res.values())
103
+ if s == 0.0:
104
+ n_params = len(res)
105
+ return dict((param, 1.0 / n_params) for param in res.keys())
106
+ else:
107
+ return dict((param, value / s) for (param, value) in res.items())
108
+ else:
109
+ warn_experimental_argument("normalize")
110
+ return res
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (4.84 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/_base.cpython-310.pyc ADDED
Binary file (7.35 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/_mean_decrease_impurity.cpython-310.pyc ADDED
Binary file (3.76 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from optuna.importance._fanova._evaluator import FanovaImportanceEvaluator
2
+
3
+
4
+ __all__ = ["FanovaImportanceEvaluator"]
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (361 Bytes). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__pycache__/_tree.cpython-310.pyc ADDED
Binary file (9.44 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/_fanova.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """An implementation of `An Efficient Approach for Assessing Hyperparameter Importance`.
2
+
3
+ See http://proceedings.mlr.press/v32/hutter14.pdf and https://automl.github.io/fanova/cite.html
4
+ for how to cite the original work.
5
+
6
+ This implementation is inspired by the efficient algorithm in
7
+ `fanova` (https://github.com/automl/fanova) and
8
+ `pyrfr` (https://github.com/automl/random_forest_run) by the original authors.
9
+
10
+ Differences include relying on scikit-learn to fit random forests
11
+ (`sklearn.ensemble.RandomForestRegressor`) and that it is otherwise written entirely in Python.
12
+ This stands in contrast to the original implementation which is partially written in C++.
13
+ Since Python runtime overhead may become noticeable, included are instead several
14
+ optimizations, e.g. vectorized NumPy functions to compute the marginals, instead of keeping all
15
+ running statistics. Known cases include assessing categorical features with a larger
16
+ number of choices since each choice is given a unique one-hot encoded raw feature.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import numpy as np
22
+
23
+ from optuna._imports import try_import
24
+ from optuna.importance._fanova._tree import _FanovaTree
25
+
26
+
27
+ with try_import() as _imports:
28
+ from sklearn.ensemble import RandomForestRegressor
29
+
30
+
31
+ class _Fanova:
32
+ def __init__(
33
+ self,
34
+ n_trees: int,
35
+ max_depth: int,
36
+ min_samples_split: int | float,
37
+ min_samples_leaf: int | float,
38
+ seed: int | None,
39
+ ) -> None:
40
+ _imports.check()
41
+
42
+ self._forest = RandomForestRegressor(
43
+ n_estimators=n_trees,
44
+ max_depth=max_depth,
45
+ min_samples_split=min_samples_split,
46
+ min_samples_leaf=min_samples_leaf,
47
+ random_state=seed,
48
+ )
49
+ self._trees: list[_FanovaTree] | None = None
50
+ self._variances: dict[int, np.ndarray] | None = None
51
+ self._column_to_encoded_columns: list[np.ndarray] | None = None
52
+
53
+ def fit(
54
+ self,
55
+ X: np.ndarray,
56
+ y: np.ndarray,
57
+ search_spaces: np.ndarray,
58
+ column_to_encoded_columns: list[np.ndarray],
59
+ ) -> None:
60
+ assert X.shape[0] == y.shape[0]
61
+ assert X.shape[1] == search_spaces.shape[0]
62
+ assert search_spaces.shape[1] == 2
63
+
64
+ self._forest.fit(X, y)
65
+
66
+ self._trees = [_FanovaTree(e.tree_, search_spaces) for e in self._forest.estimators_]
67
+ self._column_to_encoded_columns = column_to_encoded_columns
68
+ self._variances = {}
69
+
70
+ if all(tree.variance == 0 for tree in self._trees):
71
+ # If all trees have 0 variance, we cannot assess any importances.
72
+ # This could occur if for instance `X.shape[0] == 1`.
73
+ raise RuntimeError("Encountered zero total variance in all trees.")
74
+
75
+ def get_importance(self, feature: int) -> tuple[float, float]:
76
+ # Assert that `fit` has been called.
77
+ assert self._trees is not None
78
+ assert self._variances is not None
79
+
80
+ self._compute_variances(feature)
81
+
82
+ fractions: list[float] | np.ndarray = []
83
+
84
+ for tree_index, tree in enumerate(self._trees):
85
+ tree_variance = tree.variance
86
+ if tree_variance > 0.0:
87
+ fraction = self._variances[feature][tree_index] / tree_variance
88
+ fractions = np.append(fractions, fraction)
89
+
90
+ fractions = np.asarray(fractions)
91
+
92
+ return float(fractions.mean()), float(fractions.std())
93
+
94
+ def _compute_variances(self, feature: int) -> None:
95
+ assert self._trees is not None
96
+ assert self._variances is not None
97
+ assert self._column_to_encoded_columns is not None
98
+
99
+ if feature in self._variances:
100
+ return
101
+
102
+ raw_features = self._column_to_encoded_columns[feature]
103
+ variances = np.empty(len(self._trees), dtype=np.float64)
104
+
105
+ for tree_index, tree in enumerate(self._trees):
106
+ marginal_variance = tree.get_marginal_variance(raw_features)
107
+ variances[tree_index] = np.clip(marginal_variance, 0.0, None)
108
+ self._variances[feature] = variances
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from optuna.importance._ped_anova.evaluator import PedAnovaImportanceEvaluator
2
+
3
+
4
+ __all__ = ["PedAnovaImportanceEvaluator"]
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (368 Bytes). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/evaluator.cpython-310.pyc ADDED
Binary file (8.86 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/scott_parzen_estimator.cpython-310.pyc ADDED
Binary file (6.02 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/evaluator.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+ import warnings
5
+
6
+ import numpy as np
7
+
8
+ from optuna._experimental import experimental_class
9
+ from optuna.distributions import BaseDistribution
10
+ from optuna.importance._base import _get_distributions
11
+ from optuna.importance._base import _get_filtered_trials
12
+ from optuna.importance._base import _sort_dict_by_importance
13
+ from optuna.importance._base import BaseImportanceEvaluator
14
+ from optuna.importance._ped_anova.scott_parzen_estimator import _build_parzen_estimator
15
+ from optuna.logging import get_logger
16
+ from optuna.study import Study
17
+ from optuna.study import StudyDirection
18
+ from optuna.trial import FrozenTrial
19
+
20
+
21
+ _logger = get_logger(__name__)
22
+
23
+
24
+ class _QuantileFilter:
25
+ def __init__(
26
+ self,
27
+ quantile: float,
28
+ is_lower_better: bool,
29
+ min_n_top_trials: int,
30
+ target: Callable[[FrozenTrial], float] | None,
31
+ ):
32
+ assert 0 <= quantile <= 1, "quantile must be in [0, 1]."
33
+ assert min_n_top_trials > 0, "min_n_top_trials must be positive."
34
+
35
+ self._quantile = quantile
36
+ self._is_lower_better = is_lower_better
37
+ self._min_n_top_trials = min_n_top_trials
38
+ self._target = target
39
+
40
+ def filter(self, trials: list[FrozenTrial]) -> list[FrozenTrial]:
41
+ target, min_n_top_trials = self._target, self._min_n_top_trials
42
+ sign = 1.0 if self._is_lower_better else -1.0
43
+ loss_values = sign * np.asarray([t.value if target is None else target(t) for t in trials])
44
+ err_msg = "len(trials) must be larger than or equal to min_n_top_trials"
45
+ assert min_n_top_trials <= loss_values.size, err_msg
46
+
47
+ def _quantile(v: np.ndarray, q: float) -> float:
48
+ cutoff_index = int(np.ceil(q * loss_values.size)) - 1
49
+ return float(np.partition(loss_values, cutoff_index)[cutoff_index])
50
+
51
+ cutoff_val = max(
52
+ np.partition(loss_values, min_n_top_trials - 1)[min_n_top_trials - 1],
53
+ # TODO(nabenabe0928): After dropping Python3.10, replace below with
54
+ # np.quantile(loss_values, self._quantile, method="inverted_cdf").
55
+ _quantile(loss_values, self._quantile),
56
+ )
57
+ should_keep_trials = loss_values <= cutoff_val
58
+ return [t for t, should_keep in zip(trials, should_keep_trials) if should_keep]
59
+
60
+
61
+ @experimental_class("3.6.0")
62
+ class PedAnovaImportanceEvaluator(BaseImportanceEvaluator):
63
+ """PED-ANOVA importance evaluator.
64
+
65
+ Implements the PED-ANOVA hyperparameter importance evaluation algorithm.
66
+
67
+ PED-ANOVA fits Parzen estimators of :class:`~optuna.trial.TrialState.COMPLETE` trials better
68
+ than a user-specified baseline. Users can specify the baseline by a quantile.
69
+ The importance can be interpreted as how important each hyperparameter is to get
70
+ the performance better than baseline.
71
+
72
+ For further information about PED-ANOVA algorithm, please refer to the following paper:
73
+
74
+ - `PED-ANOVA: Efficiently Quantifying Hyperparameter Importance in Arbitrary Subspaces
75
+ <https://arxiv.org/abs/2304.10255>`__
76
+
77
+ .. note::
78
+
79
+ The performance of PED-ANOVA depends on how many trials to consider above baseline.
80
+ To stabilize the analysis, it is preferable to include at least 5 trials above baseline.
81
+
82
+ .. note::
83
+
84
+ Please refer to `the original work <https://github.com/nabenabe0928/local-anova>`__.
85
+
86
+ Args:
87
+ baseline_quantile:
88
+ Compute the importance of achieving top-``baseline_quantile`` quantile objective value.
89
+ For example, ``baseline_quantile=0.1`` means that the importances give the information
90
+ of which parameters were important to achieve the top-10% performance during
91
+ optimization.
92
+ evaluate_on_local:
93
+ Whether we measure the importance in the local or global space.
94
+ If :obj:`True`, the importances imply how importance each parameter is during
95
+ optimization. Meanwhile, ``evaluate_on_local=False`` gives the importances in the
96
+ specified search_space. ``evaluate_on_local=True`` is especially useful when users
97
+ modify search space during optimization.
98
+
99
+ Example:
100
+ An example of using PED-ANOVA is as follows:
101
+
102
+ .. testcode::
103
+
104
+ import optuna
105
+ from optuna.importance import PedAnovaImportanceEvaluator
106
+
107
+
108
+ def objective(trial):
109
+ x1 = trial.suggest_float("x1", -10, 10)
110
+ x2 = trial.suggest_float("x2", -10, 10)
111
+ return x1 + x2 / 1000
112
+
113
+
114
+ study = optuna.create_study()
115
+ study.optimize(objective, n_trials=100)
116
+ evaluator = PedAnovaImportanceEvaluator()
117
+ importance = optuna.importance.get_param_importances(study, evaluator=evaluator)
118
+
119
+ """
120
+
121
+ def __init__(
122
+ self,
123
+ *,
124
+ baseline_quantile: float = 0.1,
125
+ evaluate_on_local: bool = True,
126
+ ):
127
+ assert 0.0 <= baseline_quantile <= 1.0, "baseline_quantile must be in [0, 1]."
128
+ self._baseline_quantile = baseline_quantile
129
+ self._evaluate_on_local = evaluate_on_local
130
+
131
+ # Advanced Setups.
132
+ # Discretize a domain [low, high] as `np.linspace(low, high, n_steps)`.
133
+ self._n_steps: int = 50
134
+ # Control the regularization effect by prior.
135
+ self._prior_weight = 1.0
136
+ # How many `trials` must be included in `top_trials`.
137
+ self._min_n_top_trials = 2
138
+
139
+ def _get_top_trials(
140
+ self,
141
+ study: Study,
142
+ trials: list[FrozenTrial],
143
+ params: list[str],
144
+ target: Callable[[FrozenTrial], float] | None,
145
+ ) -> list[FrozenTrial]:
146
+ is_lower_better = study.directions[0] == StudyDirection.MINIMIZE
147
+ if target is not None:
148
+ warnings.warn(
149
+ f"{self.__class__.__name__} computes the importances of params to achieve "
150
+ "low `target` values. If this is not what you want, "
151
+ "please modify target, e.g., by multiplying the output by -1."
152
+ )
153
+ is_lower_better = True
154
+
155
+ top_trials = _QuantileFilter(
156
+ self._baseline_quantile, is_lower_better, self._min_n_top_trials, target
157
+ ).filter(trials)
158
+
159
+ if len(trials) == len(top_trials):
160
+ _logger.warning("All trials are in top trials, which gives equal importances.")
161
+
162
+ return top_trials
163
+
164
+ def _compute_pearson_divergence(
165
+ self,
166
+ param_name: str,
167
+ dist: BaseDistribution,
168
+ top_trials: list[FrozenTrial],
169
+ all_trials: list[FrozenTrial],
170
+ ) -> float:
171
+ # When pdf_all == pdf_top, i.e. all_trials == top_trials, this method will give 0.0.
172
+ prior_weight = self._prior_weight
173
+ pe_top = _build_parzen_estimator(param_name, dist, top_trials, self._n_steps, prior_weight)
174
+ # NOTE: pe_top.n_steps could be different from self._n_steps.
175
+ grids = np.arange(pe_top.n_steps)
176
+ pdf_top = pe_top.pdf(grids) + 1e-12
177
+
178
+ if self._evaluate_on_local: # The importance of param during the study.
179
+ pe_local = _build_parzen_estimator(
180
+ param_name, dist, all_trials, self._n_steps, prior_weight
181
+ )
182
+ pdf_local = pe_local.pdf(grids) + 1e-12
183
+ else: # The importance of param in the search space.
184
+ pdf_local = np.full(pe_top.n_steps, 1.0 / pe_top.n_steps)
185
+
186
+ return float(pdf_local @ ((pdf_top / pdf_local - 1) ** 2))
187
+
188
+ def evaluate(
189
+ self,
190
+ study: Study,
191
+ params: list[str] | None = None,
192
+ *,
193
+ target: Callable[[FrozenTrial], float] | None = None,
194
+ ) -> dict[str, float]:
195
+ dists = _get_distributions(study, params=params)
196
+ if params is None:
197
+ params = list(dists.keys())
198
+
199
+ assert params is not None
200
+ # PED-ANOVA does not support parameter distributions with a single value,
201
+ # because the importance of such params become zero.
202
+ non_single_dists = {name: dist for name, dist in dists.items() if not dist.single()}
203
+ single_dists = {name: dist for name, dist in dists.items() if dist.single()}
204
+ if len(non_single_dists) == 0:
205
+ return {}
206
+
207
+ trials = _get_filtered_trials(study, params=params, target=target)
208
+ n_params = len(non_single_dists)
209
+ # The following should be tested at _get_filtered_trials.
210
+ assert target is not None or max([len(t.values) for t in trials], default=1) == 1
211
+ if len(trials) <= self._min_n_top_trials:
212
+ param_importances = {k: 1.0 / n_params for k in non_single_dists}
213
+ param_importances.update({k: 0.0 for k in single_dists})
214
+ return {k: 0.0 for k in param_importances}
215
+
216
+ top_trials = self._get_top_trials(study, trials, params, target)
217
+ quantile = len(top_trials) / len(trials)
218
+ importance_sum = 0.0
219
+ param_importances = {}
220
+ for param_name, dist in non_single_dists.items():
221
+ param_importances[param_name] = quantile * self._compute_pearson_divergence(
222
+ param_name, dist, top_trials=top_trials, all_trials=trials
223
+ )
224
+ importance_sum += param_importances[param_name]
225
+
226
+ param_importances.update({k: 0.0 for k in single_dists})
227
+ return _sort_dict_by_importance(param_importances)
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/scott_parzen_estimator.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+
5
+ from optuna.distributions import BaseDistribution
6
+ from optuna.distributions import CategoricalDistribution
7
+ from optuna.distributions import FloatDistribution
8
+ from optuna.distributions import IntDistribution
9
+ from optuna.samplers._tpe.parzen_estimator import _ParzenEstimator
10
+ from optuna.samplers._tpe.parzen_estimator import _ParzenEstimatorParameters
11
+ from optuna.samplers._tpe.probability_distributions import _BatchedDiscreteTruncNormDistributions
12
+ from optuna.samplers._tpe.probability_distributions import _BatchedDistributions
13
+ from optuna.trial import FrozenTrial
14
+
15
+
16
+ class _ScottParzenEstimator(_ParzenEstimator):
17
+ """1D ParzenEstimator using the bandwidth selection by Scott's rule."""
18
+
19
+ def __init__(
20
+ self,
21
+ param_name: str,
22
+ dist: IntDistribution | CategoricalDistribution,
23
+ counts: np.ndarray,
24
+ prior_weight: float,
25
+ ):
26
+ assert isinstance(dist, (CategoricalDistribution, IntDistribution))
27
+ assert not isinstance(dist, IntDistribution) or dist.low == 0
28
+ n_choices = dist.high + 1 if isinstance(dist, IntDistribution) else len(dist.choices)
29
+ assert len(counts) == n_choices, counts
30
+
31
+ self._n_steps = len(counts)
32
+ self._param_name = param_name
33
+ self._counts = counts.copy()
34
+ super().__init__(
35
+ observations={param_name: np.arange(self._n_steps)[counts > 0.0]},
36
+ search_space={param_name: dist},
37
+ parameters=_ParzenEstimatorParameters(
38
+ prior_weight=prior_weight,
39
+ consider_magic_clip=False,
40
+ consider_endpoints=False,
41
+ weights=lambda x: np.empty(0),
42
+ multivariate=True,
43
+ categorical_distance_func={},
44
+ ),
45
+ predetermined_weights=counts[counts > 0.0],
46
+ )
47
+
48
+ def _calculate_numerical_distributions(
49
+ self,
50
+ observations: np.ndarray,
51
+ low: float, # The type is actually int, but typing follows the original.
52
+ high: float, # The type is actually int, but typing follows the original.
53
+ step: float | None,
54
+ parameters: _ParzenEstimatorParameters,
55
+ ) -> _BatchedDistributions:
56
+ # NOTE: The Optuna TPE bandwidth selection is too wide for this analysis.
57
+ # So use the Scott's rule by Scott, D.W. (1992),
58
+ # Multivariate Density Estimation: Theory, Practice, and Visualization.
59
+ assert step is not None and np.isclose(step, 1.0), "MyPy redefinition."
60
+
61
+ n_trials = np.sum(self._counts)
62
+ counts_non_zero = self._counts[self._counts > 0]
63
+ weights = counts_non_zero / n_trials
64
+ mus = np.arange(self.n_steps)[self._counts > 0]
65
+ mean_est = mus @ weights
66
+ sigma_est = np.sqrt((mus - mean_est) ** 2 @ counts_non_zero / max(1, n_trials - 1))
67
+
68
+ count_cum = np.cumsum(counts_non_zero)
69
+ idx_q25 = np.searchsorted(count_cum, n_trials // 4, side="left")
70
+ idx_q75 = np.searchsorted(count_cum, n_trials * 3 // 4, side="right")
71
+ interquantile_range = mus[min(mus.size - 1, idx_q75)] - mus[idx_q25]
72
+ sigma_est = 1.059 * min(interquantile_range / 1.34, sigma_est) * n_trials ** (-0.2)
73
+ # To avoid numerical errors. 0.5/1.64 means 1.64sigma (=90%) will fit in the target grid.
74
+ sigma_min = 0.5 / 1.64
75
+ sigmas = np.full_like(mus, max(sigma_est, sigma_min), dtype=np.float64)
76
+ mus = np.append(mus, [0.5 * (low + high)])
77
+ sigmas = np.append(sigmas, [1.0 * (high - low + 1)])
78
+
79
+ return _BatchedDiscreteTruncNormDistributions(
80
+ mu=mus, sigma=sigmas, low=0, high=self.n_steps - 1, step=1
81
+ )
82
+
83
+ @property
84
+ def n_steps(self) -> int:
85
+ return self._n_steps
86
+
87
+ def pdf(self, samples: np.ndarray) -> np.ndarray:
88
+ return np.exp(self.log_pdf({self._param_name: samples}))
89
+
90
+
91
+ def _get_grids_and_grid_indices_of_trials(
92
+ param_name: str,
93
+ dist: IntDistribution | FloatDistribution,
94
+ trials: list[FrozenTrial],
95
+ n_steps: int,
96
+ ) -> tuple[int, np.ndarray]:
97
+ assert isinstance(dist, (FloatDistribution, IntDistribution)), "Unexpected distribution."
98
+ if isinstance(dist, IntDistribution) and dist.log:
99
+ log2_domain_size = int(np.ceil(np.log(dist.high - dist.low + 1) / np.log(2))) + 1
100
+ n_steps = min(log2_domain_size, n_steps)
101
+ elif dist.step is not None:
102
+ assert not dist.log, "log must be False when step is not None."
103
+ n_steps = min(round((dist.high - dist.low) / dist.step) + 1, n_steps)
104
+
105
+ scaler = np.log if dist.log else np.asarray
106
+ grids = np.linspace(scaler(dist.low), scaler(dist.high), n_steps)
107
+ params = scaler([t.params[param_name] for t in trials])
108
+ step_size = grids[1] - grids[0]
109
+ # grids[indices[n] - 1] < param - step_size / 2 <= grids[indices[n]]
110
+ indices = np.searchsorted(grids, params - step_size / 2)
111
+ return grids.size, indices
112
+
113
+
114
+ def _count_numerical_param_in_grid(
115
+ param_name: str,
116
+ dist: IntDistribution | FloatDistribution,
117
+ trials: list[FrozenTrial],
118
+ n_steps: int,
119
+ ) -> np.ndarray:
120
+ n_grids, grid_indices_of_trials = _get_grids_and_grid_indices_of_trials(
121
+ param_name, dist, trials, n_steps
122
+ )
123
+ unique_vals, counts_in_unique = np.unique(grid_indices_of_trials, return_counts=True)
124
+ counts = np.zeros(n_grids, dtype=np.int32)
125
+ counts[unique_vals] += counts_in_unique
126
+ return counts
127
+
128
+
129
+ def _count_categorical_param_in_grid(
130
+ param_name: str, dist: CategoricalDistribution, trials: list[FrozenTrial]
131
+ ) -> np.ndarray:
132
+ cat_indices = [int(dist.to_internal_repr(t.params[param_name])) for t in trials]
133
+ unique_vals, counts_in_unique = np.unique(cat_indices, return_counts=True)
134
+ counts = np.zeros(len(dist.choices), dtype=np.int32)
135
+ counts[unique_vals] += counts_in_unique
136
+ return counts
137
+
138
+
139
+ def _build_parzen_estimator(
140
+ param_name: str,
141
+ dist: BaseDistribution,
142
+ trials: list[FrozenTrial],
143
+ n_steps: int,
144
+ prior_weight: float,
145
+ ) -> _ScottParzenEstimator:
146
+ rounded_dist: IntDistribution | CategoricalDistribution
147
+ if isinstance(dist, (IntDistribution, FloatDistribution)):
148
+ counts = _count_numerical_param_in_grid(param_name, dist, trials, n_steps)
149
+ rounded_dist = IntDistribution(low=0, high=counts.size - 1)
150
+ elif isinstance(dist, CategoricalDistribution):
151
+ counts = _count_categorical_param_in_grid(param_name, dist, trials)
152
+ rounded_dist = dist
153
+ else:
154
+ assert False, f"Got an unknown dist with the type {type(dist)}."
155
+
156
+ # counts.astype(float) is necessary for weight calculation in ParzenEstimator.
157
+ return _ScottParzenEstimator(param_name, rounded_dist, counts.astype(np.float64), prior_weight)
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/search_space/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from optuna.search_space.group_decomposed import _GroupDecomposedSearchSpace
2
+ from optuna.search_space.group_decomposed import _SearchSpaceGroup
3
+ from optuna.search_space.intersection import intersection_search_space
4
+ from optuna.search_space.intersection import IntersectionSearchSpace
5
+
6
+
7
+ __all__ = [
8
+ "_GroupDecomposedSearchSpace",
9
+ "_SearchSpaceGroup",
10
+ "IntersectionSearchSpace",
11
+ "intersection_search_space",
12
+ ]
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/search_space/__pycache__/group_decomposed.cpython-310.pyc ADDED
Binary file (2.95 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from optuna.terminator.callback import TerminatorCallback
2
+ from optuna.terminator.erroreval import BaseErrorEvaluator
3
+ from optuna.terminator.erroreval import CrossValidationErrorEvaluator
4
+ from optuna.terminator.erroreval import report_cross_validation_scores
5
+ from optuna.terminator.erroreval import StaticErrorEvaluator
6
+ from optuna.terminator.improvement.emmr import EMMREvaluator
7
+ from optuna.terminator.improvement.evaluator import BaseImprovementEvaluator
8
+ from optuna.terminator.improvement.evaluator import BestValueStagnationEvaluator
9
+ from optuna.terminator.improvement.evaluator import RegretBoundEvaluator
10
+ from optuna.terminator.median_erroreval import MedianErrorEvaluator
11
+ from optuna.terminator.terminator import BaseTerminator
12
+ from optuna.terminator.terminator import Terminator
13
+
14
+
15
+ __all__ = [
16
+ "TerminatorCallback",
17
+ "BaseErrorEvaluator",
18
+ "CrossValidationErrorEvaluator",
19
+ "report_cross_validation_scores",
20
+ "StaticErrorEvaluator",
21
+ "MedianErrorEvaluator",
22
+ "BaseImprovementEvaluator",
23
+ "BestValueStagnationEvaluator",
24
+ "RegretBoundEvaluator",
25
+ "EMMREvaluator",
26
+ "BaseTerminator",
27
+ "Terminator",
28
+ ]
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.05 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/callback.cpython-310.pyc ADDED
Binary file (3.32 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/erroreval.cpython-310.pyc ADDED
Binary file (5.1 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/median_erroreval.cpython-310.pyc ADDED
Binary file (3.7 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/terminator.cpython-310.pyc ADDED
Binary file (5.63 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/callback.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from optuna._experimental import experimental_class
4
+ from optuna.logging import get_logger
5
+ from optuna.study.study import Study
6
+ from optuna.terminator.terminator import BaseTerminator
7
+ from optuna.terminator.terminator import Terminator
8
+ from optuna.trial import FrozenTrial
9
+
10
+
11
+ _logger = get_logger(__name__)
12
+
13
+
14
+ @experimental_class("3.2.0")
15
+ class TerminatorCallback:
16
+ """A callback that terminates the optimization using Terminator.
17
+
18
+ This class implements a callback which wraps :class:`~optuna.terminator.Terminator`
19
+ so that it can be used with the :func:`~optuna.study.Study.optimize` method.
20
+
21
+ Args:
22
+ terminator:
23
+ A terminator object which determines whether to terminate the optimization by
24
+ assessing the room for optimization and statistical error. Defaults to a
25
+ :class:`~optuna.terminator.Terminator` object with default
26
+ ``improvement_evaluator`` and ``error_evaluator``.
27
+
28
+ Example:
29
+
30
+ .. testcode::
31
+
32
+ from sklearn.datasets import load_wine
33
+ from sklearn.ensemble import RandomForestClassifier
34
+ from sklearn.model_selection import cross_val_score
35
+ from sklearn.model_selection import KFold
36
+
37
+ import optuna
38
+ from optuna.terminator import TerminatorCallback
39
+ from optuna.terminator import report_cross_validation_scores
40
+
41
+
42
+ def objective(trial):
43
+ X, y = load_wine(return_X_y=True)
44
+
45
+ clf = RandomForestClassifier(
46
+ max_depth=trial.suggest_int("max_depth", 2, 32),
47
+ min_samples_split=trial.suggest_float("min_samples_split", 0, 1),
48
+ criterion=trial.suggest_categorical("criterion", ("gini", "entropy")),
49
+ )
50
+
51
+ scores = cross_val_score(clf, X, y, cv=KFold(n_splits=5, shuffle=True))
52
+ report_cross_validation_scores(trial, scores)
53
+ return scores.mean()
54
+
55
+
56
+ study = optuna.create_study(direction="maximize")
57
+ terminator = TerminatorCallback()
58
+ study.optimize(objective, n_trials=50, callbacks=[terminator])
59
+
60
+ .. seealso::
61
+ Please refer to :class:`~optuna.terminator.Terminator` for the details of
62
+ the terminator mechanism.
63
+ """
64
+
65
+ def __init__(self, terminator: BaseTerminator | None = None) -> None:
66
+ self._terminator = terminator or Terminator()
67
+
68
+ def __call__(self, study: Study, trial: FrozenTrial) -> None:
69
+ should_terminate = self._terminator.should_terminate(study=study)
70
+
71
+ if should_terminate:
72
+ _logger.info("The study has been stopped by the terminator.")
73
+ study.stop()
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/erroreval.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import abc
4
+ from typing import cast
5
+
6
+ import numpy as np
7
+
8
+ from optuna._experimental import experimental_class
9
+ from optuna.study import StudyDirection
10
+ from optuna.trial import FrozenTrial
11
+ from optuna.trial import Trial
12
+ from optuna.trial._state import TrialState
13
+
14
+
15
+ _CROSS_VALIDATION_SCORES_KEY = "terminator:cv_scores"
16
+
17
+
18
+ class BaseErrorEvaluator(metaclass=abc.ABCMeta):
19
+ """Base class for error evaluators."""
20
+
21
+ @abc.abstractmethod
22
+ def evaluate(
23
+ self,
24
+ trials: list[FrozenTrial],
25
+ study_direction: StudyDirection,
26
+ ) -> float:
27
+ pass
28
+
29
+
30
+ @experimental_class("3.2.0")
31
+ class CrossValidationErrorEvaluator(BaseErrorEvaluator):
32
+ """An error evaluator for objective functions based on cross-validation.
33
+
34
+ This evaluator evaluates the objective function's statistical error, which comes from the
35
+ randomness of dataset. This evaluator assumes that the objective function is the average of
36
+ the cross-validation and uses the scaled variance of the cross-validation scores in the best
37
+ trial at the moment as the statistical error.
38
+
39
+ """
40
+
41
+ def evaluate(
42
+ self,
43
+ trials: list[FrozenTrial],
44
+ study_direction: StudyDirection,
45
+ ) -> float:
46
+ """Evaluate the statistical error of the objective function based on cross-validation.
47
+
48
+ Args:
49
+ trials:
50
+ A list of trials to consider. The best trial in ``trials`` is used to compute the
51
+ statistical error.
52
+
53
+ study_direction:
54
+ The direction of the study.
55
+
56
+ Returns:
57
+ A float representing the statistical error of the objective function.
58
+
59
+ """
60
+ trials = [trial for trial in trials if trial.state == TrialState.COMPLETE]
61
+ assert len(trials) > 0
62
+
63
+ if study_direction == StudyDirection.MAXIMIZE:
64
+ best_trial = max(trials, key=lambda t: cast(float, t.value))
65
+ else:
66
+ best_trial = min(trials, key=lambda t: cast(float, t.value))
67
+
68
+ best_trial_attrs = best_trial.system_attrs
69
+ if _CROSS_VALIDATION_SCORES_KEY in best_trial_attrs:
70
+ cv_scores = best_trial_attrs[_CROSS_VALIDATION_SCORES_KEY]
71
+ else:
72
+ raise ValueError(
73
+ "Cross-validation scores have not been reported. Please call "
74
+ "`report_cross_validation_scores(trial, scores)` during a trial and pass the "
75
+ "list of scores as `scores`."
76
+ )
77
+
78
+ k = len(cv_scores)
79
+ assert k > 1, "Should be guaranteed by `report_cross_validation_scores`."
80
+ scale = 1 / k + 1 / (k - 1)
81
+
82
+ var = scale * np.var(cv_scores)
83
+ std = np.sqrt(var)
84
+
85
+ return float(std)
86
+
87
+
88
+ @experimental_class("3.2.0")
89
+ def report_cross_validation_scores(trial: Trial, scores: list[float]) -> None:
90
+ """A function to report cross-validation scores of a trial.
91
+
92
+ This function should be called within the objective function to report the cross-validation
93
+ scores. The reported scores are used to evaluate the statistical error for termination
94
+ judgement.
95
+
96
+ Args:
97
+ trial:
98
+ A :class:`~optuna.trial.Trial` object to report the cross-validation scores.
99
+ scores:
100
+ The cross-validation scores of the trial.
101
+
102
+ """
103
+ if len(scores) <= 1:
104
+ raise ValueError("The length of `scores` is expected to be greater than one.")
105
+ trial.storage.set_trial_system_attr(trial._trial_id, _CROSS_VALIDATION_SCORES_KEY, scores)
106
+
107
+
108
+ @experimental_class("3.2.0")
109
+ class StaticErrorEvaluator(BaseErrorEvaluator):
110
+ """An error evaluator that always returns a constant value.
111
+
112
+ This evaluator can be used to terminate the optimization when the evaluated improvement
113
+ potential is below the fixed threshold.
114
+
115
+ Args:
116
+ constant:
117
+ A user-specified constant value to always return as an error estimate.
118
+
119
+ """
120
+
121
+ def __init__(self, constant: float) -> None:
122
+ self._constant = constant
123
+
124
+ def evaluate(
125
+ self,
126
+ trials: list[FrozenTrial],
127
+ study_direction: StudyDirection,
128
+ ) -> float:
129
+ return self._constant
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__init__.py ADDED
File without changes
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (257 Bytes). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/emmr.cpython-310.pyc ADDED
Binary file (9.45 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/evaluator.cpython-310.pyc ADDED
Binary file (9.35 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/emmr.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import sys
5
+ from typing import cast
6
+ from typing import TYPE_CHECKING
7
+ import warnings
8
+
9
+ import numpy as np
10
+
11
+ from optuna._experimental import experimental_class
12
+ from optuna.samplers._lazy_random_state import LazyRandomState
13
+ from optuna.search_space import intersection_search_space
14
+ from optuna.study import StudyDirection
15
+ from optuna.terminator.improvement.evaluator import _compute_standardized_regret_bound
16
+ from optuna.terminator.improvement.evaluator import BaseImprovementEvaluator
17
+ from optuna.trial import FrozenTrial
18
+ from optuna.trial import TrialState
19
+
20
+
21
+ if TYPE_CHECKING:
22
+ import scipy.stats as scipy_stats
23
+ import torch
24
+
25
+ from optuna._gp import acqf as acqf_module
26
+ from optuna._gp import gp
27
+ from optuna._gp import prior
28
+ from optuna._gp import search_space as gp_search_space
29
+ else:
30
+ from optuna._imports import _LazyImport
31
+
32
+ torch = _LazyImport("torch")
33
+ gp = _LazyImport("optuna._gp.gp")
34
+ acqf_module = _LazyImport("optuna._gp.acqf")
35
+ prior = _LazyImport("optuna._gp.prior")
36
+ gp_search_space = _LazyImport("optuna._gp.search_space")
37
+ scipy_stats = _LazyImport("scipy.stats")
38
+
39
+ MARGIN_FOR_NUMARICAL_STABILITY = 0.1
40
+
41
+
42
+ @experimental_class("4.0.0")
43
+ class EMMREvaluator(BaseImprovementEvaluator):
44
+ """Evaluates a kind of regrets, called the Expected Minimum Model Regret(EMMR).
45
+
46
+ EMMR is an upper bound of "expected minimum simple regret" in the optimization process.
47
+
48
+ Expected minimum simple regret is a quantity that converges to zero only if the
49
+ optimization process has found the global optima.
50
+
51
+ For further information about expected minimum simple regret and the algorithm,
52
+ please refer to the following paper:
53
+
54
+ - `A stopping criterion for Bayesian optimization by the gap of expected minimum simple
55
+ regrets <https://proceedings.mlr.press/v206/ishibashi23a.html>`__
56
+
57
+ Also, there is our blog post explaining this evaluator:
58
+
59
+ - `Introducing A New Terminator: Early Termination of Black-box Optimization Based on
60
+ Expected Minimum Model Regret
61
+ <https://medium.com/optuna/introducing-a-new-terminator-early-termination-of-black-box-optimization-based-on-expected-9a660774fcdb>`__
62
+
63
+ Args:
64
+ deterministic_objective:
65
+ A boolean value which indicates whether the objective function is deterministic.
66
+ Default is :obj:`False`.
67
+ delta:
68
+ A float number related to the criterion for termination. Default to 0.1.
69
+ For further information about this parameter, please see the aforementioned paper.
70
+ min_n_trials:
71
+ A minimum number of complete trials to compute the criterion. Default to 2.
72
+ seed:
73
+ A random seed for EMMREvaluator.
74
+
75
+ Example:
76
+
77
+ .. testcode::
78
+
79
+ import optuna
80
+ from optuna.terminator import EMMREvaluator
81
+ from optuna.terminator import MedianErrorEvaluator
82
+ from optuna.terminator import Terminator
83
+
84
+ sampler = optuna.samplers.TPESampler(seed=0)
85
+ study = optuna.create_study(sampler=sampler, direction="minimize")
86
+ emmr_improvement_evaluator = EMMREvaluator()
87
+ median_error_evaluator = MedianErrorEvaluator(emmr_improvement_evaluator)
88
+ terminator = Terminator(
89
+ improvement_evaluator=emmr_improvement_evaluator,
90
+ error_evaluator=median_error_evaluator,
91
+ )
92
+
93
+
94
+ for i in range(1000):
95
+ trial = study.ask()
96
+
97
+ ys = [trial.suggest_float(f"x{i}", -10.0, 10.0) for i in range(5)]
98
+ value = sum(ys[i] ** 2 for i in range(5))
99
+
100
+ study.tell(trial, value)
101
+
102
+ if terminator.should_terminate(study):
103
+ # Terminated by Optuna Terminator!
104
+ break
105
+
106
+ """
107
+
108
+ def __init__(
109
+ self,
110
+ deterministic_objective: bool = False,
111
+ delta: float = 0.1,
112
+ min_n_trials: int = 2,
113
+ seed: int | None = None,
114
+ ) -> None:
115
+ if min_n_trials <= 1 or not np.isfinite(min_n_trials):
116
+ raise ValueError("`min_n_trials` is expected to be a finite integer more than one.")
117
+
118
+ self._deterministic = deterministic_objective
119
+ self._delta = delta
120
+ self.min_n_trials = min_n_trials
121
+ self._rng = LazyRandomState(seed)
122
+
123
+ def evaluate(self, trials: list[FrozenTrial], study_direction: StudyDirection) -> float:
124
+
125
+ optuna_search_space = intersection_search_space(trials)
126
+ complete_trials = [t for t in trials if t.state == TrialState.COMPLETE]
127
+
128
+ if len(complete_trials) < self.min_n_trials:
129
+ return sys.float_info.max * MARGIN_FOR_NUMARICAL_STABILITY # Do not terminate.
130
+
131
+ search_space = gp_search_space.SearchSpace(optuna_search_space)
132
+ normalized_params = search_space.get_normalized_params(complete_trials)
133
+ if not search_space.dim:
134
+ warnings.warn(
135
+ f"{self.__class__.__name__} cannot consider any search space."
136
+ "Termination will never occur in this study."
137
+ )
138
+ return sys.float_info.max * MARGIN_FOR_NUMARICAL_STABILITY # Do not terminate.
139
+
140
+ len_trials = len(complete_trials)
141
+ assert normalized_params.shape == (len_trials, search_space.dim)
142
+
143
+ # _gp module assumes that optimization direction is maximization
144
+ sign = -1 if study_direction == StudyDirection.MINIMIZE else 1
145
+ score_vals = np.array([cast(float, t.value) for t in complete_trials]) * sign
146
+ score_vals = gp.warn_and_convert_inf(score_vals)
147
+ standarized_score_vals = (score_vals - score_vals.mean()) / max(
148
+ sys.float_info.min, score_vals.std()
149
+ )
150
+
151
+ assert len(standarized_score_vals) == len(normalized_params)
152
+
153
+ gpr_t1 = gp.fit_kernel_params( # Fit kernel with up to (t-1)-th observation
154
+ X=normalized_params[..., :-1, :],
155
+ Y=standarized_score_vals[:-1],
156
+ is_categorical=search_space.is_categorical,
157
+ log_prior=prior.default_log_prior,
158
+ minimum_noise=prior.DEFAULT_MINIMUM_NOISE_VAR,
159
+ gpr_cache=None,
160
+ deterministic_objective=self._deterministic,
161
+ )
162
+
163
+ gpr_t = gp.fit_kernel_params( # Fit kernel with up to t-th observation
164
+ X=normalized_params,
165
+ Y=standarized_score_vals,
166
+ is_categorical=search_space.is_categorical,
167
+ log_prior=prior.default_log_prior,
168
+ minimum_noise=prior.DEFAULT_MINIMUM_NOISE_VAR,
169
+ gpr_cache=gpr_t1,
170
+ deterministic_objective=self._deterministic,
171
+ )
172
+
173
+ theta_t_star_index = int(np.argmax(standarized_score_vals))
174
+ theta_t1_star_index = int(np.argmax(standarized_score_vals[:-1]))
175
+ theta_t_star = normalized_params[theta_t_star_index, :]
176
+ theta_t1_star = normalized_params[theta_t1_star_index, :]
177
+
178
+ cov_t_between_theta_t_star_and_theta_t1_star = _compute_gp_posterior_cov_two_thetas(
179
+ search_space,
180
+ normalized_params,
181
+ standarized_score_vals,
182
+ gpr_t,
183
+ theta_t_star_index,
184
+ theta_t1_star_index,
185
+ )
186
+
187
+ mu_t1_theta_t_with_nu_t, variance_t1_theta_t_with_nu_t = _compute_gp_posterior(
188
+ search_space,
189
+ normalized_params[:-1, :],
190
+ standarized_score_vals[:-1],
191
+ normalized_params[-1, :],
192
+ gpr_t,
193
+ # Use gpr_t instead of gpr_t1.
194
+ # Use "t" under the assumption that "t" and "t1" are approximately the same.
195
+ # This is because kernel should same when computing KLD.
196
+ # For detailed information, please see section 4.4 of the paper:
197
+ # https://proceedings.mlr.press/v206/ishibashi23a/ishibashi23a.pdf
198
+ )
199
+ _, variance_t_theta_t1_star = _compute_gp_posterior(
200
+ search_space,
201
+ normalized_params,
202
+ standarized_score_vals,
203
+ theta_t1_star,
204
+ gpr_t,
205
+ )
206
+ mu_t_theta_t_star, variance_t_theta_t_star = _compute_gp_posterior(
207
+ search_space,
208
+ normalized_params,
209
+ standarized_score_vals,
210
+ theta_t_star,
211
+ gpr_t,
212
+ )
213
+ mu_t1_theta_t1_star, _ = _compute_gp_posterior(
214
+ search_space,
215
+ normalized_params[:-1, :],
216
+ standarized_score_vals[:-1],
217
+ theta_t1_star,
218
+ gpr_t1,
219
+ )
220
+
221
+ y_t = standarized_score_vals[-1]
222
+ kappa_t1 = _compute_standardized_regret_bound(
223
+ gpr_t1,
224
+ search_space,
225
+ normalized_params[:-1, :],
226
+ standarized_score_vals[:-1],
227
+ self._delta,
228
+ rng=self._rng.rng,
229
+ )
230
+
231
+ theorem1_delta_mu_t_star = mu_t1_theta_t1_star - mu_t_theta_t_star
232
+
233
+ alg1_delta_r_tilde_t_term1 = theorem1_delta_mu_t_star
234
+
235
+ theorem1_v = math.sqrt(
236
+ max(
237
+ 1e-10,
238
+ variance_t_theta_t_star
239
+ - 2.0 * cov_t_between_theta_t_star_and_theta_t1_star
240
+ + variance_t_theta_t1_star,
241
+ )
242
+ )
243
+ theorem1_g = (mu_t_theta_t_star - mu_t1_theta_t1_star) / theorem1_v
244
+
245
+ alg1_delta_r_tilde_t_term2 = theorem1_v * scipy_stats.norm.pdf(theorem1_g)
246
+ alg1_delta_r_tilde_t_term3 = theorem1_v * theorem1_g * scipy_stats.norm.cdf(theorem1_g)
247
+
248
+ _lambda = prior.DEFAULT_MINIMUM_NOISE_VAR**-1
249
+ eq4_rhs_term1 = 0.5 * math.log(1.0 + _lambda * variance_t1_theta_t_with_nu_t)
250
+ eq4_rhs_term2 = (
251
+ -0.5 * variance_t1_theta_t_with_nu_t / (variance_t1_theta_t_with_nu_t + _lambda**-1)
252
+ )
253
+ eq4_rhs_term3 = (
254
+ 0.5
255
+ * variance_t1_theta_t_with_nu_t
256
+ * (y_t - mu_t1_theta_t_with_nu_t) ** 2
257
+ / (variance_t1_theta_t_with_nu_t + _lambda**-1) ** 2
258
+ )
259
+
260
+ alg1_delta_r_tilde_t_term4 = kappa_t1 * math.sqrt(
261
+ 0.5 * (eq4_rhs_term1 + eq4_rhs_term2 + eq4_rhs_term3)
262
+ )
263
+
264
+ return min(
265
+ sys.float_info.max * 0.5,
266
+ alg1_delta_r_tilde_t_term1
267
+ + alg1_delta_r_tilde_t_term2
268
+ + alg1_delta_r_tilde_t_term3
269
+ + alg1_delta_r_tilde_t_term4,
270
+ )
271
+
272
+
273
+ def _compute_gp_posterior(
274
+ search_space: gp_search_space.SearchSpace,
275
+ X: np.ndarray,
276
+ Y: np.ndarray,
277
+ x_params: np.ndarray,
278
+ gpr: gp.GPRegressor,
279
+ ) -> tuple[float, float]: # mean, var
280
+ mean_tensor, var_tensor = gpr.posterior(
281
+ torch.from_numpy(x_params), # best_params or normalized_params[..., -1, :]),
282
+ )
283
+ mean = mean_tensor.detach().numpy().flatten()
284
+ var = var_tensor.detach().numpy().flatten()
285
+ assert len(mean) == 1 and len(var) == 1
286
+ return float(mean[0]), float(var[0])
287
+
288
+
289
+ def _posterior_of_batched_theta(
290
+ gpr: gp.GPRegressor,
291
+ X: torch.Tensor, # [len(trials), len(params)]
292
+ cov_Y_Y_inv: torch.Tensor, # [len(trials), len(trials)]
293
+ cov_Y_Y_inv_Y: torch.Tensor, # [len(trials)]
294
+ theta: torch.Tensor, # [batch, len(params)]
295
+ ) -> tuple[torch.Tensor, torch.Tensor]: # (mean: [(batch,)], var: [(batch,batch)])
296
+
297
+ assert len(X.shape) == 2
298
+ len_trials, len_params = X.shape
299
+ assert len(theta.shape) == 2
300
+ len_batch = theta.shape[0]
301
+ assert theta.shape == (len_batch, len_params)
302
+ assert cov_Y_Y_inv.shape == (len_trials, len_trials)
303
+ assert cov_Y_Y_inv_Y.shape == (len_trials,)
304
+
305
+ cov_ftheta_fX = gpr.kernel(theta[..., None, :], X)[..., 0, :]
306
+ assert cov_ftheta_fX.shape == (len_batch, len_trials)
307
+ cov_ftheta_ftheta = gpr.kernel(theta[..., None, :], theta)[..., 0, :]
308
+ assert cov_ftheta_ftheta.shape == (len_batch, len_batch)
309
+
310
+ assert torch.allclose(cov_ftheta_ftheta.diag(), gpr.kernel_scale)
311
+ assert torch.allclose(cov_ftheta_ftheta, cov_ftheta_ftheta.T)
312
+
313
+ mean = cov_ftheta_fX @ cov_Y_Y_inv_Y
314
+ assert mean.shape == (len_batch,)
315
+ var = cov_ftheta_ftheta - cov_ftheta_fX @ cov_Y_Y_inv @ cov_ftheta_fX.T
316
+ assert var.shape == (len_batch, len_batch)
317
+
318
+ # We need to clamp the variance to avoid negative values due to numerical errors.
319
+ return mean, torch.clamp(var, min=0.0)
320
+
321
+
322
+ def _compute_gp_posterior_cov_two_thetas(
323
+ search_space: gp_search_space.SearchSpace,
324
+ normalized_params: np.ndarray,
325
+ standarized_score_vals: np.ndarray,
326
+ gpr: gp.GPRegressor,
327
+ theta1_index: int,
328
+ theta2_index: int,
329
+ ) -> float: # cov
330
+
331
+ if theta1_index == theta2_index:
332
+ return _compute_gp_posterior(
333
+ search_space,
334
+ normalized_params,
335
+ standarized_score_vals,
336
+ normalized_params[theta1_index],
337
+ gpr,
338
+ )[1]
339
+
340
+ assert normalized_params.shape[0] == standarized_score_vals.shape[0]
341
+
342
+ cov_Y_Y_inv = gpr._cov_Y_Y_inv
343
+ cov_Y_Y_inv_Y = gpr._cov_Y_Y_inv_Y
344
+ assert cov_Y_Y_inv is not None and cov_Y_Y_inv_Y is not None
345
+ _, var = _posterior_of_batched_theta(
346
+ gpr,
347
+ gpr._X_train,
348
+ cov_Y_Y_inv,
349
+ cov_Y_Y_inv_Y,
350
+ torch.from_numpy(normalized_params[[theta1_index, theta2_index]]),
351
+ )
352
+ assert var.shape == (2, 2)
353
+ var = var.detach().numpy()[0, 1]
354
+ return float(var)
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/evaluator.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import abc
4
+ from typing import TYPE_CHECKING
5
+
6
+ import numpy as np
7
+
8
+ from optuna._experimental import experimental_class
9
+ from optuna.distributions import BaseDistribution
10
+ from optuna.samplers._lazy_random_state import LazyRandomState
11
+ from optuna.search_space import intersection_search_space
12
+ from optuna.study import StudyDirection
13
+ from optuna.trial import FrozenTrial
14
+ from optuna.trial import TrialState
15
+
16
+
17
+ if TYPE_CHECKING:
18
+
19
+ from optuna._gp import acqf as acqf_module
20
+ from optuna._gp import gp
21
+ from optuna._gp import optim_sample
22
+ from optuna._gp import prior
23
+ from optuna._gp import search_space as gp_search_space
24
+ else:
25
+ from optuna._imports import _LazyImport
26
+
27
+ gp = _LazyImport("optuna._gp.gp")
28
+ optim_sample = _LazyImport("optuna._gp.optim_sample")
29
+ acqf_module = _LazyImport("optuna._gp.acqf")
30
+ prior = _LazyImport("optuna._gp.prior")
31
+ gp_search_space = _LazyImport("optuna._gp.search_space")
32
+
33
+ DEFAULT_TOP_TRIALS_RATIO = 0.5
34
+ DEFAULT_MIN_N_TRIALS = 20
35
+
36
+
37
+ def _get_beta(n_params: int, n_trials: int, delta: float = 0.1) -> float:
38
+ # TODO(nabenabe0928): Check the original implementation to verify.
39
+ # Especially, |D| seems to be the domain size, but not the dimension based on Theorem 1.
40
+ beta = 2 * np.log(n_params * n_trials**2 * np.pi**2 / 6 / delta)
41
+
42
+ # The following div is according to the original paper: "We then further scale it down
43
+ # by a factor of 5 as defined in the experiments in
44
+ # `Srinivas et al. (2010) <https://dl.acm.org/doi/10.5555/3104322.3104451>`__"
45
+ beta /= 5
46
+
47
+ return beta
48
+
49
+
50
+ def _compute_standardized_regret_bound(
51
+ gpr: gp.GPRegressor,
52
+ search_space: gp_search_space.SearchSpace,
53
+ normalized_top_n_params: np.ndarray,
54
+ standarized_top_n_values: np.ndarray,
55
+ delta: float = 0.1,
56
+ optimize_n_samples: int = 2048,
57
+ rng: np.random.RandomState | None = None,
58
+ ) -> float:
59
+ """
60
+ # In the original paper, f(x) was intended to be minimized, but here we would like to
61
+ # maximize f(x). Hence, the following changes happen:
62
+ # 1. min(ucb) over top trials becomes max(lcb) over top trials, and
63
+ # 2. min(lcb) over the search space becomes max(ucb) over the search space, and
64
+ # 3. Regret bound becomes max(ucb) over the search space minus max(lcb) over top trials.
65
+ """
66
+
67
+ n_trials, n_params = normalized_top_n_params.shape
68
+
69
+ # calculate max_ucb
70
+ beta = _get_beta(n_params, n_trials, delta)
71
+ ucb_acqf = acqf_module.UCB(gpr, search_space, beta)
72
+ # UCB over the search space. (Original: LCB over the search space. See Change 1 above.)
73
+ standardized_ucb_value = max(
74
+ ucb_acqf.eval_acqf_no_grad(normalized_top_n_params).max(),
75
+ optim_sample.optimize_acqf_sample(ucb_acqf, n_samples=optimize_n_samples, rng=rng)[1],
76
+ )
77
+
78
+ # calculate min_lcb
79
+ lcb_acqf = acqf_module.LCB(gpr=gpr, search_space=search_space, beta=beta)
80
+ # LCB over the top trials. (Original: UCB over the top trials. See Change 2 above.)
81
+ standardized_lcb_value = np.max(lcb_acqf.eval_acqf_no_grad(normalized_top_n_params))
82
+
83
+ # max(UCB) - max(LCB). (Original: min(UCB) - min(LCB). See Change 3 above.)
84
+ return standardized_ucb_value - standardized_lcb_value # standardized regret bound
85
+
86
+
87
+ @experimental_class("3.2.0")
88
+ class BaseImprovementEvaluator(metaclass=abc.ABCMeta):
89
+ """Base class for improvement evaluators."""
90
+
91
+ @abc.abstractmethod
92
+ def evaluate(self, trials: list[FrozenTrial], study_direction: StudyDirection) -> float:
93
+ pass
94
+
95
+
96
+ @experimental_class("3.2.0")
97
+ class RegretBoundEvaluator(BaseImprovementEvaluator):
98
+ """An error evaluator for upper bound on the regret with high-probability confidence.
99
+
100
+ This evaluator evaluates the regret of current best solution, which defined as the difference
101
+ between the objective value of the best solution and of the global optimum. To be specific,
102
+ this evaluator calculates the upper bound on the regret based on the fact that empirical
103
+ estimator of the objective function is bounded by lower and upper confidence bounds with
104
+ high probability under the Gaussian process model assumption.
105
+
106
+ Args:
107
+ top_trials_ratio:
108
+ A ratio of top trials to be considered when estimating the regret. Default to 0.5.
109
+ min_n_trials:
110
+ A minimum number of complete trials to estimate the regret. Default to 20.
111
+ seed:
112
+ Seed for random number generator.
113
+
114
+ For further information about this evaluator, please refer to the following paper:
115
+
116
+ - `Automatic Termination for Hyperparameter Optimization <https://proceedings.mlr.press/v188/makarova22a.html>`__
117
+ """ # NOQA: E501
118
+
119
+ def __init__(
120
+ self,
121
+ top_trials_ratio: float = DEFAULT_TOP_TRIALS_RATIO,
122
+ min_n_trials: int = DEFAULT_MIN_N_TRIALS,
123
+ seed: int | None = None,
124
+ ) -> None:
125
+ self._top_trials_ratio = top_trials_ratio
126
+ self._min_n_trials = min_n_trials
127
+ self._log_prior = prior.default_log_prior
128
+ self._minimum_noise = prior.DEFAULT_MINIMUM_NOISE_VAR
129
+ self._optimize_n_samples = 2048
130
+ self._rng = LazyRandomState(seed)
131
+
132
+ def _get_top_n(
133
+ self, normalized_params: np.ndarray, values: np.ndarray
134
+ ) -> tuple[np.ndarray, np.ndarray]:
135
+ assert len(normalized_params) == len(values)
136
+ n_trials = len(normalized_params)
137
+ top_n = np.clip(int(n_trials * self._top_trials_ratio), self._min_n_trials, n_trials)
138
+ top_n_val = np.partition(values, n_trials - top_n)[n_trials - top_n]
139
+ top_n_mask = values >= top_n_val
140
+ return normalized_params[top_n_mask], values[top_n_mask]
141
+
142
+ def evaluate(self, trials: list[FrozenTrial], study_direction: StudyDirection) -> float:
143
+ optuna_search_space = intersection_search_space(trials)
144
+ self._validate_input(trials, optuna_search_space)
145
+
146
+ complete_trials = [t for t in trials if t.state == TrialState.COMPLETE]
147
+
148
+ # _gp module assumes that optimization direction is maximization
149
+ sign = -1 if study_direction == StudyDirection.MINIMIZE else 1
150
+ values = np.array([t.value for t in complete_trials]) * sign
151
+ search_space = gp_search_space.SearchSpace(optuna_search_space)
152
+ normalized_params = search_space.get_normalized_params(complete_trials)
153
+ normalized_top_n_params, top_n_values = self._get_top_n(normalized_params, values)
154
+ top_n_values_mean = top_n_values.mean()
155
+ top_n_values_std = max(1e-10, top_n_values.std())
156
+ standarized_top_n_values = (top_n_values - top_n_values_mean) / top_n_values_std
157
+
158
+ gpr = gp.fit_kernel_params(
159
+ X=normalized_top_n_params,
160
+ Y=standarized_top_n_values,
161
+ is_categorical=search_space.is_categorical,
162
+ log_prior=self._log_prior,
163
+ minimum_noise=self._minimum_noise,
164
+ # TODO(contramundum53): Add option to specify this.
165
+ deterministic_objective=False,
166
+ # TODO(y0z): Add `kernel_params_cache` to speedup.
167
+ gpr_cache=None,
168
+ )
169
+
170
+ standardized_regret_bound = _compute_standardized_regret_bound(
171
+ gpr,
172
+ search_space,
173
+ normalized_top_n_params,
174
+ standarized_top_n_values,
175
+ rng=self._rng.rng,
176
+ )
177
+ return standardized_regret_bound * top_n_values_std # regret bound
178
+
179
+ @classmethod
180
+ def _validate_input(
181
+ cls, trials: list[FrozenTrial], search_space: dict[str, BaseDistribution]
182
+ ) -> None:
183
+ if len([t for t in trials if t.state == TrialState.COMPLETE]) == 0:
184
+ raise ValueError(
185
+ "Because no trial has been completed yet, the regret bound cannot be evaluated."
186
+ )
187
+
188
+ if len(search_space) == 0:
189
+ raise ValueError(
190
+ "The intersection search space is empty. This condition is not supported by "
191
+ f"{cls.__name__}."
192
+ )
193
+
194
+
195
+ @experimental_class("3.4.0")
196
+ class BestValueStagnationEvaluator(BaseImprovementEvaluator):
197
+ """Evaluates the stagnation period of the best value in an optimization process.
198
+
199
+ This class is initialized with a maximum stagnation period (``max_stagnation_trials``)
200
+ and is designed to evaluate the remaining trials before reaching this maximum period
201
+ of allowed stagnation. If this remaining trials reach zero, the trial terminates.
202
+ Therefore, the default error evaluator is instantiated by ``StaticErrorEvaluator(const=0)``.
203
+
204
+ Args:
205
+ max_stagnation_trials:
206
+ The maximum number of trials allowed for stagnation.
207
+ """
208
+
209
+ def __init__(self, max_stagnation_trials: int = 30) -> None:
210
+ if max_stagnation_trials < 0:
211
+ raise ValueError("The maximum number of stagnant trials must not be negative.")
212
+ self._max_stagnation_trials = max_stagnation_trials
213
+
214
+ def evaluate(self, trials: list[FrozenTrial], study_direction: StudyDirection) -> float:
215
+ self._validate_input(trials)
216
+ is_maximize_direction = True if (study_direction == StudyDirection.MAXIMIZE) else False
217
+ trials = [t for t in trials if t.state == TrialState.COMPLETE]
218
+ current_step = len(trials) - 1
219
+
220
+ best_step = 0
221
+ for i, trial in enumerate(trials):
222
+ best_value = trials[best_step].value
223
+ current_value = trial.value
224
+ assert best_value is not None
225
+ assert current_value is not None
226
+ if is_maximize_direction and (best_value < current_value):
227
+ best_step = i
228
+ elif (not is_maximize_direction) and (best_value > current_value):
229
+ best_step = i
230
+
231
+ return self._max_stagnation_trials - (current_step - best_step)
232
+
233
+ @classmethod
234
+ def _validate_input(cls, trials: list[FrozenTrial]) -> None:
235
+ if len([t for t in trials if t.state == TrialState.COMPLETE]) == 0:
236
+ raise ValueError(
237
+ "Because no trial has been completed yet, the improvement cannot be evaluated."
238
+ )
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/median_erroreval.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+
5
+ import numpy as np
6
+
7
+ from optuna._experimental import experimental_class
8
+ from optuna.study import StudyDirection
9
+ from optuna.terminator.erroreval import BaseErrorEvaluator
10
+ from optuna.terminator.improvement.evaluator import BaseImprovementEvaluator
11
+ from optuna.trial import FrozenTrial
12
+ from optuna.trial._state import TrialState
13
+
14
+
15
+ @experimental_class("4.0.0")
16
+ class MedianErrorEvaluator(BaseErrorEvaluator):
17
+ """An error evaluator that returns the ratio to initial median.
18
+
19
+ This error evaluator is introduced as a heuristics in the following paper:
20
+
21
+ - `A stopping criterion for Bayesian optimization by the gap of expected minimum simple
22
+ regrets <https://proceedings.mlr.press/v206/ishibashi23a.html>`__
23
+
24
+ Args:
25
+ paired_improvement_evaluator:
26
+ The ``improvement_evaluator`` instance which is set with this ``error_evaluator``.
27
+ warm_up_trials:
28
+ A parameter specifies the number of initial trials to be discarded before
29
+ the calculation of median. Default to 10.
30
+ In optuna, the first 10 trials are often random sampling.
31
+ The ``warm_up_trials`` can exclude them from the calculation.
32
+ n_initial_trials:
33
+ A parameter specifies the number of initial trials considered in the calculation of
34
+ median after ``warm_up_trials``. Default to 20.
35
+ threshold_ratio:
36
+ A parameter specifies the ratio between the threshold and initial median.
37
+ Default to 0.01.
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ paired_improvement_evaluator: BaseImprovementEvaluator,
43
+ warm_up_trials: int = 10,
44
+ n_initial_trials: int = 20,
45
+ threshold_ratio: float = 0.01,
46
+ ) -> None:
47
+ if warm_up_trials < 0:
48
+ raise ValueError("`warm_up_trials` is expected to be a non-negative integer.")
49
+ if n_initial_trials <= 0:
50
+ raise ValueError("`n_initial_trials` is expected to be a positive integer.")
51
+ if threshold_ratio <= 0.0 or not np.isfinite(threshold_ratio):
52
+ raise ValueError("`threshold_ratio_to_initial_median` is expected to be a positive.")
53
+
54
+ self._paired_improvement_evaluator = paired_improvement_evaluator
55
+ self._warm_up_trials = warm_up_trials
56
+ self._n_initial_trials = n_initial_trials
57
+ self._threshold_ratio = threshold_ratio
58
+ self._threshold: float | None = None
59
+
60
+ def evaluate(
61
+ self,
62
+ trials: list[FrozenTrial],
63
+ study_direction: StudyDirection,
64
+ ) -> float:
65
+
66
+ if self._threshold is not None:
67
+ return self._threshold
68
+
69
+ trials = [trial for trial in trials if trial.state == TrialState.COMPLETE]
70
+ if len(trials) < (self._warm_up_trials + self._n_initial_trials):
71
+ return (
72
+ -sys.float_info.min
73
+ ) # Do not terminate. It assumes that improvement must non-negative.
74
+ trials.sort(key=lambda trial: trial.number)
75
+ criteria = []
76
+ for i in range(1, self._n_initial_trials + 1):
77
+ criteria.append(
78
+ self._paired_improvement_evaluator.evaluate(
79
+ trials[self._warm_up_trials : self._warm_up_trials + i], study_direction
80
+ )
81
+ )
82
+ criteria.sort()
83
+ self._threshold = criteria[len(criteria) // 2]
84
+ assert self._threshold is not None
85
+ self._threshold = min(sys.float_info.max, self._threshold * self._threshold_ratio)
86
+ return self._threshold
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/terminator.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import abc
4
+
5
+ from optuna._experimental import experimental_class
6
+ from optuna.study.study import Study
7
+ from optuna.terminator.erroreval import BaseErrorEvaluator
8
+ from optuna.terminator.erroreval import CrossValidationErrorEvaluator
9
+ from optuna.terminator.erroreval import StaticErrorEvaluator
10
+ from optuna.terminator.improvement.evaluator import BaseImprovementEvaluator
11
+ from optuna.terminator.improvement.evaluator import BestValueStagnationEvaluator
12
+ from optuna.terminator.improvement.evaluator import DEFAULT_MIN_N_TRIALS
13
+ from optuna.terminator.improvement.evaluator import RegretBoundEvaluator
14
+ from optuna.trial import TrialState
15
+
16
+
17
+ class BaseTerminator(metaclass=abc.ABCMeta):
18
+ """Base class for terminators."""
19
+
20
+ @abc.abstractmethod
21
+ def should_terminate(self, study: Study) -> bool:
22
+ pass
23
+
24
+
25
+ @experimental_class("3.2.0")
26
+ class Terminator(BaseTerminator):
27
+ """Automatic stopping mechanism for Optuna studies.
28
+
29
+ This class implements an automatic stopping mechanism for Optuna studies, aiming to prevent
30
+ unnecessary computation. The study is terminated when the statistical error, e.g.
31
+ cross-validation error, exceeds the room left for optimization.
32
+
33
+ For further information about the algorithm, please refer to the following paper:
34
+
35
+ - `A. Makarova et al. Automatic termination for hyperparameter optimization.
36
+ <https://proceedings.mlr.press/v188/makarova22a.html>`__
37
+
38
+ Args:
39
+ improvement_evaluator:
40
+ An evaluator object for assessing the room left for optimization. Defaults to a
41
+ :class:`~optuna.terminator.improvement.evaluator.RegretBoundEvaluator` object.
42
+ error_evaluator:
43
+ An evaluator for calculating the statistical error, e.g. cross-validation error.
44
+ Defaults to a :class:`~optuna.terminator.CrossValidationErrorEvaluator`
45
+ object.
46
+ min_n_trials:
47
+ The minimum number of trials before termination is considered. Defaults to ``20``.
48
+
49
+ Raises:
50
+ ValueError: If ``min_n_trials`` is not a positive integer.
51
+
52
+ Example:
53
+
54
+ .. testcode::
55
+
56
+ import logging
57
+ import sys
58
+
59
+ from sklearn.datasets import load_wine
60
+ from sklearn.ensemble import RandomForestClassifier
61
+ from sklearn.model_selection import cross_val_score
62
+ from sklearn.model_selection import KFold
63
+
64
+ import optuna
65
+ from optuna.terminator import Terminator
66
+ from optuna.terminator import report_cross_validation_scores
67
+
68
+
69
+ study = optuna.create_study(direction="maximize")
70
+ terminator = Terminator()
71
+ min_n_trials = 20
72
+
73
+ while True:
74
+ trial = study.ask()
75
+
76
+ X, y = load_wine(return_X_y=True)
77
+
78
+ clf = RandomForestClassifier(
79
+ max_depth=trial.suggest_int("max_depth", 2, 32),
80
+ min_samples_split=trial.suggest_float("min_samples_split", 0, 1),
81
+ criterion=trial.suggest_categorical("criterion", ("gini", "entropy")),
82
+ )
83
+
84
+ scores = cross_val_score(clf, X, y, cv=KFold(n_splits=5, shuffle=True))
85
+ report_cross_validation_scores(trial, scores)
86
+
87
+ value = scores.mean()
88
+ logging.info(f"Trial #{trial.number} finished with value {value}.")
89
+ study.tell(trial, value)
90
+
91
+ if trial.number > min_n_trials and terminator.should_terminate(study):
92
+ logging.info("Terminated by Optuna Terminator!")
93
+ break
94
+
95
+ .. seealso::
96
+ Please refer to :class:`~optuna.terminator.TerminatorCallback` for how to use
97
+ the terminator mechanism with the :func:`~optuna.study.Study.optimize` method.
98
+
99
+ """
100
+
101
+ def __init__(
102
+ self,
103
+ improvement_evaluator: BaseImprovementEvaluator | None = None,
104
+ error_evaluator: BaseErrorEvaluator | None = None,
105
+ min_n_trials: int = DEFAULT_MIN_N_TRIALS,
106
+ ) -> None:
107
+ if min_n_trials <= 0:
108
+ raise ValueError("`min_n_trials` is expected to be a positive integer.")
109
+
110
+ self._improvement_evaluator = improvement_evaluator or RegretBoundEvaluator()
111
+ self._error_evaluator = error_evaluator or self._initialize_error_evaluator()
112
+ self._min_n_trials = min_n_trials
113
+
114
+ def _initialize_error_evaluator(self) -> BaseErrorEvaluator:
115
+ if isinstance(self._improvement_evaluator, BestValueStagnationEvaluator):
116
+ return StaticErrorEvaluator(constant=0)
117
+ return CrossValidationErrorEvaluator()
118
+
119
+ def should_terminate(self, study: Study) -> bool:
120
+ """Judge whether the study should be terminated based on the reported values."""
121
+ trials = study.get_trials(states=[TrialState.COMPLETE])
122
+
123
+ if len(trials) < self._min_n_trials:
124
+ return False
125
+
126
+ improvement = self._improvement_evaluator.evaluate(
127
+ trials=study.trials,
128
+ study_direction=study.direction,
129
+ )
130
+
131
+ error = self._error_evaluator.evaluate(
132
+ trials=study.trials, study_direction=study.direction
133
+ )
134
+
135
+ should_terminate = improvement < error
136
+ return should_terminate
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/__init__.py ADDED
File without changes
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/objectives.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from optuna import TrialPruned
2
+ from optuna.trial import Trial
3
+
4
+
5
+ def fail_objective(_: Trial) -> float:
6
+ raise ValueError()
7
+
8
+
9
+ def pruned_objective(trial: Trial) -> float:
10
+ raise TrialPruned()
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/pruners.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import optuna
4
+
5
+
6
+ class DeterministicPruner(optuna.pruners.BasePruner):
7
+ def __init__(self, is_pruning: bool) -> None:
8
+ self.is_pruning = is_pruning
9
+
10
+ def prune(self, study: "optuna.study.Study", trial: "optuna.trial.FrozenTrial") -> bool:
11
+ return self.is_pruning
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/samplers.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import optuna
6
+ from optuna.distributions import BaseDistribution
7
+
8
+
9
+ class DeterministicSampler(optuna.samplers.BaseSampler):
10
+ def __init__(self, params: dict[str, Any]) -> None:
11
+ self.params = params
12
+
13
+ def infer_relative_search_space(
14
+ self, study: "optuna.study.Study", trial: "optuna.trial.FrozenTrial"
15
+ ) -> dict[str, BaseDistribution]:
16
+ return {}
17
+
18
+ def sample_relative(
19
+ self,
20
+ study: "optuna.study.Study",
21
+ trial: "optuna.trial.FrozenTrial",
22
+ search_space: dict[str, BaseDistribution],
23
+ ) -> dict[str, Any]:
24
+ return {}
25
+
26
+ def sample_independent(
27
+ self,
28
+ study: "optuna.study.Study",
29
+ trial: "optuna.trial.FrozenTrial",
30
+ param_name: str,
31
+ param_distribution: BaseDistribution,
32
+ ) -> Any:
33
+ param_value = self.params[param_name]
34
+ assert param_distribution._contains(param_distribution.to_internal_repr(param_value))
35
+ return param_value
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/storages.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ from contextlib import AbstractContextManager
5
+ from contextlib import contextmanager
6
+ import os
7
+ import socket
8
+ import sys
9
+ import threading
10
+ from types import TracebackType
11
+ from typing import Any
12
+ from typing import Generator
13
+ from typing import IO
14
+ from typing import TYPE_CHECKING
15
+
16
+ import fakeredis
17
+
18
+ import optuna
19
+ from optuna.storages import BaseStorage
20
+ from optuna.storages import GrpcStorageProxy
21
+ from optuna.storages.journal import JournalFileBackend
22
+ from optuna.testing.tempfile_pool import NamedTemporaryFilePool
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ import grpc
27
+ else:
28
+ from optuna._imports import _LazyImport
29
+
30
+ grpc = _LazyImport("grpc")
31
+
32
+
33
+ STORAGE_MODES: list[Any] = [
34
+ "inmemory",
35
+ "sqlite",
36
+ "cached_sqlite",
37
+ "journal",
38
+ "journal_redis",
39
+ "grpc_rdb",
40
+ "grpc_journal_file",
41
+ ]
42
+
43
+
44
+ STORAGE_MODES_HEARTBEAT = [
45
+ "sqlite",
46
+ "cached_sqlite",
47
+ ]
48
+
49
+ SQLITE3_TIMEOUT = 300
50
+
51
+
52
+ @contextmanager
53
+ def _lock_to_search_for_free_port() -> Generator[None, None, None]:
54
+ if sys.platform == "win32":
55
+ lock_path = os.path.join(
56
+ os.environ.get("PROGRAMDATA", "C:\\ProgramData"),
57
+ "optuna",
58
+ "optuna_find_free_port.lock",
59
+ )
60
+ else:
61
+ lock_path = "/tmp/optuna_find_free_port.lock"
62
+
63
+ os.makedirs(os.path.dirname(lock_path), exist_ok=True)
64
+ lockfile = open(lock_path, "w")
65
+ if sys.platform == "win32":
66
+ import msvcrt
67
+
68
+ msvcrt.locking(lockfile.fileno(), msvcrt.LK_LOCK, 1)
69
+ yield
70
+ msvcrt.locking(lockfile.fileno(), msvcrt.LK_UNLCK, 1)
71
+ else:
72
+ import fcntl
73
+
74
+ fcntl.flock(lockfile, fcntl.LOCK_EX)
75
+ yield
76
+ fcntl.flock(lockfile, fcntl.LOCK_UN)
77
+
78
+ lockfile.close()
79
+
80
+
81
+ class StorageSupplier(AbstractContextManager):
82
+ def __init__(self, storage_specifier: str, **kwargs: Any) -> None:
83
+ self.storage_specifier = storage_specifier
84
+ self.extra_args = kwargs
85
+ self.tempfile: IO[Any] | None = None
86
+ self.server: grpc.Server | None = None
87
+ self.thread: threading.Thread | None = None
88
+ self.proxy: GrpcStorageProxy | None = None
89
+
90
+ def __enter__(
91
+ self,
92
+ ) -> (
93
+ optuna.storages.InMemoryStorage
94
+ | optuna.storages._CachedStorage
95
+ | optuna.storages.RDBStorage
96
+ | optuna.storages.JournalStorage
97
+ | optuna.storages.GrpcStorageProxy
98
+ ):
99
+ if self.storage_specifier == "inmemory":
100
+ if len(self.extra_args) > 0:
101
+ raise ValueError("InMemoryStorage does not accept any arguments!")
102
+ return optuna.storages.InMemoryStorage()
103
+ elif "sqlite" in self.storage_specifier:
104
+ self.tempfile = NamedTemporaryFilePool().tempfile()
105
+ url = "sqlite:///{}".format(self.tempfile.name)
106
+ rdb_storage = optuna.storages.RDBStorage(
107
+ url,
108
+ engine_kwargs={"connect_args": {"timeout": SQLITE3_TIMEOUT}},
109
+ **self.extra_args,
110
+ )
111
+ return (
112
+ optuna.storages._CachedStorage(rdb_storage)
113
+ if "cached" in self.storage_specifier
114
+ else rdb_storage
115
+ )
116
+ elif self.storage_specifier == "journal_redis":
117
+ journal_redis_storage = optuna.storages.journal.JournalRedisBackend(
118
+ "redis://localhost"
119
+ )
120
+ journal_redis_storage._redis = self.extra_args.get(
121
+ "redis", fakeredis.FakeStrictRedis()
122
+ )
123
+ return optuna.storages.JournalStorage(journal_redis_storage)
124
+ elif self.storage_specifier == "grpc_journal_file":
125
+ self.tempfile = self.extra_args.get("file", NamedTemporaryFilePool().tempfile())
126
+ assert self.tempfile is not None
127
+ storage = optuna.storages.JournalStorage(
128
+ optuna.storages.journal.JournalFileBackend(self.tempfile.name)
129
+ )
130
+ return self._create_proxy(storage, thread_pool=self.extra_args.get("thread_pool"))
131
+ elif "journal" in self.storage_specifier:
132
+ self.tempfile = self.extra_args.get("file", NamedTemporaryFilePool().tempfile())
133
+ assert self.tempfile is not None
134
+ file_storage = JournalFileBackend(self.tempfile.name)
135
+ return optuna.storages.JournalStorage(file_storage)
136
+ elif self.storage_specifier == "grpc_rdb":
137
+ self.tempfile = NamedTemporaryFilePool().tempfile()
138
+ url = "sqlite:///{}".format(self.tempfile.name)
139
+ return self._create_proxy(optuna.storages.RDBStorage(url))
140
+ elif self.storage_specifier == "grpc_proxy":
141
+ assert "base_storage" in self.extra_args
142
+ return self._create_proxy(self.extra_args["base_storage"])
143
+ else:
144
+ assert False
145
+
146
+ def _create_proxy(
147
+ self, storage: BaseStorage, thread_pool: ThreadPoolExecutor | None = None
148
+ ) -> GrpcStorageProxy:
149
+ with _lock_to_search_for_free_port():
150
+ port = _find_free_port()
151
+ self.server = optuna.storages._grpc.server.make_server(
152
+ storage, "localhost", port, thread_pool=thread_pool
153
+ )
154
+ self.thread = threading.Thread(target=self.server.start)
155
+ self.thread.start()
156
+ self.proxy = GrpcStorageProxy(host="localhost", port=port)
157
+ self.proxy.wait_server_ready(timeout=60)
158
+ return self.proxy
159
+
160
+ def __exit__(
161
+ self,
162
+ exc_type: type[BaseException] | None,
163
+ exc_val: BaseException | None,
164
+ exc_tb: TracebackType | None,
165
+ ) -> None:
166
+ if self.tempfile:
167
+ self.tempfile.close()
168
+
169
+ if self.proxy:
170
+ self.proxy.close()
171
+ self.proxy = None
172
+
173
+ if self.server:
174
+ assert self.thread is not None
175
+ self.server.stop(5).wait()
176
+ self.thread.join()
177
+ self.server = None
178
+ self.thread = None
179
+
180
+
181
+ def _find_free_port() -> int:
182
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
183
+ for port in range(13000, 13100):
184
+ try:
185
+ sock.bind(("localhost", port))
186
+ return port
187
+ except OSError:
188
+ continue
189
+ assert False, "must not reach here"
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/tempfile_pool.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # On Windows, temporary file shold delete "after" storage was deleted
2
+ # NamedTemporaryFilePool ensures tempfile delete after tests.
3
+
4
+ from __future__ import annotations
5
+
6
+ import atexit
7
+ import gc
8
+ import os
9
+ import tempfile
10
+ from types import TracebackType
11
+ from typing import Any
12
+ from typing import IO
13
+
14
+
15
+ class NamedTemporaryFilePool:
16
+ tempfile_pool: list[IO[Any]] = []
17
+
18
+ def __new__(cls, **kwargs: Any) -> "NamedTemporaryFilePool":
19
+ if not hasattr(cls, "_instance"):
20
+ cls._instance = super(NamedTemporaryFilePool, cls).__new__(cls)
21
+ atexit.register(cls._instance.cleanup)
22
+ return cls._instance
23
+
24
+ def __init__(self, **kwargs: Any) -> None:
25
+ self.kwargs = kwargs
26
+
27
+ def tempfile(self) -> IO[Any]:
28
+ self._tempfile = tempfile.NamedTemporaryFile(delete=False, **self.kwargs)
29
+ self.tempfile_pool.append(self._tempfile)
30
+ return self._tempfile
31
+
32
+ def cleanup(self) -> None:
33
+ gc.collect()
34
+ for i in self.tempfile_pool:
35
+ os.unlink(i.name)
36
+
37
+ def __enter__(self) -> IO[Any]:
38
+ return self.tempfile()
39
+
40
+ def __exit__(
41
+ self,
42
+ exc_type: type[BaseException],
43
+ exc_val: BaseException,
44
+ exc_tb: TracebackType,
45
+ ) -> None:
46
+ self._tempfile.close()
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/threading.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+ import threading
5
+ from typing import Any
6
+
7
+
8
+ class _TestableThread(threading.Thread):
9
+ def __init__(self, target: Callable[..., Any], args: tuple):
10
+ threading.Thread.__init__(self, target=target, args=args)
11
+ self.exc: BaseException | None = None
12
+
13
+ def run(self) -> None:
14
+ try:
15
+ threading.Thread.run(self)
16
+ except BaseException as e:
17
+ self.exc = e
18
+
19
+ def join(self, timeout: float | None = None) -> None:
20
+ super(_TestableThread, self).join(timeout)
21
+ if self.exc:
22
+ raise self.exc
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/trials.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ from typing import Any
5
+
6
+ import optuna
7
+ from optuna.distributions import BaseDistribution
8
+ from optuna.samplers._base import _CONSTRAINTS_KEY
9
+ from optuna.trial import FrozenTrial
10
+ from optuna.trial import TrialState
11
+
12
+
13
+ def _create_frozen_trial(
14
+ number: int = 0,
15
+ values: Sequence[float] | None = None,
16
+ constraints: Sequence[float] | None = None,
17
+ params: dict[str, Any] | None = None,
18
+ param_distributions: dict[str, BaseDistribution] | None = None,
19
+ state: TrialState = TrialState.COMPLETE,
20
+ ) -> optuna.trial.FrozenTrial:
21
+ return FrozenTrial(
22
+ number=number,
23
+ value=1.0 if values is None else None,
24
+ values=values,
25
+ state=state,
26
+ user_attrs={},
27
+ system_attrs={} if constraints is None else {_CONSTRAINTS_KEY: list(constraints)},
28
+ params=params or {},
29
+ distributions=param_distributions or {},
30
+ intermediate_values={},
31
+ datetime_start=None,
32
+ datetime_complete=None,
33
+ trial_id=number,
34
+ )
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/visualization.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from optuna import Study
2
+ from optuna.distributions import FloatDistribution
3
+ from optuna.study import create_study
4
+ from optuna.trial import create_trial
5
+
6
+
7
+ def prepare_study_with_trials(
8
+ n_objectives: int = 1,
9
+ direction: str = "minimize",
10
+ value_for_first_trial: float = 0.0,
11
+ ) -> Study:
12
+ """Return a dummy study object for tests.
13
+
14
+ This function is added to reduce the code to set up dummy study object in each test case.
15
+ However, you can only use this function for unit tests that are loosely coupled with the
16
+ dummy study object. Unit tests that are tightly coupled with the study become difficult to
17
+ read because of
18
+ `Mystery Guest <http://xunitpatterns.com/Obscure%20Test.html#Mystery%20Guest>`__ and/or
19
+ `Eager Test <http://xunitpatterns.com/Obscure%20Test.html#Eager%20Test>`__ anti-patterns.
20
+
21
+ Args:
22
+ n_objectives: Number of objective values.
23
+ direction: Study's optimization direction.
24
+ value_for_first_trial: Objective value in first trial. This value will be broadcasted
25
+ to all objectives in multi-objective optimization.
26
+
27
+ Returns:
28
+ :class:`~optuna.study.Study`
29
+
30
+ """
31
+
32
+ study = create_study(directions=[direction] * n_objectives)
33
+ study.add_trial(
34
+ create_trial(
35
+ values=[value_for_first_trial] * n_objectives,
36
+ params={"param_a": 1.0, "param_b": 2.0, "param_c": 3.0, "param_d": 4.0},
37
+ distributions={
38
+ "param_a": FloatDistribution(0.0, 3.0),
39
+ "param_b": FloatDistribution(0.0, 3.0),
40
+ "param_c": FloatDistribution(2.0, 5.0),
41
+ "param_d": FloatDistribution(2.0, 5.0),
42
+ },
43
+ )
44
+ )
45
+ study.add_trial(
46
+ create_trial(
47
+ values=[2.0] * n_objectives,
48
+ params={"param_b": 0.0, "param_d": 4.0},
49
+ distributions={
50
+ "param_b": FloatDistribution(0.0, 3.0),
51
+ "param_d": FloatDistribution(2.0, 5.0),
52
+ },
53
+ )
54
+ )
55
+ study.add_trial(
56
+ create_trial(
57
+ values=[1.0] * n_objectives,
58
+ params={"param_a": 2.5, "param_b": 1.0, "param_c": 4.5, "param_d": 2.0},
59
+ distributions={
60
+ "param_a": FloatDistribution(0.0, 3.0),
61
+ "param_b": FloatDistribution(0.0, 3.0),
62
+ "param_c": FloatDistribution(2.0, 5.0),
63
+ "param_d": FloatDistribution(2.0, 5.0),
64
+ },
65
+ )
66
+ )
67
+ return study
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from optuna.trial._base import BaseTrial
2
+ from optuna.trial._fixed import FixedTrial
3
+ from optuna.trial._frozen import create_trial
4
+ from optuna.trial._frozen import FrozenTrial
5
+ from optuna.trial._state import TrialState
6
+ from optuna.trial._trial import Trial
7
+
8
+
9
+ __all__ = [
10
+ "BaseTrial",
11
+ "FixedTrial",
12
+ "FrozenTrial",
13
+ "Trial",
14
+ "TrialState",
15
+ "create_trial",
16
+ ]
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (591 Bytes). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_fixed.cpython-310.pyc ADDED
Binary file (7.49 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_frozen.cpython-310.pyc ADDED
Binary file (20.1 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_state.cpython-310.pyc ADDED
Binary file (1.57 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_trial.cpython-310.pyc ADDED
Binary file (28.4 kB). View file
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_base.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import abc
4
+ from collections.abc import Sequence
5
+ import datetime
6
+ from typing import Any
7
+ from typing import overload
8
+
9
+ from optuna._deprecated import deprecated_func
10
+ from optuna.distributions import BaseDistribution
11
+ from optuna.distributions import CategoricalChoiceType
12
+
13
+
14
+ _SUGGEST_INT_POSITIONAL_ARGS = ["self", "name", "low", "high", "step", "log"]
15
+
16
+
17
+ class BaseTrial(abc.ABC):
18
+ """Base class for trials.
19
+
20
+ Note that this class is not supposed to be directly accessed by library users.
21
+ """
22
+
23
+ @abc.abstractmethod
24
+ def suggest_float(
25
+ self,
26
+ name: str,
27
+ low: float,
28
+ high: float,
29
+ *,
30
+ step: float | None = None,
31
+ log: bool = False,
32
+ ) -> float:
33
+ raise NotImplementedError
34
+
35
+ @deprecated_func("3.0.0", "6.0.0")
36
+ @abc.abstractmethod
37
+ def suggest_uniform(self, name: str, low: float, high: float) -> float:
38
+ raise NotImplementedError
39
+
40
+ @deprecated_func("3.0.0", "6.0.0")
41
+ @abc.abstractmethod
42
+ def suggest_loguniform(self, name: str, low: float, high: float) -> float:
43
+ raise NotImplementedError
44
+
45
+ @deprecated_func("3.0.0", "6.0.0")
46
+ @abc.abstractmethod
47
+ def suggest_discrete_uniform(self, name: str, low: float, high: float, q: float) -> float:
48
+ raise NotImplementedError
49
+
50
+ @abc.abstractmethod
51
+ def suggest_int(
52
+ self, name: str, low: int, high: int, *, step: int = 1, log: bool = False
53
+ ) -> int:
54
+ raise NotImplementedError
55
+
56
+ @overload
57
+ @abc.abstractmethod
58
+ def suggest_categorical(self, name: str, choices: Sequence[None]) -> None: ...
59
+
60
+ @overload
61
+ @abc.abstractmethod
62
+ def suggest_categorical(self, name: str, choices: Sequence[bool]) -> bool: ...
63
+
64
+ @overload
65
+ @abc.abstractmethod
66
+ def suggest_categorical(self, name: str, choices: Sequence[int]) -> int: ...
67
+
68
+ @overload
69
+ @abc.abstractmethod
70
+ def suggest_categorical(self, name: str, choices: Sequence[float]) -> float: ...
71
+
72
+ @overload
73
+ @abc.abstractmethod
74
+ def suggest_categorical(self, name: str, choices: Sequence[str]) -> str: ...
75
+
76
+ @overload
77
+ @abc.abstractmethod
78
+ def suggest_categorical(
79
+ self, name: str, choices: Sequence[CategoricalChoiceType]
80
+ ) -> CategoricalChoiceType: ...
81
+
82
+ @abc.abstractmethod
83
+ def suggest_categorical(
84
+ self, name: str, choices: Sequence[CategoricalChoiceType]
85
+ ) -> CategoricalChoiceType:
86
+ raise NotImplementedError
87
+
88
+ @abc.abstractmethod
89
+ def report(self, value: float, step: int) -> None:
90
+ raise NotImplementedError
91
+
92
+ @abc.abstractmethod
93
+ def should_prune(self) -> bool:
94
+ raise NotImplementedError
95
+
96
+ @abc.abstractmethod
97
+ def set_user_attr(self, key: str, value: Any) -> None:
98
+ raise NotImplementedError
99
+
100
+ @abc.abstractmethod
101
+ @deprecated_func("3.1.0", "5.0.0")
102
+ def set_system_attr(self, key: str, value: Any) -> None:
103
+ raise NotImplementedError
104
+
105
+ @property
106
+ @abc.abstractmethod
107
+ def params(self) -> dict[str, Any]:
108
+ raise NotImplementedError
109
+
110
+ @property
111
+ @abc.abstractmethod
112
+ def distributions(self) -> dict[str, BaseDistribution]:
113
+ raise NotImplementedError
114
+
115
+ @property
116
+ @abc.abstractmethod
117
+ def user_attrs(self) -> dict[str, Any]:
118
+ raise NotImplementedError
119
+
120
+ @property
121
+ @abc.abstractmethod
122
+ def system_attrs(self) -> dict[str, Any]:
123
+ raise NotImplementedError
124
+
125
+ @property
126
+ @abc.abstractmethod
127
+ def datetime_start(self) -> datetime.datetime | None:
128
+ raise NotImplementedError
129
+
130
+ @property
131
+ def number(self) -> int:
132
+ raise NotImplementedError
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_fixed.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Sequence
4
+ import datetime
5
+ from typing import Any
6
+ from typing import overload
7
+ import warnings
8
+
9
+ from optuna import distributions
10
+ from optuna._convert_positional_args import convert_positional_args
11
+ from optuna._deprecated import deprecated_func
12
+ from optuna.distributions import BaseDistribution
13
+ from optuna.distributions import CategoricalChoiceType
14
+ from optuna.distributions import CategoricalDistribution
15
+ from optuna.distributions import FloatDistribution
16
+ from optuna.distributions import IntDistribution
17
+ from optuna.trial._base import _SUGGEST_INT_POSITIONAL_ARGS
18
+ from optuna.trial._base import BaseTrial
19
+
20
+
21
+ _suggest_deprecated_msg = "Use suggest_float{args} instead."
22
+
23
+
24
+ class FixedTrial(BaseTrial):
25
+ """A trial class which suggests a fixed value for each parameter.
26
+
27
+ This object has the same methods as :class:`~optuna.trial.Trial`, and it suggests pre-defined
28
+ parameter values. The parameter values can be determined at the construction of the
29
+ :class:`~optuna.trial.FixedTrial` object. In contrast to :class:`~optuna.trial.Trial`,
30
+ :class:`~optuna.trial.FixedTrial` does not depend on :class:`~optuna.study.Study`, and it is
31
+ useful for deploying optimization results.
32
+
33
+ Example:
34
+
35
+ Evaluate an objective function with parameter values given by a user.
36
+
37
+ .. testcode::
38
+
39
+ import optuna
40
+
41
+
42
+ def objective(trial):
43
+ x = trial.suggest_float("x", -100, 100)
44
+ y = trial.suggest_categorical("y", [-1, 0, 1])
45
+ return x**2 + y
46
+
47
+
48
+ assert objective(optuna.trial.FixedTrial({"x": 1, "y": 0})) == 1
49
+
50
+
51
+ .. note::
52
+ Please refer to :class:`~optuna.trial.Trial` for details of methods and properties.
53
+
54
+ Args:
55
+ params:
56
+ A dictionary containing all parameters.
57
+ number:
58
+ A trial number. Defaults to ``0``.
59
+
60
+ """
61
+
62
+ def __init__(self, params: dict[str, Any], number: int = 0) -> None:
63
+ self._params = params
64
+ self._suggested_params: dict[str, Any] = {}
65
+ self._distributions: dict[str, BaseDistribution] = {}
66
+ self._user_attrs: dict[str, Any] = {}
67
+ self._system_attrs: dict[str, Any] = {}
68
+ self._datetime_start = datetime.datetime.now()
69
+ self._number = number
70
+
71
+ def suggest_float(
72
+ self,
73
+ name: str,
74
+ low: float,
75
+ high: float,
76
+ *,
77
+ step: float | None = None,
78
+ log: bool = False,
79
+ ) -> float:
80
+ return self._suggest(name, FloatDistribution(low, high, log=log, step=step))
81
+
82
+ @deprecated_func("3.0.0", "6.0.0", text=_suggest_deprecated_msg.format(args=""))
83
+ def suggest_uniform(self, name: str, low: float, high: float) -> float:
84
+ return self.suggest_float(name, low, high)
85
+
86
+ @deprecated_func("3.0.0", "6.0.0", text=_suggest_deprecated_msg.format(args="(..., log=True)"))
87
+ def suggest_loguniform(self, name: str, low: float, high: float) -> float:
88
+ return self.suggest_float(name, low, high, log=True)
89
+
90
+ @deprecated_func("3.0.0", "6.0.0", text=_suggest_deprecated_msg.format(args="(..., step=...)"))
91
+ def suggest_discrete_uniform(self, name: str, low: float, high: float, q: float) -> float:
92
+ return self.suggest_float(name, low, high, step=q)
93
+
94
+ @convert_positional_args(
95
+ previous_positional_arg_names=_SUGGEST_INT_POSITIONAL_ARGS,
96
+ deprecated_version="3.5.0",
97
+ removed_version="5.0.0",
98
+ )
99
+ def suggest_int(
100
+ self, name: str, low: int, high: int, *, step: int = 1, log: bool = False
101
+ ) -> int:
102
+ return int(self._suggest(name, IntDistribution(low, high, log=log, step=step)))
103
+
104
+ @overload
105
+ def suggest_categorical(self, name: str, choices: Sequence[None]) -> None: ...
106
+
107
+ @overload
108
+ def suggest_categorical(self, name: str, choices: Sequence[bool]) -> bool: ...
109
+
110
+ @overload
111
+ def suggest_categorical(self, name: str, choices: Sequence[int]) -> int: ...
112
+
113
+ @overload
114
+ def suggest_categorical(self, name: str, choices: Sequence[float]) -> float: ...
115
+
116
+ @overload
117
+ def suggest_categorical(self, name: str, choices: Sequence[str]) -> str: ...
118
+
119
+ @overload
120
+ def suggest_categorical(
121
+ self, name: str, choices: Sequence[CategoricalChoiceType]
122
+ ) -> CategoricalChoiceType: ...
123
+
124
+ def suggest_categorical(
125
+ self, name: str, choices: Sequence[CategoricalChoiceType]
126
+ ) -> CategoricalChoiceType:
127
+ return self._suggest(name, CategoricalDistribution(choices=choices))
128
+
129
+ def report(self, value: float, step: int) -> None:
130
+ pass
131
+
132
+ def should_prune(self) -> bool:
133
+ return False
134
+
135
+ def set_user_attr(self, key: str, value: Any) -> None:
136
+ self._user_attrs[key] = value
137
+
138
+ @deprecated_func("3.1.0", "5.0.0")
139
+ def set_system_attr(self, key: str, value: Any) -> None:
140
+ self._system_attrs[key] = value
141
+
142
+ def _suggest(self, name: str, distribution: BaseDistribution) -> Any:
143
+ if name not in self._params:
144
+ raise ValueError(
145
+ "The value of the parameter '{}' is not found. Please set it at "
146
+ "the construction of the FixedTrial object.".format(name)
147
+ )
148
+
149
+ value = self._params[name]
150
+ param_value_in_internal_repr = distribution.to_internal_repr(value)
151
+ if not distribution._contains(param_value_in_internal_repr):
152
+ warnings.warn(
153
+ "The value {} of the parameter '{}' is out of "
154
+ "the range of the distribution {}.".format(value, name, distribution)
155
+ )
156
+
157
+ if name in self._distributions:
158
+ distributions.check_distribution_compatibility(self._distributions[name], distribution)
159
+
160
+ self._suggested_params[name] = value
161
+ self._distributions[name] = distribution
162
+
163
+ return value
164
+
165
+ @property
166
+ def params(self) -> dict[str, Any]:
167
+ return self._suggested_params
168
+
169
+ @property
170
+ def distributions(self) -> dict[str, BaseDistribution]:
171
+ return self._distributions
172
+
173
+ @property
174
+ def user_attrs(self) -> dict[str, Any]:
175
+ return self._user_attrs
176
+
177
+ @property
178
+ def system_attrs(self) -> dict[str, Any]:
179
+ return self._system_attrs
180
+
181
+ @property
182
+ def datetime_start(self) -> datetime.datetime | None:
183
+ return self._datetime_start
184
+
185
+ @property
186
+ def number(self) -> int:
187
+ return self._number